text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {absoluteFrom, getFileSystem} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {cleanPackageJson, hasBeenProcessed, markAsProcessed, needsCleaning, NGCC_VERSION} from '../../src/packages/build_marker';
import {EntryPointPackageJson} from '../../src/packages/entry_point';
import {DirectPackageJsonUpdater} from '../../src/writing/package_json_updater';
runInEachFileSystem(() => {
describe('Marker files', () => {
let _: typeof absoluteFrom;
beforeEach(() => {
_ = absoluteFrom;
loadTestFiles([
{
name: _('/node_modules/@angular/common/package.json'),
contents:
`{"fesm2015": "./fesm2015/common.js", "fesm5": "./fesm5/common.js", "typings": "./common.d.ts"}`
},
{name: _('/node_modules/@angular/common/fesm2015/common.js'), contents: 'DUMMY CONTENT'},
{name: _('/node_modules/@angular/common/fesm2015/http.js'), contents: 'DUMMY CONTENT'},
{
name: _('/node_modules/@angular/common/fesm2015/http/testing.js'),
contents: 'DUMMY CONTENT'
},
{name: _('/node_modules/@angular/common/fesm2015/testing.js'), contents: 'DUMMY CONTENT'},
{
name: _('/node_modules/@angular/common/http/package.json'),
contents:
`{"fesm2015": "../fesm2015/http.js", "fesm5": "../fesm5/http.js", "typings": "./http.d.ts"}`
},
{
name: _('/node_modules/@angular/common/http/testing/package.json'),
contents:
`{"fesm2015": "../../fesm2015/http/testing.js", "fesm5": "../../fesm5/http/testing.js", "typings": "../http/testing.d.ts" }`
},
{name: _('/node_modules/@angular/common/other/package.json'), contents: '{ }'},
{
name: _('/node_modules/@angular/common/testing/package.json'),
contents:
`{"fesm2015": "../fesm2015/testing.js", "fesm5": "../fesm5/testing.js", "typings": "../testing.d.ts"}`
},
{name: _('/node_modules/@angular/common/node_modules/tslib/package.json'), contents: '{ }'},
{
name: _(
'/node_modules/@angular/common/node_modules/tslib/node_modules/other-lib/package.json'),
contents: '{ }'
},
{
name: _('/node_modules/@angular/no-typings/package.json'),
contents: `{ "fesm2015": "./fesm2015/index.js" }`
},
{name: _('/node_modules/@angular/no-typings/fesm2015/index.js'), contents: 'DUMMY CONTENT'},
{
name: _('/node_modules/@angular/no-typings/fesm2015/index.d.ts'),
contents: 'DUMMY CONTENT'
},
{
name: _('/node_modules/@angular/other/not-package.json'),
contents: '{ "fesm2015": "./fesm2015/other.js" }'
},
{
name: _('/node_modules/@angular/other/package.jsonot'),
contents: '{ "fesm5": "./fesm5/other.js" }'
},
{
name: _('/node_modules/@angular/other2/node_modules_not/lib1/package.json'),
contents: '{ }'
},
{
name: _('/node_modules/@angular/other2/not_node_modules/lib2/package.json'),
contents: '{ }'
},
]);
});
describe('markAsProcessed', () => {
it('should write properties in the package.json containing the version placeholder', () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
// TODO: Determine the correct/best type for the `pkg` type.
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__).toBeUndefined();
expect(pkg.scripts).toBeUndefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBeUndefined();
expect(pkg.scripts!.prepublishOnly).toBeDefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['esm2015', 'esm5']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts!.prepublishOnly).toBeDefined();
});
it('should update the packageJson object in-place', () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__).toBeUndefined();
expect(pkg.scripts).toBeUndefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5']);
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBeUndefined();
expect(pkg.scripts!.prepublishOnly).toBeDefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['esm2015', 'esm5']);
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts!.prepublishOnly).toBeDefined();
});
it('should one perform one write operation for all updated properties', () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const writeFileSpy = spyOn(fs, 'writeFile');
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
markAsProcessed(
pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5', 'esm2015', 'esm5']);
expect(writeFileSpy).toHaveBeenCalledTimes(1);
});
it(`should keep backup of existing 'prepublishOnly' script`, () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const prepublishOnly = 'existing script';
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
pkg.scripts = {prepublishOnly};
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBe(prepublishOnly);
});
it(`should not keep backup of overwritten 'prepublishOnly' script`, () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
// Running again, now that there is `prepublishOnly` script (created by `ngcc`), it should
// still not back it up as `prepublishOnly__ivy_ngcc_bak`.
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
});
});
describe('hasBeenProcessed', () => {
it('should return true if the marker exists for the given format property', () => {
expect(hasBeenProcessed(
{name: 'test', __processed_by_ivy_ngcc__: {'fesm2015': '0.0.0-PLACEHOLDER'}},
'fesm2015'))
.toBe(true);
});
it('should return false if the marker does not exist for the given format property', () => {
expect(hasBeenProcessed(
{name: 'test', __processed_by_ivy_ngcc__: {'fesm2015': '0.0.0-PLACEHOLDER'}},
'module'))
.toBe(false);
});
it('should return false if no markers exist', () => {
expect(hasBeenProcessed({name: 'test'}, 'module')).toBe(false);
});
});
describe('needsCleaning()', () => {
it('should return true if any format has been compiled with a different version', () => {
expect(needsCleaning({
name: 'test',
__processed_by_ivy_ngcc__: {'fesm2015': '8.0.0', 'esm5': NGCC_VERSION}
})).toBe(true);
});
it('should return false if all formats have been compiled with the current version', () => {
expect(needsCleaning({name: 'test', __processed_by_ivy_ngcc__: {'fesm2015': NGCC_VERSION}}))
.toBe(false);
});
it('should return false if no formats have been compiled', () => {
expect(needsCleaning({name: 'test', __processed_by_ivy_ngcc__: {}})).toBe(false);
expect(needsCleaning({name: 'test'})).toBe(false);
});
});
describe('cleanPackageJson()', () => {
it('should not touch the object if there is no build marker', () => {
const packageJson: EntryPointPackageJson = {name: 'test-package'};
const result = cleanPackageJson(packageJson);
expect(result).toBe(false);
expect(packageJson).toEqual({name: 'test-package'});
});
it('should remove the processed marker', () => {
const packageJson: EntryPointPackageJson = {
name: 'test-package',
__processed_by_ivy_ngcc__: {'fesm2015': '8.0.0'}
};
const result = cleanPackageJson(packageJson);
expect(result).toBe(true);
expect(packageJson).toEqual({name: 'test-package'});
});
it('should remove new entry-point format properties', () => {
const packageJson: EntryPointPackageJson = {
name: 'test-package',
__processed_by_ivy_ngcc__: {'fesm2015': '8.0.0'},
fesm2015: 'index.js',
fesm2015_ivy_ngcc: '__ivy_ngcc__/index.js'
};
const result = cleanPackageJson(packageJson);
expect(result).toBe(true);
expect(packageJson).toEqual({name: 'test-package', fesm2015: 'index.js'});
});
it('should remove the prepublish script if there was a processed marker', () => {
const packageJson: EntryPointPackageJson = {
name: 'test-package',
__processed_by_ivy_ngcc__: {'fesm2015': '8.0.0'},
scripts: {prepublishOnly: 'added by ngcc', test: 'do testing'},
};
const result = cleanPackageJson(packageJson);
expect(result).toBe(true);
expect(packageJson).toEqual({
name: 'test-package',
scripts: {test: 'do testing'},
});
});
it('should revert and remove the backup for the prepublish script if there was a processed marker',
() => {
const packageJson: EntryPointPackageJson = {
name: 'test-package',
__processed_by_ivy_ngcc__: {'fesm2015': '8.0.0'},
scripts: {
prepublishOnly: 'added by ngcc',
prepublishOnly__ivy_ngcc_bak: 'original',
test: 'do testing'
},
};
const result = cleanPackageJson(packageJson);
expect(result).toBe(true);
expect(packageJson).toEqual({
name: 'test-package',
scripts: {prepublishOnly: 'original', test: 'do testing'},
});
});
it('should not touch the scripts if there was no processed marker', () => {
const packageJson: EntryPointPackageJson = {
name: 'test-package',
scripts: {
prepublishOnly: 'added by ngcc',
prepublishOnly__ivy_ngcc_bak: 'original',
test: 'do testing'
},
};
const result = cleanPackageJson(packageJson);
expect(result).toBe(false);
expect(packageJson).toEqual({
name: 'test-package',
scripts: {
prepublishOnly: 'added by ngcc',
prepublishOnly__ivy_ngcc_bak: 'original',
test: 'do testing'
}
});
});
});
});
}); | the_stack |
import Editor, { EditorChangeEvent } from '../Editor';
import TextDocument from '../doc/TextDocument';
import { EditorRange } from '../doc/EditorRange';
import { combineLines, Combined, getChangedRanges, HTMLLineElement, renderLine, setLineNodesRanges } from '../rendering/rendering';
import isEqual from '../util/isEqual';
import { h, patch, VNode } from '../rendering/vdom';
import { setSelection } from '../rendering/selection';
export interface VirtualRenderWhat {
old?: TextDocument;
doc?: TextDocument;
selection: EditorRange | null;
}
type HeightInfo = [marginTop: number, height: number, marginBottom: number];
export function virtualRendering(editor: Editor) {
let start = 0;
let end = 0;
let heightMap = [] as HeightInfo[];
let children: HTMLLineElement[] = [];
let viewport = getScrollParent(editor.root);
let offsetTop: number;
let viewportHeight = 0;
let averageHeight = 40;
let items: Combined;
let itemsDoc: TextDocument;
let lastSelection: EditorRange | null = null;
let lineSelection: EditorRange | null = null; // not doc index but Combined index
let toRender: number[];
let hasChanged = false;
let updateQueued = true;
viewport.addEventListener('scroll', onScroll, { passive: true });
editor.on('change', onChange);
const offResize = onResize(viewport, (width, height, changed) => {
viewportHeight = height;
if (changed & WIDTH) heightMap = []; // content may be different heights, recalculate everything
update();
});
function render(what?: VirtualRenderWhat) {
if (!what || !items) {
const { doc } = editor.modules.decorations as { doc: TextDocument } || editor;
items = combineLines(editor, doc.lines).combined;
itemsDoc = doc;
hasChanged = true;
lastSelection = doc.selection;
update();
} else {
const { doc, old } = what;
const selection = what.selection || null;
const newSelection = selection && selectedLineIndexes(selection, items).sort((a, b) => a - b);
if (!isEqual(newSelection, lineSelection)) {
hasChanged = hasChanged || !withinRender(newSelection, true);
lineSelection = newSelection;
}
if (old && doc) {
const newItems = combineLines(editor, doc.lines).combined;
const [ oldRange, newRange ] = getChangedRanges(items, newItems);
if (oldRange[0] + oldRange[1] + newRange[0] + newRange[1] > 0) {
hasChanged = true;
const oldLength = oldRange[1] - oldRange[0], newLength = newRange[1] - newRange[0];
if (oldLength < newLength) {
// lines were added, add empty spots into the heightMap
const empty = new Array(newLength - oldLength).fill(undefined)
heightMap.splice(oldRange[1], 0, ...empty);
} else if (oldLength > newLength) {
heightMap.splice(oldRange[0], oldLength - newLength);
}
}
items = newItems;
itemsDoc = doc;
} else if (doc) {
items = combineLines(editor, doc.lines).combined;
itemsDoc = doc;
hasChanged = true;
}
lastSelection = selection;
if (hasChanged) update();
}
}
// Determine start and end of visible range
function update() {
updateQueued = false;
if (!items) return;
const { scrollTop } = viewport;
offsetTop = getOffsetTop();
const oldStart = start;
const previousHeights = heightMap.slice();
let didUpdate = false;
let count = 0; // failsafe
while (shouldUpdate() && count++ < 20) {
didUpdate = true;
hasChanged = false;
renderToDom();
updateHeights();
}
if (count >= 20) console.error('Updated virtual max times');
setSelection(editor, lastSelection);
if (!didUpdate) return;
// prevent jumping if we scrolled up into unknown territory
if (start < oldStart) {
let expectedHeight = 0;
let actualHeight = 0;
let offset = toRender.indexOf(start);
for (let i = start; i < oldStart; i++) {
const childIndex = i - start + offset;
if (children[childIndex]) {
expectedHeight += getHeightFor(i, previousHeights);
actualHeight += getHeightFor(i);
}
}
const d = actualHeight - expectedHeight;
viewport.scrollTo(0, scrollTop + d);
}
}
function shouldUpdate() {
const { scrollTop } = viewport;
const renderSet = new Set([ 0, items.length - 1, ...(lineSelection || []) ]);
let i = 0;
let y = offsetTop;
let newStart = 0;
let newEnd = 0;
while (i < items.length) {
const rowHeight = getHeightFor(i);
if (y + rowHeight > scrollTop) {
newStart = i;
break;
}
y += rowHeight;
i += 1;
}
while (i < items.length) {
renderSet.add(i);
y += getHeightFor(i);
i += 1;
if (y > scrollTop + viewportHeight) break;
}
// Include one extra item at the bottom to make a smoother visual update (should be i - 1)
newEnd = Math.min(i, items.length - 1);
const newRender = Array.from(renderSet).sort((a, b) => a - b);
if (!isEqual(newRender, toRender)) {
start = newStart;
end = newEnd;
toRender = newRender;
return true;
}
return hasChanged;
}
function renderToDom() {
const nodes: VNode[] = [];
// Always render the first line, the last line, and the lines with the start/end selection so that deletion and
// selection commands will work (e.g. selecting from one line to another no in-screen and let Select All work).
const renderSet = new Set(toRender);
let spacerKey: string = '';
let spacerMarginTop = 0;
let spacerMarginBottom = 0;
let total = 0;
for (let i = 0, space = 0; i < items.length; i++) {
if (renderSet.has(i)) {
if (space) {
spacerMarginBottom = getMarginBetween(i, -1);
space -= spacerMarginTop;
const spacer = h('div', { class: '-spacer-', ['data-key']: spacerKey, style: `height:${space}px;margin-top:${spacerMarginTop}px;margin-bottom:${spacerMarginBottom}px;`, key: spacerKey });
spacerKey = '';
nodes.push(spacer);
}
space = 0;
const node = renderLine(editor, items[i]);
nodes.push(node);
} else {
if (i === 1) spacerKey = 'spacer-start';
else if (i === items.length - 2) spacerKey = 'spacer-end';
else if (!spacerKey && lineSelection && i > lineSelection[1]) spacerKey = 'spacer-selection-end';
else if (!spacerKey && lineSelection && i > lineSelection[0]) spacerKey = 'spacer-selection-start';
if (!space) spacerMarginTop = getMarginBetween(i, -1);
space += getHeightFor(i);
}
total += getHeightFor(i);
}
editor.dispatchEvent(new Event('rendering'));
patch(editor.root, nodes);
setLineNodesRanges(editor);
editor.dispatchEvent(new Event('render'));
editor.dispatchEvent(new Event('rendered'));
}
function updateHeights() {
children = Array.from(editor.root.children).filter(child => child.className !== '-spacer-') as HTMLLineElement[];
for (let i = 0; i < children.length; i++) {
const index = toRender[i];
heightMap[index] = getHeightInfo(children[i]);
}
if (!children.length) return;
const heights = heightMap.filter(Boolean);
averageHeight = Math.round(
getMarginBetween(0, -1, heights) +
heights.reduce((a, b, i, arr) => a + getHeightFor(i, arr), 0) / heights.length
);
}
function getOffsetTop() {
const { scrollTop } = viewport;
const { root } = editor;
if (viewport === root) return parseInt(getComputedStyle(root).paddingTop);
return root.getBoundingClientRect().top
+ parseInt(getComputedStyle(root).paddingTop)
+ scrollTop
- viewport.getBoundingClientRect().top;
}
function getHeightInfo(node: HTMLLineElement): HeightInfo {
const styles = getComputedStyle(node);
return [ parseInt(styles.marginTop), node.offsetHeight, parseInt(styles.marginBottom) ];
}
function getHeightFor(i: number, array = heightMap) {
if (!array[i]) return averageHeight;
return (i === 0 ? getMarginBetween(i, -1, array) : 0) + array[i][1] + getMarginBetween(i, 1, array);
}
function getMarginBetween(i: number, direction: -1 | 1, array = heightMap) {
return Math.max(array[i] && array[i][2] || 0, array[i + direction] && array[i + direction][0] || 0)
}
function withinRender(range: EditorRange | null, inclusive?: boolean) {
if (!range) return false;
let [ from, to ] = range;
if (inclusive) to++;
return toRender.some(i => i >= from && i < to);
}
function onScroll() {
if (updateQueued) return;
requestAnimationFrame(update);
updateQueued = true;
}
function onChange(event: EditorChangeEvent) {
const { old, doc } = editor.modules.decorations as { old: TextDocument, doc: TextDocument } || event;
const selection = event.doc.selection;
render({ old, doc, selection });
}
return {
render,
init() {
if (editor.modules.decorations) {
editor.modules.decorations.gatherDecorations();
}
render();
},
destroy() {
offResize();
viewport.removeEventListener('scroll', onScroll);
editor.off('change', onChange);
}
}
}
const scrollable = /auto|scroll/;
function getScrollParent(node: HTMLElement) {
while (node && node !== node.ownerDocument.scrollingElement) {
if (scrollable.test(getComputedStyle(node).overflowY)) return node;
node = node.parentNode as HTMLElement;
}
return node;
}
const WIDTH = 1;
const HEIGHT = 2;
const BOTH = 3;
function onResize(node: HTMLElement, callback: (width: number, height: number, changed: number) => void): () => void {
let width = node.offsetWidth;
let height = node.offsetHeight;
callback(width, height, BOTH);
if (typeof (window as any).ResizeObserver !== 'undefined') {
const observer = new (window as any).ResizeObserver(onResize);
observer.observe(node);
return () => observer.disconnect();
} else {
const window = node.ownerDocument.defaultView as Window;
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}
function onResize() {
const { offsetWidth, offsetHeight } = node;
const changed = (width !== offsetWidth ? WIDTH : 0) | (height !== offsetHeight ? HEIGHT : 0);
if (changed) {
width = offsetWidth;
height = offsetHeight;
callback(width, height, changed);
}
}
}
function selectedLineIndexes([ from, to ]: EditorRange, lines: Combined): EditorRange {
let first: number = 0, last: number = 0;
for (let i = 0, pos = 0; i < lines.length; i++) {
const entry = lines[i];
const length = Array.isArray(entry) ? entry.reduce((length, line) => length + line.length, 0) : entry.length;
if (from >= pos && from < pos + length) first = i;
if (to >= pos && to < pos + length) {
last = i;
break;
}
pos += length;
}
return [ first, last ];
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import {
fromKueryExpression,
fromLiteralExpression,
toOpenSearchQuery,
doesKueryExpressionHaveLuceneSyntaxError,
} from './ast';
import { nodeTypes } from '../node_types';
import { fields } from '../../../index_patterns/mocks';
import { IIndexPattern } from '../../../index_patterns';
import { KueryNode } from '../types';
describe('kuery AST API', () => {
let indexPattern: IIndexPattern;
beforeEach(() => {
indexPattern = ({
fields,
} as unknown) as IIndexPattern;
});
describe('fromKueryExpression', () => {
test('should return a match all "is" function for whitespace', () => {
const expected = nodeTypes.function.buildNode('is', '*', '*');
const actual = fromKueryExpression(' ');
expect(actual).toEqual(expected);
});
test('should return an "is" function with a null field for single literals', () => {
const expected = nodeTypes.function.buildNode('is', null, 'foo');
const actual = fromKueryExpression('foo');
expect(actual).toEqual(expected);
});
test('should ignore extraneous whitespace at the beginning and end of the query', () => {
const expected = nodeTypes.function.buildNode('is', null, 'foo');
const actual = fromKueryExpression(' foo ');
expect(actual).toEqual(expected);
});
test('should not split on whitespace', () => {
const expected = nodeTypes.function.buildNode('is', null, 'foo bar');
const actual = fromKueryExpression('foo bar');
expect(actual).toEqual(expected);
});
test('should support "and" as a binary operator', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('is', null, 'foo'),
nodeTypes.function.buildNode('is', null, 'bar'),
]);
const actual = fromKueryExpression('foo and bar');
expect(actual).toEqual(expected);
});
test('should support "or" as a binary operator', () => {
const expected = nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', null, 'foo'),
nodeTypes.function.buildNode('is', null, 'bar'),
]);
const actual = fromKueryExpression('foo or bar');
expect(actual).toEqual(expected);
});
test('should support negation of queries with a "not" prefix', () => {
const expected = nodeTypes.function.buildNode(
'not',
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', null, 'foo'),
nodeTypes.function.buildNode('is', null, 'bar'),
])
);
const actual = fromKueryExpression('not (foo or bar)');
expect(actual).toEqual(expected);
});
test('"and" should have a higher precedence than "or"', () => {
const expected = nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', null, 'foo'),
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('is', null, 'bar'),
nodeTypes.function.buildNode('is', null, 'baz'),
]),
nodeTypes.function.buildNode('is', null, 'qux'),
]),
]);
const actual = fromKueryExpression('foo or bar and baz or qux');
expect(actual).toEqual(expected);
});
test('should support grouping to override default precedence', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', null, 'foo'),
nodeTypes.function.buildNode('is', null, 'bar'),
]),
nodeTypes.function.buildNode('is', null, 'baz'),
]);
const actual = fromKueryExpression('(foo or bar) and baz');
expect(actual).toEqual(expected);
});
test('should support matching against specific fields', () => {
const expected = nodeTypes.function.buildNode('is', 'foo', 'bar');
const actual = fromKueryExpression('foo:bar');
expect(actual).toEqual(expected);
});
test('should also not split on whitespace when matching specific fields', () => {
const expected = nodeTypes.function.buildNode('is', 'foo', 'bar baz');
const actual = fromKueryExpression('foo:bar baz');
expect(actual).toEqual(expected);
});
test('should treat quoted values as phrases', () => {
const expected = nodeTypes.function.buildNode('is', 'foo', 'bar baz', true);
const actual = fromKueryExpression('foo:"bar baz"');
expect(actual).toEqual(expected);
});
test('should support a shorthand for matching multiple values against a single field', () => {
const expected = nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', 'foo', 'bar'),
nodeTypes.function.buildNode('is', 'foo', 'baz'),
]);
const actual = fromKueryExpression('foo:(bar or baz)');
expect(actual).toEqual(expected);
});
test('should support "and" and "not" operators and grouping in the shorthand as well', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', 'foo', 'bar'),
nodeTypes.function.buildNode('is', 'foo', 'baz'),
]),
nodeTypes.function.buildNode('not', nodeTypes.function.buildNode('is', 'foo', 'qux')),
]);
const actual = fromKueryExpression('foo:((bar or baz) and not qux)');
expect(actual).toEqual(expected);
});
test('should support exclusive range operators', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('range', 'bytes', {
gt: 1000,
}),
nodeTypes.function.buildNode('range', 'bytes', {
lt: 8000,
}),
]);
const actual = fromKueryExpression('bytes > 1000 and bytes < 8000');
expect(actual).toEqual(expected);
});
test('should support inclusive range operators', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('range', 'bytes', {
gte: 1000,
}),
nodeTypes.function.buildNode('range', 'bytes', {
lte: 8000,
}),
]);
const actual = fromKueryExpression('bytes >= 1000 and bytes <= 8000');
expect(actual).toEqual(expected);
});
test('should support wildcards in field names', () => {
const expected = nodeTypes.function.buildNode('is', 'machine*', 'osx');
const actual = fromKueryExpression('machine*:osx');
expect(actual).toEqual(expected);
});
test('should support wildcards in values', () => {
const expected = nodeTypes.function.buildNode('is', 'foo', 'ba*');
const actual = fromKueryExpression('foo:ba*');
expect(actual).toEqual(expected);
});
test('should create an exists "is" query when a field is given and "*" is the value', () => {
const expected = nodeTypes.function.buildNode('is', 'foo', '*');
const actual = fromKueryExpression('foo:*');
expect(actual).toEqual(expected);
});
test('should support nested queries indicated by curly braces', () => {
const expected = nodeTypes.function.buildNode(
'nested',
'nestedField',
nodeTypes.function.buildNode('is', 'childOfNested', 'foo')
);
const actual = fromKueryExpression('nestedField:{ childOfNested: foo }');
expect(actual).toEqual(expected);
});
test('should support nested subqueries and subqueries inside nested queries', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('is', 'response', '200'),
nodeTypes.function.buildNode(
'nested',
'nestedField',
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode('is', 'childOfNested', 'foo'),
nodeTypes.function.buildNode('is', 'childOfNested', 'bar'),
])
),
]);
const actual = fromKueryExpression(
'response:200 and nestedField:{ childOfNested:foo or childOfNested:bar }'
);
expect(actual).toEqual(expected);
});
test('should support nested sub-queries inside paren groups', () => {
const expected = nodeTypes.function.buildNode('and', [
nodeTypes.function.buildNode('is', 'response', '200'),
nodeTypes.function.buildNode('or', [
nodeTypes.function.buildNode(
'nested',
'nestedField',
nodeTypes.function.buildNode('is', 'childOfNested', 'foo')
),
nodeTypes.function.buildNode(
'nested',
'nestedField',
nodeTypes.function.buildNode('is', 'childOfNested', 'bar')
),
]),
]);
const actual = fromKueryExpression(
'response:200 and ( nestedField:{ childOfNested:foo } or nestedField:{ childOfNested:bar } )'
);
expect(actual).toEqual(expected);
});
test('should support nested groups inside other nested groups', () => {
const expected = nodeTypes.function.buildNode(
'nested',
'nestedField',
nodeTypes.function.buildNode(
'nested',
'nestedChild',
nodeTypes.function.buildNode('is', 'doublyNestedChild', 'foo')
)
);
const actual = fromKueryExpression('nestedField:{ nestedChild:{ doublyNestedChild:foo } }');
expect(actual).toEqual(expected);
});
});
describe('fromLiteralExpression', () => {
test('should create literal nodes for unquoted values with correct primitive types', () => {
const stringLiteral = nodeTypes.literal.buildNode('foo');
const booleanFalseLiteral = nodeTypes.literal.buildNode(false);
const booleanTrueLiteral = nodeTypes.literal.buildNode(true);
const numberLiteral = nodeTypes.literal.buildNode(42);
expect(fromLiteralExpression('foo')).toEqual(stringLiteral);
expect(fromLiteralExpression('true')).toEqual(booleanTrueLiteral);
expect(fromLiteralExpression('false')).toEqual(booleanFalseLiteral);
expect(fromLiteralExpression('42')).toEqual(numberLiteral);
expect(fromLiteralExpression('.3').value).toEqual(0.3);
expect(fromLiteralExpression('.36').value).toEqual(0.36);
expect(fromLiteralExpression('.00001').value).toEqual(0.00001);
expect(fromLiteralExpression('3').value).toEqual(3);
expect(fromLiteralExpression('-4').value).toEqual(-4);
expect(fromLiteralExpression('0').value).toEqual(0);
expect(fromLiteralExpression('0.0').value).toEqual(0);
expect(fromLiteralExpression('2.0').value).toEqual(2.0);
expect(fromLiteralExpression('0.8').value).toEqual(0.8);
expect(fromLiteralExpression('790.9').value).toEqual(790.9);
expect(fromLiteralExpression('0.0001').value).toEqual(0.0001);
expect(fromLiteralExpression('96565646732345').value).toEqual(96565646732345);
expect(fromLiteralExpression('..4').value).toEqual('..4');
expect(fromLiteralExpression('.3text').value).toEqual('.3text');
expect(fromLiteralExpression('text').value).toEqual('text');
expect(fromLiteralExpression('.').value).toEqual('.');
expect(fromLiteralExpression('-').value).toEqual('-');
expect(fromLiteralExpression('001').value).toEqual('001');
expect(fromLiteralExpression('00.2').value).toEqual('00.2');
expect(fromLiteralExpression('0.0.1').value).toEqual('0.0.1');
expect(fromLiteralExpression('3.').value).toEqual('3.');
expect(fromLiteralExpression('--4').value).toEqual('--4');
expect(fromLiteralExpression('-.4').value).toEqual('-.4');
expect(fromLiteralExpression('-0').value).toEqual('-0');
expect(fromLiteralExpression('00949').value).toEqual('00949');
});
test('should allow escaping of special characters with a backslash', () => {
const expected = nodeTypes.literal.buildNode('\\():<>"*');
// yo dawg
const actual = fromLiteralExpression('\\\\\\(\\)\\:\\<\\>\\"\\*');
expect(actual).toEqual(expected);
});
test('should support double quoted strings that do not need escapes except for quotes', () => {
const expected = nodeTypes.literal.buildNode('\\():<>"*');
const actual = fromLiteralExpression('"\\():<>\\"*"');
expect(actual).toEqual(expected);
});
test('should support escaped backslashes inside quoted strings', () => {
const expected = nodeTypes.literal.buildNode('\\');
const actual = fromLiteralExpression('"\\\\"');
expect(actual).toEqual(expected);
});
test('should detect wildcards and build wildcard AST nodes', () => {
const expected = nodeTypes.wildcard.buildNode('foo*bar');
const actual = fromLiteralExpression('foo*bar');
expect(actual).toEqual(expected);
});
});
describe('toOpenSearchQuery', () => {
test("should return the given node type's OpenSearch query representation", () => {
const node = nodeTypes.function.buildNode('exists', 'response');
const expected = nodeTypes.function.toOpenSearchQuery(node, indexPattern);
const result = toOpenSearchQuery(node, indexPattern);
expect(result).toEqual(expected);
});
test('should return an empty "and" function for undefined nodes and unknown node types', () => {
const expected = nodeTypes.function.toOpenSearchQuery(
nodeTypes.function.buildNode('and', []),
indexPattern
);
expect(toOpenSearchQuery((null as unknown) as KueryNode, undefined)).toEqual(expected);
const noTypeNode = nodeTypes.function.buildNode('exists', 'foo');
// @ts-expect-error
delete noTypeNode.type;
expect(toOpenSearchQuery(noTypeNode)).toEqual(expected);
const unknownTypeNode = nodeTypes.function.buildNode('exists', 'foo');
// @ts-expect-error
unknownTypeNode.type = 'notValid';
expect(toOpenSearchQuery(unknownTypeNode)).toEqual(expected);
});
test("should return the given node type's OpenSearch query representation including a time zone parameter when one is provided", () => {
const config = { dateFormatTZ: 'America/Phoenix' };
const node = nodeTypes.function.buildNode('is', '@timestamp', '"2018-04-03T19:04:17"');
const expected = nodeTypes.function.toOpenSearchQuery(node, indexPattern, config);
const result = toOpenSearchQuery(node, indexPattern, config);
expect(result).toEqual(expected);
});
});
describe('doesKueryExpressionHaveLuceneSyntaxError', () => {
test('should return true for Lucene ranges', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: [1 TO 10]');
expect(result).toEqual(true);
});
test('should return false for DQL ranges', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar < 1');
expect(result).toEqual(false);
});
test('should return true for Lucene exists', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('_exists_: bar');
expect(result).toEqual(true);
});
test('should return false for DQL exists', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar:*');
expect(result).toEqual(false);
});
test('should return true for Lucene wildcards', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: ba?');
expect(result).toEqual(true);
});
test('should return false for DQL wildcards', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: ba*');
expect(result).toEqual(false);
});
test('should return true for Lucene regex', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: /ba.*/');
expect(result).toEqual(true);
});
test('should return true for Lucene fuzziness', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: ba~');
expect(result).toEqual(true);
});
test('should return true for Lucene proximity', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: "ba"~2');
expect(result).toEqual(true);
});
test('should return true for Lucene boosting', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('bar: ba^2');
expect(result).toEqual(true);
});
test('should return true for Lucene + operator', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('+foo: bar');
expect(result).toEqual(true);
});
test('should return true for Lucene - operators', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('-foo: bar');
expect(result).toEqual(true);
});
test('should return true for Lucene && operators', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('foo: bar && baz: qux');
expect(result).toEqual(true);
});
test('should return true for Lucene || operators', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('foo: bar || baz: qux');
expect(result).toEqual(true);
});
test('should return true for mixed DQL/Lucene queries', () => {
const result = doesKueryExpressionHaveLuceneSyntaxError('foo: bar and (baz: qux || bag)');
expect(result).toEqual(true);
});
});
}); | the_stack |
import { Exception } from '@poppinss/utils'
import { string } from '@poppinss/utils/build/helpers'
import { EmitterContract } from '@ioc:Adonis/Core/Event'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import {
UserProviderContract,
SessionGuardConfig,
SessionGuardContract,
ProviderUserContract,
SessionLoginEventData,
SessionAuthenticateEventData,
} from '@ioc:Adonis/Addons/Auth'
import { BaseGuard } from '../Base'
import { AuthenticationException } from '../../Exceptions/AuthenticationException'
/**
* Session guard enables user login using sessions. Also it allows for
* setting remember me tokens for life long login
*/
export class SessionGuard extends BaseGuard<any> implements SessionGuardContract<any, any> {
constructor(
name: string,
config: SessionGuardConfig<any>,
private emitter: EmitterContract,
provider: UserProviderContract<any>,
private ctx: HttpContextContract
) {
super(name, config, provider)
}
/**
* Number of years for the remember me token expiry
*/
private rememberMeTokenExpiry = '5y'
/**
* The name of the session key name
*/
public get sessionKeyName() {
return `auth_${this.name}`
}
/**
* The name of the session key name
*/
public get rememberMeKeyName() {
return `remember_${this.name}`
}
/**
* Returns the session object from the context.
*/
private getSession() {
if (!this.ctx.session) {
throw new Exception('"@adonisjs/session" is required to use the "session" auth driver')
}
return this.ctx.session
}
/**
* Set the user id inside the session. Also forces the session module
* to re-generate the session id
*/
private setSession(userId: string | number) {
this.getSession().put(this.sessionKeyName, userId)
this.getSession().regenerate()
}
/**
* Generate remember me token
*/
private generateRememberMeToken(): string {
return string.generateRandom(20)
}
/**
* Sets the remember me cookie with the remember me token
*/
private setRememberMeCookie(userId: string | number, token: string) {
const value = {
id: userId,
token: token,
}
this.ctx.response.encryptedCookie(this.rememberMeKeyName, value, {
maxAge: this.rememberMeTokenExpiry,
httpOnly: true,
})
}
/**
* Clears the remember me cookie
*/
private clearRememberMeCookie() {
this.ctx.response.clearCookie(this.rememberMeKeyName)
}
/**
* Clears user session and remember me cookie
*/
private clearUserFromStorage() {
this.getSession().forget(this.sessionKeyName)
this.clearRememberMeCookie()
}
/**
* Returns data packet for the login event. Arguments are
*
* - The mapping identifier
* - Logged in user
* - HTTP context
* - Remember me token (optional)
*/
private getLoginEventData(user: any, token: string | null): SessionLoginEventData<any> {
return {
name: this.name,
ctx: this.ctx,
user,
token,
}
}
/**
* Returns data packet for the authenticate event. Arguments are
*
* - The mapping identifier
* - Logged in user
* - HTTP context
* - A boolean to tell if logged in viaRemember or not
*/
private getAuthenticateEventData(
user: any,
viaRemember: boolean
): SessionAuthenticateEventData<any> {
return {
name: this.name,
ctx: this.ctx,
user,
viaRemember,
}
}
/**
* Returns the user id for the current HTTP request
*/
private getRequestSessionId() {
return this.getSession().get(this.sessionKeyName)
}
/**
* Verifies the remember me token
*/
private verifyRememberMeToken(
rememberMeToken: any
): asserts rememberMeToken is { id: string; token: string } {
if (!rememberMeToken || !rememberMeToken.id || !rememberMeToken.token) {
throw AuthenticationException.invalidSession(this.name)
}
}
/**
* Returns user from the user session id
*/
private async getUserForSessionId(id: string | number) {
const authenticatable = await this.provider.findById(id)
if (!authenticatable.user) {
throw AuthenticationException.invalidSession(this.name)
}
return authenticatable
}
/**
* Returns user for the remember me token
*/
private async getUserForRememberMeToken(id: string, token: string) {
const authenticatable = await this.provider.findByRememberMeToken(id, token)
if (!authenticatable.user) {
throw AuthenticationException.invalidSession(this.name)
}
return authenticatable
}
/**
* Returns the remember me token of the user that is persisted
* inside the db. If not persisted, we create one and persist
* it
*/
private async getPersistedRememberMeToken(
providerUser: ProviderUserContract<any>
): Promise<string> {
/**
* Create and persist the user remember me token, when an existing one is missing
*/
if (!providerUser.getRememberMeToken()) {
this.ctx.logger.trace('generating fresh remember me token')
providerUser.setRememberMeToken(this.generateRememberMeToken())
await this.provider.updateRememberMeToken(providerUser)
}
return providerUser.getRememberMeToken()!
}
/**
* Verify user credentials and perform login
*/
public async attempt(uid: string, password: string, remember?: boolean): Promise<any> {
const user = await this.verifyCredentials(uid, password)
await this.login(user, remember)
return user
}
/**
* Login user using their id
*/
public async loginViaId(id: string | number, remember?: boolean): Promise<void> {
const providerUser = await this.findById(id)
await this.login(providerUser.user, remember)
return providerUser.user
}
/**
* Login a user
*/
public async login(user: any, remember?: boolean): Promise<void> {
/**
* Since the login method is exposed to the end user, we cannot expect
* them to instantiate and return an instance of authenticatable, so
* we create one manually.
*/
const providerUser = await this.getUserForLogin(user, this.config.provider.identifierKey)
/**
* getUserForLogin raises exception when id is missing, so we can
* safely assume it is defined
*/
const id = providerUser.getId()!
/**
* Set session
*/
this.setSession(id)
/**
* Set remember me token when enabled
*/
if (remember) {
const rememberMeToken = await this.getPersistedRememberMeToken(providerUser)
this.ctx.logger.trace('setting remember me cookie', { name: this.rememberMeKeyName })
this.setRememberMeCookie(id, rememberMeToken)
} else {
/**
* Clear remember me cookie, which may have been set previously.
*/
this.clearRememberMeCookie()
}
/**
* Emit login event. It can be used to track user logins and their devices.
*/
this.emitter.emit(
'adonis:session:login',
this.getLoginEventData(providerUser.user, providerUser.getRememberMeToken())
)
this.markUserAsLoggedIn(providerUser.user)
return providerUser.user
}
/**
* Authenticates the current HTTP request by checking for the user
* session.
*/
public async authenticate(): Promise<any> {
if (this.authenticationAttempted) {
return this.user
}
this.authenticationAttempted = true
const sessionId = this.getRequestSessionId()
/**
* If session id exists, then attempt to login the user using the
* session and return early
*/
if (sessionId) {
const providerUser = await this.getUserForSessionId(sessionId)
this.markUserAsLoggedIn(providerUser.user, true)
this.emitter.emit(
'adonis:session:authenticate',
this.getAuthenticateEventData(providerUser.user, false)
)
return this.user
}
/**
* Otherwise look for remember me token. Raise exception, if both remember
* me token and session id are missing.
*/
const rememberMeToken = this.ctx.request.encryptedCookie(this.rememberMeKeyName)
if (!rememberMeToken) {
throw AuthenticationException.invalidSession(this.name)
}
/**
* Ensure remember me token is valid after reading it from the cookie
*/
this.verifyRememberMeToken(rememberMeToken)
/**
* Attempt to locate the user for remember me token
*/
const providerUser = await this.getUserForRememberMeToken(
rememberMeToken.id,
rememberMeToken.token
)
this.setSession(providerUser.getId()!)
this.setRememberMeCookie(rememberMeToken.id, rememberMeToken.token)
this.markUserAsLoggedIn(providerUser.user, true, true)
this.emitter.emit(
'adonis:session:authenticate',
this.getAuthenticateEventData(providerUser.user, true)
)
return this.user
}
/**
* Same as [[authenticate]] but returns a boolean over raising exceptions
*/
public async check(): Promise<boolean> {
try {
await this.authenticate()
} catch (error) {
/**
* Throw error when it is not an instance of the authentication
*/
if (error instanceof AuthenticationException === false) {
throw error
}
this.ctx.logger.trace(error, 'Authentication failure')
}
return this.isAuthenticated
}
/**
* Logout by clearing session and cookies
*/
public async logout(recycleRememberToken?: boolean) {
/**
* Return early when not attempting to re-generate the remember me token
*/
if (!recycleRememberToken) {
this.clearUserFromStorage()
this.markUserAsLoggedOut()
return
}
/**
* Attempt to authenticate the current request if not already authenticated. This
* will help us get an instance of the current user
*/
if (!this.authenticationAttempted) {
await this.check()
}
/**
* If authentication passed, then re-generate the remember me token
* for the current user.
*/
if (this.user) {
const providerUser = await this.provider.getUserFor(this.user)
this.ctx.logger.trace('re-generating remember me token')
providerUser.setRememberMeToken(this.generateRememberMeToken())
await this.provider.updateRememberMeToken(providerUser)
}
/**
* Logout user
*/
this.clearUserFromStorage()
this.markUserAsLoggedOut()
}
/**
* Serialize toJSON for JSON.stringify
*/
public toJSON() {
return {
isLoggedIn: this.isLoggedIn,
isGuest: this.isGuest,
viaRemember: this.viaRemember,
authenticationAttempted: this.authenticationAttempted,
isAuthenticated: this.isAuthenticated,
user: this.user,
}
}
} | the_stack |
import G6, { GraphData } from '@antv/g6';
import TimeBar from '../../src/timeBar';
const div = document.createElement('div');
div.id = 'timebar-plugin';
document.body.appendChild(div);
// div.style.backgroundColor = '#252728'
const data: GraphData = {
nodes: [
{
id: 'node1',
label: 'node1',
x: 100,
y: 100,
},
{
id: 'node2',
label: 'node2',
x: 150,
y: 300,
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
],
};
for (let i = 0; i < 100; i++) {
const id = `node-${i}`;
data.nodes.push({
id,
label: `node${i}`,
date: i,
value: Math.round(Math.random() * 300),
});
const edgeDate = Math.round(Math.random() * 100);
data.edges.push({
date: edgeDate,
label: `${edgeDate}`,
source: `node-${Math.round(Math.random() * 90)}`,
target: `node-${Math.round(Math.random() * 90)}`,
});
}
describe('timeline filter edges', () => {
it('timeline filter edges', () => {
const timeBarData = [];
for (let i = 1; i < 60; i++) {
timeBarData.push({
date: i,
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 15,
y: 0,
width: 500,
height: 150,
padding: 10,
type: 'trend',
filterEdge: true,
trend: {
data: timeBarData,
isArea: true,
areaStyle: {
fill: '#08214E',
opacity: 0.3
}
},
tick: {
tickLabelFormatter: (d) => {
const i = d.date;
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
return `2020${month}${day}`;
},
tickLabelStyle: {
fill: '#000'
},
tickLineStyle: {
stroke: '#000'
}
},
backgroundStyle: {
fill: '#115EEB',
opacity: 0.3
},
foregroundStyle: {
fill: '#000',
opacity: 0.25
},
textStyle: {
fill: '#000',
fontWeight: 500
},
controllerCfg: {
// scale: 0.7,
// offsetX: -250,
x: 200,
y: 45,
width: 480,
fill: '#fff',
stroke: '#fff',
preBtnStyle: {
fill: '#155EE1',
stroke: '#155EE1',
opacity: 0.85
},
nextBtnStyle: {
fill: '#155EE1',
stroke: '#155EE1',
opacity: 0.85
},
playBtnStyle: {
fill: '#155EE1',
stroke: '#155EE1',
opacity: 0.85,
fillOpacity: 0.2
},
speedControllerStyle: {
pointer: {
fill: '#155EE1',
lineWidth: 0,
},
scroller: {
fill: '#155EE1',
stroke: '#155EE1'
},
text: {
fill: '#000',
opacity: 0.65
},
},
timeTypeControllerStyle: {
box: {
fillOpacity: 0,
stroke: '#155EE1',
},
check: {
lineWidth: 1,
stroke: '#155EE1',
},
text: {
fill: '#000',
opacity: 0.65
},
},
},
slider: {
handlerStyle: {
fill: '#497CD8',
stroke: '#497CD8',
highLightFill: '#f00'
}
}
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 250,
// renderer: 'svg',
plugins: [timeLine],
// layout: {
// type: 'force'
// },
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
// graph.destroy();
});
});
describe('timeline play with timebar', () => {
it('trend timebar', () => {
const timeBarData = [];
for (let i = 1; i < 60; i++) {
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
timeBarData.push({
date: parseInt(`2020${month}${day}`, 10),
value: Math.round(Math.random() * 300),
});
}
const intervalData = [];
for (let i = 0; i < 50; i++) {
intervalData.push({
date: i,
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 0,
y: 0,
width: 500,
height: 150,
padding: 10,
type: 'trend',
trend: {
data: timeBarData,
// areaStyle: {
// fill: 'pink'
// },
isArea: true,
lineStyle: {
stroke: 'green',
lineWidth: 1,
},
interval: {
data: intervalData.map((d) => d.value),
style: {
// stroke: '#ccc',
fill: '#ccc',
stroke: '#5E6B73',
barWidth: 10,
// lineWidth: 3
},
},
},
slider: {
// height: 50,
// backgroundStyle: {
// fill: 'blue',
// opacity: 0.2
// },
// foregroundStyle: {
// fill: 'yellow'
// },
textStyle: {
fill: 'red',
fontSize: 16,
},
// handlerStyle: {
// style: {
// fill: '#1890ff',
// stroke: '#1890ff'
// }
// }
},
// loop: true
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
// renderer: 'svg',
plugins: [timeLine],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
// graph.on('sliderchange', evt => {
// console.log('范围', evt)
// })
// graph.on('timelinechange', evt => {
// console.log('timeline', evt)
// })
});
it('simple timebar', () => {
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
},
],
};
const timeBarData = [];
for (let i = 1; i < 60; i++) {
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
timeBarData.push({
date: parseInt(`2020${month}${day}`, 10),
value: Math.round(Math.random() * 300),
});
}
const intervalData = [];
for (let i = 0; i < 50; i++) {
intervalData.push({
date: i,
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 0,
y: 0,
width: 500,
height: 150,
padding: 10,
type: 'trend',
trend: {
data: timeBarData,
isArea: true,
// areaStyle: {
// fill: 'pink'
// },
lineStyle: {
stroke: 'green',
lineWidth: 1,
},
interval: {
data: intervalData.map((d) => d.value),
style: {
// stroke: '#ccc',
fill: '#ccc',
},
},
},
slider: {
// height: 50,
// backgroundStyle: {
// fill: 'blue',
// opacity: 0.2
// },
// foregroundStyle: {
// fill: 'yellow'
// },
textStyle: {
fill: 'red',
fontSize: 16,
},
// handlerStyle: {
// style: {
// fill: '#1890ff',
// stroke: '#1890ff'
// }
// }
},
// loop: true
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
// renderer: 'svg',
plugins: [timeLine],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
// graph.on('sliderchange', evt => {
// console.log('范围', evt)
// })
// graph.on('timelinechange', evt => {
// console.log('timeline', evt)
// })
});
it('simple timebar', () => {
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
},
],
};
const timeBarData = [];
for (let i = 1; i < 60; i++) {
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
timeBarData.push({
date: parseInt(`2020${month}${day}`, 10),
value: Math.round(Math.random() * 300),
});
}
const intervalData = [];
for (let i = 0; i < 50; i++) {
intervalData.push({
date: i,
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 0,
y: 0,
width: 500,
height: 150,
padding: 10,
type: 'simple',
trend: {
data: timeBarData,
isArea: true,
// areaStyle: {
// fill: 'pink'
// },
lineStyle: {
stroke: 'green',
lineWidth: 1,
},
interval: {
data: intervalData.map((d) => d.value),
style: {
// stroke: '#ccc',
fill: '#ccc',
},
},
},
slider: {
// height: 50,
// backgroundStyle: {
// fill: 'blue',
// opacity: 0.2
// },
// foregroundStyle: {
// fill: 'yellow'
// },
textStyle: {
fill: 'red',
fontSize: 16,
},
// handlerStyle: {
// style: {
// fill: '#1890ff',
// stroke: '#1890ff'
// }
// }
},
// loop: true
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
// renderer: 'svg',
plugins: [timeLine],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
// graph.on('sliderchange', evt => {
// console.log('范围', evt)
// })
// graph.on('timelinechange', evt => {
// console.log('timeline', evt)
// })
});
it('slice timebar', () => {
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
},
],
};
const timeBarData = [];
for (let i = 1; i < 60; i++) {
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
timeBarData.push({
date: parseInt(`2020${month}${day}`, 10),
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 0,
y: 0,
width: 500,
height: 150,
padding: 10,
type: 'slice',
slice: {
data: timeBarData,
width: 500,
height: 42,
padding: 2,
},
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
// renderer: 'svg',
plugins: [timeLine],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
// graph.on('sliderchange', evt => {
// console.log('范围', evt)
// })
// graph.on('timelinechange', evt => {
// console.log('timeline', evt)
// })
});
});
xdescribe('timebar filter edges', () => {
it('trend timebar', () => {
const timeBarData = [];
for (let i = 1; i < 60; i++) {
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
timeBarData.push({
date: i, //parseInt(`2020${month}${day}`, 10),
value: Math.round(Math.random() * 300),
});
}
const intervalData = [];
for (let i = 0; i < 50; i++) {
intervalData.push({
date: i,
value: Math.round(Math.random() * 300),
});
}
const timeLine = new TimeBar({
x: 20,
y: 0,
width: 450,
height: 150,
padding: 10,
type: 'simple',
tick: {
tickLabelFormatter: (d) => {
const i = d.date;
const month = i < 30 ? '01' : '02';
const day = i % 30 < 10 ? `0${i % 30}` : `${i % 30}`;
return `2020${month}${day}`;
},
},
trend: {
data: timeBarData,
// isArea: true,
// // areaStyle: {
// // fill: 'pink'
// // },
// lineStyle: {
// stroke: 'green',
// lineWidth: 1,
// },
// interval: {
// data: intervalData.map((d) => d.value),
// style: {
// // stroke: '#ccc',
// fill: '#ccc',
// },
// },
},
slider: {
// height: 50,
// backgroundStyle: {
// fill: 'blue',
// opacity: 0.2
// },
// foregroundStyle: {
// fill: 'yellow'
// },
textStyle: {
fill: 'red',
fontSize: 16,
},
// handlerStyle: {
// style: {
// fill: '#1890ff',
// stroke: '#1890ff'
// }
// }
},
// loop: true
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 300,
// renderer: 'svg',
plugins: [timeLine],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
console.log('data', data);
graph.data(data);
graph.render();
// graph.on('sliderchange', evt => {
// console.log('范围', evt)
// })
// graph.on('timelinechange', evt => {
// console.log('timeline', evt)
// })
});
}); | the_stack |
import { IClone } from "./IClone";
import { MathUtil } from "./MathUtil";
import { Matrix3x3 } from "./Matrix3x3";
import { Vector3 } from "./Vector3";
/**
* Represents a four dimensional mathematical quaternion.
*/
export class Quaternion implements IClone {
/** @internal */
static readonly _tempVector3 = new Vector3();
/** @internal */
static readonly _tempQuat1 = new Quaternion();
/**
* Determines the sum of two quaternions.
* @param left - The first quaternion to add
* @param right - The second quaternion to add
* @param out - The sum of two quaternions
*/
static add(left: Quaternion, right: Quaternion, out: Quaternion): void {
out.x = left.x + right.x;
out.y = left.y + right.y;
out.z = left.z + right.z;
out.w = left.w + right.w;
}
/**
* Determines the product of two quaternions.
* @param left - The first quaternion to multiply
* @param right - The second quaternion to multiply
* @param out - The product of two quaternions
*/
static multiply(left: Quaternion, right: Quaternion, out: Quaternion): void {
const ax = left.x,
ay = left.y,
az = left.z,
aw = left.w;
const bx = right.x,
by = right.y,
bz = right.z,
bw = right.w;
out.x = ax * bw + aw * bx + ay * bz - az * by;
out.y = ay * bw + aw * by + az * bx - ax * bz;
out.z = az * bw + aw * bz + ax * by - ay * bx;
out.w = aw * bw - ax * bx - ay * by - az * bz;
}
/**
* Calculate quaternion that contains conjugated version of the specified quaternion.
* @param a - The specified quaternion
* @param out - The conjugate version of the specified quaternion
*/
static conjugate(a: Quaternion, out: Quaternion): void {
out.x = -a.x;
out.y = -a.y;
out.z = -a.z;
out.w = a.w;
}
/**
* Determines the dot product of two quaternions.
* @param left - The first quaternion to dot
* @param right - The second quaternion to dot
* @returns The dot product of two quaternions
*/
static dot(left: Quaternion, right: Quaternion): number {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
}
/**
* Determines whether the specified quaternions are equals.
* @param left - The first quaternion to compare
* @param right - The second quaternion to compare
* @returns True if the specified quaternions are equals, false otherwise
*/
static equals(left: Quaternion, right: Quaternion): boolean {
return (
MathUtil.equals(left.x, right.x) &&
MathUtil.equals(left.y, right.y) &&
MathUtil.equals(left.z, right.z) &&
MathUtil.equals(left.w, right.w)
);
}
/**
* Calculate a quaternion rotates around an arbitrary axis.
* @param axis - The axis
* @param rad - The rotation angle in radians
* @param out - The quaternion after rotate
*/
static rotationAxisAngle(axis: Vector3, rad: number, out: Quaternion): void {
const normalAxis = Quaternion._tempVector3;
Vector3.normalize(axis, normalAxis);
rad *= 0.5;
const s = Math.sin(rad);
out.x = normalAxis.x * s;
out.y = normalAxis.y * s;
out.z = normalAxis.z * s;
out.w = Math.cos(rad);
}
/**
* Calculate a quaternion rotates around x, y, z axis (pitch/yaw/roll).
* @param x - The radian of rotation around X (pitch)
* @param y - The radian of rotation around Y (yaw)
* @param z - The radian of rotation around Z (roll)
* @param out - The calculated quaternion
*/
static rotationEuler(x: number, y: number, z: number, out: Quaternion): void {
Quaternion.rotationYawPitchRoll(y, x, z, out);
}
/**
* Calculate a quaternion from the specified yaw, pitch and roll angles.
* @param yaw - Yaw around the y axis in radians
* @param pitch - Pitch around the x axis in radians
* @param roll - Roll around the z axis in radians
* @param out - The calculated quaternion
*/
static rotationYawPitchRoll(yaw: number, pitch: number, roll: number, out: Quaternion): void {
const halfRoll = roll * 0.5;
const halfPitch = pitch * 0.5;
const halfYaw = yaw * 0.5;
const sinRoll = Math.sin(halfRoll);
const cosRoll = Math.cos(halfRoll);
const sinPitch = Math.sin(halfPitch);
const cosPitch = Math.cos(halfPitch);
const sinYaw = Math.sin(halfYaw);
const cosYaw = Math.cos(halfYaw);
const cosYawPitch = cosYaw * cosPitch;
const sinYawPitch = sinYaw * sinPitch;
out.x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll;
out.y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll;
out.z = cosYawPitch * sinRoll - sinYawPitch * cosRoll;
out.w = cosYawPitch * cosRoll + sinYawPitch * sinRoll;
}
/**
* Calculate a quaternion from the specified 3x3 matrix.
* @param m - The specified 3x3 matrix
* @param out - The calculated quaternion
*/
static rotationMatrix3x3(m: Matrix3x3, out: Quaternion): void {
const me = m.elements;
const m11 = me[0],
m12 = me[1],
m13 = me[2];
const m21 = me[3],
m22 = me[4],
m23 = me[5];
const m31 = me[6],
m32 = me[7],
m33 = me[8];
const scale = m11 + m22 + m33;
let sqrt, half;
if (scale > 0) {
sqrt = Math.sqrt(scale + 1.0);
out.w = sqrt * 0.5;
sqrt = 0.5 / sqrt;
out.x = (m23 - m32) * sqrt;
out.y = (m31 - m13) * sqrt;
out.z = (m12 - m21) * sqrt;
} else if (m11 >= m22 && m11 >= m33) {
sqrt = Math.sqrt(1.0 + m11 - m22 - m33);
half = 0.5 / sqrt;
out.x = 0.5 * sqrt;
out.y = (m12 + m21) * half;
out.z = (m13 + m31) * half;
out.w = (m23 - m32) * half;
} else if (m22 > m33) {
sqrt = Math.sqrt(1.0 + m22 - m11 - m33);
half = 0.5 / sqrt;
out.x = (m21 + m12) * half;
out.y = 0.5 * sqrt;
out.z = (m32 + m23) * half;
out.w = (m31 - m13) * half;
} else {
sqrt = Math.sqrt(1.0 + m33 - m11 - m22);
half = 0.5 / sqrt;
out.x = (m13 + m31) * half;
out.y = (m23 + m32) * half;
out.z = 0.5 * sqrt;
out.w = (m12 - m21) * half;
}
}
/**
* Calculate the inverse of the specified quaternion.
* @param a - The quaternion whose inverse is to be calculated
* @param out - The inverse of the specified quaternion
*/
static invert(a: Quaternion, out: Quaternion): void {
const { x, y, z, w } = a;
const dot = x * x + y * y + z * z + w * w;
if (dot > MathUtil.zeroTolerance) {
const invDot = 1.0 / dot;
out.x = -x * invDot;
out.y = -y * invDot;
out.z = -z * invDot;
out.w = w * invDot;
}
}
/**
* Performs a linear blend between two quaternions.
* @param start - The first quaternion
* @param end - The second quaternion
* @param t - The blend amount where 0 returns start and 1 end
* @param out - The result of linear blending between two quaternions
*/
static lerp(start: Quaternion, end: Quaternion, t: number, out: Quaternion): void {
const inv = 1.0 - t;
if (Quaternion.dot(start, end) >= 0) {
out.x = start.x * inv + end.x * t;
out.y = start.y * inv + end.y * t;
out.z = start.z * inv + end.z * t;
out.w = start.w * inv + end.w * t;
} else {
out.x = start.x * inv - end.x * t;
out.y = start.y * inv - end.y * t;
out.z = start.z * inv - end.z * t;
out.w = start.w * inv - end.w * t;
}
out.normalize();
}
/**
* Performs a spherical linear blend between two quaternions.
* @param start - The first quaternion
* @param end - The second quaternion
* @param t - The blend amount where 0 returns start and 1 end
* @param out - The result of spherical linear blending between two quaternions
*/
static slerp(start: Quaternion, end: Quaternion, t: number, out: Quaternion): void {
const ax = start.x;
const ay = start.y;
const az = start.z;
const aw = start.w;
let bx = end.x;
let by = end.y;
let bz = end.z;
let bw = end.w;
let scale0, scale1;
// calc cosine
let cosom = ax * bx + ay * by + az * bz + aw * bw;
// adjust signs (if necessary)
if (cosom < 0.0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
// calculate coefficients
if (1.0 - cosom > MathUtil.zeroTolerance) {
// standard case (slerp)
const omega = Math.acos(cosom);
const sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - t;
scale1 = t;
}
// calculate final values
out.x = scale0 * ax + scale1 * bx;
out.y = scale0 * ay + scale1 * by;
out.z = scale0 * az + scale1 * bz;
out.w = scale0 * aw + scale1 * bw;
}
/**
* Scales the specified quaternion magnitude to unit length.
* @param a - The specified quaternion
* @param out - The normalized quaternion
*/
static normalize(a: Quaternion, out: Quaternion): void {
const { x, y, z, w } = a;
let len: number = Math.sqrt(x * x + y * y + z * z + w * w);
if (len > MathUtil.zeroTolerance) {
len = 1 / len;
out.x = x * len;
out.y = y * len;
out.z = z * len;
out.w = w * len;
}
}
/**
* Calculate a quaternion rotate around X axis.
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotationX(rad: number, out: Quaternion): void {
rad *= 0.5;
const s = Math.sin(rad);
const c = Math.cos(rad);
out.x = s;
out.y = 0;
out.z = 0;
out.w = c;
}
/**
* Calculate a quaternion rotate around Y axis.
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotationY(rad: number, out: Quaternion): void {
rad *= 0.5;
const s = Math.sin(rad);
const c = Math.cos(rad);
out.x = 0;
out.y = s;
out.z = 0;
out.w = c;
}
/**
* Calculate a quaternion rotate around Z axis.
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotationZ(rad: number, out: Quaternion): void {
rad *= 0.5;
const s = Math.sin(rad);
const c = Math.cos(rad);
out.x = 0;
out.y = 0;
out.z = s;
out.w = c;
}
/**
* Calculate a quaternion that the specified quaternion rotate around X axis.
* @param quaternion - The specified quaternion
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotateX(quaternion: Quaternion, rad: number, out: Quaternion): void {
const { x, y, z, w } = quaternion;
rad *= 0.5;
const bx = Math.sin(rad);
const bw = Math.cos(rad);
out.x = x * bw + w * bx;
out.y = y * bw + z * bx;
out.z = z * bw - y * bx;
out.w = w * bw - x * bx;
}
/**
* Calculate a quaternion that the specified quaternion rotate around Y axis.
* @param quaternion - The specified quaternion
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotateY(quaternion: Quaternion, rad: number, out: Quaternion): void {
const { x, y, z, w } = quaternion;
rad *= 0.5;
const by = Math.sin(rad);
const bw = Math.cos(rad);
out.x = x * bw - z * by;
out.y = y * bw + w * by;
out.z = z * bw + x * by;
out.w = w * bw - y * by;
}
/**
* Calculate a quaternion that the specified quaternion rotate around Z axis.
* @param quaternion - The specified quaternion
* @param rad - The rotation angle in radians
* @param out - The calculated quaternion
*/
static rotateZ(quaternion: Quaternion, rad: number, out: Quaternion): void {
const { x, y, z, w } = quaternion;
rad *= 0.5;
const bz = Math.sin(rad);
const bw = Math.cos(rad);
out.x = x * bw + y * bz;
out.y = y * bw - x * bz;
out.z = z * bw + w * bz;
out.w = w * bw - z * bz;
}
/**
* Scale a quaternion by a given number.
* @param a - The quaternion
* @param s - The given number
* @param out - The scaled quaternion
*/
static scale(a: Quaternion, s: number, out: Quaternion): void {
out.x = a.x * s;
out.y = a.y * s;
out.z = a.z * s;
out.w = a.w * s;
}
/** The x component of the quaternion. */
x: number;
/** The y component of the quaternion. */
y: number;
/** The z component of the quaternion. */
z: number;
/** The w component of the quaternion. */
w: number;
/**
* Constructor of Quaternion.
* @param x - The x component of the quaternion, default 0
* @param y - The y component of the quaternion, default 0
* @param z - The z component of the quaternion, default 0
* @param w - The w component of the quaternion, default 1
*/
constructor(x: number = 0, y: number = 0, z: number = 0, w: number = 1) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Set the value of this quaternion, and return this quaternion.
* @param x - The x component of the quaternion
* @param y - The y component of the quaternion
* @param z - The z component of the quaternion
* @param w - The w component of the quaternion
* @returns This quaternion
*/
setValue(x: number, y: number, z: number, w: number): Quaternion {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
}
/**
* Set the value of this quaternion by an array.
* @param array - The array
* @param offset - The start offset of the array
* @returns This quaternion
*/
setValueByArray(array: ArrayLike<number>, offset: number = 0): Quaternion {
this.x = array[offset];
this.y = array[offset + 1];
this.z = array[offset + 2];
this.w = array[offset + 3];
return this;
}
/**
* Transforms this quaternion into its conjugated version.
* @returns This quaternion
*/
conjugate(): Quaternion {
this.x *= -1;
this.y *= -1;
this.z *= -1;
return this;
}
/**
* Get the rotation axis and rotation angle of the quaternion (unit: radians).
* @param out - The axis as an output parameter
* @returns The rotation angle (unit: radians)
*/
getAxisAngle(out: Vector3): number {
const { x, y, z } = this;
const length = x * x + y * y + z * z;
if (length < MathUtil.zeroTolerance) {
out.x = 1;
out.y = 0;
out.z = 0;
return 0;
} else {
const inv = 1.0 / length;
out.x = this.x * inv;
out.y = this.y * inv;
out.z = this.z * inv;
return Math.acos(this.w) * 2.0;
}
}
/**
* Identity this quaternion.
* @returns This quaternion after identity
*/
identity(): Quaternion {
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 1;
return this;
}
/**
* Calculate the length of this quaternion.
* @returns The length of this quaternion
*/
length(): number {
const { x, y, z, w } = this;
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* Calculates the squared length of this quaternion.
* @returns The squared length of this quaternion
*/
lengthSquared(): number {
const { x, y, z, w } = this;
return x * x + y * y + z * z + w * w;
}
/**
* Converts this quaternion into a unit quaternion.
* @returns This quaternion
*/
normalize(): Quaternion {
Quaternion.normalize(this, this);
return this;
}
/**
* Get the euler of this quaternion.
* @param out - The euler (in radians) as an output parameter
* @returns Euler x->pitch y->yaw z->roll
*/
toEuler(out: Vector3): Vector3 {
this.toYawPitchRoll(out);
const t = out.x;
out.x = out.y;
out.y = t;
return out;
}
/**
* Get the euler of this quaternion.
* @param out - The euler (in radians) as an output parameter
* @returns Euler x->yaw y->pitch z->roll
*/
toYawPitchRoll(out: Vector3): Vector3 {
const { x, y, z, w } = this;
const xx = x * x;
const yy = y * y;
const zz = z * z;
const xy = x * y;
const zw = z * w;
const zx = z * x;
const yw = y * w;
const yz = y * z;
const xw = x * w;
out.y = Math.asin(2.0 * (xw - yz));
if (Math.cos(out.y) > MathUtil.zeroTolerance) {
out.z = Math.atan2(2.0 * (xy + zw), 1.0 - 2.0 * (zz + xx));
out.x = Math.atan2(2.0 * (zx + yw), 1.0 - 2.0 * (yy + xx));
} else {
out.z = Math.atan2(-2.0 * (xy - zw), 1.0 - 2.0 * (yy + zz));
out.x = 0.0;
}
return out;
}
/**
* Clone the value of this quaternion to an array.
* @param out - The array
* @param outOffset - The start offset of the array
*/
toArray(out: number[] | Float32Array | Float64Array, outOffset: number = 0) {
out[outOffset] = this.x;
out[outOffset + 1] = this.y;
out[outOffset + 2] = this.z;
out[outOffset + 3] = this.w;
}
/**
* Creates a clone of this quaternion.
* @returns A clone of this quaternion
*/
clone(): Quaternion {
return new Quaternion(this.x, this.y, this.z, this.w);
}
/**
* Clones this quaternion to the specified quaternion.
* @param out - The specified quaternion
* @returns The specified quaternion
*/
cloneTo(out: Quaternion): Quaternion {
out.x = this.x;
out.y = this.y;
out.z = this.z;
out.w = this.w;
return out;
}
/**
* Calculate this quaternion rotate around X axis.
* @param rad - The rotation angle in radians
* @returns This quaternion
*/
rotateX(rad: number): Quaternion {
Quaternion.rotateX(this, rad, this);
return this;
}
/**
* Calculate this quaternion rotate around Y axis.
* @param rad - The rotation angle in radians
* @returns This quaternion
*/
rotateY(rad: number): Quaternion {
Quaternion.rotateY(this, rad, this);
return this;
}
/**
* Calculate this quaternion rotate around Z axis.
* @param rad - The rotation angle in radians
* @returns This quaternion
*/
rotateZ(rad: number): Quaternion {
Quaternion.rotateZ(this, rad, this);
return this;
}
/**
* Calculate this quaternion rotates around an arbitrary axis.
* @param axis - The axis
* @param rad - The rotation angle in radians
* @returns This quaternion
*/
rotationAxisAngle(axis: Vector3, rad: number): Quaternion {
Quaternion.rotationAxisAngle(axis, rad, this);
return this;
}
/**
* Determines the product of this quaternion and the specified quaternion.
* @param quat - The specified quaternion
* @returns The product of the two quaternions
*/
multiply(quat: Quaternion): Quaternion {
Quaternion.multiply(this, quat, this);
return this;
}
/**
* Invert this quaternion.
* @returns This quaternion after invert
*/
invert(): Quaternion {
Quaternion.invert(this, this);
return this;
}
/**
* Determines the dot product of this quaternion and the specified quaternion.
* @param quat - The specified quaternion
* @returns The dot product of two quaternions
*/
dot(quat: Quaternion): number {
return Quaternion.dot(this, quat);
}
/**
* Performs a linear blend between this quaternion and the specified quaternion.
* @param quat - The specified quaternion
* @param t - The blend amount where 0 returns this and 1 quat
* @returns - The result of linear blending between two quaternions
*/
lerp(quat: Quaternion, t: number): Quaternion {
Quaternion.lerp(this, quat, t, this);
return this;
}
/**
* Calculate this quaternion rotation around an arbitrary axis.
* @param axis - The axis
* @param rad - The rotation angle in radians
* @returns This quaternion
*/
rotateAxisAngle(axis: Vector3, rad: number): Quaternion {
Quaternion._tempQuat1.rotationAxisAngle(axis, rad);
this.multiply(Quaternion._tempQuat1);
return this;
}
} | the_stack |
import {
expect
} from 'chai';
import {
VirtualDOM, VirtualElement, VirtualText, h
} from '@phosphor/virtualdom';
describe('@phosphor/virtualdom', () => {
describe('VirtualText', () => {
describe('#constructor()', () => {
it('should create a virtual text node', () => {
let vnode = new VirtualText('foo');
expect(vnode).to.be.an.instanceof(VirtualText);
});
});
describe('#type', () => {
it('should be `text`', () => {
let vnode = new VirtualText('foo');
expect(vnode.type).to.equal('text');
});
});
describe('#content', () => {
it('should be the text content', () => {
let vnode = new VirtualText('foo');
expect(vnode.content).to.equal('foo');
});
});
});
describe('VirtualElement', () => {
describe('#constructor()', () => {
it('should create a virtual element node', () => {
let vnode = new VirtualElement('img', {}, []);
expect(vnode).to.be.an.instanceof(VirtualElement);
});
});
describe('#type', () => {
it('should be `element`', () => {
let vnode = new VirtualElement('img', {}, []);
expect(vnode.type).to.equal('element');
});
});
describe('#tag', () => {
it('should be the element tag name', () => {
let vnode = new VirtualElement('img', {}, []);
expect(vnode.tag).to.equal('img');
});
});
describe('#attrs', () => {
it('should be the element attrs', () => {
let attrs = { className: 'bar' };
let vnode = new VirtualElement('img', attrs, []);
expect(vnode.attrs).to.deep.equal(attrs);
});
});
describe('#children', () => {
it('should be the element children', () => {
let children = [h.a(), h.img()];
let vnode = new VirtualElement('div', {}, children);
expect(vnode.children).to.equal(children);
});
});
});
describe('h()', () => {
it('should create a new virtual element node', () => {
let vnode = h('a');
expect(vnode).to.be.an.instanceof(VirtualElement);
});
it('should accept string literals for children and convert them to text nodes', () => {
let vnode = h('div', {}, ['foo', 'bar']);
expect(vnode.children[0]).to.be.an.instanceof(VirtualText);
expect(vnode.children[1]).to.be.an.instanceof(VirtualText);
expect(vnode.children[0].type).to.equal('text');
expect(vnode.children[1].type).to.equal('text');
expect((vnode.children[0] as VirtualText).content).to.equal('foo');
expect((vnode.children[1] as VirtualText).content).to.equal('bar');
});
it('should accept other virtual DOM nodes for children', () => {
let children = [h('a'), h('img')];
let vnode = h('div', {}, children);
expect(vnode.children[0]).to.equal(children[0]);
expect(vnode.children[1]).to.equal(children[1]);
expect(vnode.children[0].type).to.equal('element');
expect(vnode.children[1].type).to.equal('element');
expect((vnode.children[0] as VirtualElement).tag).to.equal('a');
expect((vnode.children[1] as VirtualElement).tag).to.equal('img');
});
it('should accept a mix of string literals and virtual DOM nodes', () => {
let children = ['foo', h('img')];
let vnode = h('div', {}, children);
expect(vnode.children[1]).to.equal(children[1]);
expect(vnode.children[0].type).to.equal('text');
expect((vnode.children[0] as VirtualText).content).to.equal('foo');
expect(vnode.children[1].type).to.equal('element');
expect((vnode.children[1] as VirtualElement).tag).to.equal('img');
});
it('should ignore `null` child values', () => {
let children = ['foo', null, h('img')];
let vnode = h('div', {}, children);
expect(vnode.children[1]).to.equal(children[2]);
expect(vnode.children[0].type).to.equal('text');
expect((vnode.children[0] as VirtualText).content).to.equal('foo');
expect(vnode.children[1].type).to.equal('element');
expect((vnode.children[1] as VirtualElement).tag).to.equal('img');
});
it('should accept a string as the second argument', () => {
let vnode = h('div', 'foo');
expect(vnode.children[0].type).to.equal('text');
expect((vnode.children[0] as VirtualText).content).to.equal('foo');
});
it('should accept a virtual node as the second argument', () => {
let vnode = h('div', h('a'));
expect(vnode.children[0].type).to.equal('element');
expect((vnode.children[0] as VirtualElement).tag).to.equal('a');
});
it('should accept an array as the second argument', () => {
let children = [h('a'), h('img')];
let vnode = h('div', children);
expect(vnode.children[0]).to.equal(children[0]);
expect(vnode.children[0].type).to.equal('element');
expect((vnode.children[0] as VirtualElement).tag).to.equal('a');
expect(vnode.children[1].type).to.equal('element');
expect((vnode.children[1] as VirtualElement).tag).to.equal('img');
});
it('should accept other nodes as variadic args', () => {
let vnode = h('div', h('a'), h('img'));
expect(vnode.children[0].type).to.equal('element');
expect((vnode.children[0] as VirtualElement).tag).to.equal('a');
expect(vnode.children[1].type).to.equal('element');
expect((vnode.children[1] as VirtualElement).tag).to.equal('img');
});
it('should set the attrs directly', () => {
let attrs = { style: { color: 'red' }, dataset: { a: '1' } };
let vnode = h('img', attrs);
expect(vnode.attrs).to.deep.equal(attrs);
});
});
describe('h', () => {
it('should create the appropriate element tag', () => {
expect(h.a().tag).to.equal('a');
expect(h.abbr().tag).to.equal('abbr');
expect(h.address().tag).to.equal('address');
expect(h.area().tag).to.equal('area');
expect(h.article().tag).to.equal('article');
expect(h.aside().tag).to.equal('aside');
expect(h.audio().tag).to.equal('audio');
expect(h.b().tag).to.equal('b');
expect(h.bdi().tag).to.equal('bdi');
expect(h.bdo().tag).to.equal('bdo');
expect(h.blockquote().tag).to.equal('blockquote');
expect(h.br().tag).to.equal('br');
expect(h.button().tag).to.equal('button');
expect(h.canvas().tag).to.equal('canvas');
expect(h.caption().tag).to.equal('caption');
expect(h.cite().tag).to.equal('cite');
expect(h.code().tag).to.equal('code');
expect(h.col().tag).to.equal('col');
expect(h.colgroup().tag).to.equal('colgroup');
expect(h.data().tag).to.equal('data');
expect(h.datalist().tag).to.equal('datalist');
expect(h.dd().tag).to.equal('dd');
expect(h.del().tag).to.equal('del');
expect(h.dfn().tag).to.equal('dfn');
expect(h.div().tag).to.equal('div');
expect(h.dl().tag).to.equal('dl');
expect(h.dt().tag).to.equal('dt');
expect(h.em().tag).to.equal('em');
expect(h.embed().tag).to.equal('embed');
expect(h.fieldset().tag).to.equal('fieldset');
expect(h.figcaption().tag).to.equal('figcaption');
expect(h.figure().tag).to.equal('figure');
expect(h.footer().tag).to.equal('footer');
expect(h.form().tag).to.equal('form');
expect(h.h1().tag).to.equal('h1');
expect(h.h2().tag).to.equal('h2');
expect(h.h3().tag).to.equal('h3');
expect(h.h4().tag).to.equal('h4');
expect(h.h5().tag).to.equal('h5');
expect(h.h6().tag).to.equal('h6');
expect(h.header().tag).to.equal('header');
expect(h.hr().tag).to.equal('hr');
expect(h.i().tag).to.equal('i');
expect(h.iframe().tag).to.equal('iframe');
expect(h.img().tag).to.equal('img');
expect(h.input().tag).to.equal('input');
expect(h.ins().tag).to.equal('ins');
expect(h.kbd().tag).to.equal('kbd');
expect(h.label().tag).to.equal('label');
expect(h.legend().tag).to.equal('legend');
expect(h.li().tag).to.equal('li');
expect(h.main().tag).to.equal('main');
expect(h.map().tag).to.equal('map');
expect(h.mark().tag).to.equal('mark');
expect(h.meter().tag).to.equal('meter');
expect(h.nav().tag).to.equal('nav');
expect(h.noscript().tag).to.equal('noscript');
expect(h.object().tag).to.equal('object');
expect(h.ol().tag).to.equal('ol');
expect(h.optgroup().tag).to.equal('optgroup');
expect(h.option().tag).to.equal('option');
expect(h.output().tag).to.equal('output');
expect(h.p().tag).to.equal('p');
expect(h.param().tag).to.equal('param');
expect(h.pre().tag).to.equal('pre');
expect(h.progress().tag).to.equal('progress');
expect(h.q().tag).to.equal('q');
expect(h.rp().tag).to.equal('rp');
expect(h.rt().tag).to.equal('rt');
expect(h.ruby().tag).to.equal('ruby');
expect(h.s().tag).to.equal('s');
expect(h.samp().tag).to.equal('samp');
expect(h.section().tag).to.equal('section');
expect(h.select().tag).to.equal('select');
expect(h.small().tag).to.equal('small');
expect(h.source().tag).to.equal('source');
expect(h.span().tag).to.equal('span');
expect(h.strong().tag).to.equal('strong');
expect(h.sub().tag).to.equal('sub');
expect(h.summary().tag).to.equal('summary');
expect(h.sup().tag).to.equal('sup');
expect(h.table().tag).to.equal('table');
expect(h.tbody().tag).to.equal('tbody');
expect(h.td().tag).to.equal('td');
expect(h.textarea().tag).to.equal('textarea');
expect(h.tfoot().tag).to.equal('tfoot');
expect(h.th().tag).to.equal('th');
expect(h.thead().tag).to.equal('thead');
expect(h.time().tag).to.equal('time');
expect(h.title().tag).to.equal('title');
expect(h.tr().tag).to.equal('tr');
expect(h.track().tag).to.equal('track');
expect(h.u().tag).to.equal('u');
expect(h.ul().tag).to.equal('ul');
expect(h.var_().tag).to.equal('var');
expect(h.video().tag).to.equal('video');
expect(h.wbr().tag).to.equal('wbr');
});
});
describe('VirtualDOM', () => {
describe('realize()', () => {
it('should create a real DOM node from a virtual DOM node', () => {
let node = VirtualDOM.realize(h.div([h.a(), h.img()]));
expect(node.nodeName.toLowerCase()).to.equal('div');
expect(node.children[0].nodeName.toLowerCase()).to.equal('a');
expect(node.children[1].nodeName.toLowerCase()).to.equal('img');
});
});
describe('render()', () => {
it('should render virtual DOM content into a host elememnt', () => {
let host = document.createElement('div');
VirtualDOM.render(h.img(), host);
expect(host.children[0].nodeName.toLowerCase()).to.equal('img');
});
it('should render the delta from the previous rendering', () => {
let host = document.createElement('div');
let children = [h.a(), h.span(), h.img()];
VirtualDOM.render(children, host);
let first = host.children[0];
let last = host.children[2];
expect(first.nodeName.toLowerCase()).to.equal('a');
expect(last.nodeName.toLowerCase()).to.equal('img');
children = [children[0], h.div(), children[1]];
VirtualDOM.render(children, host);
expect(host.children[0]).to.equal(first);
expect(host.children[2]).to.not.equal(last);
expect(host.children[2].nodeName.toLowerCase()).to.equal('span');
});
it('should clear the rendering if `null` content is provided', () => {
let host = document.createElement('div');
VirtualDOM.render(h('div', ['bar', 'foo']), host);
expect(host.children[0].childNodes.length).to.equal(2);
VirtualDOM.render(null, host);
expect(host.children.length).to.equal(0);
});
it('should update attributes', () => {
let host = document.createElement('div');
let attrs1 = {
alt: 'foo', height: '100', style: { color: 'white' },
dataset: { foo: '2', bar: '2' }, onload: () => { }, srcset: 'foo'
};
let attrs2 = {
alt: 'bar', width: '100', style: { border: '1px' },
dataset: { bar: '1', baz: '3' }, sizes: 'baz'
};
VirtualDOM.render([h.a(), h.img(attrs1)], host);
VirtualDOM.render([h.a(), h.img(attrs2)], host);
expect((host.children[1] as HTMLImageElement).alt).to.equal('bar');
});
it('should not recreate a DOM node that moves if it has a key id', () => {
let host = document.createElement('div');
let children1 = [
h.span({ key: '1' }),
h.span({ key: '2' }),
h.span({ key: '3' }),
h.span({ key: '4' })
];
let children2 = [
h.span({ key: '1' }),
h.span({ key: '3' }),
h.span({ key: '2' }),
h.span({ key: '4' })
];
VirtualDOM.render(children1, host);
let child1 = host.children[1];
let child2 = host.children[2];
VirtualDOM.render(children2, host);
expect(host.children[1]).to.equal(child2);
expect(host.children[2]).to.equal(child1);
});
it('should still recreate the DOM node if the node type changes', () => {
let host = document.createElement('div');
let children1 = [
h.span({ key: '1' }),
h.span({ key: '2' }),
h.span({ key: '3' }),
h.span({ key: '4' })
];
let children2 = [
h.span({ key: '1' }),
h.div({ key: '3' }),
h.span({ key: '2' }),
h.span({ key: '4' })
];
VirtualDOM.render(children1, host);
VirtualDOM.render(children2, host);
expect(host.children[1].nodeName.toLowerCase()).to.equal('div');
});
it('should handle a new keyed item', () => {
let host = document.createElement('div');
let children1 = [
h.span({ key: '1' }),
h.span({ key: '2' }),
h.span({ key: '3' }),
h.span({ key: '4' })
];
let children2 = [
h.span({ key: '1' }),
h.span({ key: '2' }),
h.span({ key: '3' }),
h.div({ key: '5' })
];
VirtualDOM.render(children1, host);
VirtualDOM.render(children2, host);
expect(host.children[3].nodeName.toLowerCase()).to.equal('div');
});
it('should update the text of a text node', () => {
let host = document.createElement('div');
VirtualDOM.render(h.div('foo'), host);
let div = host.children[0];
expect(div.textContent).to.equal('foo');
VirtualDOM.render(h.div('bar'), host);
expect(host.children[0]).to.equal(div);
expect(div.textContent).to.equal('bar');
});
});
});
}); | the_stack |
Zone.__load_patch('ZoneAwarePromise', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const ObjectDefineProperty = Object.defineProperty;
function readableObjectToString(obj: any) {
if (obj && obj.toString === Object.prototype.toString) {
const className = obj.constructor && obj.constructor.name;
return (className ? className : '') + ': ' + JSON.stringify(obj);
}
return obj ? obj.toString() : Object.prototype.toString.call(obj);
}
const __symbol__ = api.symbol;
const _uncaughtPromiseErrors: UncaughtPromiseError[] = [];
const symbolPromise = __symbol__('Promise');
const symbolThen = __symbol__('then');
const creationTrace = '__creationTrace__';
api.onUnhandledError = (e: any) => {
if (api.showUncaughtError()) {
const rejection = e && e.rejection;
if (rejection) {
console.error(
'Unhandled Promise rejection:',
rejection instanceof Error ? rejection.message : rejection,
'; Zone:', (<Zone>e.zone).name, '; Task:', e.task && (<Task>e.task).source,
'; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
} else {
console.error(e);
}
}
};
api.microtaskDrainDone = () => {
while (_uncaughtPromiseErrors.length) {
while (_uncaughtPromiseErrors.length) {
const uncaughtPromiseError: UncaughtPromiseError = _uncaughtPromiseErrors.shift()!;
try {
uncaughtPromiseError.zone.runGuarded(() => {
throw uncaughtPromiseError;
});
} catch (error) {
handleUnhandledRejection(error);
}
}
}
};
const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
function handleUnhandledRejection(e: any) {
api.onUnhandledError(e);
try {
const handler = (Zone as any)[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
if (handler && typeof handler === 'function') {
handler.call(this, e);
}
} catch (err) {
}
}
function isThenable(value: any): boolean {
return value && value.then;
}
function forwardResolution(value: any): any {
return value;
}
function forwardRejection(rejection: any): any {
return ZoneAwarePromise.reject(rejection);
}
const symbolState: string = __symbol__('state');
const symbolValue: string = __symbol__('value');
const symbolFinally: string = __symbol__('finally');
const symbolParentPromiseValue: string = __symbol__('parentPromiseValue');
const symbolParentPromiseState: string = __symbol__('parentPromiseState');
const source: string = 'Promise.then';
const UNRESOLVED: null = null;
const RESOLVED = true;
const REJECTED = false;
const REJECTED_NO_CATCH = 0;
function makeResolver(promise: ZoneAwarePromise<any>, state: boolean): (value: any) => void {
return (v) => {
try {
resolvePromise(promise, state, v);
} catch (err) {
resolvePromise(promise, false, err);
}
// Do not return value or you will break the Promise spec.
};
}
const once = function() {
let wasCalled = false;
return function wrapper(wrappedFunction: Function) {
return function() {
if (wasCalled) {
return;
}
wasCalled = true;
wrappedFunction.apply(null, arguments);
};
};
};
const TYPE_ERROR = 'Promise resolved with itself';
const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
// Promise Resolution
function resolvePromise(
promise: ZoneAwarePromise<any>, state: boolean, value: any): ZoneAwarePromise<any> {
const onceWrapper = once();
if (promise === value) {
throw new TypeError(TYPE_ERROR);
}
if ((promise as any)[symbolState] === UNRESOLVED) {
// should only get value.then once based on promise spec.
let then: any = null;
try {
if (typeof value === 'object' || typeof value === 'function') {
then = value && value.then;
}
} catch (err) {
onceWrapper(() => {
resolvePromise(promise, false, err);
})();
return promise;
}
// if (value instanceof ZoneAwarePromise) {
if (state !== REJECTED && value instanceof ZoneAwarePromise &&
value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
(value as any)[symbolState] !== UNRESOLVED) {
clearRejectedNoCatch(<Promise<any>>value as any);
resolvePromise(promise, (value as any)[symbolState], (value as any)[symbolValue]);
} else if (state !== REJECTED && typeof then === 'function') {
try {
then.call(
value, onceWrapper(makeResolver(promise, state)),
onceWrapper(makeResolver(promise, false)));
} catch (err) {
onceWrapper(() => {
resolvePromise(promise, false, err);
})();
}
} else {
(promise as any)[symbolState] = state;
const queue = (promise as any)[symbolValue];
(promise as any)[symbolValue] = value;
if ((promise as any)[symbolFinally] === symbolFinally) {
// the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
(promise as any)[symbolState] = (promise as any)[symbolParentPromiseState];
(promise as any)[symbolValue] = (promise as any)[symbolParentPromiseValue];
}
}
// record task information in value when error occurs, so we can
// do some additional work such as render longStackTrace
if (state === REJECTED && value instanceof Error) {
// check if longStackTraceZone is here
const trace = Zone.currentTask && Zone.currentTask.data &&
(Zone.currentTask.data as any)[creationTrace];
if (trace) {
// only keep the long stack trace into error when in longStackTraceZone
ObjectDefineProperty(
value, CURRENT_TASK_TRACE_SYMBOL,
{configurable: true, enumerable: false, writable: true, value: trace});
}
}
for (let i = 0; i < queue.length;) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
(promise as any)[symbolState] = REJECTED_NO_CATCH;
try {
// try to print more readable error log
throw new Error(
'Uncaught (in promise): ' + readableObjectToString(value) +
(value && value.stack ? '\n' + value.stack : ''));
} catch (err) {
const error: UncaughtPromiseError = err;
error.rejection = value;
error.promise = promise;
error.zone = Zone.current;
error.task = Zone.currentTask!;
_uncaughtPromiseErrors.push(error);
api.scheduleMicroTask(); // to make sure that it is running
}
}
}
}
// Resolving an already resolved promise is a noop.
return promise;
}
const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
function clearRejectedNoCatch(promise: ZoneAwarePromise<any>): void {
if ((promise as any)[symbolState] === REJECTED_NO_CATCH) {
// if the promise is rejected no catch status
// and queue.length > 0, means there is a error handler
// here to handle the rejected promise, we should trigger
// windows.rejectionhandled eventHandler or nodejs rejectionHandled
// eventHandler
try {
const handler = (Zone as any)[REJECTION_HANDLED_HANDLER];
if (handler && typeof handler === 'function') {
handler.call(this, {rejection: (promise as any)[symbolValue], promise: promise});
}
} catch (err) {
}
(promise as any)[symbolState] = REJECTED;
for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
_uncaughtPromiseErrors.splice(i, 1);
}
}
}
}
function scheduleResolveOrReject<R, U1, U2>(
promise: ZoneAwarePromise<any>, zone: AmbientZone, chainPromise: ZoneAwarePromise<any>,
onFulfilled?: ((value: R) => U1)|null|undefined,
onRejected?: ((error: any) => U2)|null|undefined): void {
clearRejectedNoCatch(promise);
const promiseState = (promise as any)[symbolState];
const delegate = promiseState ?
(typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
(typeof onRejected === 'function') ? onRejected : forwardRejection;
zone.scheduleMicroTask(source, () => {
try {
const parentPromiseValue = (promise as any)[symbolValue];
const isFinallyPromise =
!!chainPromise && symbolFinally === (chainPromise as any)[symbolFinally];
if (isFinallyPromise) {
// if the promise is generated from finally call, keep parent promise's state and value
(chainPromise as any)[symbolParentPromiseValue] = parentPromiseValue;
(chainPromise as any)[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
const value = zone.run(
delegate, undefined,
isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
[] :
[parentPromiseValue]);
resolvePromise(chainPromise, true, value);
} catch (error) {
// if error occurs, should always return this error
resolvePromise(chainPromise, false, error);
}
}, chainPromise as TaskData);
}
const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
class ZoneAwarePromise<R> implements Promise<R> {
static toString() {
return ZONE_AWARE_PROMISE_TO_STRING;
}
static resolve<R>(value: R): Promise<R> {
return resolvePromise(<ZoneAwarePromise<R>>new this(null as any), RESOLVED, value);
}
static reject<U>(error: U): Promise<U> {
return resolvePromise(<ZoneAwarePromise<U>>new this(null as any), REJECTED, error);
}
static race<R>(values: PromiseLike<any>[]): Promise<R> {
let resolve: (v: any) => void;
let reject: (v: any) => void;
let promise: any = new this((res, rej) => {
resolve = res;
reject = rej;
});
function onResolve(value: any) {
resolve(value);
}
function onReject(error: any) {
reject(error);
}
for (let value of values) {
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then(onResolve, onReject);
}
return promise;
}
static all<R>(values: any): Promise<R> {
let resolve: (v: any) => void;
let reject: (v: any) => void;
let promise = new this<R>((res, rej) => {
resolve = res;
reject = rej;
});
// Start at 2 to prevent prematurely resolving if .then is called immediately.
let unresolvedCount = 2;
let valueIndex = 0;
const resolvedValues: any[] = [];
for (let value of values) {
if (!isThenable(value)) {
value = this.resolve(value);
}
const curValueIndex = valueIndex;
value.then((value: any) => {
resolvedValues[curValueIndex] = value;
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
}, reject!);
unresolvedCount++;
valueIndex++;
}
// Make the unresolvedCount zero-based again.
unresolvedCount -= 2;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
return promise;
}
constructor(
executor:
(resolve: (value?: R|PromiseLike<R>) => void, reject: (error?: any) => void) => void) {
const promise: ZoneAwarePromise<R> = this;
if (!(promise instanceof ZoneAwarePromise)) {
throw new Error('Must be an instanceof Promise.');
}
(promise as any)[symbolState] = UNRESOLVED;
(promise as any)[symbolValue] = []; // queue;
try {
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
} catch (error) {
resolvePromise(promise, false, error);
}
}
get[Symbol.toStringTag]() {
return 'Promise' as any;
}
then<TResult1 = R, TResult2 = never>(
onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>)|undefined|null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>)|undefined|
null): Promise<TResult1|TResult2> {
const chainPromise: Promise<TResult1|TResult2> =
new (this.constructor as typeof ZoneAwarePromise)(null as any);
const zone = Zone.current;
if ((this as any)[symbolState] == UNRESOLVED) {
(<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFulfilled, onRejected);
} else {
scheduleResolveOrReject(this, zone, chainPromise as any, onFulfilled, onRejected);
}
return chainPromise;
}
catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>)|undefined|
null): Promise<R|TResult> {
return this.then(null, onRejected);
}
finally<U>(onFinally?: () => U | PromiseLike<U>): Promise<R> {
const chainPromise: Promise<R|never> =
new (this.constructor as typeof ZoneAwarePromise)(null as any);
(chainPromise as any)[symbolFinally] = symbolFinally;
const zone = Zone.current;
if ((this as any)[symbolState] == UNRESOLVED) {
(<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFinally, onFinally);
} else {
scheduleResolveOrReject(this, zone, chainPromise as any, onFinally, onFinally);
}
return chainPromise;
}
}
// Protect against aggressive optimizers dropping seemingly unused properties.
// E.g. Closure Compiler in advanced mode.
ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
ZoneAwarePromise['race'] = ZoneAwarePromise.race;
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
const NativePromise = global[symbolPromise] = global['Promise'];
const ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
let desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
if (!desc || desc.configurable) {
desc && delete desc.writable;
desc && delete desc.value;
if (!desc) {
desc = {configurable: true, enumerable: true};
}
desc.get = function() {
// if we already set ZoneAwarePromise, use patched one
// otherwise return native one.
return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
};
desc.set = function(NewNativePromise) {
if (NewNativePromise === ZoneAwarePromise) {
// if the NewNativePromise is ZoneAwarePromise
// save to global
global[ZONE_AWARE_PROMISE] = NewNativePromise;
} else {
// if the NewNativePromise is not ZoneAwarePromise
// for example: after load zone.js, some library just
// set es6-promise to global, if we set it to global
// directly, assertZonePatched will fail and angular
// will not loaded, so we just set the NewNativePromise
// to global[symbolPromise], so the result is just like
// we load ES6 Promise before zone.js
global[symbolPromise] = NewNativePromise;
if (!NewNativePromise.prototype[symbolThen]) {
patchThen(NewNativePromise);
}
api.setNativePromise(NewNativePromise);
}
};
ObjectDefineProperty(global, 'Promise', desc);
}
global['Promise'] = ZoneAwarePromise;
const symbolThenPatched = __symbol__('thenPatched');
function patchThen(Ctor: Function) {
const proto = Ctor.prototype;
const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
if (prop && (prop.writable === false || !prop.configurable)) {
// check Ctor.prototype.then propertyDescriptor is writable or not
// in meteor env, writable is false, we should ignore such case
return;
}
const originalThen = proto.then;
// Keep a reference to the original method.
proto[symbolThen] = originalThen;
Ctor.prototype.then = function(onResolve: any, onReject: any) {
const wrapped = new ZoneAwarePromise((resolve, reject) => {
originalThen.call(this, resolve, reject);
});
return wrapped.then(onResolve, onReject);
};
(Ctor as any)[symbolThenPatched] = true;
}
api.patchThen = patchThen;
function zoneify(fn: Function) {
return function() {
let resultPromise = fn.apply(this, arguments);
if (resultPromise instanceof ZoneAwarePromise) {
return resultPromise;
}
let ctor = resultPromise.constructor;
if (!ctor[symbolThenPatched]) {
patchThen(ctor);
}
return resultPromise;
};
}
if (NativePromise) {
patchThen(NativePromise);
const fetch = global['fetch'];
if (typeof fetch == 'function') {
global[api.symbol('fetch')] = fetch;
global['fetch'] = zoneify(fetch);
}
}
// This is not part of public API, but it is useful for tests, so we expose it.
(Promise as any)[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
return ZoneAwarePromise;
}); | the_stack |
import { ValidateMessagesTemplateType } from 'b-validate';
import { ReactNode, CSSProperties, HTMLAttributes, FormHTMLAttributes } from 'react';
import { Options as ScrollIntoViewOptions } from 'scroll-into-view-if-needed';
import { ColProps } from '../Grid/col';
import Store from './store';
export type IndexedObject = { [key: string]: any };
export type KeyType = string | number | symbol;
export type ComponentType = keyof JSX.IntrinsicElements | React.ComponentType<any>;
export type FieldError<FieldValue = any> = {
value?: FieldValue;
message?: ReactNode;
type?: string;
requiredError?: boolean;
};
export type ValidateFieldsErrors<FieldValue = any, FieldKey extends KeyType = string> =
| Record<FieldKey, FieldValue>
| undefined
| null;
/**
* @title Form
*/
export interface FormProps<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> extends Omit<FormHTMLAttributes<any>, 'className' | 'onChange' | 'onSubmit'> {
style?: CSSProperties;
className?: string | string[];
prefixCls?: string;
/**
* @zh form
* @en form
*/
form?: FormInstance<FormData, FieldValue, FieldKey>;
/**
* @zh 设置后,会作为表单控件 `id`的前缀。
* @en prefix of `id` attr
*/
id?: string;
/**
* @zh 表单的布局,有三种布局,水平、垂直、多列。
* @en The layout of Form
* @defaultValue horizontal
*/
layout?: 'horizontal' | 'vertical' | 'inline';
/**
* @zh 不同尺寸。
* @en size of form
*/
size?: 'mini' | 'small' | 'default' | 'large';
/**
* @zh
* `<label>`标签布局,同[<Grid.Col>](/react/components/grid)组件接收的参数相同,
* 可以配置`span`和`offset`值,会覆盖全局的`labelCol`设置
* @en
* Global `<label>` label layout. Same as the props received by the `<Grid.Col>`,
* the values of `span` and `offset` can be configured,
* which will be overwritten by the `labelCol` set by `Form.Item`
* @defaultValue { span: 5, offset: 0 }
*/
labelCol?: ColProps;
/**
* @zh
* 控件布局,同`labelCol`的设置方法一致,会覆盖全局的`wrapperCol`设置,[ColProps](/react/components/grid)
* @en
* The global control layout, which is the same as the setting method of `labelCol`,
* will be overwritten by the `wrapperCol` set by `Form.Item`
* @defaultValue { span: 19, offset: 0 }
*/
wrapperCol?: ColProps;
/**
* @zh 是否在 required 的时候显示加重的红色星号,设置 position 可选择将星号置于 label 前/后
* @en Whether show red symbol when item is required,Set position props, you can choose to place the symbol before/after the label
* @defaultValue true
* @version `position` in 2.24.0
*/
requiredSymbol?: boolean | { position: 'start' | 'end' };
/**
* @zh 标签的文本对齐方式
* @en Text alignment of `label`
* @defaultValue right
*/
labelAlign?: 'left' | 'right';
/**
* @zh 设置表单初始值
* @en Default value of form data
*/
initialValues?: Partial<FormData>;
/**
* @zh
* 触发验证的时机。
* @en
* When to trigger verification.
* @defaultValue onChange
* @version 2.28.0
*/
validateTrigger?: string | string[];
/**
* @zh 任意表单项值改变时候触发。第一个参数是被改变表单项的值,第二个参数是所有的表单项值
* @en Callback when any form item value changes.The first is the changed value, and the second is the value of all items
*/
onValuesChange?: (value: Partial<FormData>, values: Partial<FormData>) => void;
/**
* @zh 表单项值改变时候触发。和 onValuesChange 不同的是只会在用户操作表单项时触发
* @en Callback when the form item value changes. Unlike `onValuesChange`, it will only be called when the user manipulates the form item
*/
onChange?: (value: Partial<FormData>, values: Partial<FormData>) => void;
/**
* @zh 配置最外层标签,可以是 html 标签或是组件
* @en Custom outer tag. Can be html tags or React components
* @defaultValue form
*/
wrapper?: ComponentType;
/**
* @zh 配置 `wrapper` 之后,可以传一些参数到 wrapper 上。
* @en If set `wrapper`, You can pass some parameters to the wrapper.
*/
wrapperProps?: IndexedObject;
/**
* @zh 统一配置表单控件是否可用
* @en Whether All Form item is disabled
*/
disabled?: boolean;
/**
* @zh 是否显示标签后的一个冒号,优先级小于 `Form.Item` 中 `colon` 的优先级。
* @en Whether show colon after `label`. Priority is lower than `colon` in `Form.Item`.
*/
colon?: boolean;
/**
* @zh 验证失败后滚动到第一个错误字段。(`ScrollIntoViewOptions` 类型在 `2.19.0` 开始支持)
* @en Whether scroll to first error item after validation fails. (`ScrollIntoViewOptions` is supported at `2.19.0`)
*/
scrollToFirstError?: boolean | ScrollIntoViewOptions;
/**
* @zh 校验提示信息模板 [demo](/react/components/form#表单校验信息模板)
* @en validation prompt template [demo](/react/en-US/components/form#validate%20messages)
* @version 2.32.0
*/
validateMessages?: Partial<{
[key in keyof ValidateMessagesTemplateType]: ValidateMessagesTemplateType[key] extends string
? ValidateMessagesTemplateType[key]
: Record<keyof ValidateMessagesTemplateType[key], (data, { label }) => any | string>;
}>;
/**
* @zh 数据验证成功后回调事件
* @en Callback when submit data
*/
onSubmit?: (values: FormData) => void;
/**
* @zh 数据验证失败后回调事件
* @en Callback when validate fail
* @version 2.21.0
*/
onSubmitFailed?: (errors: { [key: string]: FieldError }) => void;
}
export interface RulesProps<FieldValue = any> {
validateTrigger?: string | string[];
// 校验失败时候以 `error` 或 `warning` 形式展示错误信息。当设置为 `warning` 时不会阻塞表单提交
validateLevel?: 'error' | 'warning';
required?: boolean;
type?: string;
length?: number;
// Array
maxLength?: number;
minLength?: number;
includes?: boolean;
deepEqual?: any;
empty?: boolean;
// Number
min?: number;
max?: number;
equal?: number;
positive?: boolean;
negative?: boolean;
// Object
hasKeys?: string[];
// String
match?: RegExp;
uppercase?: boolean;
lowercase?: boolean;
// Boolean
true?: boolean;
false?: boolean;
// custom
validator?: (value: FieldValue | undefined, callback: (error?: ReactNode) => void) => void;
message?: ReactNode;
}
export type FormItemChildrenFn<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> = (formData: any, form: FormInstance<FormData, FieldValue, FieldKey>) => React.ReactNode;
/**
* @title Form.Item
*/
export interface FormItemProps<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> extends Omit<HTMLAttributes<any>, 'className' | 'children'> {
style?: CSSProperties;
className?: string | string[];
prefixCls?: string;
store?: FormInstance<FormData, FieldValue, FieldKey>;
/**
* @zh 设置控件初始值.(初始值,请不要使用受控组件的defaultValue了)
* @en Default value
*/
initialValue?: FieldValue;
/**
* @zh 受控组件的唯一标示
* @en Unique identification of controlled components
*/
field?: FieldKey;
/**
* @zh 标签的文本
* @en Label text
*/
label?: ReactNode;
/**
* @zh
* `<label>`标签布局,同[<Grid.Col>](/react/components/grid)组件接收的参数相同,可以配置`span`和`offset`值,会覆盖全局的`labelCol`设置
* @en
* The layout of `<label>`, the same as the props received by the `<Grid.Col>`.
* The values of `span` and `offset` can be configured, which will override the global `labelCol` setting
*/
labelCol?: ColProps;
/**
* @zh 控件布局,同`labelCol`的设置方法一致,会覆盖全局的`wrapperCol`设置,[ColProps](/react/components/grid)
* @en The control layout, which is the same as the setting method of `labelCol`, which will override the global `wrapperCol` setting
*/
wrapperCol?: ColProps;
/**
* @zh 是否显示标签后的一个冒号
* @en Whether to add a colon after label
*/
colon?: boolean;
/**
* @zh 是否禁用,优先级高于 `Form` 的 `disabled` 属性
* @en Whether the FormItem is disabled. Priority is higher than the `disabled` prop of `Form`
*/
disabled?: boolean;
/**
* @zh 受控模式下的验证规则,[RulesProps](#rules)
* @en Validation rules in controlled component, [RulesProps](#rules)
*/
rules?: RulesProps<FieldValue>[];
/**
* @zh 接管子节点,搜集子节点值的时机。
* @en When to take over and collecting the child nodes.
* @defaultValue onChange
*/
trigger?: string;
/**
* @zh 子节点被接管的值的属性名,默认是 `value`,比如 `<Checkbox>` 为 `checked`。
* @en The attribute name of the child node being taken over, default is `value`, ex, `<Checkbox>` is `checked`.
* @defaultValue value
*/
triggerPropName?: string;
/**
* @zh 指定在子节点触发`onChange`事件时如何处理值。(如果自定义了`trigger`属性,那么这里的参数就是对应的事件回调函数的参数类型)
* @en Specify how to handle the value when the child node triggers the `onChange` event. (If the `trigger` attribute is customized, then the parameter here is the parameter type of the corresponding event callback function)
* @version 2.23.0
*/
getValueFromEvent?: (...args) => FieldValue;
/**
* @zh
* 触发验证的时机。取值和跟包裹的控件有关系,控件支持的触发事件,都可以作为值。
* 例如`Input`支持的 `onFocus`、 `onBlur`、 `onChange` 都可以作为 `validateTrigger` 的值。传递为 `[]` 时,
* 仅会在调用表单 `validate` 方法时执行校验规则。
* @en
* When to trigger verification. The value is related to the wrapped item, and all events supported.
* For example, `onFocus`, `onBlur`, and `onChange` supported by `Input` can be used as the value of `validateTrigger`.
* When passed as `[]`, the validation rules will only be executed when the form `validate` method is called
* @defaultValue onChange
*/
validateTrigger?: string | string[];
/**
* @zh
* 不渲染任何外部标签/样式,只进行字段绑定。**注意**: 设置该属性为true时,该字段若未通过校验,
* 错误信息将不会显示出来。可以传入对象,并设置 showErrorTip( `2.5.0` 开始支持) 为true,错误信息将会展示在上层 formItem 节点下。
* @en
* No external tags/styles are rendered, only binding field. **Notice**: When set to true, if the field verification failed,
* the error message will not be displayed. You can pass in an object and set showErrorTip to true(Support at `2.5.0`),
* The error message will be displayed under the upper formItem node
*/
noStyle?: boolean | { showErrorTip: boolean };
/**
* @zh
* 是否必选,会在 `label` 标签前显示加重红色符号,如果这里不设置,会从 rules 中寻找是否是 required
* @en
* Whether The FormItem is Required, Will display an red symbol in front of the `label` label.
* If it is not set here, it will look for `required` from the rules
*/
required?: boolean;
/**
* @zh 隐藏表单项. 表单字段值仍然会被获取
* @en hide the form item
* @version 2.29.0
*/
hidden?: boolean;
/**
* @zh 额外的提示内容。
* @en Additional hint content.
*/
extra?: ReactNode;
/**
* @zh 校验状态
* @en Validate status
*/
validateStatus?: 'success' | 'warning' | 'error' | 'validating';
/**
* @zh 是否显示校验图标,配置 validateStatus 使用。
* @en Whether to show the verification icon, configure `validateStatus` to use.
*/
hasFeedback?: boolean;
/**
* @zh 自定义校验文案
* @en Custom help text
*/
help?: ReactNode;
/**
* @zh 将控件的 `value` 进行一定的转换再保存到form中。
* @en Convert the `value` to the FormItem
*/
normalize?: (
value: FieldValue | undefined,
prevValue: FieldValue | undefined,
allValues: Partial<FormData>
) => any;
/**
* @zh 将Form内保存的当前控件对应的值进行一定的转换,再传递给控件。
* @en Convert the `value` of the FormItem to children;
* @version 2.23.0
*/
formatter?: (value: FieldValue | undefined) => any;
/**
* @zh 是否在其他控件值改变时候重新渲染当前区域。设置为true时候,表单的任意改变都会重新渲染该区域。
* @en Whether to re-render when other FormItem value change. When set to true, any changes to the Form will re-render.
*/
shouldUpdate?:
| boolean
| ((
prevValues: Partial<FormData>,
currentValues: Partial<FormData>,
info: {
isFormList?: boolean;
field?: FieldKey | FieldKey[];
isInner?: boolean;
}
) => boolean);
/**
* @zh 标签的文本对齐方式,优先级高于 `Form`
* @en Text alignment of `label`
* @defaultValue right
*/
labelAlign?: 'left' | 'right';
layout?: 'horizontal' | 'vertical' | 'inline';
/**
* @zh 是否在 required 的时候显示加重的红色星号,设置 position 可选择将星号置于 label 前/后
* @en Whether show red symbol when item is required,Set position props, you can choose to place the symbol before/after the label
* @defaultValue true
* @version `position` in 2.24.0
*/
requiredSymbol?: boolean | { position: 'start' | 'end' };
isFormList?: boolean;
children?: React.ReactNode | FormItemChildrenFn<FormData, FieldValue, FieldKey>;
}
export interface FormControlProps<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> {
/** 受控组件的唯一标示。 */
field?: FieldKey;
initialValue?: FieldValue;
getValueFromEvent?: FormItemProps['getValueFromEvent'];
rules?: RulesProps<FieldValue>[];
/** 接管子节点,搜集子节点的时机 */
trigger?: string;
/** 子节点被接管的值的属性名,默认是`value`,比如`<Checkbox>`为`checked` */
triggerPropName?: string;
/** 触发验证的时机 */
validateTrigger?: string | string[];
/** 转换默认的 `value` 给控件。 */
normalize?: (
value: FieldValue | undefined,
prevValue: FieldValue | undefined,
allValues: Partial<FormData>
) => any;
formatter?: FormItemProps['formatter'];
onValuesChange?: (value: Partial<FormData>, values: Partial<FormData>) => void;
noStyle?: boolean;
shouldUpdate?: FormItemProps['shouldUpdate'];
disabled?: boolean;
validateStatus?: 'success' | 'warning' | 'error' | 'validating';
help?: ReactNode;
isFormList?: boolean;
hasFeedback?: boolean;
}
/**
* @title Form.List
*/
export interface FormListProps<
SubFieldValue = any,
SubFieldKey extends KeyType = string,
FieldKey extends KeyType = string
> {
/**
* @zh 字段名
* @en Field name
*/
field: FieldKey;
/**
* @zh 初始值
* @en Default value
* @version 2.22.0
*/
initialValue?: SubFieldValue[];
/**
* @zh 函数类型的 children
* @en Function type children
*/
children?: (
fields: { key: number; field: SubFieldKey }[],
operation: {
add: (defaultValue?: SubFieldValue, index?: number) => void;
remove: (index: number) => void;
move: (fromIndex: number, toIndex: number) => void;
}
) => React.ReactNode;
}
export type FormContextProps<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> = Pick<
FormProps<FormData, FieldValue, FieldKey>,
| 'prefixCls'
| 'labelCol'
| 'wrapperCol'
| 'requiredSymbol'
| 'labelAlign'
| 'disabled'
| 'colon'
| 'layout'
| 'validateTrigger'
> & {
validateMessages?: FormProps['validateMessages'];
getFormElementId?: (field: FieldKey) => string;
store?: FormInstance<FormData, FieldValue, FieldKey>;
};
export type FormItemContextProps<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> = FormContextProps<FormData, FieldValue, FieldKey> & {
validateMessages?: FormProps['validateMessages'];
updateFormItem?: (
field: string,
params: { errors?: FieldError<FieldValue>; warnings?: ReactNode[] }
) => void;
};
export type FormInstance<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> = Pick<
Store<FormData, FieldValue, FieldKey>,
| 'getFieldsValue'
| 'getFieldValue'
| 'getFieldError'
| 'getFieldsError'
| 'getTouchedFields'
| 'getFields'
| 'setFieldValue'
| 'setFieldsValue'
| 'setFields'
| 'resetFields'
| 'clearFields'
| 'submit'
| 'validate'
> & {
scrollToField: (field: FieldKey, options?: ScrollIntoViewOptions) => void;
getInnerMethods: (inner?: boolean) => InnerMethodsReturnType<FormData, FieldValue, FieldKey>;
};
export type InnerMethodsReturnType<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> = Pick<
Store<FormData, FieldValue, FieldKey>,
| 'registerField'
| 'registerWatcher'
| 'innerSetInitialValues'
| 'innerSetInitialValue'
| 'innerSetCallbacks'
| 'innerSetFieldValue'
| 'innerGetStore'
>;
export interface FormValidateFn<
FormData = any,
FieldValue = FormData[keyof FormData],
FieldKey extends KeyType = keyof FormData
> {
/**
* 验证所有表单的值,并且返回报错和表单数据
*/
(): Promise<FormData>;
/**
* 验证所有表单的值,并且返回报错和表单数据
* @param fields 需要校验的表单字段
*/
(fields: FieldKey[]): Promise<Partial<FormData>>;
/**
* 验证所有表单的值,并且返回报错和表单数据
* @param callback 校验完成后的回调函数
*/
(
callback: (errors?: ValidateFieldsErrors<FieldValue, FieldKey>, values?: FormData) => void
): void;
/**
* 验证所有表单的值,并且返回报错和表单数据
* @param fields 需要校验的表单字段
* @param callback 校验完成后的回调函数
*/
(
fields: FieldKey[],
callback: (
errors?: ValidateFieldsErrors<FieldValue, FieldKey>,
values?: Partial<FormData>
) => void
): void;
}
export const VALIDATE_STATUS = {
error: 'error',
success: 'success',
warning: 'warning',
validating: 'validating',
};
/**
* @title Form.Provider(`2.30.0`)
*/
export interface FormProviderProps {
/**
* @zh 包裹的任意 `Form` 组件的值改变时,该方法会被调用
* @en This method is called when the value of any wrapped `Form` component changes
*/
onFormValuesChange?: (
id: string | undefined,
changedValues,
{
forms,
}: {
forms: {
[key: string]: FormInstance;
};
}
) => void;
/**
* @zh 包裹的任意 `Form` 组件触发提交时,该方法会被调用
* @en This method will be called when any wrapped `Form` component triggers a submit
*/
onFormSubmit?: (
id: string | undefined,
values,
{
forms,
}: {
forms: {
[key: string]: FormInstance;
};
}
) => void;
} | the_stack |
import { canvas, glcompute } from './gl';
import { initRandomPositions } from './particles';
import { PassThroughFragmentShader, PointsVertexShader, SingleColorFragShader } from 'glcompute';
import { DT } from './constants';
import { velocityState } from './fluid';
const advectParticlesSource = require('./kernels/AdvectSVGParticlesShader.glsl');
import { saveAs } from 'file-saver';
import { paths2DToGcode } from './plotterUtils';
import MicroModal from 'micromodal';
export const guiState = {
'Num Particles': 1000,
'Trail Length': 1000,
'Trail Subsampling': 10,
'Regenerate': generateNewSVGParticles,
}
export const svgExportState = {
'Min Segment Length (pt)': 1,
'Save SVG': saveSVG,
}
export const gcodeExportState = {
'Units': 'inch',
'Width (in)': canvas.clientWidth / 72,
'Height (in)': canvas.clientHeight / 72,
'Min Segment Length (in)': 0.03,
'Draw Height (in)': 0,
'Retract Height (in)': 0.125,
'Draw Both Directions': true,
'Feed Rate (ipm)': 60,
'Save G-Code': saveGcode,
}
let numSteps = 0;
let pathGenerator: PathGenerator | null = null;
let initialPositions = initRandomPositions(new Float32Array(guiState['Num Particles'] * 2), canvas.clientWidth, canvas.clientHeight);
const particlePositionState = glcompute.initDataLayer('position', {
dimensions: guiState['Num Particles'],
type: 'float32',
numComponents: 2,
data: initialPositions,
}, true, 2);
// Init a render target for trail effect.
const trailState = glcompute.initDataLayer('trails', {
dimensions: [canvas.clientWidth, canvas.clientHeight],
type: 'uint8',
numComponents: 4,
}, true, 2);
const advectParticles = glcompute.initProgram('advectParticles', advectParticlesSource, [
{
name: 'u_positions',
value: 0,
dataType: 'INT',
},
{
name: 'u_velocity',
value: 1,
dataType: 'INT',
},
{
name: 'u_dt',
value: DT / guiState['Trail Subsampling'],
dataType: 'FLOAT',
},
{
name: 'u_pxSize',
value: [ 1 / canvas.clientWidth, 1 / canvas.clientHeight ],
dataType: 'FLOAT',
},
]);
const renderParticles = glcompute.initProgram('renderParticles', SingleColorFragShader, [], PointsVertexShader);
const overlayTexture = glcompute.initProgram('particleOverlay', PassThroughFragmentShader, [
{
name: 'u_state',
value: 0,
dataType: 'INT',
},
]);
export function generateNewSVGParticles() {
initialPositions = initRandomPositions(new Float32Array(guiState['Num Particles'] * 2), canvas.clientWidth, canvas.clientHeight)
generateNewSVGTrails();
}
export function generateNewSVGTrails() {
// Use same initial positions, just generate new trails.
particlePositionState.resize(guiState['Num Particles'], initialPositions);
// Clear the current particleTrails.
trailState.clear();
numSteps = 0;
}
export function stepSVGParticles() {
if (pathGenerator) {
pathGenerator.step();
return;
}
for (let i = 0; i < 20 * guiState['Trail Subsampling']; i++) { // this helps to speeds things along with the visualization.
if (numSteps++ < guiState['Trail Length'] * guiState['Trail Subsampling']) {
// Advect particles.
advectParticles.setUniform('u_dt', DT / guiState['Trail Subsampling'], 'FLOAT');
glcompute.step(advectParticles, [particlePositionState, velocityState], particlePositionState);
// Render particles to texture for trail effect.
glcompute.drawPoints(renderParticles, [particlePositionState], trailState);
// Render to screen.
glcompute.step(overlayTexture, [trailState], undefined);
} else {
return;
}
}
}
function getEdgeIntersectionWithBounds(p1: [number, number], p2: [number, number]) {
let t = (0 - p2[0]) / (p1[0] - p2[0]);
if (t < 0 || t > 1) {
t = (canvas.clientWidth - p2[0]) / (p1[0] - p2[0]);
if (t < 0 || t > 1) {
t = (0 - p2[1]) / (p1[1] - p2[1]);
if (t < 0 || t > 1) {
t = (canvas.clientHeight - p2[1]) / (p1[1] - p2[1]);
}
}
}
if (t < 0 || t > 1) {
return null;
}
return [p1[0] * t + p2[0] * (1 - t), p1[1] * t + p2[1] * (1 - t)] as [number, number];
}
const exportMsg = document.getElementById('exportMsg') as HTMLDivElement;
class PathGenerator {
private readonly numParticles: number;
private readonly trailLength: number;
private readonly numSubsamples: number;
private readonly minSegmentLength: number;
private readonly paths: [number, number][][] = [];
private readonly lastPositions: [number, number][] = [];
private iternum = 0;
private readonly onFinish: (paths: [number, number][][]) => void;
constructor(minSegmentLength: number, onFinish: (paths: [number, number][][]) => void) {
this.numParticles = guiState['Num Particles'];
this.trailLength = guiState['Trail Length'];
this.numSubsamples = guiState['Trail Subsampling'];
this.minSegmentLength = minSegmentLength;
this.onFinish = onFinish;
// Set initial positions.
for (let j = 0; j < this.numParticles; j++) {
const position = [initialPositions[2 * j], initialPositions[2 * j + 1]] as [number, number];
this.paths.push([position]);
this.lastPositions.push(position);
}
// Set back to initial state.
particlePositionState.resize(this.numParticles, initialPositions);
}
step() {
// Init a place to store the current positions.
let currentPositions!: Float32Array;
const minSegmentLengthSq = this.minSegmentLength * this.minSegmentLength;
for (let i = 0; i < 20 * this.numSubsamples; i++) {
// Advect particles.
advectParticles.setUniform('u_dt', DT / this.numSubsamples, 'FLOAT');
glcompute.step(advectParticles, [particlePositionState, velocityState], particlePositionState);
// Read data to CPU.
currentPositions = glcompute.getValues(particlePositionState);
exportMsg.innerHTML = `Saving particle paths ${this.iternum} / ${this.trailLength * this.numSubsamples}`;
for (let j = 0; j < this.numParticles; j++) {
const lastPosition = this.lastPositions[j];
const position = [currentPositions[2*j], currentPositions[2*j+1]] as [number, number];
// Check that segment is sufficiently large.
// Too many short segments will slow down the plotting time.
let segLengthSq = (lastPosition[0] - position[0]) * (lastPosition[0] - position[0]) + (lastPosition[1] - position[1]) * (lastPosition[1] - position[1]);
if (segLengthSq < minSegmentLengthSq) {
continue;
}
// Check that we haven't wrapped over the edge of the canvas onto the other side.
if (Math.abs(lastPosition[0] - position[0]) / canvas.clientWidth > 0.9 ||
Math.abs(lastPosition[1] - position[1]) / canvas.clientHeight > 0.9) {
// Extend this to the edge of the canvas by calculating an intersection.
const extendedPosition1 = position.slice() as [number, number];
const extendedPosition2 = lastPosition.slice() as [number, number];
if (Math.abs(lastPosition[0] - position[0]) / canvas.clientWidth > 0.9) {
if (lastPosition[0] > position[0]) {
extendedPosition1[0] += canvas.clientWidth;
extendedPosition2[0] -= canvas.clientWidth;
} else {
extendedPosition1[0] -= canvas.clientWidth;
extendedPosition2[0] += canvas.clientWidth;
}
}
if (Math.abs(lastPosition[1] - position[1]) / canvas.clientHeight > 0.9) {
if (lastPosition[1] > position[1]) {
extendedPosition1[1] += canvas.clientHeight;
extendedPosition2[1] -= canvas.clientHeight;
} else {
extendedPosition1[1] -= canvas.clientHeight;
extendedPosition2[1] += canvas.clientHeight;
}
}
const edge1 = getEdgeIntersectionWithBounds(lastPosition, extendedPosition1);
if (edge1) {
this.paths[j].push(edge1);
}
this.paths.push(this.paths[j].slice());// Push this path to the end of the list.
// Start a new path at this index.
this.paths[j] = [];
const edge2 = getEdgeIntersectionWithBounds(extendedPosition2, position);
if (edge2) {
this.paths[j].push(edge2);
}
} else if (segLengthSq > 100){
// TODO: sometimes there is a factor of two error from the float conversion.
// I need to fix this.
if (Math.round(position[0] / lastPosition[0]) === 2) {
position[0] /= 2;
}
if (Math.round(position[1] / lastPosition[1]) === 2) {
position[1] /= 2;
}
segLengthSq = (lastPosition[0] - position[0]) * (lastPosition[0] - position[0]) + (lastPosition[1] - position[1]) * (lastPosition[1] - position[1]);
if (segLengthSq > 100) {
console.warn('Bad position: ', lastPosition, position);
continue;// Ignore this point.
}
}
this.paths[j].push(position);
this.lastPositions[j] = position;
}
this.iternum += 1;
if (this.iternum >= this.trailLength * this.numSubsamples) {
this.finalChecks(currentPositions);
return;
}
}
}
finalChecks(currentPositions: Float32Array) {
for (let j = 0; j < this.numParticles; j++) {
// Check if any of these paths don't contain any segments.
if (this.paths[j].length === 1) {
// Add a segment, even if it is < minSegLength;
this.paths[j].push([currentPositions[2 * j], currentPositions[2 * j + 1]]);
}
}
this.onFinish(this.paths);
}
cancel() {
pathGenerator = null;
}
}
function saveSVG() {
// Get params.
const numParticles = guiState['Num Particles'];
const trailLength = guiState['Trail Length'];
pathGenerator = new PathGenerator(svgExportState['Min Segment Length (pt)'], (paths: [number, number][][]) => {
let svg = `<?xml version="1.0" standalone="no"?>\r\n<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${canvas.clientWidth}" height="${canvas.clientHeight}">`;
for (let j = 0; j < paths.length; j++) {
svg += `<path fill="none" stroke="black" stroke-width="1" d="M${paths[j][0][0]} ${canvas.clientHeight - paths[j][0][1]} `;
for (let i = 1; i < paths[j].length; i++) {
svg += `L${paths[j][i][0]} ${canvas.clientHeight - paths[j][i][1]} `;
}
svg += '" />';
}
svg += '</svg>';
const blob = new Blob([svg], {type: "image/svg+xml;charset=utf-8"});
saveAs(blob, `fluidsim_${numParticles}particles_${trailLength}length.svg`);
MicroModal.close('exportModal');
pathGenerator = null;
});
exportMsg.innerHTML = 'Saving SVG...';
MicroModal.show('exportModal', {
onClose: pathGenerator.cancel,
});
}
function saveGcode() {
// Get gcode params.
const retractHeight = gcodeExportState['Retract Height (in)'];
const feedHeight = gcodeExportState['Draw Height (in)'];
const feedRate = gcodeExportState['Feed Rate (ipm)'];
const scale = gcodeExportState['Width (in)'] / canvas.clientWidth;
const preservePathDirection = !gcodeExportState['Draw Both Directions'];
const numParticles = guiState['Num Particles'];
const trailLength = guiState['Trail Length'];
pathGenerator = new PathGenerator(gcodeExportState['Min Segment Length (in)'] / gcodeExportState['Width (in)'] * canvas.clientWidth, (paths: [number, number][][]) => {
exportMsg.innerHTML = `Sorting paths...`;
const gcode = paths2DToGcode(paths, {
bounds: {
min: [0, 0],
max: [canvas.clientWidth, canvas.clientHeight],
},
retractHeight,
feedHeight,
feedRate,
scale,
preservePathDirection,
});
const blob = new Blob([gcode], {type: "text/plain;charset=utf-8"});
saveAs(blob, `fluidsim_${numParticles}particles_${trailLength}length.nc`);
MicroModal.close('exportModal');
pathGenerator = null;
});
exportMsg.innerHTML = 'Saving G-Code...';
MicroModal.show('exportModal', {
onClose: pathGenerator.cancel,
});
}
export function exportsOnResize(width: number, height: number) {
trailState.resize([width, height]);
advectParticles.setUniform('u_pxSize', [1 / width, 1 / height], 'FLOAT');
} | the_stack |
import 'neuroglancer/noselect.css';
import './layer_bar.css';
import svg_plus from 'ikonate/icons/plus.svg';
import {DisplayContext} from 'neuroglancer/display_context';
import {addNewLayer, deleteLayer, LayerListSpecification, makeLayer, ManagedUserLayer, SelectedLayerState} from 'neuroglancer/layer';
import {LinkedViewerNavigationState} from 'neuroglancer/layer_group_viewer';
import {NavigationLinkType} from 'neuroglancer/navigation_state';
import {WatchableValueInterface} from 'neuroglancer/trackable_value';
import {DropLayers, registerLayerBarDragLeaveHandler, registerLayerBarDropHandlers, registerLayerDragHandlers} from 'neuroglancer/ui/layer_drag_and_drop';
import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce';
import {Owned, RefCounted} from 'neuroglancer/util/disposable';
import {removeFromParent} from 'neuroglancer/util/dom';
import {preventDrag} from 'neuroglancer/util/drag_and_drop';
import {makeCloseButton} from 'neuroglancer/widget/close_button';
import {makeDeleteButton} from 'neuroglancer/widget/delete_button';
import {makeIcon} from 'neuroglancer/widget/icon';
import {PositionWidget} from 'neuroglancer/widget/position_widget';
class LayerWidget extends RefCounted {
element = document.createElement('div');
layerNumberElement = document.createElement('div');
labelElement = document.createElement('div');
visibleProgress = document.createElement('div');
prefetchProgress = document.createElement('div');
labelElementText = document.createTextNode('');
valueElement = document.createElement('div');
maxLength: number = 0;
prevValueText: string = '';
constructor(public layer: ManagedUserLayer, public panel: LayerBar) {
super();
const {
element,
labelElement,
layerNumberElement,
valueElement,
visibleProgress,
prefetchProgress,
labelElementText
} = this;
element.className = 'neuroglancer-layer-item neuroglancer-noselect';
element.appendChild(visibleProgress);
element.appendChild(prefetchProgress);
labelElement.className = 'neuroglancer-layer-item-label';
labelElement.appendChild(labelElementText);
visibleProgress.className = 'neuroglancer-layer-item-visible-progress';
prefetchProgress.className = 'neuroglancer-layer-item-prefetch-progress';
layerNumberElement.className = 'neuroglancer-layer-item-number';
valueElement.className = 'neuroglancer-layer-item-value';
const valueContainer = document.createElement('div');
valueContainer.className = 'neuroglancer-layer-item-value-container';
const buttonContainer = document.createElement('div');
buttonContainer.className = 'neuroglancer-layer-item-button-container';
const closeElement = makeCloseButton();
closeElement.title = 'Remove layer from this layer group';
closeElement.addEventListener('click', (event: MouseEvent) => {
if (this.panel.layerManager === this.panel.manager.rootLayers) {
// The layer bar corresponds to a TopLevelLayerListSpecification. That means there is just
// a single layer group, archive the layer unconditionally.
this.layer.setArchived(true);
} else {
// The layer bar corresponds to a LayerSubsetSpecification. The layer is always contained
// in the root LayerManager, as well as the LayerManager for each LayerSubsetSpecification.
if (this.layer.containers.size > 2) {
// Layer is contained in at least one other layer group, just remove it from this layer
// group.
this.panel.layerManager.removeManagedLayer(this.layer);
} else {
// Layer is not contained in any other layer group. Archive it.
this.layer.setArchived(true);
}
}
event.stopPropagation();
});
const deleteElement = makeDeleteButton();
deleteElement.title = 'Delete this layer';
deleteElement.addEventListener('click', (event: MouseEvent) => {
deleteLayer(this.layer);
event.stopPropagation();
});
element.appendChild(layerNumberElement);
valueContainer.appendChild(valueElement);
valueContainer.appendChild(buttonContainer);
buttonContainer.appendChild(closeElement);
buttonContainer.appendChild(deleteElement);
element.appendChild(labelElement);
element.appendChild(valueContainer);
const positionWidget = this.registerDisposer(new PositionWidget(
layer.localPosition, layer.localCoordinateSpaceCombiner, {copyButton: false}));
element.appendChild(positionWidget.element);
positionWidget.element.addEventListener('click', (event: MouseEvent) => {
event.stopPropagation();
});
positionWidget.element.addEventListener('dblclick', (event: MouseEvent) => {
event.stopPropagation();
});
element.addEventListener('click', (event: MouseEvent) => {
if (event.ctrlKey) {
panel.selectedLayer.toggle(layer);
} else if (event.altKey) {
layer.pickEnabled = !layer.pickEnabled;
} else {
layer.setVisible(!layer.visible);
}
});
element.addEventListener('contextmenu', (event: MouseEvent) => {
panel.selectedLayer.layer = layer;
panel.selectedLayer.visible = true;
event.stopPropagation();
event.preventDefault();
});
registerLayerDragHandlers(
panel, element, layer, {getLayoutSpec: () => panel.getLayoutSpecForDrag()});
registerLayerBarDropHandlers(this.panel, element, this.layer);
}
update() {
const {layer, element} = this;
this.labelElementText.textContent = layer.name;
element.dataset.visible = layer.visible.toString();
element.dataset.selected = (layer === this.panel.selectedLayer.layer).toString();
element.dataset.pick = layer.pickEnabled.toString();
let title = `Click to ${layer.visible ? 'hide' : 'show'}, control+click to show side panel`;
if (layer.supportsPickOption) {
title +=
`, alt+click to ${layer.pickEnabled ? 'disable' : 'enable'} spatial object selection`;
}
title += `, drag to move, shift+drag to copy`;
element.title = title;
}
disposed() {
this.element.remove();
super.disposed();
}
}
export class LayerBar extends RefCounted {
layerWidgets = new Map<ManagedUserLayer, LayerWidget>();
element = document.createElement('div');
private layerUpdateNeeded = true;
private valueUpdateNeeded = false;
dropZone: HTMLDivElement;
private layerWidgetInsertionPoint = document.createElement('div');
private positionWidget = this.registerDisposer(new PositionWidget(
this.viewerNavigationState.position.value, this.manager.root.coordinateSpaceCombiner));
/**
* For use within this module only.
*/
dropLayers: DropLayers|undefined;
dragEnterCount = 0;
get layerManager() {
return this.manager.layerManager;
}
constructor(
public display: DisplayContext, public manager: LayerListSpecification,
public viewerNavigationState: LinkedViewerNavigationState,
public selectedLayer: Owned<SelectedLayerState>, public getLayoutSpecForDrag: () => any,
public showLayerHoverValues: WatchableValueInterface<boolean>) {
super();
this.registerDisposer(selectedLayer);
const {element} = this;
element.className = 'neuroglancer-layer-panel';
this.registerDisposer(manager.layerSelectedValues.changed.add(() => {
this.handleLayerValuesChanged();
}));
this.registerDisposer(manager.layerManager.layersChanged.add(() => {
this.handleLayersChanged();
}));
this.registerDisposer(selectedLayer.changed.add(() => {
this.handleLayersChanged();
}));
this.registerDisposer(showLayerHoverValues.changed.add(() => {
this.handleLayerItemValueChanged();
}));
this.element.dataset.showHoverValues = this.showLayerHoverValues.value.toString();
this.layerWidgetInsertionPoint.style.display = 'none';
this.element.appendChild(this.layerWidgetInsertionPoint);
let addButton = makeIcon({
svg: svg_plus,
title: 'Click to add layer, control+click/right click/⌘+click to add local annotation layer.',
});
addButton.classList.add('neuroglancer-layer-add-button');
let dropZone = this.dropZone = document.createElement('div');
dropZone.className = 'neuroglancer-layer-panel-drop-zone';
const addLayer = (event: MouseEvent) => {
if (event.ctrlKey || event.metaKey || event.type === 'contextmenu') {
const layer = makeLayer(
this.manager, 'annotation', {type: 'annotation', 'source': 'local://annotations'});
this.manager.add(layer);
this.selectedLayer.layer = layer;
this.selectedLayer.visible = true;
} else {
this.addLayerMenu();
}
};
this.registerEventListener(addButton, 'click', addLayer);
this.registerEventListener(addButton, 'contextmenu', addLayer);
element.appendChild(addButton);
element.appendChild(dropZone);
this.registerDisposer(preventDrag(addButton));
element.appendChild(this.positionWidget.element);
const updatePositionWidgetVisibility = () => {
const linkValue = this.viewerNavigationState.position.link.value;
this.positionWidget.element.style.display =
linkValue === NavigationLinkType.LINKED ? 'none' : '';
};
this.registerDisposer(
this.viewerNavigationState.position.link.changed.add(updatePositionWidgetVisibility));
updatePositionWidgetVisibility();
this.update();
this.updateChunkStatistics();
registerLayerBarDragLeaveHandler(this);
registerLayerBarDropHandlers(this, dropZone, undefined);
// Ensure layer widgets are updated before WebGL drawing starts; we don't want the layout to
// change after WebGL drawing or we will get flicker.
this.registerDisposer(display.updateStarted.add(() => this.updateLayers()));
this.registerDisposer(manager.chunkManager.layerChunkStatisticsUpdated.add(
this.registerCancellable(animationFrameDebounce(() => this.updateChunkStatistics()))));
}
disposed() {
this.layerWidgets.forEach(x => x.dispose());
this.layerWidgets = <any>undefined;
removeFromParent(this.element);
super.disposed();
}
handleLayersChanged() {
this.layerUpdateNeeded = true;
this.handleLayerValuesChanged();
}
handleLayerValuesChanged() {
if (!this.valueUpdateNeeded) {
this.valueUpdateNeeded = true;
this.scheduleUpdate();
}
}
handleLayerItemValueChanged() {
this.element.dataset.showHoverValues = this.showLayerHoverValues.value.toString()
}
private scheduleUpdate = this.registerCancellable(animationFrameDebounce(() => this.update()));
private update() {
this.valueUpdateNeeded = false;
this.updateLayers();
if (this.showLayerHoverValues.value === false) {
return
}
let values = this.manager.layerSelectedValues;
for (let [layer, widget] of this.layerWidgets) {
let userLayer = layer.layer;
let text = '';
if (userLayer !== null) {
let state = values.get(userLayer);
if (state !== undefined) {
const {value} = state;
if (value !== undefined) {
text = '' + value;
}
}
}
if (text === widget.prevValueText) continue;
widget.prevValueText = text;
if (text.length > widget.maxLength) {
const length = widget.maxLength = text.length;
widget.valueElement.style.width = `${length}ch`;
}
widget.valueElement.textContent = text;
}
}
private updateChunkStatistics() {
for (const [layer, widget] of this.layerWidgets) {
let numVisibleChunksNeeded = 0;
let numVisibleChunksAvailable = 0;
let numPrefetchChunksNeeded = 0;
let numPrefetchChunksAvailable = 0;
const userLayer = layer.layer;
if (userLayer !== null) {
for (const {layerChunkProgressInfo} of userLayer.renderLayers) {
numVisibleChunksNeeded += layerChunkProgressInfo.numVisibleChunksNeeded;
numVisibleChunksAvailable += layerChunkProgressInfo.numVisibleChunksAvailable;
numPrefetchChunksNeeded += layerChunkProgressInfo.numPrefetchChunksNeeded;
numPrefetchChunksAvailable += layerChunkProgressInfo.numPrefetchChunksAvailable;
}
}
widget.visibleProgress.style.width =
`${numVisibleChunksAvailable / Math.max(1, numVisibleChunksNeeded) * 100}%`;
widget.prefetchProgress.style.width =
`${numPrefetchChunksAvailable / Math.max(1, numPrefetchChunksNeeded) * 100}%`;
}
}
updateLayers() {
if (!this.layerUpdateNeeded) {
return;
}
this.layerUpdateNeeded = false;
let container = this.element;
let layers = new Set();
let nextChild = this.layerWidgetInsertionPoint.nextElementSibling;
this.manager.rootLayers.updateNonArchivedLayerIndices();
for (const layer of this.manager.layerManager.managedLayers) {
if (layer.archived && !this.dropLayers?.layers.has(layer)) continue;
layers.add(layer);
let widget = this.layerWidgets.get(layer);
const layerIndex = layer.nonArchivedLayerIndex;
if (widget === undefined) {
widget = new LayerWidget(layer, this);
this.layerWidgets.set(layer, widget);
}
widget.layerNumberElement.textContent = '' + (1 + layerIndex);
widget.update();
let {element} = widget;
if (element !== nextChild) {
container.insertBefore(widget.element, nextChild);
}
nextChild = element.nextElementSibling;
}
for (let [layer, widget] of this.layerWidgets) {
if (!layers.has(layer)) {
this.layerWidgets.delete(layer);
widget.dispose();
}
}
}
addLayerMenu() {
addNewLayer(this.manager, this.selectedLayer);
}
} | the_stack |
module TypeScript.SyntaxFacts {
var textToKeywordKind: any = {
"any": SyntaxKind.AnyKeyword,
"async": SyntaxKind.AsyncKeyword,
"await": SyntaxKind.AwaitKeyword,
"boolean": SyntaxKind.BooleanKeyword,
"break": SyntaxKind.BreakKeyword,
"case": SyntaxKind.CaseKeyword,
"catch": SyntaxKind.CatchKeyword,
"class": SyntaxKind.ClassKeyword,
"continue": SyntaxKind.ContinueKeyword,
"const": SyntaxKind.ConstKeyword,
"constructor": SyntaxKind.ConstructorKeyword,
"debugger": SyntaxKind.DebuggerKeyword,
"declare": SyntaxKind.DeclareKeyword,
"default": SyntaxKind.DefaultKeyword,
"delete": SyntaxKind.DeleteKeyword,
"do": SyntaxKind.DoKeyword,
"else": SyntaxKind.ElseKeyword,
"enum": SyntaxKind.EnumKeyword,
"export": SyntaxKind.ExportKeyword,
"extends": SyntaxKind.ExtendsKeyword,
"false": SyntaxKind.FalseKeyword,
"finally": SyntaxKind.FinallyKeyword,
"for": SyntaxKind.ForKeyword,
"function": SyntaxKind.FunctionKeyword,
"get": SyntaxKind.GetKeyword,
"if": SyntaxKind.IfKeyword,
"implements": SyntaxKind.ImplementsKeyword,
"import": SyntaxKind.ImportKeyword,
"in": SyntaxKind.InKeyword,
"instanceof": SyntaxKind.InstanceOfKeyword,
"interface": SyntaxKind.InterfaceKeyword,
"let": SyntaxKind.LetKeyword,
"module": SyntaxKind.ModuleKeyword,
"new": SyntaxKind.NewKeyword,
"null": SyntaxKind.NullKeyword,
"number":SyntaxKind.NumberKeyword,
"package": SyntaxKind.PackageKeyword,
"private": SyntaxKind.PrivateKeyword,
"protected": SyntaxKind.ProtectedKeyword,
"public": SyntaxKind.PublicKeyword,
"require": SyntaxKind.RequireKeyword,
"return": SyntaxKind.ReturnKeyword,
"set": SyntaxKind.SetKeyword,
"static": SyntaxKind.StaticKeyword,
"string": SyntaxKind.StringKeyword,
"super": SyntaxKind.SuperKeyword,
"switch": SyntaxKind.SwitchKeyword,
"this": SyntaxKind.ThisKeyword,
"throw": SyntaxKind.ThrowKeyword,
"true": SyntaxKind.TrueKeyword,
"try": SyntaxKind.TryKeyword,
"type": SyntaxKind.TypeKeyword,
"typeof": SyntaxKind.TypeOfKeyword,
"var": SyntaxKind.VarKeyword,
"void": SyntaxKind.VoidKeyword,
"while": SyntaxKind.WhileKeyword,
"with": SyntaxKind.WithKeyword,
"yield": SyntaxKind.YieldKeyword,
"{": SyntaxKind.OpenBraceToken,
"}": SyntaxKind.CloseBraceToken,
"(": SyntaxKind.OpenParenToken,
")": SyntaxKind.CloseParenToken,
"[": SyntaxKind.OpenBracketToken,
"]": SyntaxKind.CloseBracketToken,
".": SyntaxKind.DotToken,
"...": SyntaxKind.DotDotDotToken,
";": SyntaxKind.SemicolonToken,
",": SyntaxKind.CommaToken,
"<": SyntaxKind.LessThanToken,
">": SyntaxKind.GreaterThanToken,
"<=": SyntaxKind.LessThanEqualsToken,
">=": SyntaxKind.GreaterThanEqualsToken,
"==": SyntaxKind.EqualsEqualsToken,
"=>": SyntaxKind.EqualsGreaterThanToken,
"!=": SyntaxKind.ExclamationEqualsToken,
"===": SyntaxKind.EqualsEqualsEqualsToken,
"!==": SyntaxKind.ExclamationEqualsEqualsToken,
"+": SyntaxKind.PlusToken,
"-": SyntaxKind.MinusToken,
"*": SyntaxKind.AsteriskToken,
"%": SyntaxKind.PercentToken,
"++": SyntaxKind.PlusPlusToken,
"--": SyntaxKind.MinusMinusToken,
"<<": SyntaxKind.LessThanLessThanToken,
">>": SyntaxKind.GreaterThanGreaterThanToken,
">>>": SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
"&": SyntaxKind.AmpersandToken,
"|": SyntaxKind.BarToken,
"^": SyntaxKind.CaretToken,
"!": SyntaxKind.ExclamationToken,
"~": SyntaxKind.TildeToken,
"&&": SyntaxKind.AmpersandAmpersandToken,
"||": SyntaxKind.BarBarToken,
"?": SyntaxKind.QuestionToken,
":": SyntaxKind.ColonToken,
"=": SyntaxKind.EqualsToken,
"+=": SyntaxKind.PlusEqualsToken,
"-=": SyntaxKind.MinusEqualsToken,
"*=": SyntaxKind.AsteriskEqualsToken,
"%=": SyntaxKind.PercentEqualsToken,
"<<=": SyntaxKind.LessThanLessThanEqualsToken,
">>=": SyntaxKind.GreaterThanGreaterThanEqualsToken,
">>>=": SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
"&=": SyntaxKind.AmpersandEqualsToken,
"|=": SyntaxKind.BarEqualsToken,
"^=": SyntaxKind.CaretEqualsToken,
"/": SyntaxKind.SlashToken,
"/=": SyntaxKind.SlashEqualsToken,
};
var kindToText = new Array<string>();
for (var name in textToKeywordKind) {
if (textToKeywordKind.hasOwnProperty(name)) {
// Debug.assert(kindToText[textToKeywordKind[name]] === undefined);
kindToText[textToKeywordKind[name]] = name;
}
}
// Manually work around a bug in the CScript 5.8 runtime where 'constructor' is not
// listed when SyntaxFacts.textToKeywordKind is enumerated because it is the name of
// the constructor function.
kindToText[SyntaxKind.ConstructorKeyword] = "constructor";
export function getTokenKind(text: string): SyntaxKind {
if (textToKeywordKind.hasOwnProperty(text)) {
return textToKeywordKind[text];
}
return SyntaxKind.None;
}
export function getText(kind: SyntaxKind): string {
var result = kindToText[kind];
return result;// !== undefined ? result : undefined;
}
export function isAnyKeyword(kind: SyntaxKind): boolean {
return kind >= SyntaxKind.FirstKeyword && kind <= SyntaxKind.LastKeyword;
}
export function isAnyPunctuation(kind: SyntaxKind): boolean {
return kind >= SyntaxKind.FirstPunctuation && kind <= SyntaxKind.LastPunctuation;
}
export function isPrefixUnaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean {
switch (tokenKind) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
return true;
default:
return false;
}
}
export function isBinaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean {
switch (tokenKind) {
case SyntaxKind.AsteriskToken:
case SyntaxKind.SlashToken:
case SyntaxKind.PercentToken:
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.LessThanEqualsToken:
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
case SyntaxKind.AmpersandToken:
case SyntaxKind.CaretToken:
case SyntaxKind.BarToken:
case SyntaxKind.AmpersandAmpersandToken:
case SyntaxKind.BarBarToken:
case SyntaxKind.BarEqualsToken:
case SyntaxKind.AmpersandEqualsToken:
case SyntaxKind.CaretEqualsToken:
case SyntaxKind.LessThanLessThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PercentEqualsToken:
case SyntaxKind.EqualsToken:
case SyntaxKind.CommaToken:
return true;
default:
return false;
}
}
export function isAssignmentOperatorToken(tokenKind: SyntaxKind): boolean {
switch (tokenKind) {
case SyntaxKind.BarEqualsToken:
case SyntaxKind.AmpersandEqualsToken:
case SyntaxKind.CaretEqualsToken:
case SyntaxKind.LessThanLessThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PercentEqualsToken:
case SyntaxKind.EqualsToken:
return true;
default:
return false;
}
}
export function isType(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.ArrayType:
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.FunctionType:
case SyntaxKind.ObjectType:
case SyntaxKind.ConstructorType:
case SyntaxKind.TypeQuery:
case SyntaxKind.GenericType:
case SyntaxKind.QualifiedName:
case SyntaxKind.IdentifierName:
return true;
}
return false;
}
} | the_stack |
declare module com {
export module google {
export module cloud {
export module datastore {
export module core {
export module number {
export class IndexNumberDecoder {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.IndexNumberDecoder>;
public constructor();
public resultAsLong(): number;
public isResultDouble(): boolean;
public resultAsDouble(): number;
public decode(param0: boolean, param1: native.Array<number>, param2: number): number;
public isResultLong(): boolean;
public reset(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module cloud {
export module datastore {
export module core {
export module number {
export class IndexNumberEncoder {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.IndexNumberEncoder>;
public static MAX_ENCODED_BYTES: number;
public static encodeDouble(param0: boolean, param1: number, param2: native.Array<number>, param3: number): number;
public static encodeLong(param0: boolean, param1: number, param2: native.Array<number>, param3: number): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module cloud {
export module datastore {
export module core {
export module number {
export class NumberComparisonHelper {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.NumberComparisonHelper>;
public static LONG_INCLUSIVE_LOWER_BOUND_AS_DOUBLE: number;
public static LONG_EXCLUSIVE_UPPER_BOUND_AS_DOUBLE: number;
public static MAX_SAFE_LONG: number;
public static MIN_SAFE_LONG: number;
public static firestoreCompareDoubles(param0: number, param1: number): number;
public static compareLongs(param0: number, param1: number): number;
public static firestoreCompareDoubleWithLong(param0: number, param1: number): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module cloud {
export module datastore {
export module core {
export module number {
export class NumberIndexEncoder {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.NumberIndexEncoder>;
public constructor();
public static encode(param0: com.google.cloud.datastore.core.number.NumberParts): native.Array<number>;
public static decodeDouble(param0: native.Array<number>): number;
public static encodeDouble(param0: number): native.Array<number>;
public static decodeLong(param0: native.Array<number>): number;
public static encodeLong(param0: number): native.Array<number>;
public static decode(param0: native.Array<number>): com.google.cloud.datastore.core.number.NumberIndexEncoder.DecodedNumberParts;
}
export module NumberIndexEncoder {
export class DecodedNumberParts {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.NumberIndexEncoder.DecodedNumberParts>;
public bytesRead(): number;
public parts(): com.google.cloud.datastore.core.number.NumberParts;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module cloud {
export module datastore {
export module core {
export module number {
export class NumberParts {
public static class: java.lang.Class<com.google.cloud.datastore.core.number.NumberParts>;
public static create(param0: boolean, param1: number, param2: number): com.google.cloud.datastore.core.number.NumberParts;
public negate(): com.google.cloud.datastore.core.number.NumberParts;
public asLong(): number;
public hashCode(): number;
public representableAsDouble(): boolean;
public asDouble(): number;
public isNaN(): boolean;
public static fromLong(param0: number): com.google.cloud.datastore.core.number.NumberParts;
public isInfinite(): boolean;
public representableAsLong(): boolean;
public significand(): number;
public exponent(): number;
public isZero(): boolean;
public negative(): boolean;
public static fromDouble(param0: number): com.google.cloud.datastore.core.number.NumberParts;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export class Timestamp extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.Timestamp>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.firebase.Timestamp>;
public constructor(param0: number, param1: number);
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public static now(): com.google.firebase.Timestamp;
public getSeconds(): number;
public constructor(param0: java.util.Date);
public toString(): string;
public constructor(param0: globalAndroid.os.Parcel);
public toDate(): java.util.Date;
public hashCode(): number;
public describeContents(): number;
public equals(param0: any): boolean;
public getNanoseconds(): number;
public compareTo(param0: com.google.firebase.Timestamp): number;
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class Blob extends java.lang.Comparable<com.google.firebase.firestore.Blob> {
public static class: java.lang.Class<com.google.firebase.firestore.Blob>;
public static fromBytes(param0: native.Array<number>): com.google.firebase.firestore.Blob;
public equals(param0: any): boolean;
public toString(): string;
public compareTo(param0: com.google.firebase.firestore.Blob): number;
public static fromByteString(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.Blob;
public toByteString(): com.google.protobuf.ByteString;
public hashCode(): number;
public toBytes(): native.Array<number>;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class BuildConfig {
public static class: java.lang.Class<com.google.firebase.firestore.BuildConfig>;
public static DEBUG: boolean;
public static APPLICATION_ID: string;
public static BUILD_TYPE: string;
public static FLAVOR: string;
public static VERSION_CODE: number;
public static VERSION_NAME: string;
public static USE_EMULATOR_FOR_TESTS: boolean;
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class CollectionReference extends com.google.firebase.firestore.Query {
public static class: java.lang.Class<com.google.firebase.firestore.CollectionReference>;
public getPath(): string;
public getId(): string;
public add(param0: any): com.google.android.gms.tasks.Task<com.google.firebase.firestore.DocumentReference>;
public document(): com.google.firebase.firestore.DocumentReference;
public document(param0: string): com.google.firebase.firestore.DocumentReference;
public getParent(): com.google.firebase.firestore.DocumentReference;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class DocumentChange {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentChange>;
public equals(param0: any): boolean;
public getNewIndex(): number;
public getDocument(): com.google.firebase.firestore.QueryDocumentSnapshot;
public getOldIndex(): number;
public getType(): com.google.firebase.firestore.DocumentChange.Type;
public hashCode(): number;
}
export module DocumentChange {
export class Type {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentChange.Type>;
public static ADDED: com.google.firebase.firestore.DocumentChange.Type;
public static MODIFIED: com.google.firebase.firestore.DocumentChange.Type;
public static REMOVED: com.google.firebase.firestore.DocumentChange.Type;
public static valueOf(param0: string): com.google.firebase.firestore.DocumentChange.Type;
public static values(): native.Array<com.google.firebase.firestore.DocumentChange.Type>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class DocumentId {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentId>;
/**
* Constructs a new instance of the com.google.firebase.firestore.DocumentId interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class DocumentReference {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentReference>;
public update(param0: string, param1: any, param2: native.Array<any>): com.google.android.gms.tasks.Task<java.lang.Void>;
public addSnapshotListener(param0: java.util.concurrent.Executor, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
public addSnapshotListener(param0: globalAndroid.app.Activity, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
public getId(): string;
public addSnapshotListener(param0: com.google.firebase.firestore.MetadataChanges, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
public get(): com.google.android.gms.tasks.Task<com.google.firebase.firestore.DocumentSnapshot>;
public update(param0: java.util.Map<string,any>): com.google.android.gms.tasks.Task<java.lang.Void>;
public delete(): com.google.android.gms.tasks.Task<java.lang.Void>;
public addSnapshotListener(param0: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
public addSnapshotListener(param0: globalAndroid.app.Activity, param1: com.google.firebase.firestore.MetadataChanges, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
public collection(param0: string): com.google.firebase.firestore.CollectionReference;
public set(param0: any): com.google.android.gms.tasks.Task<java.lang.Void>;
public getPath(): string;
public equals(param0: any): boolean;
public update(param0: com.google.firebase.firestore.FieldPath, param1: any, param2: native.Array<any>): com.google.android.gms.tasks.Task<java.lang.Void>;
public get(param0: com.google.firebase.firestore.Source): com.google.android.gms.tasks.Task<com.google.firebase.firestore.DocumentSnapshot>;
public getParent(): com.google.firebase.firestore.CollectionReference;
public getFirestore(): com.google.firebase.firestore.FirebaseFirestore;
public set(param0: any, param1: com.google.firebase.firestore.SetOptions): com.google.android.gms.tasks.Task<java.lang.Void>;
public hashCode(): number;
public addSnapshotListener(param0: java.util.concurrent.Executor, param1: com.google.firebase.firestore.MetadataChanges, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.DocumentSnapshot>): com.google.firebase.firestore.ListenerRegistration;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class DocumentSnapshot {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentSnapshot>;
public getData(param0: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): java.util.Map<string,any>;
public get(param0: string, param1: java.lang.Class): any;
public getId(): string;
public getDocumentReference(param0: string): com.google.firebase.firestore.DocumentReference;
public getBlob(param0: string): com.google.firebase.firestore.Blob;
public contains(param0: com.google.firebase.firestore.FieldPath): boolean;
public getReference(): com.google.firebase.firestore.DocumentReference;
public toObject(param0: java.lang.Class): any;
public get(param0: com.google.firebase.firestore.FieldPath, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public getDate(param0: string, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): java.util.Date;
public toString(): string;
public get(param0: string, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public get(param0: com.google.firebase.firestore.FieldPath, param1: java.lang.Class, param2: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public toObject(param0: java.lang.Class, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public contains(param0: string): boolean;
public getTimestamp(param0: string): com.google.firebase.Timestamp;
public hashCode(): number;
public get(param0: string): any;
public getTimestamp(param0: string, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): com.google.firebase.Timestamp;
public getData(): java.util.Map<string,any>;
public getString(param0: string): string;
public get(param0: com.google.firebase.firestore.FieldPath, param1: java.lang.Class): any;
public getLong(param0: string): java.lang.Long;
public exists(): boolean;
public getDate(param0: string): java.util.Date;
public getGeoPoint(param0: string): com.google.firebase.firestore.GeoPoint;
public get(param0: string, param1: java.lang.Class, param2: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public equals(param0: any): boolean;
public get(param0: com.google.firebase.firestore.FieldPath): any;
public getBoolean(param0: string): java.lang.Boolean;
public getDouble(param0: string): java.lang.Double;
public getMetadata(): com.google.firebase.firestore.SnapshotMetadata;
}
export module DocumentSnapshot {
export class FieldValueOptions {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentSnapshot.FieldValueOptions>;
}
export class ServerTimestampBehavior {
public static class: java.lang.Class<com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior>;
public static NONE: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior;
public static ESTIMATE: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior;
public static PREVIOUS: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior;
public static values(): native.Array<com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior>;
public static valueOf(param0: string): com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class EventListener<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.EventListener<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.EventListener<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onEvent(param0: T, param1: com.google.firebase.firestore.FirebaseFirestoreException): void;
});
public constructor();
public onEvent(param0: T, param1: com.google.firebase.firestore.FirebaseFirestoreException): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class Exclude {
public static class: java.lang.Class<com.google.firebase.firestore.Exclude>;
/**
* Constructs a new instance of the com.google.firebase.firestore.Exclude interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FieldPath {
public static class: java.lang.Class<com.google.firebase.firestore.FieldPath>;
public equals(param0: any): boolean;
public static of(param0: native.Array<string>): com.google.firebase.firestore.FieldPath;
public toString(): string;
public static documentId(): com.google.firebase.firestore.FieldPath;
public hashCode(): number;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export abstract class FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue>;
public static serverTimestamp(): com.google.firebase.firestore.FieldValue;
public static increment(param0: number): com.google.firebase.firestore.FieldValue;
public static arrayRemove(param0: native.Array<any>): com.google.firebase.firestore.FieldValue;
public static arrayUnion(param0: native.Array<any>): com.google.firebase.firestore.FieldValue;
public static delete(): com.google.firebase.firestore.FieldValue;
}
export module FieldValue {
export class ArrayRemoveFieldValue extends com.google.firebase.firestore.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue.ArrayRemoveFieldValue>;
}
export class ArrayUnionFieldValue extends com.google.firebase.firestore.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue.ArrayUnionFieldValue>;
}
export class DeleteFieldValue extends com.google.firebase.firestore.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue.DeleteFieldValue>;
}
export class NumericIncrementFieldValue extends com.google.firebase.firestore.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue.NumericIncrementFieldValue>;
}
export class ServerTimestampFieldValue extends com.google.firebase.firestore.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.FieldValue.ServerTimestampFieldValue>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FirebaseFirestore {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestore>;
public document(param0: string): com.google.firebase.firestore.DocumentReference;
public static getInstance(): com.google.firebase.firestore.FirebaseFirestore;
public static getInstance(param0: com.google.firebase.FirebaseApp): com.google.firebase.firestore.FirebaseFirestore;
public collection(param0: string): com.google.firebase.firestore.CollectionReference;
public collectionGroup(param0: string): com.google.firebase.firestore.Query;
public waitForPendingWrites(): com.google.android.gms.tasks.Task<java.lang.Void>;
public getApp(): com.google.firebase.FirebaseApp;
public disableNetwork(): com.google.android.gms.tasks.Task<java.lang.Void>;
public static setLoggingEnabled(param0: boolean): void;
public enableNetwork(): com.google.android.gms.tasks.Task<java.lang.Void>;
public addSnapshotsInSyncListener(param0: java.util.concurrent.Executor, param1: java.lang.Runnable): com.google.firebase.firestore.ListenerRegistration;
public runTransaction(param0: com.google.firebase.firestore.Transaction.Function<any>): com.google.android.gms.tasks.Task;
public batch(): com.google.firebase.firestore.WriteBatch;
public runBatch(param0: com.google.firebase.firestore.WriteBatch.Function): com.google.android.gms.tasks.Task<java.lang.Void>;
public addSnapshotsInSyncListener(param0: java.lang.Runnable): com.google.firebase.firestore.ListenerRegistration;
public setFirestoreSettings(param0: com.google.firebase.firestore.FirebaseFirestoreSettings): void;
public clearPersistence(): com.google.android.gms.tasks.Task<java.lang.Void>;
public addSnapshotsInSyncListener(param0: globalAndroid.app.Activity, param1: java.lang.Runnable): com.google.firebase.firestore.ListenerRegistration;
public terminate(): com.google.android.gms.tasks.Task<java.lang.Void>;
public getFirestoreSettings(): com.google.firebase.firestore.FirebaseFirestoreSettings;
}
export module FirebaseFirestore {
export class InstanceRegistry {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestore.InstanceRegistry>;
/**
* Constructs a new instance of the com.google.firebase.firestore.FirebaseFirestore$InstanceRegistry interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
remove(param0: string): void;
});
public constructor();
public remove(param0: string): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FirebaseFirestoreException {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestoreException>;
public constructor(param0: string, param1: com.google.firebase.firestore.FirebaseFirestoreException.Code);
public getCode(): com.google.firebase.firestore.FirebaseFirestoreException.Code;
public constructor(param0: string, param1: com.google.firebase.firestore.FirebaseFirestoreException.Code, param2: java.lang.Throwable);
}
export module FirebaseFirestoreException {
export class Code {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestoreException.Code>;
public static OK: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static CANCELLED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static UNKNOWN: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static INVALID_ARGUMENT: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static DEADLINE_EXCEEDED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static NOT_FOUND: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static ALREADY_EXISTS: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static PERMISSION_DENIED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static RESOURCE_EXHAUSTED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static FAILED_PRECONDITION: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static ABORTED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static OUT_OF_RANGE: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static UNIMPLEMENTED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static INTERNAL: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static UNAVAILABLE: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static DATA_LOSS: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static UNAUTHENTICATED: com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static fromValue(param0: number): com.google.firebase.firestore.FirebaseFirestoreException.Code;
public value(): number;
public static valueOf(param0: string): com.google.firebase.firestore.FirebaseFirestoreException.Code;
public static values(): native.Array<com.google.firebase.firestore.FirebaseFirestoreException.Code>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FirebaseFirestoreSettings {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestoreSettings>;
public static CACHE_SIZE_UNLIMITED: number;
public equals(param0: any): boolean;
public toString(): string;
public isSslEnabled(): boolean;
public areTimestampsInSnapshotsEnabled(): boolean;
public hashCode(): number;
public isPersistenceEnabled(): boolean;
public getCacheSizeBytes(): number;
public getHost(): string;
}
export module FirebaseFirestoreSettings {
export class Builder {
public static class: java.lang.Class<com.google.firebase.firestore.FirebaseFirestoreSettings.Builder>;
public setCacheSizeBytes(param0: number): com.google.firebase.firestore.FirebaseFirestoreSettings.Builder;
public constructor();
public isPersistenceEnabled(): boolean;
public getCacheSizeBytes(): number;
public setPersistenceEnabled(param0: boolean): com.google.firebase.firestore.FirebaseFirestoreSettings.Builder;
public build(): com.google.firebase.firestore.FirebaseFirestoreSettings;
public setHost(param0: string): com.google.firebase.firestore.FirebaseFirestoreSettings.Builder;
public getHost(): string;
public setTimestampsInSnapshotsEnabled(param0: boolean): com.google.firebase.firestore.FirebaseFirestoreSettings.Builder;
public isSslEnabled(): boolean;
public setSslEnabled(param0: boolean): com.google.firebase.firestore.FirebaseFirestoreSettings.Builder;
public constructor(param0: com.google.firebase.firestore.FirebaseFirestoreSettings);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FirestoreMultiDbComponent extends com.google.firebase.firestore.FirebaseFirestore.InstanceRegistry {
public static class: java.lang.Class<com.google.firebase.firestore.FirestoreMultiDbComponent>;
public remove(param0: string): void;
public onDeleted(param0: string, param1: com.google.firebase.FirebaseOptions): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class FirestoreRegistrar {
public static class: java.lang.Class<com.google.firebase.firestore.FirestoreRegistrar>;
public constructor();
public getComponents(): java.util.List<com.google.firebase.components.Component<any>>;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class GeoPoint extends java.lang.Comparable<com.google.firebase.firestore.GeoPoint> {
public static class: java.lang.Class<com.google.firebase.firestore.GeoPoint>;
public compareTo(param0: com.google.firebase.firestore.GeoPoint): number;
public equals(param0: any): boolean;
public toString(): string;
public getLatitude(): number;
public getLongitude(): number;
public hashCode(): number;
public constructor(param0: number, param1: number);
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class IgnoreExtraProperties {
public static class: java.lang.Class<com.google.firebase.firestore.IgnoreExtraProperties>;
/**
* Constructs a new instance of the com.google.firebase.firestore.IgnoreExtraProperties interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class ListenerRegistration {
public static class: java.lang.Class<com.google.firebase.firestore.ListenerRegistration>;
/**
* Constructs a new instance of the com.google.firebase.firestore.ListenerRegistration interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
remove(): void;
});
public constructor();
public remove(): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class MetadataChanges {
public static class: java.lang.Class<com.google.firebase.firestore.MetadataChanges>;
public static EXCLUDE: com.google.firebase.firestore.MetadataChanges;
public static INCLUDE: com.google.firebase.firestore.MetadataChanges;
public static valueOf(param0: string): com.google.firebase.firestore.MetadataChanges;
public static values(): native.Array<com.google.firebase.firestore.MetadataChanges>;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class PropertyName {
public static class: java.lang.Class<com.google.firebase.firestore.PropertyName>;
/**
* Constructs a new instance of the com.google.firebase.firestore.PropertyName interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class Query {
public static class: java.lang.Class<com.google.firebase.firestore.Query>;
public get(param0: com.google.firebase.firestore.Source): com.google.android.gms.tasks.Task<com.google.firebase.firestore.QuerySnapshot>;
public whereEqualTo(param0: string, param1: any): com.google.firebase.firestore.Query;
public orderBy(param0: com.google.firebase.firestore.FieldPath, param1: com.google.firebase.firestore.Query.Direction): com.google.firebase.firestore.Query;
public whereArrayContainsAny(param0: string, param1: java.util.List<any>): com.google.firebase.firestore.Query;
public endBefore(param0: com.google.firebase.firestore.DocumentSnapshot): com.google.firebase.firestore.Query;
public endAt(param0: native.Array<any>): com.google.firebase.firestore.Query;
public addSnapshotListener(param0: com.google.firebase.firestore.MetadataChanges, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public orderBy(param0: string): com.google.firebase.firestore.Query;
public whereLessThanOrEqualTo(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public whereArrayContains(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public whereLessThanOrEqualTo(param0: string, param1: any): com.google.firebase.firestore.Query;
public whereArrayContains(param0: string, param1: any): com.google.firebase.firestore.Query;
public whereEqualTo(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public whereIn(param0: string, param1: java.util.List<any>): com.google.firebase.firestore.Query;
public whereLessThan(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public whereGreaterThanOrEqualTo(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public getFirestore(): com.google.firebase.firestore.FirebaseFirestore;
public addSnapshotListener(param0: globalAndroid.app.Activity, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public orderBy(param0: com.google.firebase.firestore.FieldPath): com.google.firebase.firestore.Query;
public hashCode(): number;
public addSnapshotListener(param0: globalAndroid.app.Activity, param1: com.google.firebase.firestore.MetadataChanges, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public limit(param0: number): com.google.firebase.firestore.Query;
public whereGreaterThan(param0: string, param1: any): com.google.firebase.firestore.Query;
public addSnapshotListener(param0: java.util.concurrent.Executor, param1: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public whereGreaterThan(param0: com.google.firebase.firestore.FieldPath, param1: any): com.google.firebase.firestore.Query;
public addSnapshotListener(param0: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public whereLessThan(param0: string, param1: any): com.google.firebase.firestore.Query;
public whereArrayContainsAny(param0: com.google.firebase.firestore.FieldPath, param1: java.util.List<any>): com.google.firebase.firestore.Query;
public addSnapshotListener(param0: java.util.concurrent.Executor, param1: com.google.firebase.firestore.MetadataChanges, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.QuerySnapshot>): com.google.firebase.firestore.ListenerRegistration;
public endBefore(param0: native.Array<any>): com.google.firebase.firestore.Query;
public startAt(param0: com.google.firebase.firestore.DocumentSnapshot): com.google.firebase.firestore.Query;
public startAfter(param0: com.google.firebase.firestore.DocumentSnapshot): com.google.firebase.firestore.Query;
public whereIn(param0: com.google.firebase.firestore.FieldPath, param1: java.util.List<any>): com.google.firebase.firestore.Query;
public endAt(param0: com.google.firebase.firestore.DocumentSnapshot): com.google.firebase.firestore.Query;
public equals(param0: any): boolean;
public orderBy(param0: string, param1: com.google.firebase.firestore.Query.Direction): com.google.firebase.firestore.Query;
public startAt(param0: native.Array<any>): com.google.firebase.firestore.Query;
public get(): com.google.android.gms.tasks.Task<com.google.firebase.firestore.QuerySnapshot>;
public whereGreaterThanOrEqualTo(param0: string, param1: any): com.google.firebase.firestore.Query;
public startAfter(param0: native.Array<any>): com.google.firebase.firestore.Query;
}
export module Query {
export class Direction {
public static class: java.lang.Class<com.google.firebase.firestore.Query.Direction>;
public static ASCENDING: com.google.firebase.firestore.Query.Direction;
public static DESCENDING: com.google.firebase.firestore.Query.Direction;
public static values(): native.Array<com.google.firebase.firestore.Query.Direction>;
public static valueOf(param0: string): com.google.firebase.firestore.Query.Direction;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class QueryDocumentSnapshot extends com.google.firebase.firestore.DocumentSnapshot {
public static class: java.lang.Class<com.google.firebase.firestore.QueryDocumentSnapshot>;
public getData(param0: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): java.util.Map<string,any>;
public toObject(param0: java.lang.Class, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): any;
public getData(): java.util.Map<string,any>;
public toObject(param0: java.lang.Class): any;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class QuerySnapshot extends java.lang.Iterable<com.google.firebase.firestore.QueryDocumentSnapshot> {
public static class: java.lang.Class<com.google.firebase.firestore.QuerySnapshot>;
public equals(param0: any): boolean;
public getDocumentChanges(param0: com.google.firebase.firestore.MetadataChanges): java.util.List<com.google.firebase.firestore.DocumentChange>;
public isEmpty(): boolean;
public getDocumentChanges(): java.util.List<com.google.firebase.firestore.DocumentChange>;
public toObjects(param0: java.lang.Class): java.util.List;
public toObjects(param0: java.lang.Class, param1: com.google.firebase.firestore.DocumentSnapshot.ServerTimestampBehavior): java.util.List;
public size(): number;
public getQuery(): com.google.firebase.firestore.Query;
public hashCode(): number;
public getMetadata(): com.google.firebase.firestore.SnapshotMetadata;
public getDocuments(): java.util.List<com.google.firebase.firestore.DocumentSnapshot>;
public iterator(): java.util.Iterator<com.google.firebase.firestore.QueryDocumentSnapshot>;
}
export module QuerySnapshot {
export class QuerySnapshotIterator extends java.util.Iterator<com.google.firebase.firestore.QueryDocumentSnapshot> {
public static class: java.lang.Class<com.google.firebase.firestore.QuerySnapshot.QuerySnapshotIterator>;
public next(): com.google.firebase.firestore.QueryDocumentSnapshot;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class ServerTimestamp {
public static class: java.lang.Class<com.google.firebase.firestore.ServerTimestamp>;
/**
* Constructs a new instance of the com.google.firebase.firestore.ServerTimestamp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class SetOptions {
public static class: java.lang.Class<com.google.firebase.firestore.SetOptions>;
public getFieldMask(): com.google.firebase.firestore.model.mutation.FieldMask;
public equals(param0: any): boolean;
public static mergeFields(param0: java.util.List<string>): com.google.firebase.firestore.SetOptions;
public static merge(): com.google.firebase.firestore.SetOptions;
public static mergeFields(param0: native.Array<string>): com.google.firebase.firestore.SetOptions;
public hashCode(): number;
public static mergeFieldPaths(param0: java.util.List<com.google.firebase.firestore.FieldPath>): com.google.firebase.firestore.SetOptions;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class SnapshotMetadata {
public static class: java.lang.Class<com.google.firebase.firestore.SnapshotMetadata>;
public equals(param0: any): boolean;
public toString(): string;
public isFromCache(): boolean;
public hashCode(): number;
public hasPendingWrites(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class Source {
public static class: java.lang.Class<com.google.firebase.firestore.Source>;
public static DEFAULT: com.google.firebase.firestore.Source;
public static SERVER: com.google.firebase.firestore.Source;
public static CACHE: com.google.firebase.firestore.Source;
public static values(): native.Array<com.google.firebase.firestore.Source>;
public static valueOf(param0: string): com.google.firebase.firestore.Source;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class ThrowOnExtraProperties {
public static class: java.lang.Class<com.google.firebase.firestore.ThrowOnExtraProperties>;
/**
* Constructs a new instance of the com.google.firebase.firestore.ThrowOnExtraProperties interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class Transaction {
public static class: java.lang.Class<com.google.firebase.firestore.Transaction>;
public set(param0: com.google.firebase.firestore.DocumentReference, param1: any): com.google.firebase.firestore.Transaction;
public delete(param0: com.google.firebase.firestore.DocumentReference): com.google.firebase.firestore.Transaction;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: com.google.firebase.firestore.FieldPath, param2: any, param3: native.Array<any>): com.google.firebase.firestore.Transaction;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: string, param2: any, param3: native.Array<any>): com.google.firebase.firestore.Transaction;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: java.util.Map<string,any>): com.google.firebase.firestore.Transaction;
public set(param0: com.google.firebase.firestore.DocumentReference, param1: any, param2: com.google.firebase.firestore.SetOptions): com.google.firebase.firestore.Transaction;
public get(param0: com.google.firebase.firestore.DocumentReference): com.google.firebase.firestore.DocumentSnapshot;
}
export module Transaction {
export class Function<TResult> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.Transaction.Function<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.Transaction$Function interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
apply(param0: com.google.firebase.firestore.Transaction): TResult;
});
public constructor();
public apply(param0: com.google.firebase.firestore.Transaction): TResult;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class UserDataConverter {
public static class: java.lang.Class<com.google.firebase.firestore.UserDataConverter>;
public parseMergeData(param0: any, param1: com.google.firebase.firestore.model.mutation.FieldMask): com.google.firebase.firestore.core.UserData.ParsedSetData;
public parseUpdateData(param0: java.util.Map<string,any>): com.google.firebase.firestore.core.UserData.ParsedUpdateData;
public constructor(param0: com.google.firebase.firestore.model.DatabaseId);
public parseSetData(param0: any): com.google.firebase.firestore.core.UserData.ParsedSetData;
public parseUpdateData(param0: java.util.List<any>): com.google.firebase.firestore.core.UserData.ParsedUpdateData;
public parseQueryValue(param0: any): com.google.firebase.firestore.model.value.FieldValue;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export class WriteBatch {
public static class: java.lang.Class<com.google.firebase.firestore.WriteBatch>;
public set(param0: com.google.firebase.firestore.DocumentReference, param1: any): com.google.firebase.firestore.WriteBatch;
public set(param0: com.google.firebase.firestore.DocumentReference, param1: any, param2: com.google.firebase.firestore.SetOptions): com.google.firebase.firestore.WriteBatch;
public delete(param0: com.google.firebase.firestore.DocumentReference): com.google.firebase.firestore.WriteBatch;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: com.google.firebase.firestore.FieldPath, param2: any, param3: native.Array<any>): com.google.firebase.firestore.WriteBatch;
public commit(): com.google.android.gms.tasks.Task<java.lang.Void>;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: string, param2: any, param3: native.Array<any>): com.google.firebase.firestore.WriteBatch;
public update(param0: com.google.firebase.firestore.DocumentReference, param1: java.util.Map<string,any>): com.google.firebase.firestore.WriteBatch;
}
export module WriteBatch {
export class Function {
public static class: java.lang.Class<com.google.firebase.firestore.WriteBatch.Function>;
/**
* Constructs a new instance of the com.google.firebase.firestore.WriteBatch$Function interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
apply(param0: com.google.firebase.firestore.WriteBatch): void;
});
public constructor();
public apply(param0: com.google.firebase.firestore.WriteBatch): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module auth {
export abstract class CredentialsProvider {
public static class: java.lang.Class<com.google.firebase.firestore.auth.CredentialsProvider>;
public constructor();
public removeChangeListener(): void;
public invalidateToken(): void;
public setChangeListener(param0: com.google.firebase.firestore.util.Listener<com.google.firebase.firestore.auth.User>): void;
public getToken(): com.google.android.gms.tasks.Task<string>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module auth {
export class EmptyCredentialsProvider extends com.google.firebase.firestore.auth.CredentialsProvider {
public static class: java.lang.Class<com.google.firebase.firestore.auth.EmptyCredentialsProvider>;
public constructor();
public removeChangeListener(): void;
public invalidateToken(): void;
public setChangeListener(param0: com.google.firebase.firestore.util.Listener<com.google.firebase.firestore.auth.User>): void;
public getToken(): com.google.android.gms.tasks.Task<string>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module auth {
export class FirebaseAuthCredentialsProvider extends com.google.firebase.firestore.auth.CredentialsProvider {
public static class: java.lang.Class<com.google.firebase.firestore.auth.FirebaseAuthCredentialsProvider>;
public constructor();
public constructor(param0: com.google.firebase.auth.internal.InternalAuthProvider);
public removeChangeListener(): void;
public invalidateToken(): void;
public setChangeListener(param0: com.google.firebase.firestore.util.Listener<com.google.firebase.firestore.auth.User>): void;
public getToken(): com.google.android.gms.tasks.Task<string>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module auth {
export class Token {
public static class: java.lang.Class<com.google.firebase.firestore.auth.Token>;
public constructor(param0: string, param1: com.google.firebase.firestore.auth.User);
public getUser(): com.google.firebase.firestore.auth.User;
public getValue(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module auth {
export class User {
public static class: java.lang.Class<com.google.firebase.firestore.auth.User>;
public static UNAUTHENTICATED: com.google.firebase.firestore.auth.User;
public getUid(): string;
public isAuthenticated(): boolean;
public equals(param0: any): boolean;
public hashCode(): number;
public toString(): string;
public constructor(param0: string);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ActivityScope {
public static class: java.lang.Class<com.google.firebase.firestore.core.ActivityScope>;
public constructor();
public static bind(param0: globalAndroid.app.Activity, param1: com.google.firebase.firestore.ListenerRegistration): com.google.firebase.firestore.ListenerRegistration;
}
export module ActivityScope {
export class CallbackList {
public static class: java.lang.Class<com.google.firebase.firestore.core.ActivityScope.CallbackList>;
}
export class StopListenerFragment {
public static class: java.lang.Class<com.google.firebase.firestore.core.ActivityScope.StopListenerFragment>;
public constructor();
public onStop(): void;
}
export class StopListenerSupportFragment {
public static class: java.lang.Class<com.google.firebase.firestore.core.ActivityScope.StopListenerSupportFragment>;
public constructor();
public onStop(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ArrayContainsAnyFilter extends com.google.firebase.firestore.core.FieldFilter {
public static class: java.lang.Class<com.google.firebase.firestore.core.ArrayContainsAnyFilter>;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ArrayContainsFilter extends com.google.firebase.firestore.core.FieldFilter {
public static class: java.lang.Class<com.google.firebase.firestore.core.ArrayContainsFilter>;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class AsyncEventListener<T> extends com.google.firebase.firestore.EventListener<any> {
public static class: java.lang.Class<com.google.firebase.firestore.core.AsyncEventListener<any>>;
public constructor(param0: java.util.concurrent.Executor, param1: com.google.firebase.firestore.EventListener<any>);
public mute(): void;
public onEvent(param0: any, param1: com.google.firebase.firestore.FirebaseFirestoreException): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class Bound {
public static class: java.lang.Class<com.google.firebase.firestore.core.Bound>;
public sortsBeforeDocument(param0: java.util.List<com.google.firebase.firestore.core.OrderBy>, param1: com.google.firebase.firestore.model.Document): boolean;
public canonicalString(): string;
public equals(param0: any): boolean;
public hashCode(): number;
public isBefore(): boolean;
public constructor(param0: java.util.List<com.google.firebase.firestore.model.value.FieldValue>, param1: boolean);
public getPosition(): java.util.List<com.google.firebase.firestore.model.value.FieldValue>;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class DatabaseInfo {
public static class: java.lang.Class<com.google.firebase.firestore.core.DatabaseInfo>;
public getHost(): string;
public isSslEnabled(): boolean;
public constructor(param0: com.google.firebase.firestore.model.DatabaseId, param1: string, param2: string, param3: boolean);
public getDatabaseId(): com.google.firebase.firestore.model.DatabaseId;
public toString(): string;
public getPersistenceKey(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class DocumentViewChange {
public static class: java.lang.Class<com.google.firebase.firestore.core.DocumentViewChange>;
public static create(param0: com.google.firebase.firestore.core.DocumentViewChange.Type, param1: com.google.firebase.firestore.model.Document): com.google.firebase.firestore.core.DocumentViewChange;
public getDocument(): com.google.firebase.firestore.model.Document;
public equals(param0: any): boolean;
public hashCode(): number;
public getType(): com.google.firebase.firestore.core.DocumentViewChange.Type;
public toString(): string;
}
export module DocumentViewChange {
export class Type {
public static class: java.lang.Class<com.google.firebase.firestore.core.DocumentViewChange.Type>;
public static REMOVED: com.google.firebase.firestore.core.DocumentViewChange.Type;
public static ADDED: com.google.firebase.firestore.core.DocumentViewChange.Type;
public static MODIFIED: com.google.firebase.firestore.core.DocumentViewChange.Type;
public static METADATA: com.google.firebase.firestore.core.DocumentViewChange.Type;
public static valueOf(param0: string): com.google.firebase.firestore.core.DocumentViewChange.Type;
public static values(): native.Array<com.google.firebase.firestore.core.DocumentViewChange.Type>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class DocumentViewChangeSet {
public static class: java.lang.Class<com.google.firebase.firestore.core.DocumentViewChangeSet>;
public constructor();
public addChange(param0: com.google.firebase.firestore.core.DocumentViewChange): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class EventManager extends com.google.firebase.firestore.core.SyncEngine.SyncEngineCallback {
public static class: java.lang.Class<com.google.firebase.firestore.core.EventManager>;
public onError(param0: com.google.firebase.firestore.core.Query, param1: io.grpc.Status): void;
public removeQueryListener(param0: com.google.firebase.firestore.core.QueryListener): void;
public removeSnapshotsInSyncListener(param0: com.google.firebase.firestore.EventListener<java.lang.Void>): void;
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
public constructor(param0: com.google.firebase.firestore.core.SyncEngine);
public addQueryListener(param0: com.google.firebase.firestore.core.QueryListener): number;
public addSnapshotsInSyncListener(param0: com.google.firebase.firestore.EventListener<java.lang.Void>): void;
public onViewSnapshots(param0: java.util.List<com.google.firebase.firestore.core.ViewSnapshot>): void;
}
export module EventManager {
export class ListenOptions {
public static class: java.lang.Class<com.google.firebase.firestore.core.EventManager.ListenOptions>;
public includeDocumentMetadataChanges: boolean;
public includeQueryMetadataChanges: boolean;
public waitForSyncWhenOnline: boolean;
public constructor();
}
export class QueryListenersInfo {
public static class: java.lang.Class<com.google.firebase.firestore.core.EventManager.QueryListenersInfo>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class FieldFilter extends com.google.firebase.firestore.core.Filter {
public static class: java.lang.Class<com.google.firebase.firestore.core.FieldFilter>;
public isInequality(): boolean;
public constructor();
public getValue(): com.google.firebase.firestore.model.value.FieldValue;
public equals(param0: any): boolean;
public hashCode(): number;
public constructor(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.core.Filter.Operator, param2: com.google.firebase.firestore.model.value.FieldValue);
public static create(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.core.Filter.Operator, param2: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.core.FieldFilter;
public toString(): string;
public getField(): com.google.firebase.firestore.model.FieldPath;
public getCanonicalId(): string;
public getOperator(): com.google.firebase.firestore.core.Filter.Operator;
public matchesComparison(param0: number): boolean;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export abstract class Filter {
public static class: java.lang.Class<com.google.firebase.firestore.core.Filter>;
public getField(): com.google.firebase.firestore.model.FieldPath;
public getCanonicalId(): string;
public constructor();
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
export module Filter {
export class Operator {
public static class: java.lang.Class<com.google.firebase.firestore.core.Filter.Operator>;
public static LESS_THAN: com.google.firebase.firestore.core.Filter.Operator;
public static LESS_THAN_OR_EQUAL: com.google.firebase.firestore.core.Filter.Operator;
public static EQUAL: com.google.firebase.firestore.core.Filter.Operator;
public static GREATER_THAN: com.google.firebase.firestore.core.Filter.Operator;
public static GREATER_THAN_OR_EQUAL: com.google.firebase.firestore.core.Filter.Operator;
public static ARRAY_CONTAINS: com.google.firebase.firestore.core.Filter.Operator;
public static ARRAY_CONTAINS_ANY: com.google.firebase.firestore.core.Filter.Operator;
public static IN: com.google.firebase.firestore.core.Filter.Operator;
public static valueOf(param0: string): com.google.firebase.firestore.core.Filter.Operator;
public toString(): string;
public static values(): native.Array<com.google.firebase.firestore.core.Filter.Operator>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class FirestoreClient extends com.google.firebase.firestore.remote.RemoteStore.RemoteStoreCallback {
public static class: java.lang.Class<com.google.firebase.firestore.core.FirestoreClient>;
public terminate(): com.google.android.gms.tasks.Task<java.lang.Void>;
public isTerminated(): boolean;
public removeSnapshotsInSyncListener(param0: com.google.firebase.firestore.EventListener<java.lang.Void>): void;
public disableNetwork(): com.google.android.gms.tasks.Task<java.lang.Void>;
public handleRejectedListen(param0: number, param1: io.grpc.Status): void;
public getDocumentFromLocalCache(param0: com.google.firebase.firestore.model.DocumentKey): com.google.android.gms.tasks.Task<com.google.firebase.firestore.model.Document>;
public handleRejectedWrite(param0: number, param1: io.grpc.Status): void;
public stopListening(param0: com.google.firebase.firestore.core.QueryListener): void;
public listen(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.core.EventManager.ListenOptions, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.core.ViewSnapshot>): com.google.firebase.firestore.core.QueryListener;
public enableNetwork(): com.google.android.gms.tasks.Task<java.lang.Void>;
public write(param0: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.android.gms.tasks.Task<java.lang.Void>;
public handleRemoteEvent(param0: com.google.firebase.firestore.remote.RemoteEvent): void;
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
public handleSuccessfulWrite(param0: com.google.firebase.firestore.model.mutation.MutationBatchResult): void;
public constructor(param0: globalAndroid.content.Context, param1: com.google.firebase.firestore.core.DatabaseInfo, param2: com.google.firebase.firestore.FirebaseFirestoreSettings, param3: com.google.firebase.firestore.auth.CredentialsProvider, param4: com.google.firebase.firestore.util.AsyncQueue, param5: com.google.firebase.firestore.remote.GrpcMetadataProvider);
public getDocumentsFromLocalCache(param0: com.google.firebase.firestore.core.Query): com.google.android.gms.tasks.Task<com.google.firebase.firestore.core.ViewSnapshot>;
public waitForPendingWrites(): com.google.android.gms.tasks.Task<java.lang.Void>;
public getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public addSnapshotsInSyncListener(param0: com.google.firebase.firestore.EventListener<java.lang.Void>): void;
public transaction(param0: com.google.common.base.Function): com.google.android.gms.tasks.Task;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class InFilter extends com.google.firebase.firestore.core.FieldFilter {
public static class: java.lang.Class<com.google.firebase.firestore.core.InFilter>;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class IndexRange {
public static class: java.lang.Class<com.google.firebase.firestore.core.IndexRange>;
public getStart(): com.google.firebase.firestore.model.value.FieldValue;
public getEnd(): com.google.firebase.firestore.model.value.FieldValue;
public getFieldPath(): com.google.firebase.firestore.model.FieldPath;
public static builder(): com.google.firebase.firestore.core.IndexRange.Builder;
}
export module IndexRange {
export class Builder {
public static class: java.lang.Class<com.google.firebase.firestore.core.IndexRange.Builder>;
public constructor();
public setStart(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.core.IndexRange.Builder;
public build(): com.google.firebase.firestore.core.IndexRange;
public setFieldPath(param0: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.core.IndexRange.Builder;
public setEnd(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.core.IndexRange.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class KeyFieldFilter extends com.google.firebase.firestore.core.FieldFilter {
public static class: java.lang.Class<com.google.firebase.firestore.core.KeyFieldFilter>;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class KeyFieldInFilter extends com.google.firebase.firestore.core.FieldFilter {
public static class: java.lang.Class<com.google.firebase.firestore.core.KeyFieldInFilter>;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class LimboDocumentChange {
public static class: java.lang.Class<com.google.firebase.firestore.core.LimboDocumentChange>;
public constructor(param0: com.google.firebase.firestore.core.LimboDocumentChange.Type, param1: com.google.firebase.firestore.model.DocumentKey);
public equals(param0: any): boolean;
public hashCode(): number;
public getType(): com.google.firebase.firestore.core.LimboDocumentChange.Type;
public getKey(): com.google.firebase.firestore.model.DocumentKey;
}
export module LimboDocumentChange {
export class Type {
public static class: java.lang.Class<com.google.firebase.firestore.core.LimboDocumentChange.Type>;
public static ADDED: com.google.firebase.firestore.core.LimboDocumentChange.Type;
public static REMOVED: com.google.firebase.firestore.core.LimboDocumentChange.Type;
public static values(): native.Array<com.google.firebase.firestore.core.LimboDocumentChange.Type>;
public static valueOf(param0: string): com.google.firebase.firestore.core.LimboDocumentChange.Type;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ListenSequence {
public static class: java.lang.Class<com.google.firebase.firestore.core.ListenSequence>;
public static INVALID: number;
public next(): number;
public constructor(param0: number);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ListenerRegistrationImpl extends com.google.firebase.firestore.ListenerRegistration {
public static class: java.lang.Class<com.google.firebase.firestore.core.ListenerRegistrationImpl>;
public constructor(param0: com.google.firebase.firestore.core.FirestoreClient, param1: com.google.firebase.firestore.core.QueryListener, param2: com.google.firebase.firestore.core.AsyncEventListener<com.google.firebase.firestore.core.ViewSnapshot>);
public remove(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class OnlineState {
public static class: java.lang.Class<com.google.firebase.firestore.core.OnlineState>;
public static UNKNOWN: com.google.firebase.firestore.core.OnlineState;
public static ONLINE: com.google.firebase.firestore.core.OnlineState;
public static OFFLINE: com.google.firebase.firestore.core.OnlineState;
public static values(): native.Array<com.google.firebase.firestore.core.OnlineState>;
public static valueOf(param0: string): com.google.firebase.firestore.core.OnlineState;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class OrderBy {
public static class: java.lang.Class<com.google.firebase.firestore.core.OrderBy>;
public getField(): com.google.firebase.firestore.model.FieldPath;
public getDirection(): com.google.firebase.firestore.core.OrderBy.Direction;
public static getInstance(param0: com.google.firebase.firestore.core.OrderBy.Direction, param1: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.core.OrderBy;
public equals(param0: any): boolean;
public hashCode(): number;
public toString(): string;
}
export module OrderBy {
export class Direction {
public static class: java.lang.Class<com.google.firebase.firestore.core.OrderBy.Direction>;
public static ASCENDING: com.google.firebase.firestore.core.OrderBy.Direction;
public static DESCENDING: com.google.firebase.firestore.core.OrderBy.Direction;
public static valueOf(param0: string): com.google.firebase.firestore.core.OrderBy.Direction;
public static values(): native.Array<com.google.firebase.firestore.core.OrderBy.Direction>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class Query {
public static class: java.lang.Class<com.google.firebase.firestore.core.Query>;
public static NO_LIMIT: number;
public constructor(param0: com.google.firebase.firestore.model.ResourcePath, param1: string);
public getPath(): com.google.firebase.firestore.model.ResourcePath;
public comparator(): java.util.Comparator<com.google.firebase.firestore.model.Document>;
public getFirstOrderByField(): com.google.firebase.firestore.model.FieldPath;
public startAt(param0: com.google.firebase.firestore.core.Bound): com.google.firebase.firestore.core.Query;
public equals(param0: any): boolean;
public hashCode(): number;
public constructor(param0: com.google.firebase.firestore.model.ResourcePath, param1: string, param2: java.util.List<com.google.firebase.firestore.core.Filter>, param3: java.util.List<com.google.firebase.firestore.core.OrderBy>, param4: number, param5: com.google.firebase.firestore.core.Bound, param6: com.google.firebase.firestore.core.Bound);
public isDocumentQuery(): boolean;
public getCanonicalId(): string;
public asCollectionQueryAtPath(param0: com.google.firebase.firestore.model.ResourcePath): com.google.firebase.firestore.core.Query;
public static atPath(param0: com.google.firebase.firestore.model.ResourcePath): com.google.firebase.firestore.core.Query;
public inequalityField(): com.google.firebase.firestore.model.FieldPath;
public getOrderBy(): java.util.List<com.google.firebase.firestore.core.OrderBy>;
public filter(param0: com.google.firebase.firestore.core.Filter): com.google.firebase.firestore.core.Query;
public endAt(param0: com.google.firebase.firestore.core.Bound): com.google.firebase.firestore.core.Query;
public getLimit(): number;
public matchesAllDocuments(): boolean;
public getExplicitOrderBy(): java.util.List<com.google.firebase.firestore.core.OrderBy>;
public hasLimit(): boolean;
public limit(param0: number): com.google.firebase.firestore.core.Query;
public findFilterOperator(param0: java.util.List<com.google.firebase.firestore.core.Filter.Operator>): com.google.firebase.firestore.core.Filter.Operator;
public getCollectionGroup(): string;
public toString(): string;
public orderBy(param0: com.google.firebase.firestore.core.OrderBy): com.google.firebase.firestore.core.Query;
public getFilters(): java.util.List<com.google.firebase.firestore.core.Filter>;
public getEndAt(): com.google.firebase.firestore.core.Bound;
public isCollectionGroupQuery(): boolean;
public getStartAt(): com.google.firebase.firestore.core.Bound;
public matches(param0: com.google.firebase.firestore.model.Document): boolean;
}
export module Query {
export class QueryComparator extends java.util.Comparator<com.google.firebase.firestore.model.Document> {
public static class: java.lang.Class<com.google.firebase.firestore.core.Query.QueryComparator>;
public compare(param0: com.google.firebase.firestore.model.Document, param1: com.google.firebase.firestore.model.Document): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class QueryListener {
public static class: java.lang.Class<com.google.firebase.firestore.core.QueryListener>;
public constructor(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.core.EventManager.ListenOptions, param2: com.google.firebase.firestore.EventListener<com.google.firebase.firestore.core.ViewSnapshot>);
public getQuery(): com.google.firebase.firestore.core.Query;
public onViewSnapshot(param0: com.google.firebase.firestore.core.ViewSnapshot): boolean;
public onOnlineStateChanged(param0: com.google.firebase.firestore.core.OnlineState): boolean;
public onError(param0: com.google.firebase.firestore.FirebaseFirestoreException): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class QueryView {
public static class: java.lang.Class<com.google.firebase.firestore.core.QueryView>;
public getQuery(): com.google.firebase.firestore.core.Query;
public getTargetId(): number;
public getView(): com.google.firebase.firestore.core.View;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class SyncEngine extends com.google.firebase.firestore.remote.RemoteStore.RemoteStoreCallback {
public static class: java.lang.Class<com.google.firebase.firestore.core.SyncEngine>;
public registerPendingWritesTask(param0: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void;
public writeMutations(param0: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void;
public getCurrentLimboDocuments(): java.util.Map<com.google.firebase.firestore.model.DocumentKey,java.lang.Integer>;
public constructor(param0: com.google.firebase.firestore.local.LocalStore, param1: com.google.firebase.firestore.remote.RemoteStore, param2: com.google.firebase.firestore.auth.User);
public handleRejectedListen(param0: number, param1: io.grpc.Status): void;
public transaction(param0: com.google.firebase.firestore.util.AsyncQueue, param1: com.google.common.base.Function): com.google.android.gms.tasks.Task;
public handleRejectedWrite(param0: number, param1: io.grpc.Status): void;
public handleCredentialChange(param0: com.google.firebase.firestore.auth.User): void;
public handleRemoteEvent(param0: com.google.firebase.firestore.remote.RemoteEvent): void;
public setCallback(param0: com.google.firebase.firestore.core.SyncEngine.SyncEngineCallback): void;
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
public handleSuccessfulWrite(param0: com.google.firebase.firestore.model.mutation.MutationBatchResult): void;
public getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public listen(param0: com.google.firebase.firestore.core.Query): number;
}
export module SyncEngine {
export class LimboResolution {
public static class: java.lang.Class<com.google.firebase.firestore.core.SyncEngine.LimboResolution>;
}
export class SyncEngineCallback {
public static class: java.lang.Class<com.google.firebase.firestore.core.SyncEngine.SyncEngineCallback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.core.SyncEngine$SyncEngineCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onViewSnapshots(param0: java.util.List<com.google.firebase.firestore.core.ViewSnapshot>): void;
onError(param0: com.google.firebase.firestore.core.Query, param1: io.grpc.Status): void;
handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
});
public constructor();
public onViewSnapshots(param0: java.util.List<com.google.firebase.firestore.core.ViewSnapshot>): void;
public onError(param0: com.google.firebase.firestore.core.Query, param1: io.grpc.Status): void;
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class TargetIdGenerator {
public static class: java.lang.Class<com.google.firebase.firestore.core.TargetIdGenerator>;
public static forSyncEngine(): com.google.firebase.firestore.core.TargetIdGenerator;
public static forQueryCache(param0: number): com.google.firebase.firestore.core.TargetIdGenerator;
public nextId(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class Transaction {
public static class: java.lang.Class<com.google.firebase.firestore.core.Transaction>;
public set(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.core.UserData.ParsedSetData): void;
public update(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.core.UserData.ParsedUpdateData): void;
public delete(param0: com.google.firebase.firestore.model.DocumentKey): void;
public static getDefaultExecutor(): java.util.concurrent.Executor;
public lookup(param0: java.util.List<com.google.firebase.firestore.model.DocumentKey>): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.firestore.model.MaybeDocument>>;
public commit(): com.google.android.gms.tasks.Task<java.lang.Void>;
public constructor(param0: com.google.firebase.firestore.remote.Datastore);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class TransactionRunner<TResult> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.core.TransactionRunner<any>>;
public constructor(param0: com.google.firebase.firestore.util.AsyncQueue, param1: com.google.firebase.firestore.remote.RemoteStore, param2: com.google.common.base.Function<com.google.firebase.firestore.core.Transaction,com.google.android.gms.tasks.Task<TResult>>);
public run(): com.google.android.gms.tasks.Task<TResult>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class UserData {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData>;
}
export module UserData {
export class ParseAccumulator {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData.ParseAccumulator>;
public toMergeData(param0: com.google.firebase.firestore.model.value.ObjectValue): com.google.firebase.firestore.core.UserData.ParsedSetData;
public toMergeData(param0: com.google.firebase.firestore.model.value.ObjectValue, param1: com.google.firebase.firestore.model.mutation.FieldMask): com.google.firebase.firestore.core.UserData.ParsedSetData;
public getDataSource(): com.google.firebase.firestore.core.UserData.Source;
public toUpdateData(param0: com.google.firebase.firestore.model.value.ObjectValue): com.google.firebase.firestore.core.UserData.ParsedUpdateData;
public getFieldTransforms(): java.util.List<com.google.firebase.firestore.model.mutation.FieldTransform>;
public contains(param0: com.google.firebase.firestore.model.FieldPath): boolean;
public toSetData(param0: com.google.firebase.firestore.model.value.ObjectValue): com.google.firebase.firestore.core.UserData.ParsedSetData;
public constructor(param0: com.google.firebase.firestore.core.UserData.Source);
public rootContext(): com.google.firebase.firestore.core.UserData.ParseContext;
}
export class ParseContext {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData.ParseContext>;
public childContext(param0: string): com.google.firebase.firestore.core.UserData.ParseContext;
public getDataSource(): com.google.firebase.firestore.core.UserData.Source;
public isArrayElement(): boolean;
public isWrite(): boolean;
public childContext(param0: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.core.UserData.ParseContext;
public getPath(): com.google.firebase.firestore.model.FieldPath;
public addToFieldMask(param0: com.google.firebase.firestore.model.FieldPath): void;
public createError(param0: string): java.lang.RuntimeException;
public childContext(param0: number): com.google.firebase.firestore.core.UserData.ParseContext;
public addToFieldTransforms(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.model.mutation.TransformOperation): void;
}
export class ParsedSetData {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData.ParsedSetData>;
public toMutationList(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.mutation.Precondition): java.util.List<com.google.firebase.firestore.model.mutation.Mutation>;
}
export class ParsedUpdateData {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData.ParsedUpdateData>;
public getFieldTransforms(): java.util.List<com.google.firebase.firestore.model.mutation.FieldTransform>;
public toMutationList(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.mutation.Precondition): java.util.List<com.google.firebase.firestore.model.mutation.Mutation>;
}
export class Source {
public static class: java.lang.Class<com.google.firebase.firestore.core.UserData.Source>;
public static Set: com.google.firebase.firestore.core.UserData.Source;
public static MergeSet: com.google.firebase.firestore.core.UserData.Source;
public static Update: com.google.firebase.firestore.core.UserData.Source;
public static Argument: com.google.firebase.firestore.core.UserData.Source;
public static values(): native.Array<com.google.firebase.firestore.core.UserData.Source>;
public static valueOf(param0: string): com.google.firebase.firestore.core.UserData.Source;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class View {
public static class: java.lang.Class<com.google.firebase.firestore.core.View>;
public applyChanges(param0: com.google.firebase.firestore.core.View.DocumentChanges): com.google.firebase.firestore.core.ViewChange;
public applyOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): com.google.firebase.firestore.core.ViewChange;
public constructor(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>);
public applyChanges(param0: com.google.firebase.firestore.core.View.DocumentChanges, param1: com.google.firebase.firestore.remote.TargetChange): com.google.firebase.firestore.core.ViewChange;
public computeDocChanges(param0: com.google.firebase.database.collection.ImmutableSortedMap, param1: com.google.firebase.firestore.core.View.DocumentChanges): com.google.firebase.firestore.core.View.DocumentChanges;
public computeDocChanges(param0: com.google.firebase.database.collection.ImmutableSortedMap): com.google.firebase.firestore.core.View.DocumentChanges;
}
export module View {
export class DocumentChanges {
public static class: java.lang.Class<com.google.firebase.firestore.core.View.DocumentChanges>;
public needsRefill(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ViewChange {
public static class: java.lang.Class<com.google.firebase.firestore.core.ViewChange>;
public getLimboChanges(): java.util.List<com.google.firebase.firestore.core.LimboDocumentChange>;
public getSnapshot(): com.google.firebase.firestore.core.ViewSnapshot;
public constructor(param0: com.google.firebase.firestore.core.ViewSnapshot, param1: java.util.List<com.google.firebase.firestore.core.LimboDocumentChange>);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module core {
export class ViewSnapshot {
public static class: java.lang.Class<com.google.firebase.firestore.core.ViewSnapshot>;
public equals(param0: any): boolean;
public hashCode(): number;
public getOldDocuments(): com.google.firebase.firestore.model.DocumentSet;
public excludesMetadataChanges(): boolean;
public getMutatedKeys(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public toString(): string;
public getQuery(): com.google.firebase.firestore.core.Query;
public constructor(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.DocumentSet, param2: com.google.firebase.firestore.model.DocumentSet, param3: java.util.List<com.google.firebase.firestore.core.DocumentViewChange>, param4: boolean, param5: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param6: boolean, param7: boolean);
public isFromCache(): boolean;
public static fromInitialDocuments(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.DocumentSet, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param3: boolean, param4: boolean): com.google.firebase.firestore.core.ViewSnapshot;
public getChanges(): java.util.List<com.google.firebase.firestore.core.DocumentViewChange>;
public hasPendingWrites(): boolean;
public getDocuments(): com.google.firebase.firestore.model.DocumentSet;
public didSyncStateChange(): boolean;
}
export module ViewSnapshot {
export class SyncState {
public static class: java.lang.Class<com.google.firebase.firestore.core.ViewSnapshot.SyncState>;
public static NONE: com.google.firebase.firestore.core.ViewSnapshot.SyncState;
public static LOCAL: com.google.firebase.firestore.core.ViewSnapshot.SyncState;
public static SYNCED: com.google.firebase.firestore.core.ViewSnapshot.SyncState;
public static values(): native.Array<com.google.firebase.firestore.core.ViewSnapshot.SyncState>;
public static valueOf(param0: string): com.google.firebase.firestore.core.ViewSnapshot.SyncState;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class DocumentReference {
public static class: java.lang.Class<com.google.firebase.firestore.local.DocumentReference>;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: number);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class EncodedPath {
public static class: java.lang.Class<com.google.firebase.firestore.local.EncodedPath>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class IndexCursor {
public static class: java.lang.Class<com.google.firebase.firestore.local.IndexCursor>;
public constructor();
public close(): void;
public getDocumentKey(): com.google.firebase.firestore.model.DocumentKey;
public next(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class IndexFreeQueryEngine extends com.google.firebase.firestore.local.QueryEngine {
public static class: java.lang.Class<com.google.firebase.firestore.local.IndexFreeQueryEngine>;
public constructor();
public handleDocumentChange(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument): void;
public getDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public setLocalDocumentsView(param0: com.google.firebase.firestore.local.LocalDocumentsView): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class IndexManager {
public static class: java.lang.Class<com.google.firebase.firestore.local.IndexManager>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.IndexManager interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
addToCollectionParentIndex(param0: com.google.firebase.firestore.model.ResourcePath): void;
getCollectionParents(param0: string): java.util.List<com.google.firebase.firestore.model.ResourcePath>;
});
public constructor();
public getCollectionParents(param0: string): java.util.List<com.google.firebase.firestore.model.ResourcePath>;
public addToCollectionParentIndex(param0: com.google.firebase.firestore.model.ResourcePath): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class IndexedQueryEngine extends com.google.firebase.firestore.local.QueryEngine {
public static class: java.lang.Class<com.google.firebase.firestore.local.IndexedQueryEngine>;
public handleDocumentChange(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument): void;
public getDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public setLocalDocumentsView(param0: com.google.firebase.firestore.local.LocalDocumentsView): void;
public constructor(param0: com.google.firebase.firestore.local.SQLiteCollectionIndex);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LocalDocumentsView {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalDocumentsView>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LocalSerializer {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalSerializer>;
public constructor(param0: com.google.firebase.firestore.remote.RemoteSerializer);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LocalStore {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalStore>;
public getHighestUnacknowledgedBatchId(): number;
public getLastStreamToken(): com.google.protobuf.ByteString;
public constructor(param0: com.google.firebase.firestore.local.Persistence, param1: com.google.firebase.firestore.local.QueryEngine, param2: com.google.firebase.firestore.auth.User);
public applyRemoteEvent(param0: com.google.firebase.firestore.remote.RemoteEvent): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public handleUserChange(param0: com.google.firebase.firestore.auth.User): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getNextMutationBatch(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public acknowledgeBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatchResult): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getRemoteDocumentKeys(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public notifyLocalViewChanges(param0: java.util.List<com.google.firebase.firestore.local.LocalViewChanges>): void;
public getLastRemoteSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public allocateQuery(param0: com.google.firebase.firestore.core.Query): com.google.firebase.firestore.local.QueryData;
public releaseQuery(param0: com.google.firebase.firestore.core.Query): void;
public collectGarbage(param0: com.google.firebase.firestore.local.LruGarbageCollector): com.google.firebase.firestore.local.LruGarbageCollector.Results;
public start(): void;
public writeLocally(param0: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.firebase.firestore.local.LocalWriteResult;
public rejectBatch(param0: number): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public readDocument(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.MaybeDocument;
public executeQuery(param0: com.google.firebase.firestore.core.Query, param1: boolean): com.google.firebase.firestore.local.QueryResult;
public setLastStreamToken(param0: com.google.protobuf.ByteString): void;
}
export module LocalStore {
export class AllocateQueryHolder {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalStore.AllocateQueryHolder>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LocalViewChanges {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalViewChanges>;
public getTargetId(): number;
public static fromViewSnapshot(param0: number, param1: com.google.firebase.firestore.core.ViewSnapshot): com.google.firebase.firestore.local.LocalViewChanges;
public getAdded(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public getRemoved(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public isFromCache(): boolean;
public constructor(param0: number, param1: boolean, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param3: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LocalWriteResult {
public static class: java.lang.Class<com.google.firebase.firestore.local.LocalWriteResult>;
public getChanges(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getBatchId(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LruDelegate {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruDelegate>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.LruDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
getSequenceNumberCount(): number;
forEachOrphanedDocumentSequenceNumber(param0: com.google.firebase.firestore.util.Consumer<java.lang.Long>): void;
removeTargets(param0: number, param1: globalAndroid.util.SparseArray<any>): number;
removeOrphanedDocuments(param0: number): number;
getGarbageCollector(): com.google.firebase.firestore.local.LruGarbageCollector;
getByteSize(): number;
});
public constructor();
public forEachOrphanedDocumentSequenceNumber(param0: com.google.firebase.firestore.util.Consumer<java.lang.Long>): void;
public getByteSize(): number;
public removeTargets(param0: number, param1: globalAndroid.util.SparseArray<any>): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public getSequenceNumberCount(): number;
public getGarbageCollector(): com.google.firebase.firestore.local.LruGarbageCollector;
public removeOrphanedDocuments(param0: number): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class LruGarbageCollector {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruGarbageCollector>;
public newScheduler(param0: com.google.firebase.firestore.util.AsyncQueue, param1: com.google.firebase.firestore.local.LocalStore): com.google.firebase.firestore.local.LruGarbageCollector.Scheduler;
}
export module LruGarbageCollector {
export class Params {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruGarbageCollector.Params>;
public static WithCacheSizeBytes(param0: number): com.google.firebase.firestore.local.LruGarbageCollector.Params;
public static Default(): com.google.firebase.firestore.local.LruGarbageCollector.Params;
public static Disabled(): com.google.firebase.firestore.local.LruGarbageCollector.Params;
}
export class Results {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruGarbageCollector.Results>;
public getSequenceNumbersCollected(): number;
public getTargetsRemoved(): number;
public getDocumentsRemoved(): number;
public hasRun(): boolean;
}
export class RollingSequenceNumberBuffer {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruGarbageCollector.RollingSequenceNumberBuffer>;
}
export class Scheduler {
public static class: java.lang.Class<com.google.firebase.firestore.local.LruGarbageCollector.Scheduler>;
public constructor(param0: com.google.firebase.firestore.local.LruGarbageCollector, param1: com.google.firebase.firestore.util.AsyncQueue, param2: com.google.firebase.firestore.local.LocalStore);
public stop(): void;
public start(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryEagerReferenceDelegate extends com.google.firebase.firestore.local.ReferenceDelegate {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryEagerReferenceDelegate>;
public updateLimboDocument(param0: com.google.firebase.firestore.model.DocumentKey): void;
public addReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public removeMutationReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionCommitted(): void;
public getCurrentSequenceNumber(): number;
public removeTarget(param0: com.google.firebase.firestore.local.QueryData): void;
public setInMemoryPins(param0: com.google.firebase.firestore.local.ReferenceSet): void;
public removeReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionStarted(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryIndexManager extends com.google.firebase.firestore.local.IndexManager {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryIndexManager>;
public getCollectionParents(param0: string): java.util.List<com.google.firebase.firestore.model.ResourcePath>;
public addToCollectionParentIndex(param0: com.google.firebase.firestore.model.ResourcePath): void;
}
export module MemoryIndexManager {
export class MemoryCollectionParentIndex {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryIndexManager.MemoryCollectionParentIndex>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryLruReferenceDelegate implements com.google.firebase.firestore.local.ReferenceDelegate, com.google.firebase.firestore.local.LruDelegate {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryLruReferenceDelegate>;
public forEachOrphanedDocumentSequenceNumber(param0: com.google.firebase.firestore.util.Consumer<java.lang.Long>): void;
public getByteSize(): number;
public removeTargets(param0: number, param1: globalAndroid.util.SparseArray<any>): number;
public addReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionCommitted(): void;
public getCurrentSequenceNumber(): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public getSequenceNumberCount(): number;
public getGarbageCollector(): com.google.firebase.firestore.local.LruGarbageCollector;
public removeTarget(param0: com.google.firebase.firestore.local.QueryData): void;
public removeReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public updateLimboDocument(param0: com.google.firebase.firestore.model.DocumentKey): void;
public removeMutationReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public setInMemoryPins(param0: com.google.firebase.firestore.local.ReferenceSet): void;
public removeOrphanedDocuments(param0: number): number;
public onTransactionStarted(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryMutationQueue extends com.google.firebase.firestore.local.MutationQueue {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryMutationQueue>;
public getAllMutationBatchesAffectingDocumentKey(param0: com.google.firebase.firestore.model.DocumentKey): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getAllMutationBatchesAffectingDocumentKeys(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getLastStreamToken(): com.google.protobuf.ByteString;
public getHighestUnacknowledgedBatchId(): number;
public lookupMutationBatch(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public addMutationBatch(param0: com.google.firebase.Timestamp, param1: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param2: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.firebase.firestore.model.mutation.MutationBatch;
public acknowledgeBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch, param1: com.google.protobuf.ByteString): void;
public getAllMutationBatches(): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public performConsistencyCheck(): void;
public getAllMutationBatchesAffectingQuery(param0: com.google.firebase.firestore.core.Query): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public start(): void;
public isEmpty(): boolean;
public getNextMutationBatchAfterBatchId(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public removeMutationBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch): void;
public setLastStreamToken(param0: com.google.protobuf.ByteString): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryPersistence extends com.google.firebase.firestore.local.Persistence {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryPersistence>;
public shutdown(): void;
public start(): void;
public static createEagerGcMemoryPersistence(): com.google.firebase.firestore.local.MemoryPersistence;
public isStarted(): boolean;
public static createLruGcMemoryPersistence(param0: com.google.firebase.firestore.local.LruGarbageCollector.Params, param1: com.google.firebase.firestore.local.LocalSerializer): com.google.firebase.firestore.local.MemoryPersistence;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryQueryCache extends com.google.firebase.firestore.local.QueryCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryQueryCache>;
public removeMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public getHighestTargetId(): number;
public getTargetCount(): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public updateQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public getQueryData(param0: com.google.firebase.firestore.core.Query): com.google.firebase.firestore.local.QueryData;
public addMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public setLastRemoteSnapshotVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): void;
public getLastRemoteSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public getHighestListenSequenceNumber(): number;
public removeQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public containsKey(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
public getMatchingKeysForTargetId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public addQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MemoryRemoteDocumentCache extends com.google.firebase.firestore.local.RemoteDocumentCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryRemoteDocumentCache>;
public getAll(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getAllDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public add(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.SnapshotVersion): void;
public remove(param0: com.google.firebase.firestore.model.DocumentKey): void;
public get(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.MaybeDocument;
}
export module MemoryRemoteDocumentCache {
export class DocumentIterable extends java.lang.Iterable<com.google.firebase.firestore.model.MaybeDocument> {
public static class: java.lang.Class<com.google.firebase.firestore.local.MemoryRemoteDocumentCache.DocumentIterable>;
public iterator(): java.util.Iterator<com.google.firebase.firestore.model.MaybeDocument>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class MutationQueue {
public static class: java.lang.Class<com.google.firebase.firestore.local.MutationQueue>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.MutationQueue interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
start(): void;
isEmpty(): boolean;
acknowledgeBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch, param1: com.google.protobuf.ByteString): void;
getLastStreamToken(): com.google.protobuf.ByteString;
setLastStreamToken(param0: com.google.protobuf.ByteString): void;
addMutationBatch(param0: com.google.firebase.Timestamp, param1: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param2: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.firebase.firestore.model.mutation.MutationBatch;
lookupMutationBatch(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
getNextMutationBatchAfterBatchId(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
getHighestUnacknowledgedBatchId(): number;
getAllMutationBatches(): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
getAllMutationBatchesAffectingDocumentKey(param0: com.google.firebase.firestore.model.DocumentKey): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
getAllMutationBatchesAffectingDocumentKeys(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
getAllMutationBatchesAffectingQuery(param0: com.google.firebase.firestore.core.Query): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
removeMutationBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch): void;
performConsistencyCheck(): void;
});
public constructor();
public getAllMutationBatchesAffectingDocumentKey(param0: com.google.firebase.firestore.model.DocumentKey): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getAllMutationBatchesAffectingDocumentKeys(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getLastStreamToken(): com.google.protobuf.ByteString;
public getHighestUnacknowledgedBatchId(): number;
public lookupMutationBatch(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public addMutationBatch(param0: com.google.firebase.Timestamp, param1: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param2: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.firebase.firestore.model.mutation.MutationBatch;
public acknowledgeBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch, param1: com.google.protobuf.ByteString): void;
public getAllMutationBatches(): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public performConsistencyCheck(): void;
public getAllMutationBatchesAffectingQuery(param0: com.google.firebase.firestore.core.Query): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public start(): void;
public isEmpty(): boolean;
public getNextMutationBatchAfterBatchId(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public removeMutationBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch): void;
public setLastStreamToken(param0: com.google.protobuf.ByteString): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export abstract class Persistence {
public static class: java.lang.Class<com.google.firebase.firestore.local.Persistence>;
public static INDEXING_SUPPORT_ENABLED: boolean;
public shutdown(): void;
public start(): void;
public isStarted(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class QueryCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.QueryCache>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.QueryCache interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getHighestTargetId(): number;
getHighestListenSequenceNumber(): number;
getTargetCount(): number;
forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
getLastRemoteSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
setLastRemoteSnapshotVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): void;
addQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
updateQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
removeQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
getQueryData(param0: com.google.firebase.firestore.core.Query): com.google.firebase.firestore.local.QueryData;
addMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
removeMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
getMatchingKeysForTargetId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
containsKey(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
});
public constructor();
public removeMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public getHighestTargetId(): number;
public getTargetCount(): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public updateQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public getQueryData(param0: com.google.firebase.firestore.core.Query): com.google.firebase.firestore.local.QueryData;
public addMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public setLastRemoteSnapshotVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): void;
public getLastRemoteSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public getHighestListenSequenceNumber(): number;
public removeQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public containsKey(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
public getMatchingKeysForTargetId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public addQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class QueryData {
public static class: java.lang.Class<com.google.firebase.firestore.local.QueryData>;
public withLastLimboFreeSnapshotVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.firestore.local.QueryData;
public getPurpose(): com.google.firebase.firestore.local.QueryPurpose;
public getLastLimboFreeSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public getSequenceNumber(): number;
public equals(param0: any): boolean;
public hashCode(): number;
public withResumeToken(param0: com.google.protobuf.ByteString, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.firestore.local.QueryData;
public toString(): string;
public withSequenceNumber(param0: number): com.google.firebase.firestore.local.QueryData;
public getQuery(): com.google.firebase.firestore.core.Query;
public getTargetId(): number;
public getResumeToken(): com.google.protobuf.ByteString;
public getSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public constructor(param0: com.google.firebase.firestore.core.Query, param1: number, param2: number, param3: com.google.firebase.firestore.local.QueryPurpose);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class QueryEngine {
public static class: java.lang.Class<com.google.firebase.firestore.local.QueryEngine>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.QueryEngine interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setLocalDocumentsView(param0: com.google.firebase.firestore.local.LocalDocumentsView): void;
getDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
handleDocumentChange(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument): void;
});
public constructor();
public handleDocumentChange(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument): void;
public getDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public setLocalDocumentsView(param0: com.google.firebase.firestore.local.LocalDocumentsView): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class QueryPurpose {
public static class: java.lang.Class<com.google.firebase.firestore.local.QueryPurpose>;
public static LISTEN: com.google.firebase.firestore.local.QueryPurpose;
public static EXISTENCE_FILTER_MISMATCH: com.google.firebase.firestore.local.QueryPurpose;
public static LIMBO_RESOLUTION: com.google.firebase.firestore.local.QueryPurpose;
public static values(): native.Array<com.google.firebase.firestore.local.QueryPurpose>;
public static valueOf(param0: string): com.google.firebase.firestore.local.QueryPurpose;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class QueryResult {
public static class: java.lang.Class<com.google.firebase.firestore.local.QueryResult>;
public getRemoteKeys(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public getDocuments(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public constructor(param0: com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>, param1: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class ReferenceDelegate {
public static class: java.lang.Class<com.google.firebase.firestore.local.ReferenceDelegate>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.ReferenceDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setInMemoryPins(param0: com.google.firebase.firestore.local.ReferenceSet): void;
addReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
removeReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
removeMutationReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
removeTarget(param0: com.google.firebase.firestore.local.QueryData): void;
updateLimboDocument(param0: com.google.firebase.firestore.model.DocumentKey): void;
getCurrentSequenceNumber(): number;
onTransactionStarted(): void;
onTransactionCommitted(): void;
});
public constructor();
public updateLimboDocument(param0: com.google.firebase.firestore.model.DocumentKey): void;
public addReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public removeMutationReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionCommitted(): void;
public getCurrentSequenceNumber(): number;
public removeTarget(param0: com.google.firebase.firestore.local.QueryData): void;
public setInMemoryPins(param0: com.google.firebase.firestore.local.ReferenceSet): void;
public removeReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionStarted(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class ReferenceSet {
public static class: java.lang.Class<com.google.firebase.firestore.local.ReferenceSet>;
public constructor();
public removeReference(param0: com.google.firebase.firestore.model.DocumentKey, param1: number): void;
public removeReferences(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public containsKey(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
public removeReferencesForId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public isEmpty(): boolean;
public addReferences(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public referencesForId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public removeAllReferences(): void;
public addReference(param0: com.google.firebase.firestore.model.DocumentKey, param1: number): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class RemoteDocumentCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.RemoteDocumentCache>;
/**
* Constructs a new instance of the com.google.firebase.firestore.local.RemoteDocumentCache interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
add(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.SnapshotVersion): void;
remove(param0: com.google.firebase.firestore.model.DocumentKey): void;
get(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.MaybeDocument;
getAll(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
getAllDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
});
public constructor();
public getAll(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getAllDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public add(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.SnapshotVersion): void;
public remove(param0: com.google.firebase.firestore.model.DocumentKey): void;
public get(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.MaybeDocument;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteCollectionIndex {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteCollectionIndex>;
public removeEntry(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.model.value.FieldValue, param2: com.google.firebase.firestore.model.DocumentKey): void;
public addEntry(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.model.value.FieldValue, param2: com.google.firebase.firestore.model.DocumentKey): void;
public getCursor(param0: com.google.firebase.firestore.model.ResourcePath, param1: com.google.firebase.firestore.core.IndexRange): com.google.firebase.firestore.local.IndexCursor;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteIndexManager extends com.google.firebase.firestore.local.IndexManager {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteIndexManager>;
public getCollectionParents(param0: string): java.util.List<com.google.firebase.firestore.model.ResourcePath>;
public addToCollectionParentIndex(param0: com.google.firebase.firestore.model.ResourcePath): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteLruReferenceDelegate implements com.google.firebase.firestore.local.ReferenceDelegate, com.google.firebase.firestore.local.LruDelegate {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteLruReferenceDelegate>;
public forEachOrphanedDocumentSequenceNumber(param0: com.google.firebase.firestore.util.Consumer<java.lang.Long>): void;
public getByteSize(): number;
public removeTargets(param0: number, param1: globalAndroid.util.SparseArray<any>): number;
public addReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public onTransactionCommitted(): void;
public getCurrentSequenceNumber(): number;
public getSequenceNumberCount(): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public getGarbageCollector(): com.google.firebase.firestore.local.LruGarbageCollector;
public removeTarget(param0: com.google.firebase.firestore.local.QueryData): void;
public removeReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public updateLimboDocument(param0: com.google.firebase.firestore.model.DocumentKey): void;
public removeMutationReference(param0: com.google.firebase.firestore.model.DocumentKey): void;
public setInMemoryPins(param0: com.google.firebase.firestore.local.ReferenceSet): void;
public removeOrphanedDocuments(param0: number): number;
public onTransactionStarted(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteMutationQueue extends com.google.firebase.firestore.local.MutationQueue {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteMutationQueue>;
public getAllMutationBatchesAffectingDocumentKey(param0: com.google.firebase.firestore.model.DocumentKey): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getAllMutationBatchesAffectingDocumentKeys(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public getLastStreamToken(): com.google.protobuf.ByteString;
public getHighestUnacknowledgedBatchId(): number;
public lookupMutationBatch(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public addMutationBatch(param0: com.google.firebase.Timestamp, param1: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param2: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.firebase.firestore.model.mutation.MutationBatch;
public acknowledgeBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch, param1: com.google.protobuf.ByteString): void;
public getAllMutationBatches(): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public performConsistencyCheck(): void;
public getAllMutationBatchesAffectingQuery(param0: com.google.firebase.firestore.core.Query): java.util.List<com.google.firebase.firestore.model.mutation.MutationBatch>;
public start(): void;
public isEmpty(): boolean;
public getNextMutationBatchAfterBatchId(param0: number): com.google.firebase.firestore.model.mutation.MutationBatch;
public removeMutationBatch(param0: com.google.firebase.firestore.model.mutation.MutationBatch): void;
public setLastStreamToken(param0: com.google.protobuf.ByteString): void;
}
export module SQLiteMutationQueue {
export class BlobAccumulator extends com.google.firebase.firestore.util.Consumer<globalAndroid.database.Cursor> {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteMutationQueue.BlobAccumulator>;
public accept(param0: any): void;
public accept(param0: globalAndroid.database.Cursor): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLitePersistence extends com.google.firebase.firestore.local.Persistence {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLitePersistence>;
public getReferenceDelegate(): com.google.firebase.firestore.local.SQLiteLruReferenceDelegate;
public shutdown(): void;
public constructor(param0: globalAndroid.content.Context, param1: string, param2: com.google.firebase.firestore.model.DatabaseId, param3: com.google.firebase.firestore.local.LocalSerializer, param4: com.google.firebase.firestore.local.LruGarbageCollector.Params);
public constructor(param0: com.google.firebase.firestore.local.LocalSerializer, param1: com.google.firebase.firestore.local.LruGarbageCollector.Params, param2: globalAndroid.database.sqlite.SQLiteOpenHelper);
public start(): void;
public isStarted(): boolean;
public static databaseName(param0: string, param1: com.google.firebase.firestore.model.DatabaseId): string;
public static clearPersistence(param0: globalAndroid.content.Context, param1: com.google.firebase.firestore.model.DatabaseId, param2: string): void;
}
export module SQLitePersistence {
export class LongQuery {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLitePersistence.LongQuery>;
}
export class OpenHelper {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLitePersistence.OpenHelper>;
public onUpgrade(param0: globalAndroid.database.sqlite.SQLiteDatabase, param1: number, param2: number): void;
public onConfigure(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public onOpen(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public onCreate(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public onDowngrade(param0: globalAndroid.database.sqlite.SQLiteDatabase, param1: number, param2: number): void;
}
export class Query {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLitePersistence.Query>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteQueryCache extends com.google.firebase.firestore.local.QueryCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteQueryCache>;
public removeMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public getHighestTargetId(): number;
public getTargetCount(): number;
public forEachTarget(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.local.QueryData>): void;
public updateQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public getQueryData(param0: com.google.firebase.firestore.core.Query): com.google.firebase.firestore.local.QueryData;
public addMatchingKeys(param0: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param1: number): void;
public setLastRemoteSnapshotVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): void;
public getLastRemoteSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public getHighestListenSequenceNumber(): number;
public removeQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
public containsKey(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
public getMatchingKeysForTargetId(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public addQueryData(param0: com.google.firebase.firestore.local.QueryData): void;
}
export module SQLiteQueryCache {
export class DocumentKeysHolder {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteQueryCache.DocumentKeysHolder>;
}
export class QueryDataHolder {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteQueryCache.QueryDataHolder>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteRemoteDocumentCache extends com.google.firebase.firestore.local.RemoteDocumentCache {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteRemoteDocumentCache>;
public getAll(param0: java.lang.Iterable<com.google.firebase.firestore.model.DocumentKey>): java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getAllDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public add(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.SnapshotVersion): void;
public remove(param0: com.google.firebase.firestore.model.DocumentKey): void;
public get(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.MaybeDocument;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SQLiteSchema {
public static class: java.lang.Class<com.google.firebase.firestore.local.SQLiteSchema>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module local {
export class SimpleQueryEngine extends com.google.firebase.firestore.local.QueryEngine {
public static class: java.lang.Class<com.google.firebase.firestore.local.SimpleQueryEngine>;
public constructor();
public handleDocumentChange(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument): void;
public getDocumentsMatchingQuery(param0: com.google.firebase.firestore.core.Query, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public setLocalDocumentsView(param0: com.google.firebase.firestore.local.LocalDocumentsView): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export abstract class BasePath<B> extends java.lang.Comparable<any> {
public static class: java.lang.Class<com.google.firebase.firestore.model.BasePath<any>>;
public popFirst(param0: number): any;
public getFirstSegment(): string;
public canonicalString(): string;
public length(): number;
public equals(param0: any): boolean;
public hashCode(): number;
public compareTo(param0: any): number;
public append(param0: any): any;
public isPrefixOf(param0: any): boolean;
public toString(): string;
public getSegment(param0: number): string;
public append(param0: string): any;
public keepFirst(param0: number): any;
public popLast(): any;
public getLastSegment(): string;
public isImmediateParentOf(param0: any): boolean;
public isEmpty(): boolean;
public popFirst(): any;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class DatabaseId extends java.lang.Comparable<com.google.firebase.firestore.model.DatabaseId> {
public static class: java.lang.Class<com.google.firebase.firestore.model.DatabaseId>;
public static DEFAULT_DATABASE_ID: string;
public compareTo(param0: com.google.firebase.firestore.model.DatabaseId): number;
public getProjectId(): string;
public equals(param0: any): boolean;
public hashCode(): number;
public static forProject(param0: string): com.google.firebase.firestore.model.DatabaseId;
public static forDatabase(param0: string, param1: string): com.google.firebase.firestore.model.DatabaseId;
public getDatabaseId(): string;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class Document extends com.google.firebase.firestore.model.MaybeDocument {
public static class: java.lang.Class<com.google.firebase.firestore.model.Document>;
public getProto(): com.google.firestore.v1.Document;
public getField(param0: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.model.value.FieldValue;
public hasCommittedMutations(): boolean;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.firestore.model.Document.DocumentState, param3: com.google.firestore.v1.Document, param4: com.google.common.base.Function<com.google.firestore.v1.Value,com.google.firebase.firestore.model.value.FieldValue>);
public equals(param0: any): boolean;
public hashCode(): number;
public toString(): string;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: com.google.firebase.firestore.model.Document.DocumentState, param3: com.google.firebase.firestore.model.value.ObjectValue);
public hasLocalMutations(): boolean;
public static keyComparator(): java.util.Comparator<com.google.firebase.firestore.model.Document>;
public getData(): com.google.firebase.firestore.model.value.ObjectValue;
public getFieldValue(param0: com.google.firebase.firestore.model.FieldPath): any;
public hasPendingWrites(): boolean;
}
export module Document {
export class DocumentState {
public static class: java.lang.Class<com.google.firebase.firestore.model.Document.DocumentState>;
public static LOCAL_MUTATIONS: com.google.firebase.firestore.model.Document.DocumentState;
public static COMMITTED_MUTATIONS: com.google.firebase.firestore.model.Document.DocumentState;
public static SYNCED: com.google.firebase.firestore.model.Document.DocumentState;
public static values(): native.Array<com.google.firebase.firestore.model.Document.DocumentState>;
public static valueOf(param0: string): com.google.firebase.firestore.model.Document.DocumentState;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class DocumentCollections {
public static class: java.lang.Class<com.google.firebase.firestore.model.DocumentCollections>;
public static emptyMaybeDocumentMap(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public constructor();
public static emptyDocumentMap(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.Document>;
public static emptyVersionMap(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.SnapshotVersion>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class DocumentKey extends java.lang.Comparable<com.google.firebase.firestore.model.DocumentKey> {
public static class: java.lang.Class<com.google.firebase.firestore.model.DocumentKey>;
public static KEY_FIELD_NAME: string;
public static comparator(): java.util.Comparator<com.google.firebase.firestore.model.DocumentKey>;
public getPath(): com.google.firebase.firestore.model.ResourcePath;
public static isDocumentKey(param0: com.google.firebase.firestore.model.ResourcePath): boolean;
public static empty(): com.google.firebase.firestore.model.DocumentKey;
public compareTo(param0: com.google.firebase.firestore.model.DocumentKey): number;
public equals(param0: any): boolean;
public hashCode(): number;
public static fromSegments(param0: java.util.List<string>): com.google.firebase.firestore.model.DocumentKey;
public static fromPathString(param0: string): com.google.firebase.firestore.model.DocumentKey;
public toString(): string;
public hasCollectionId(param0: string): boolean;
public static fromPath(param0: com.google.firebase.firestore.model.ResourcePath): com.google.firebase.firestore.model.DocumentKey;
public static emptyKeySet(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class DocumentSet extends java.lang.Iterable<com.google.firebase.firestore.model.Document> {
public static class: java.lang.Class<com.google.firebase.firestore.model.DocumentSet>;
public getLastDocument(): com.google.firebase.firestore.model.Document;
public getDocument(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.Document;
public indexOf(param0: com.google.firebase.firestore.model.DocumentKey): number;
public add(param0: com.google.firebase.firestore.model.Document): com.google.firebase.firestore.model.DocumentSet;
public equals(param0: any): boolean;
public hashCode(): number;
public remove(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.DocumentSet;
public static emptySet(param0: java.util.Comparator<com.google.firebase.firestore.model.Document>): com.google.firebase.firestore.model.DocumentSet;
public toString(): string;
public iterator(): java.util.Iterator<com.google.firebase.firestore.model.Document>;
public isEmpty(): boolean;
public toList(): java.util.List<com.google.firebase.firestore.model.Document>;
public getPredecessor(param0: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.Document;
public size(): number;
public contains(param0: com.google.firebase.firestore.model.DocumentKey): boolean;
public getFirstDocument(): com.google.firebase.firestore.model.Document;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class FieldPath extends com.google.firebase.firestore.model.BasePath<com.google.firebase.firestore.model.FieldPath> {
public static class: java.lang.Class<com.google.firebase.firestore.model.FieldPath>;
public static KEY_PATH: com.google.firebase.firestore.model.FieldPath;
public static EMPTY_PATH: com.google.firebase.firestore.model.FieldPath;
public static fromServerFormat(param0: string): com.google.firebase.firestore.model.FieldPath;
public canonicalString(): string;
public static fromSegments(param0: java.util.List<string>): com.google.firebase.firestore.model.FieldPath;
public static fromSingleSegment(param0: string): com.google.firebase.firestore.model.FieldPath;
public isKeyField(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export abstract class MaybeDocument {
public static class: java.lang.Class<com.google.firebase.firestore.model.MaybeDocument>;
public getVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public hasPendingWrites(): boolean;
public getKey(): com.google.firebase.firestore.model.DocumentKey;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class NoDocument extends com.google.firebase.firestore.model.MaybeDocument {
public static class: java.lang.Class<com.google.firebase.firestore.model.NoDocument>;
public hasCommittedMutations(): boolean;
public equals(param0: any): boolean;
public hashCode(): number;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: boolean);
public hasPendingWrites(): boolean;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class ResourcePath extends com.google.firebase.firestore.model.BasePath<com.google.firebase.firestore.model.ResourcePath> {
public static class: java.lang.Class<com.google.firebase.firestore.model.ResourcePath>;
public static EMPTY: com.google.firebase.firestore.model.ResourcePath;
public static fromString(param0: string): com.google.firebase.firestore.model.ResourcePath;
public canonicalString(): string;
public static fromSegments(param0: java.util.List<string>): com.google.firebase.firestore.model.ResourcePath;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class SnapshotVersion extends java.lang.Comparable<com.google.firebase.firestore.model.SnapshotVersion> {
public static class: java.lang.Class<com.google.firebase.firestore.model.SnapshotVersion>;
public static NONE: com.google.firebase.firestore.model.SnapshotVersion;
public constructor(param0: com.google.firebase.Timestamp);
public equals(param0: any): boolean;
public hashCode(): number;
public getTimestamp(): com.google.firebase.Timestamp;
public compareTo(param0: com.google.firebase.firestore.model.SnapshotVersion): number;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export class UnknownDocument extends com.google.firebase.firestore.model.MaybeDocument {
public static class: java.lang.Class<com.google.firebase.firestore.model.UnknownDocument>;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.SnapshotVersion);
public equals(param0: any): boolean;
public hashCode(): number;
public hasPendingWrites(): boolean;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export abstract class ArrayTransformOperation extends com.google.firebase.firestore.model.mutation.TransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.ArrayTransformOperation>;
public getElements(): java.util.List<com.google.firebase.firestore.model.value.FieldValue>;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public hashCode(): number;
public apply(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.ArrayValue;
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
public equals(param0: any): boolean;
}
export module ArrayTransformOperation {
export class Remove extends com.google.firebase.firestore.model.mutation.ArrayTransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.ArrayTransformOperation.Remove>;
public constructor(param0: java.util.List<com.google.firebase.firestore.model.value.FieldValue>);
public apply(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.ArrayValue;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
}
export class Union extends com.google.firebase.firestore.model.mutation.ArrayTransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.ArrayTransformOperation.Union>;
public constructor(param0: java.util.List<com.google.firebase.firestore.model.value.FieldValue>);
public apply(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.ArrayValue;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class DeleteMutation extends com.google.firebase.firestore.model.mutation.Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.DeleteMutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.Timestamp): com.google.firebase.firestore.model.MaybeDocument;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.mutation.MutationResult): com.google.firebase.firestore.model.MaybeDocument;
public hashCode(): number;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.mutation.Precondition);
public extractBaseValue(param0: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.value.ObjectValue;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class FieldMask {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.FieldMask>;
public hashCode(): number;
public static fromSet(param0: java.util.Set<com.google.firebase.firestore.model.FieldPath>): com.google.firebase.firestore.model.mutation.FieldMask;
public getMask(): java.util.Set<com.google.firebase.firestore.model.FieldPath>;
public covers(param0: com.google.firebase.firestore.model.FieldPath): boolean;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class FieldTransform {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.FieldTransform>;
public getOperation(): com.google.firebase.firestore.model.mutation.TransformOperation;
public hashCode(): number;
public getFieldPath(): com.google.firebase.firestore.model.FieldPath;
public equals(param0: any): boolean;
public constructor(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.model.mutation.TransformOperation);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export abstract class Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.Mutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.Timestamp): com.google.firebase.firestore.model.MaybeDocument;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.mutation.MutationResult): com.google.firebase.firestore.model.MaybeDocument;
public extractBaseValue(param0: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.value.ObjectValue;
public getKey(): com.google.firebase.firestore.model.DocumentKey;
public getPrecondition(): com.google.firebase.firestore.model.mutation.Precondition;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class MutationBatch {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.MutationBatch>;
public static UNKNOWN: number;
public hashCode(): number;
public applyToLocalDocumentSet(param0: com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public getBatchId(): number;
public getBaseMutations(): java.util.List<com.google.firebase.firestore.model.mutation.Mutation>;
public getKeys(): java.util.Set<com.google.firebase.firestore.model.DocumentKey>;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.firestore.model.mutation.MutationBatchResult): com.google.firebase.firestore.model.MaybeDocument;
public toString(): string;
public constructor(param0: number, param1: com.google.firebase.Timestamp, param2: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>, param3: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>);
public getMutations(): java.util.List<com.google.firebase.firestore.model.mutation.Mutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.MaybeDocument;
public equals(param0: any): boolean;
public getLocalWriteTime(): com.google.firebase.Timestamp;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class MutationBatchResult {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.MutationBatchResult>;
public getMutationResults(): java.util.List<com.google.firebase.firestore.model.mutation.MutationResult>;
public getCommitVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public static create(param0: com.google.firebase.firestore.model.mutation.MutationBatch, param1: com.google.firebase.firestore.model.SnapshotVersion, param2: java.util.List<com.google.firebase.firestore.model.mutation.MutationResult>, param3: com.google.protobuf.ByteString): com.google.firebase.firestore.model.mutation.MutationBatchResult;
public getDocVersions(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.SnapshotVersion>;
public getBatch(): com.google.firebase.firestore.model.mutation.MutationBatch;
public getStreamToken(): com.google.protobuf.ByteString;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class MutationResult {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.MutationResult>;
public constructor(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: java.util.List<com.google.firebase.firestore.model.value.FieldValue>);
public getVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public getTransformResults(): java.util.List<com.google.firebase.firestore.model.value.FieldValue>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class NumericIncrementTransformOperation extends com.google.firebase.firestore.model.mutation.TransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.NumericIncrementTransformOperation>;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public constructor(param0: com.google.firebase.firestore.model.value.NumberValue);
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.NumberValue;
public getOperand(): com.google.firebase.firestore.model.value.FieldValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class PatchMutation extends com.google.firebase.firestore.model.mutation.Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.PatchMutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.Timestamp): com.google.firebase.firestore.model.MaybeDocument;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.mutation.MutationResult): com.google.firebase.firestore.model.MaybeDocument;
public hashCode(): number;
public extractBaseValue(param0: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.value.ObjectValue;
public getValue(): com.google.firebase.firestore.model.value.ObjectValue;
public toString(): string;
public getMask(): com.google.firebase.firestore.model.mutation.FieldMask;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.value.ObjectValue, param2: com.google.firebase.firestore.model.mutation.FieldMask, param3: com.google.firebase.firestore.model.mutation.Precondition);
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class Precondition {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.Precondition>;
public static NONE: com.google.firebase.firestore.model.mutation.Precondition;
public static exists(param0: boolean): com.google.firebase.firestore.model.mutation.Precondition;
public static updateTime(param0: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.firestore.model.mutation.Precondition;
public getExists(): java.lang.Boolean;
public hashCode(): number;
public isValidFor(param0: com.google.firebase.firestore.model.MaybeDocument): boolean;
public toString(): string;
public getUpdateTime(): com.google.firebase.firestore.model.SnapshotVersion;
public equals(param0: any): boolean;
public isNone(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class ServerTimestampOperation extends com.google.firebase.firestore.model.mutation.TransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.ServerTimestampOperation>;
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
public static getInstance(): com.google.firebase.firestore.model.mutation.ServerTimestampOperation;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class SetMutation extends com.google.firebase.firestore.model.mutation.Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.SetMutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.Timestamp): com.google.firebase.firestore.model.MaybeDocument;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.mutation.MutationResult): com.google.firebase.firestore.model.MaybeDocument;
public hashCode(): number;
public extractBaseValue(param0: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.value.ObjectValue;
public getValue(): com.google.firebase.firestore.model.value.ObjectValue;
public toString(): string;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.value.ObjectValue, param2: com.google.firebase.firestore.model.mutation.Precondition);
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class TransformMutation extends com.google.firebase.firestore.model.mutation.Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.TransformMutation>;
public applyToLocalView(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.MaybeDocument, param2: com.google.firebase.Timestamp): com.google.firebase.firestore.model.MaybeDocument;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.MaybeDocument, param1: com.google.firebase.firestore.model.mutation.MutationResult): com.google.firebase.firestore.model.MaybeDocument;
public hashCode(): number;
public extractBaseValue(param0: com.google.firebase.firestore.model.MaybeDocument): com.google.firebase.firestore.model.value.ObjectValue;
public getFieldTransforms(): java.util.List<com.google.firebase.firestore.model.mutation.FieldTransform>;
public constructor(param0: com.google.firebase.firestore.model.DocumentKey, param1: java.util.List<com.google.firebase.firestore.model.mutation.FieldTransform>);
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module mutation {
export class TransformOperation {
public static class: java.lang.Class<com.google.firebase.firestore.model.mutation.TransformOperation>;
/**
* Constructs a new instance of the com.google.firebase.firestore.model.mutation.TransformOperation interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
});
public constructor();
public computeBaseValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToRemoteDocument(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.FieldValue;
public applyToLocalView(param0: com.google.firebase.firestore.model.value.FieldValue, param1: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.FieldValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class ArrayValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.ArrayValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public getInternalValue(): java.util.List<com.google.firebase.firestore.model.value.FieldValue>;
public equals(param0: any): boolean;
public value(): java.util.List<any>;
public static fromList(param0: java.util.List<com.google.firebase.firestore.model.value.FieldValue>): com.google.firebase.firestore.model.value.ArrayValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class BlobValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.BlobValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public value(): com.google.firebase.firestore.Blob;
public equals(param0: any): boolean;
public static valueOf(param0: com.google.firebase.firestore.Blob): com.google.firebase.firestore.model.value.BlobValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class BooleanValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.BooleanValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public static valueOf(param0: java.lang.Boolean): com.google.firebase.firestore.model.value.BooleanValue;
public value(): java.lang.Boolean;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class DoubleValue extends com.google.firebase.firestore.model.value.NumberValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.DoubleValue>;
public static NaN: com.google.firebase.firestore.model.value.DoubleValue;
public value(): java.lang.Double;
public static valueOf(param0: java.lang.Double): com.google.firebase.firestore.model.value.DoubleValue;
public hashCode(): number;
public value(): any;
public equals(param0: any): boolean;
public getInternalValue(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export abstract class FieldValue extends java.lang.Comparable<com.google.firebase.firestore.model.value.FieldValue> {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.FieldValue>;
public constructor();
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public defaultCompareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public toString(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class GeoPointValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.GeoPointValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public static valueOf(param0: com.google.firebase.firestore.GeoPoint): com.google.firebase.firestore.model.value.GeoPointValue;
public value(): com.google.firebase.firestore.GeoPoint;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class IntegerValue extends com.google.firebase.firestore.model.value.NumberValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.IntegerValue>;
public static valueOf(param0: java.lang.Long): com.google.firebase.firestore.model.value.IntegerValue;
public hashCode(): number;
public value(): any;
public value(): java.lang.Long;
public equals(param0: any): boolean;
public getInternalValue(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class NullValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.NullValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public equals(param0: any): boolean;
public static nullValue(): com.google.firebase.firestore.model.value.NullValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export abstract class NumberValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.NumberValue>;
public constructor();
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public typeOrder(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class ObjectValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.ObjectValue>;
public value(): java.util.Map<string,any>;
public hashCode(): number;
public value(): any;
public toString(): string;
public getInternalValue(): com.google.firebase.database.collection.ImmutableSortedMap<string,com.google.firebase.firestore.model.value.FieldValue>;
public get(param0: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.model.value.FieldValue;
public static fromImmutableMap(param0: com.google.firebase.database.collection.ImmutableSortedMap<string,com.google.firebase.firestore.model.value.FieldValue>): com.google.firebase.firestore.model.value.ObjectValue;
public delete(param0: com.google.firebase.firestore.model.FieldPath): com.google.firebase.firestore.model.value.ObjectValue;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public typeOrder(): number;
public getFieldMask(): com.google.firebase.firestore.model.mutation.FieldMask;
public equals(param0: any): boolean;
public static fromMap(param0: java.util.Map<string,com.google.firebase.firestore.model.value.FieldValue>): com.google.firebase.firestore.model.value.ObjectValue;
public static emptyObject(): com.google.firebase.firestore.model.value.ObjectValue;
public set(param0: com.google.firebase.firestore.model.FieldPath, param1: com.google.firebase.firestore.model.value.FieldValue): com.google.firebase.firestore.model.value.ObjectValue;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class ReferenceValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.ReferenceValue>;
public getDatabaseId(): com.google.firebase.firestore.model.DatabaseId;
public value(): com.google.firebase.firestore.model.DocumentKey;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public static valueOf(param0: com.google.firebase.firestore.model.DatabaseId, param1: com.google.firebase.firestore.model.DocumentKey): com.google.firebase.firestore.model.value.ReferenceValue;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class ServerTimestampValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.ServerTimestampValue>;
public constructor();
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public constructor(param0: com.google.firebase.Timestamp, param1: com.google.firebase.firestore.model.value.FieldValue);
public typeOrder(): number;
public getPreviousValue(): any;
public toString(): string;
public equals(param0: any): boolean;
public getLocalWriteTime(): com.google.firebase.Timestamp;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class StringValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.StringValue>;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public static valueOf(param0: string): com.google.firebase.firestore.model.value.StringValue;
public value(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module model {
export module value {
export class TimestampValue extends com.google.firebase.firestore.model.value.FieldValue {
public static class: java.lang.Class<com.google.firebase.firestore.model.value.TimestampValue>;
public value(): com.google.firebase.Timestamp;
public static valueOf(param0: com.google.firebase.Timestamp): com.google.firebase.firestore.model.value.TimestampValue;
public hashCode(): number;
public compareTo(param0: com.google.firebase.firestore.model.value.FieldValue): number;
public value(): any;
public typeOrder(): number;
public toString(): string;
public getInternalValue(): com.google.firebase.Timestamp;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class MaybeDocument extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.MaybeDocument,com.google.firebase.firestore.proto.MaybeDocument.Builder> implements com.google.firebase.firestore.proto.MaybeDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MaybeDocument>;
public static NO_DOCUMENT_FIELD_NUMBER: number;
public static DOCUMENT_FIELD_NUMBER: number;
public static UNKNOWN_DOCUMENT_FIELD_NUMBER: number;
public static HAS_COMMITTED_MUTATIONS_FIELD_NUMBER: number;
public getDocument(): com.google.firestore.v1.Document;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MaybeDocument;
public getNoDocument(): com.google.firebase.firestore.proto.NoDocument;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.MaybeDocument;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getHasCommittedMutations(): boolean;
public static getDefaultInstance(): com.google.firebase.firestore.proto.MaybeDocument;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MaybeDocument;
public getDocumentTypeCase(): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.MaybeDocument;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getUnknownDocument(): com.google.firebase.firestore.proto.UnknownDocument;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MaybeDocument;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.MaybeDocument;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MaybeDocument;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.MaybeDocument;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MaybeDocument;
public static newBuilder(param0: com.google.firebase.firestore.proto.MaybeDocument): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.MaybeDocument;
public static newBuilder(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.MaybeDocument>;
}
export module MaybeDocument {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.MaybeDocument,com.google.firebase.firestore.proto.MaybeDocument.Builder> implements com.google.firebase.firestore.proto.MaybeDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MaybeDocument.Builder>;
public clearHasCommittedMutations(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public clearDocumentType(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public setDocument(param0: com.google.firestore.v1.Document.Builder): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public mergeUnknownDocument(param0: com.google.firebase.firestore.proto.UnknownDocument): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public getHasCommittedMutations(): boolean;
public getDocument(): com.google.firestore.v1.Document;
public clearNoDocument(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public setUnknownDocument(param0: com.google.firebase.firestore.proto.UnknownDocument): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public setHasCommittedMutations(param0: boolean): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public getNoDocument(): com.google.firebase.firestore.proto.NoDocument;
public clearDocument(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public mergeDocument(param0: com.google.firestore.v1.Document): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public setDocument(param0: com.google.firestore.v1.Document): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public setNoDocument(param0: com.google.firebase.firestore.proto.NoDocument): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public clearUnknownDocument(): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public mergeNoDocument(param0: com.google.firebase.firestore.proto.NoDocument): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public getUnknownDocument(): com.google.firebase.firestore.proto.UnknownDocument;
public setUnknownDocument(param0: com.google.firebase.firestore.proto.UnknownDocument.Builder): com.google.firebase.firestore.proto.MaybeDocument.Builder;
public getDocumentTypeCase(): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public setNoDocument(param0: com.google.firebase.firestore.proto.NoDocument.Builder): com.google.firebase.firestore.proto.MaybeDocument.Builder;
}
export class DocumentTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase>;
public static NO_DOCUMENT: com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static DOCUMENT: com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static UNKNOWN_DOCUMENT: com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static DOCUMENTTYPE_NOT_SET: com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static valueOf(param0: number): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public getNumber(): number;
public static values(): native.Array<com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase>;
public static valueOf(param0: string): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public static forNumber(param0: number): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class MaybeDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MaybeDocumentOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.MaybeDocumentOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getNoDocument(): com.google.firebase.firestore.proto.NoDocument;
getDocument(): com.google.firestore.v1.Document;
getUnknownDocument(): com.google.firebase.firestore.proto.UnknownDocument;
getHasCommittedMutations(): boolean;
getDocumentTypeCase(): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
});
public constructor();
public getDocument(): com.google.firestore.v1.Document;
public getNoDocument(): com.google.firebase.firestore.proto.NoDocument;
public getHasCommittedMutations(): boolean;
public getDocumentTypeCase(): com.google.firebase.firestore.proto.MaybeDocument.DocumentTypeCase;
public getUnknownDocument(): com.google.firebase.firestore.proto.UnknownDocument;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class MaybeDocumentOuterClass {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MaybeDocumentOuterClass>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class Mutation {
public static class: java.lang.Class<com.google.firebase.firestore.proto.Mutation>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class MutationQueue extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.MutationQueue,com.google.firebase.firestore.proto.MutationQueue.Builder> implements com.google.firebase.firestore.proto.MutationQueueOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MutationQueue>;
public static LAST_ACKNOWLEDGED_BATCH_ID_FIELD_NUMBER: number;
public static LAST_STREAM_TOKEN_FIELD_NUMBER: number;
public static newBuilder(): com.google.firebase.firestore.proto.MutationQueue.Builder;
public getLastStreamToken(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MutationQueue;
public static getDefaultInstance(): com.google.firebase.firestore.proto.MutationQueue;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.MutationQueue>;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MutationQueue;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.MutationQueue;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(param0: com.google.firebase.firestore.proto.MutationQueue): com.google.firebase.firestore.proto.MutationQueue.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MutationQueue;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.MutationQueue;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MutationQueue;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.MutationQueue;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.MutationQueue;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.MutationQueue;
public getLastAcknowledgedBatchId(): number;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.MutationQueue;
}
export module MutationQueue {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.MutationQueue,com.google.firebase.firestore.proto.MutationQueue.Builder> implements com.google.firebase.firestore.proto.MutationQueueOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MutationQueue.Builder>;
public setLastStreamToken(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.MutationQueue.Builder;
public getLastAcknowledgedBatchId(): number;
public getLastStreamToken(): com.google.protobuf.ByteString;
public clearLastStreamToken(): com.google.firebase.firestore.proto.MutationQueue.Builder;
public setLastAcknowledgedBatchId(param0: number): com.google.firebase.firestore.proto.MutationQueue.Builder;
public clearLastAcknowledgedBatchId(): com.google.firebase.firestore.proto.MutationQueue.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class MutationQueueOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.MutationQueueOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.MutationQueueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getLastAcknowledgedBatchId(): number;
getLastStreamToken(): com.google.protobuf.ByteString;
});
public constructor();
public getLastStreamToken(): com.google.protobuf.ByteString;
public getLastAcknowledgedBatchId(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class NoDocument extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.NoDocument,com.google.firebase.firestore.proto.NoDocument.Builder> implements com.google.firebase.firestore.proto.NoDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.NoDocument>;
public static NAME_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.NoDocument;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static getDefaultInstance(): com.google.firebase.firestore.proto.NoDocument;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.NoDocument>;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.NoDocument;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getName(): string;
public hasReadTime(): boolean;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.NoDocument;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.NoDocument;
public getReadTime(): com.google.protobuf.Timestamp;
public static newBuilder(param0: com.google.firebase.firestore.proto.NoDocument): com.google.firebase.firestore.proto.NoDocument.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.NoDocument;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.NoDocument;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.NoDocument;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.NoDocument;
public static newBuilder(): com.google.firebase.firestore.proto.NoDocument.Builder;
public getNameBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.NoDocument;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.NoDocument;
}
export module NoDocument {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.NoDocument,com.google.firebase.firestore.proto.NoDocument.Builder> implements com.google.firebase.firestore.proto.NoDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.NoDocument.Builder>;
public setNameBytes(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.NoDocument.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.NoDocument.Builder;
public clearReadTime(): com.google.firebase.firestore.proto.NoDocument.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public getName(): string;
public clearName(): com.google.firebase.firestore.proto.NoDocument.Builder;
public setName(param0: string): com.google.firebase.firestore.proto.NoDocument.Builder;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.NoDocument.Builder;
public getNameBytes(): com.google.protobuf.ByteString;
public hasReadTime(): boolean;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.NoDocument.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class NoDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.NoDocumentOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.NoDocumentOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
getNameBytes(): com.google.protobuf.ByteString;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
});
public constructor();
public hasReadTime(): boolean;
public getReadTime(): com.google.protobuf.Timestamp;
public getNameBytes(): com.google.protobuf.ByteString;
public getName(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class Target extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.Target,com.google.firebase.firestore.proto.Target.Builder> implements com.google.firebase.firestore.proto.TargetOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.Target>;
public static TARGET_ID_FIELD_NUMBER: number;
public static SNAPSHOT_VERSION_FIELD_NUMBER: number;
public static RESUME_TOKEN_FIELD_NUMBER: number;
public static LAST_LISTEN_SEQUENCE_NUMBER_FIELD_NUMBER: number;
public static QUERY_FIELD_NUMBER: number;
public static DOCUMENTS_FIELD_NUMBER: number;
public static LAST_LIMBO_FREE_SNAPSHOT_VERSION_FIELD_NUMBER: number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.Target;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
public getLastLimboFreeSnapshotVersion(): com.google.protobuf.Timestamp;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.Target;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.Target;
public getTargetId(): number;
public hasSnapshotVersion(): boolean;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.Target;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.Target;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.Target;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.Target>;
public static newBuilder(): com.google.firebase.firestore.proto.Target.Builder;
public getTargetTypeCase(): com.google.firebase.firestore.proto.Target.TargetTypeCase;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.Target;
public static newBuilder(param0: com.google.firebase.firestore.proto.Target): com.google.firebase.firestore.proto.Target.Builder;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.Target;
public getResumeToken(): com.google.protobuf.ByteString;
public getLastListenSequenceNumber(): number;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.Target;
public hasLastLimboFreeSnapshotVersion(): boolean;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.Target;
public static getDefaultInstance(): com.google.firebase.firestore.proto.Target;
public getSnapshotVersion(): com.google.protobuf.Timestamp;
}
export module Target {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.Target,com.google.firebase.firestore.proto.Target.Builder> implements com.google.firebase.firestore.proto.TargetOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.Target.Builder>;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
public hasSnapshotVersion(): boolean;
public mergeQuery(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firebase.firestore.proto.Target.Builder;
public clearSnapshotVersion(): com.google.firebase.firestore.proto.Target.Builder;
public mergeLastLimboFreeSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.Target.Builder;
public clearLastLimboFreeSnapshotVersion(): com.google.firebase.firestore.proto.Target.Builder;
public clearDocuments(): com.google.firebase.firestore.proto.Target.Builder;
public getLastListenSequenceNumber(): number;
public setSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.Target.Builder;
public setResumeToken(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.Target.Builder;
public setDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget.Builder): com.google.firebase.firestore.proto.Target.Builder;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public clearResumeToken(): com.google.firebase.firestore.proto.Target.Builder;
public mergeDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firebase.firestore.proto.Target.Builder;
public mergeSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.Target.Builder;
public setLastListenSequenceNumber(param0: number): com.google.firebase.firestore.proto.Target.Builder;
public getTargetId(): number;
public setTargetId(param0: number): com.google.firebase.firestore.proto.Target.Builder;
public setQuery(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firebase.firestore.proto.Target.Builder;
public clearTargetId(): com.google.firebase.firestore.proto.Target.Builder;
public clearTargetType(): com.google.firebase.firestore.proto.Target.Builder;
public getLastLimboFreeSnapshotVersion(): com.google.protobuf.Timestamp;
public clearQuery(): com.google.firebase.firestore.proto.Target.Builder;
public setDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firebase.firestore.proto.Target.Builder;
public hasLastLimboFreeSnapshotVersion(): boolean;
public getResumeToken(): com.google.protobuf.ByteString;
public setSnapshotVersion(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.Target.Builder;
public setQuery(param0: com.google.firestore.v1.Target.QueryTarget.Builder): com.google.firebase.firestore.proto.Target.Builder;
public clearLastListenSequenceNumber(): com.google.firebase.firestore.proto.Target.Builder;
public setLastLimboFreeSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.Target.Builder;
public getSnapshotVersion(): com.google.protobuf.Timestamp;
public setLastLimboFreeSnapshotVersion(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.Target.Builder;
public getTargetTypeCase(): com.google.firebase.firestore.proto.Target.TargetTypeCase;
}
export class TargetTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firebase.firestore.proto.Target.TargetTypeCase>;
public static QUERY: com.google.firebase.firestore.proto.Target.TargetTypeCase;
public static DOCUMENTS: com.google.firebase.firestore.proto.Target.TargetTypeCase;
public static TARGETTYPE_NOT_SET: com.google.firebase.firestore.proto.Target.TargetTypeCase;
public static forNumber(param0: number): com.google.firebase.firestore.proto.Target.TargetTypeCase;
public static values(): native.Array<com.google.firebase.firestore.proto.Target.TargetTypeCase>;
public static valueOf(param0: string): com.google.firebase.firestore.proto.Target.TargetTypeCase;
public getNumber(): number;
public static valueOf(param0: number): com.google.firebase.firestore.proto.Target.TargetTypeCase;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class TargetGlobal extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.TargetGlobal,com.google.firebase.firestore.proto.TargetGlobal.Builder> implements com.google.firebase.firestore.proto.TargetGlobalOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.TargetGlobal>;
public static HIGHEST_TARGET_ID_FIELD_NUMBER: number;
public static HIGHEST_LISTEN_SEQUENCE_NUMBER_FIELD_NUMBER: number;
public static LAST_REMOTE_SNAPSHOT_VERSION_FIELD_NUMBER: number;
public static TARGET_COUNT_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.TargetGlobal;
public getHighestTargetId(): number;
public hasLastRemoteSnapshotVersion(): boolean;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getTargetCount(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.TargetGlobal;
public static newBuilder(): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.TargetGlobal;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.TargetGlobal;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.TargetGlobal;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.TargetGlobal;
public getHighestListenSequenceNumber(): number;
public static newBuilder(param0: com.google.firebase.firestore.proto.TargetGlobal): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public getSerializedSize(): number;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.TargetGlobal>;
public getLastRemoteSnapshotVersion(): com.google.protobuf.Timestamp;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.TargetGlobal;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.TargetGlobal;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.TargetGlobal;
public static getDefaultInstance(): com.google.firebase.firestore.proto.TargetGlobal;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.TargetGlobal;
}
export module TargetGlobal {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.TargetGlobal,com.google.firebase.firestore.proto.TargetGlobal.Builder> implements com.google.firebase.firestore.proto.TargetGlobalOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.TargetGlobal.Builder>;
public hasLastRemoteSnapshotVersion(): boolean;
public clearTargetCount(): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public getHighestTargetId(): number;
public getTargetCount(): number;
public setHighestTargetId(param0: number): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public getHighestListenSequenceNumber(): number;
public setTargetCount(param0: number): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public clearLastRemoteSnapshotVersion(): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public getLastRemoteSnapshotVersion(): com.google.protobuf.Timestamp;
public mergeLastRemoteSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public clearHighestTargetId(): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public setHighestListenSequenceNumber(param0: number): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public clearHighestListenSequenceNumber(): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public setLastRemoteSnapshotVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.TargetGlobal.Builder;
public setLastRemoteSnapshotVersion(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.TargetGlobal.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class TargetGlobalOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.TargetGlobalOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.TargetGlobalOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getHighestTargetId(): number;
getHighestListenSequenceNumber(): number;
hasLastRemoteSnapshotVersion(): boolean;
getLastRemoteSnapshotVersion(): com.google.protobuf.Timestamp;
getTargetCount(): number;
});
public constructor();
public getHighestTargetId(): number;
public hasLastRemoteSnapshotVersion(): boolean;
public getLastRemoteSnapshotVersion(): com.google.protobuf.Timestamp;
public getTargetCount(): number;
public getHighestListenSequenceNumber(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class TargetOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.TargetOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.TargetOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTargetId(): number;
hasSnapshotVersion(): boolean;
getSnapshotVersion(): com.google.protobuf.Timestamp;
getResumeToken(): com.google.protobuf.ByteString;
getLastListenSequenceNumber(): number;
getQuery(): com.google.firestore.v1.Target.QueryTarget;
getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
hasLastLimboFreeSnapshotVersion(): boolean;
getLastLimboFreeSnapshotVersion(): com.google.protobuf.Timestamp;
getTargetTypeCase(): com.google.firebase.firestore.proto.Target.TargetTypeCase;
});
public constructor();
public getTargetId(): number;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public getResumeToken(): com.google.protobuf.ByteString;
public getLastListenSequenceNumber(): number;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
public getTargetTypeCase(): com.google.firebase.firestore.proto.Target.TargetTypeCase;
public getLastLimboFreeSnapshotVersion(): com.google.protobuf.Timestamp;
public hasSnapshotVersion(): boolean;
public hasLastLimboFreeSnapshotVersion(): boolean;
public getSnapshotVersion(): com.google.protobuf.Timestamp;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class TargetOuterClass {
public static class: java.lang.Class<com.google.firebase.firestore.proto.TargetOuterClass>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class UnknownDocument extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.UnknownDocument,com.google.firebase.firestore.proto.UnknownDocument.Builder> implements com.google.firebase.firestore.proto.UnknownDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.UnknownDocument>;
public static NAME_FIELD_NUMBER: number;
public static VERSION_FIELD_NUMBER: number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.UnknownDocument;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.UnknownDocument;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.UnknownDocument;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.UnknownDocument;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.UnknownDocument;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.UnknownDocument;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.UnknownDocument>;
public getVersion(): com.google.protobuf.Timestamp;
public hasVersion(): boolean;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getName(): string;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.UnknownDocument;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.UnknownDocument;
public static newBuilder(): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public static getDefaultInstance(): com.google.firebase.firestore.proto.UnknownDocument;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.UnknownDocument;
public getNameBytes(): com.google.protobuf.ByteString;
public static newBuilder(param0: com.google.firebase.firestore.proto.UnknownDocument): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.UnknownDocument;
}
export module UnknownDocument {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.UnknownDocument,com.google.firebase.firestore.proto.UnknownDocument.Builder> implements com.google.firebase.firestore.proto.UnknownDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.UnknownDocument.Builder>;
public setVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public setVersion(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public getName(): string;
public clearName(): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public getVersion(): com.google.protobuf.Timestamp;
public setNameBytes(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public hasVersion(): boolean;
public mergeVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public clearVersion(): com.google.firebase.firestore.proto.UnknownDocument.Builder;
public getNameBytes(): com.google.protobuf.ByteString;
public setName(param0: string): com.google.firebase.firestore.proto.UnknownDocument.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class UnknownDocumentOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.UnknownDocumentOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.UnknownDocumentOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
getNameBytes(): com.google.protobuf.ByteString;
hasVersion(): boolean;
getVersion(): com.google.protobuf.Timestamp;
});
public constructor();
public getVersion(): com.google.protobuf.Timestamp;
public getNameBytes(): com.google.protobuf.ByteString;
public hasVersion(): boolean;
public getName(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class WriteBatch extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.firestore.proto.WriteBatch,com.google.firebase.firestore.proto.WriteBatch.Builder> implements com.google.firebase.firestore.proto.WriteBatchOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.WriteBatch>;
public static BATCH_ID_FIELD_NUMBER: number;
public static WRITES_FIELD_NUMBER: number;
public static LOCAL_WRITE_TIME_FIELD_NUMBER: number;
public static BASE_WRITES_FIELD_NUMBER: number;
public getWritesCount(): number;
public getWrites(param0: number): com.google.firestore.v1.Write;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.WriteBatch;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getBaseWritesList(): java.util.List<com.google.firestore.v1.Write>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.WriteBatch;
public static newBuilder(param0: com.google.firebase.firestore.proto.WriteBatch): com.google.firebase.firestore.proto.WriteBatch.Builder;
public getBaseWrites(param0: number): com.google.firestore.v1.Write;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.firestore.proto.WriteBatch;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getBatchId(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.WriteBatch;
public getWritesOrBuilderList(): java.util.List<any>;
public static parseFrom(param0: native.Array<number>): com.google.firebase.firestore.proto.WriteBatch;
public getLocalWriteTime(): com.google.protobuf.Timestamp;
public hasLocalWriteTime(): boolean;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.firestore.proto.WriteBatch;
public getBaseWritesOrBuilderList(): java.util.List<any>;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.WriteBatch;
public getWritesOrBuilder(param0: number): com.google.firestore.v1.WriteOrBuilder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.WriteBatch;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.firestore.proto.WriteBatch;
public getSerializedSize(): number;
public getBaseWritesCount(): number;
public static getDefaultInstance(): com.google.firebase.firestore.proto.WriteBatch;
public static parseFrom(param0: java.io.InputStream): com.google.firebase.firestore.proto.WriteBatch;
public getBaseWritesOrBuilder(param0: number): com.google.firestore.v1.WriteOrBuilder;
public static newBuilder(): com.google.firebase.firestore.proto.WriteBatch.Builder;
public static parser(): com.google.protobuf.Parser<com.google.firebase.firestore.proto.WriteBatch>;
}
export module WriteBatch {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.firestore.proto.WriteBatch,com.google.firebase.firestore.proto.WriteBatch.Builder> implements com.google.firebase.firestore.proto.WriteBatchOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.WriteBatch.Builder>;
public getWritesCount(): number;
public setLocalWriteTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getWrites(param0: number): com.google.firestore.v1.Write;
public setBaseWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public clearLocalWriteTime(): com.google.firebase.firestore.proto.WriteBatch.Builder;
public setWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public getBaseWritesCount(): number;
public addBaseWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public setBaseWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public setBatchId(param0: number): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addAllBaseWrites(param0: java.lang.Iterable<any>): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addAllWrites(param0: java.lang.Iterable<any>): com.google.firebase.firestore.proto.WriteBatch.Builder;
public getLocalWriteTime(): com.google.protobuf.Timestamp;
public getBaseWrites(param0: number): com.google.firestore.v1.Write;
public setWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addWrites(param0: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public mergeLocalWriteTime(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addBaseWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public getBatchId(): number;
public clearBatchId(): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addBaseWrites(param0: com.google.firestore.v1.Write.Builder): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addBaseWrites(param0: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addWrites(param0: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public removeBaseWrites(param0: number): com.google.firebase.firestore.proto.WriteBatch.Builder;
public addWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firebase.firestore.proto.WriteBatch.Builder;
public hasLocalWriteTime(): boolean;
public getBaseWritesList(): java.util.List<com.google.firestore.v1.Write>;
public setLocalWriteTime(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.proto.WriteBatch.Builder;
public clearWrites(): com.google.firebase.firestore.proto.WriteBatch.Builder;
public removeWrites(param0: number): com.google.firebase.firestore.proto.WriteBatch.Builder;
public clearBaseWrites(): com.google.firebase.firestore.proto.WriteBatch.Builder;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module proto {
export class WriteBatchOrBuilder {
public static class: java.lang.Class<com.google.firebase.firestore.proto.WriteBatchOrBuilder>;
/**
* Constructs a new instance of the com.google.firebase.firestore.proto.WriteBatchOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getBatchId(): number;
getWritesList(): java.util.List<com.google.firestore.v1.Write>;
getWrites(param0: number): com.google.firestore.v1.Write;
getWritesCount(): number;
hasLocalWriteTime(): boolean;
getLocalWriteTime(): com.google.protobuf.Timestamp;
getBaseWritesList(): java.util.List<com.google.firestore.v1.Write>;
getBaseWrites(param0: number): com.google.firestore.v1.Write;
getBaseWritesCount(): number;
});
public constructor();
public getWritesCount(): number;
public getWrites(param0: number): com.google.firestore.v1.Write;
public getBaseWritesCount(): number;
public getBaseWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getLocalWriteTime(): com.google.protobuf.Timestamp;
public getBaseWrites(param0: number): com.google.firestore.v1.Write;
public hasLocalWriteTime(): boolean;
public getBatchId(): number;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export abstract class AbstractStream<ReqT, RespT, CallbackT> extends com.google.firebase.firestore.remote.Stream<any> {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AbstractStream<any,any,any>>;
public tearDown(): void;
public inhibitBackoff(): void;
public start(): void;
public isStarted(): boolean;
public onNext(param0: any): void;
public isOpen(): boolean;
public stop(): void;
public writeRequest(param0: any): void;
}
export module AbstractStream {
export class CloseGuardedRunner {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AbstractStream.CloseGuardedRunner>;
}
export class IdleTimeoutRunnable {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AbstractStream.IdleTimeoutRunnable>;
public run(): void;
}
export class StreamObserver extends com.google.firebase.firestore.remote.IncomingStreamObserver<any> {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AbstractStream.StreamObserver>;
public onNext(param0: any): void;
public onHeaders(param0: io.grpc.Metadata): void;
public onOpen(): void;
public onClose(param0: io.grpc.Status): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class AndroidConnectivityMonitor extends com.google.firebase.firestore.remote.ConnectivityMonitor {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AndroidConnectivityMonitor>;
public shutdown(): void;
public constructor(param0: globalAndroid.content.Context);
public addCallback(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus>): void;
}
export module AndroidConnectivityMonitor {
export class DefaultNetworkCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AndroidConnectivityMonitor.DefaultNetworkCallback>;
public onLost(param0: globalAndroid.net.Network): void;
public onAvailable(param0: globalAndroid.net.Network): void;
}
export class NetworkReceiver {
public static class: java.lang.Class<com.google.firebase.firestore.remote.AndroidConnectivityMonitor.NetworkReceiver>;
public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class ConnectivityMonitor {
public static class: java.lang.Class<com.google.firebase.firestore.remote.ConnectivityMonitor>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.ConnectivityMonitor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
addCallback(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus>): void;
shutdown(): void;
});
public constructor();
public shutdown(): void;
public addCallback(param0: com.google.firebase.firestore.util.Consumer<com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus>): void;
}
export module ConnectivityMonitor {
export class NetworkStatus {
public static class: java.lang.Class<com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus>;
public static UNREACHABLE: com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus;
public static REACHABLE: com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus;
public static values(): native.Array<com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus>;
public static valueOf(param0: string): com.google.firebase.firestore.remote.ConnectivityMonitor.NetworkStatus;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class Datastore {
public static class: java.lang.Class<com.google.firebase.firestore.remote.Datastore>;
public commit(param0: java.util.List<com.google.firebase.firestore.model.mutation.Mutation>): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.firestore.model.mutation.MutationResult>>;
public constructor(param0: com.google.firebase.firestore.core.DatabaseInfo, param1: com.google.firebase.firestore.util.AsyncQueue, param2: com.google.firebase.firestore.auth.CredentialsProvider, param3: globalAndroid.content.Context, param4: com.google.firebase.firestore.remote.GrpcMetadataProvider);
public static isPermanentError(param0: com.google.firebase.firestore.FirebaseFirestoreException.Code): boolean;
public lookup(param0: java.util.List<com.google.firebase.firestore.model.DocumentKey>): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.firestore.model.MaybeDocument>>;
public static isPermanentWriteError(param0: io.grpc.Status): boolean;
public static isPermanentError(param0: io.grpc.Status): boolean;
public static isMissingSslCiphers(param0: io.grpc.Status): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class ExistenceFilter {
public static class: java.lang.Class<com.google.firebase.firestore.remote.ExistenceFilter>;
public constructor(param0: number);
public getCount(): number;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class FirebaseClientGrpcMetadataProvider extends com.google.firebase.firestore.remote.GrpcMetadataProvider {
public static class: java.lang.Class<com.google.firebase.firestore.remote.FirebaseClientGrpcMetadataProvider>;
public constructor(param0: com.google.firebase.inject.Provider<com.google.firebase.platforminfo.UserAgentPublisher>, param1: com.google.firebase.inject.Provider<com.google.firebase.heartbeatinfo.HeartBeatInfo>);
public updateMetadata(param0: io.grpc.Metadata): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class FirestoreCallCredentials {
public static class: java.lang.Class<com.google.firebase.firestore.remote.FirestoreCallCredentials>;
public applyRequestMetadata(param0: io.grpc.CallCredentials.RequestInfo, param1: java.util.concurrent.Executor, param2: io.grpc.CallCredentials.MetadataApplier): void;
public thisUsesUnstableApi(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class FirestoreChannel {
public static class: java.lang.Class<com.google.firebase.firestore.remote.FirestoreChannel>;
public shutdown(): void;
public invalidateToken(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class GrpcCallProvider {
public static class: java.lang.Class<com.google.firebase.firestore.remote.GrpcCallProvider>;
public static overrideChannelBuilder(param0: com.google.firebase.firestore.util.Supplier<io.grpc.ManagedChannelBuilder<any>>): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class GrpcMetadataProvider {
public static class: java.lang.Class<com.google.firebase.firestore.remote.GrpcMetadataProvider>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.GrpcMetadataProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
updateMetadata(param0: io.grpc.Metadata): void;
});
public constructor();
public updateMetadata(param0: io.grpc.Metadata): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class IncomingStreamObserver<RespT> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.remote.IncomingStreamObserver<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.IncomingStreamObserver<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onHeaders(param0: io.grpc.Metadata): void;
onNext(param0: RespT): void;
onOpen(): void;
onClose(param0: io.grpc.Status): void;
});
public constructor();
public onNext(param0: RespT): void;
public onOpen(): void;
public onClose(param0: io.grpc.Status): void;
public onHeaders(param0: io.grpc.Metadata): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class OnlineStateTracker {
public static class: java.lang.Class<com.google.firebase.firestore.remote.OnlineStateTracker>;
}
export module OnlineStateTracker {
export class OnlineStateCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.OnlineStateTracker.OnlineStateCallback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.OnlineStateTracker$OnlineStateCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
});
public constructor();
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class RemoteEvent {
public static class: java.lang.Class<com.google.firebase.firestore.remote.RemoteEvent>;
public getResolvedLimboDocuments(): java.util.Set<com.google.firebase.firestore.model.DocumentKey>;
public getTargetChanges(): java.util.Map<java.lang.Integer,com.google.firebase.firestore.remote.TargetChange>;
public getSnapshotVersion(): com.google.firebase.firestore.model.SnapshotVersion;
public constructor(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: java.util.Map<java.lang.Integer,com.google.firebase.firestore.remote.TargetChange>, param2: java.util.Set<java.lang.Integer>, param3: java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>, param4: java.util.Set<com.google.firebase.firestore.model.DocumentKey>);
public getTargetMismatches(): java.util.Set<java.lang.Integer>;
public getDocumentUpdates(): java.util.Map<com.google.firebase.firestore.model.DocumentKey,com.google.firebase.firestore.model.MaybeDocument>;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class RemoteSerializer {
public static class: java.lang.Class<com.google.firebase.firestore.remote.RemoteSerializer>;
public encodeVersion(param0: com.google.firebase.firestore.model.SnapshotVersion): com.google.protobuf.Timestamp;
public decodeQueryTarget(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firebase.firestore.core.Query;
public decodeWatchChange(param0: com.google.firestore.v1.ListenResponse): com.google.firebase.firestore.remote.WatchChange;
public encodeTarget(param0: com.google.firebase.firestore.local.QueryData): com.google.firestore.v1.Target;
public encodeMutation(param0: com.google.firebase.firestore.model.mutation.Mutation): com.google.firestore.v1.Write;
public constructor(param0: com.google.firebase.firestore.model.DatabaseId);
public decodeValue(param0: com.google.firestore.v1.Value): com.google.firebase.firestore.model.value.FieldValue;
public encodeTimestamp(param0: com.google.firebase.Timestamp): com.google.protobuf.Timestamp;
public decodeMaybeDocument(param0: com.google.firestore.v1.BatchGetDocumentsResponse): com.google.firebase.firestore.model.MaybeDocument;
public decodeKey(param0: string): com.google.firebase.firestore.model.DocumentKey;
public decodeMutation(param0: com.google.firestore.v1.Write): com.google.firebase.firestore.model.mutation.Mutation;
public decodeVersion(param0: com.google.protobuf.Timestamp): com.google.firebase.firestore.model.SnapshotVersion;
public decodeFields(param0: java.util.Map<string,com.google.firestore.v1.Value>): com.google.firebase.firestore.model.value.ObjectValue;
public decodeDocumentsTarget(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firebase.firestore.core.Query;
public decodeVersionFromListenResponse(param0: com.google.firestore.v1.ListenResponse): com.google.firebase.firestore.model.SnapshotVersion;
public decodeTimestamp(param0: com.google.protobuf.Timestamp): com.google.firebase.Timestamp;
public encodeDocumentsTarget(param0: com.google.firebase.firestore.core.Query): com.google.firestore.v1.Target.DocumentsTarget;
public encodeKey(param0: com.google.firebase.firestore.model.DocumentKey): string;
public decodeMutationResult(param0: com.google.firestore.v1.WriteResult, param1: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.firestore.model.mutation.MutationResult;
public encodeListenRequestLabels(param0: com.google.firebase.firestore.local.QueryData): java.util.Map<string,string>;
public encodeQueryTarget(param0: com.google.firebase.firestore.core.Query): com.google.firestore.v1.Target.QueryTarget;
public databaseName(): string;
public encodeValue(param0: com.google.firebase.firestore.model.value.FieldValue): com.google.firestore.v1.Value;
public encodeDocument(param0: com.google.firebase.firestore.model.DocumentKey, param1: com.google.firebase.firestore.model.value.ObjectValue): com.google.firestore.v1.Document;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class RemoteStore extends com.google.firebase.firestore.remote.WatchChangeAggregator.TargetMetadataProvider {
public static class: java.lang.Class<com.google.firebase.firestore.remote.RemoteStore>;
public getQueryDataForTarget(param0: number): com.google.firebase.firestore.local.QueryData;
public fillWritePipeline(): void;
public stopListening(param0: number): void;
public handleCredentialChange(): void;
public enableNetwork(): void;
public createTransaction(): com.google.firebase.firestore.core.Transaction;
public listen(param0: com.google.firebase.firestore.local.QueryData): void;
public shutdown(): void;
public constructor(param0: com.google.firebase.firestore.remote.RemoteStore.RemoteStoreCallback, param1: com.google.firebase.firestore.local.LocalStore, param2: com.google.firebase.firestore.remote.Datastore, param3: com.google.firebase.firestore.util.AsyncQueue, param4: com.google.firebase.firestore.remote.ConnectivityMonitor);
public start(): void;
public disableNetwork(): void;
public canUseNetwork(): boolean;
public getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
}
export module RemoteStore {
export class RemoteStoreCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.RemoteStore.RemoteStoreCallback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.RemoteStore$RemoteStoreCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
handleRemoteEvent(param0: com.google.firebase.firestore.remote.RemoteEvent): void;
handleRejectedListen(param0: number, param1: io.grpc.Status): void;
handleSuccessfulWrite(param0: com.google.firebase.firestore.model.mutation.MutationBatchResult): void;
handleRejectedWrite(param0: number, param1: io.grpc.Status): void;
handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
});
public constructor();
public getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public handleRemoteEvent(param0: com.google.firebase.firestore.remote.RemoteEvent): void;
public handleSuccessfulWrite(param0: com.google.firebase.firestore.model.mutation.MutationBatchResult): void;
public handleRejectedWrite(param0: number, param1: io.grpc.Status): void;
public handleOnlineStateChange(param0: com.google.firebase.firestore.core.OnlineState): void;
public handleRejectedListen(param0: number, param1: io.grpc.Status): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class Stream<CallbackType> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.remote.Stream<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.Stream<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
isStarted(): boolean;
isOpen(): boolean;
start(): void;
stop(): void;
inhibitBackoff(): void;
});
public constructor();
public inhibitBackoff(): void;
public start(): void;
public isStarted(): boolean;
public isOpen(): boolean;
public stop(): void;
}
export module Stream {
export class State {
public static class: java.lang.Class<com.google.firebase.firestore.remote.Stream.State>;
public static Initial: com.google.firebase.firestore.remote.Stream.State;
public static Starting: com.google.firebase.firestore.remote.Stream.State;
public static Open: com.google.firebase.firestore.remote.Stream.State;
public static Error: com.google.firebase.firestore.remote.Stream.State;
public static Backoff: com.google.firebase.firestore.remote.Stream.State;
public static valueOf(param0: string): com.google.firebase.firestore.remote.Stream.State;
public static values(): native.Array<com.google.firebase.firestore.remote.Stream.State>;
}
export class StreamCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.Stream.StreamCallback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.Stream$StreamCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onOpen(): void;
onClose(param0: io.grpc.Status): void;
});
public constructor();
public onOpen(): void;
public onClose(param0: io.grpc.Status): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class TargetChange {
public static class: java.lang.Class<com.google.firebase.firestore.remote.TargetChange>;
public getResumeToken(): com.google.protobuf.ByteString;
public isCurrent(): boolean;
public constructor(param0: com.google.protobuf.ByteString, param1: boolean, param2: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param3: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>, param4: com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>);
public getAddedDocuments(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public equals(param0: any): boolean;
public hashCode(): number;
public getRemovedDocuments(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public getModifiedDocuments(): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class TargetState {
public static class: java.lang.Class<com.google.firebase.firestore.remote.TargetState>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export abstract class WatchChange {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChange>;
}
export module WatchChange {
export class DocumentChange extends com.google.firebase.firestore.remote.WatchChange {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChange.DocumentChange>;
public getDocumentKey(): com.google.firebase.firestore.model.DocumentKey;
public getRemovedTargetIds(): java.util.List<java.lang.Integer>;
public hashCode(): number;
public toString(): string;
public constructor(param0: java.util.List<java.lang.Integer>, param1: java.util.List<java.lang.Integer>, param2: com.google.firebase.firestore.model.DocumentKey, param3: com.google.firebase.firestore.model.MaybeDocument);
public equals(param0: any): boolean;
public getNewDocument(): com.google.firebase.firestore.model.MaybeDocument;
public getUpdatedTargetIds(): java.util.List<java.lang.Integer>;
}
export class ExistenceFilterWatchChange extends com.google.firebase.firestore.remote.WatchChange {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChange.ExistenceFilterWatchChange>;
public getExistenceFilter(): com.google.firebase.firestore.remote.ExistenceFilter;
public toString(): string;
public constructor(param0: number, param1: com.google.firebase.firestore.remote.ExistenceFilter);
public getTargetId(): number;
}
export class WatchTargetChange extends com.google.firebase.firestore.remote.WatchChange {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChange.WatchTargetChange>;
public getTargetIds(): java.util.List<java.lang.Integer>;
public getResumeToken(): com.google.protobuf.ByteString;
public getChangeType(): com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public hashCode(): number;
public getCause(): io.grpc.Status;
public constructor(param0: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType, param1: java.util.List<java.lang.Integer>);
public toString(): string;
public constructor(param0: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType, param1: java.util.List<java.lang.Integer>, param2: com.google.protobuf.ByteString);
public equals(param0: any): boolean;
public constructor(param0: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType, param1: java.util.List<java.lang.Integer>, param2: com.google.protobuf.ByteString, param3: io.grpc.Status);
}
export class WatchTargetChangeType {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType>;
public static NoChange: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public static Added: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public static Removed: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public static Current: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public static Reset: com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
public static values(): native.Array<com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType>;
public static valueOf(param0: string): com.google.firebase.firestore.remote.WatchChange.WatchTargetChangeType;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class WatchChangeAggregator {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChangeAggregator>;
public constructor(param0: com.google.firebase.firestore.remote.WatchChangeAggregator.TargetMetadataProvider);
public handleDocumentChange(param0: com.google.firebase.firestore.remote.WatchChange.DocumentChange): void;
public createRemoteEvent(param0: com.google.firebase.firestore.model.SnapshotVersion): com.google.firebase.firestore.remote.RemoteEvent;
public handleTargetChange(param0: com.google.firebase.firestore.remote.WatchChange.WatchTargetChange): void;
public handleExistenceFilter(param0: com.google.firebase.firestore.remote.WatchChange.ExistenceFilterWatchChange): void;
}
export module WatchChangeAggregator {
export class TargetMetadataProvider {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchChangeAggregator.TargetMetadataProvider>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.WatchChangeAggregator$TargetMetadataProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
getQueryDataForTarget(param0: number): com.google.firebase.firestore.local.QueryData;
});
public constructor();
public getRemoteKeysForTarget(param0: number): com.google.firebase.database.collection.ImmutableSortedSet<com.google.firebase.firestore.model.DocumentKey>;
public getQueryDataForTarget(param0: number): com.google.firebase.firestore.local.QueryData;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class WatchStream extends com.google.firebase.firestore.remote.AbstractStream<com.google.firestore.v1.ListenRequest,com.google.firestore.v1.ListenResponse,com.google.firebase.firestore.remote.WatchStream.Callback> {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchStream>;
public static EMPTY_RESUME_TOKEN: com.google.protobuf.ByteString;
public watchQuery(param0: com.google.firebase.firestore.local.QueryData): void;
public inhibitBackoff(): void;
public start(): void;
public isStarted(): boolean;
public onNext(param0: any): void;
public isOpen(): boolean;
public stop(): void;
public unwatchTarget(param0: number): void;
public onNext(param0: com.google.firestore.v1.ListenResponse): void;
}
export module WatchStream {
export class Callback extends com.google.firebase.firestore.remote.Stream.StreamCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WatchStream.Callback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.WatchStream$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onWatchChange(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: com.google.firebase.firestore.remote.WatchChange): void;
onOpen(): void;
onClose(param0: io.grpc.Status): void;
});
public constructor();
public onOpen(): void;
public onClose(param0: io.grpc.Status): void;
public onWatchChange(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: com.google.firebase.firestore.remote.WatchChange): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module remote {
export class WriteStream extends com.google.firebase.firestore.remote.AbstractStream<com.google.firestore.v1.WriteRequest,com.google.firestore.v1.WriteResponse,com.google.firebase.firestore.remote.WriteStream.Callback> {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WriteStream>;
public static EMPTY_STREAM_TOKEN: com.google.protobuf.ByteString;
public handshakeComplete: boolean;
public tearDown(): void;
public inhibitBackoff(): void;
public start(): void;
public isStarted(): boolean;
public onNext(param0: any): void;
public onNext(param0: com.google.firestore.v1.WriteResponse): void;
public isOpen(): boolean;
public stop(): void;
}
export module WriteStream {
export class Callback extends com.google.firebase.firestore.remote.Stream.StreamCallback {
public static class: java.lang.Class<com.google.firebase.firestore.remote.WriteStream.Callback>;
/**
* Constructs a new instance of the com.google.firebase.firestore.remote.WriteStream$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onHandshakeComplete(): void;
onWriteResponse(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: java.util.List<com.google.firebase.firestore.model.mutation.MutationResult>): void;
onOpen(): void;
onClose(param0: io.grpc.Status): void;
});
public constructor();
public onOpen(): void;
public onHandshakeComplete(): void;
public onClose(param0: io.grpc.Status): void;
public onWriteResponse(param0: com.google.firebase.firestore.model.SnapshotVersion, param1: java.util.List<com.google.firebase.firestore.model.mutation.MutationResult>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class ApiUtil {
public static class: java.lang.Class<com.google.firebase.firestore.util.ApiUtil>;
public constructor();
public static newAssertionError(param0: string, param1: java.lang.Throwable): java.lang.AssertionError;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Assert {
public static class: java.lang.Class<com.google.firebase.firestore.util.Assert>;
public constructor();
public static fail(param0: java.lang.Throwable, param1: string, param2: native.Array<any>): java.lang.AssertionError;
public static fail(param0: string, param1: native.Array<any>): java.lang.AssertionError;
public static hardAssert(param0: boolean, param1: string, param2: native.Array<any>): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class AsyncQueue {
public static class: java.lang.Class<com.google.firebase.firestore.util.AsyncQueue>;
public enqueueAndForgetEvenAfterShutdown(param0: java.lang.Runnable): void;
public verifyIsCurrentThread(): void;
public constructor();
public static callTask(param0: java.util.concurrent.Executor, param1: java.util.concurrent.Callable): com.google.android.gms.tasks.Task;
public enqueueAndForget(param0: java.lang.Runnable): void;
public enqueue(param0: java.lang.Runnable): com.google.android.gms.tasks.Task<java.lang.Void>;
public getExecutor(): java.util.concurrent.Executor;
public containsDelayedTask(param0: com.google.firebase.firestore.util.AsyncQueue.TimerId): boolean;
public runDelayedTasksUntil(param0: com.google.firebase.firestore.util.AsyncQueue.TimerId): void;
public panic(param0: java.lang.Throwable): void;
public skipDelaysForTimerId(param0: com.google.firebase.firestore.util.AsyncQueue.TimerId): void;
public shutdown(): void;
public enqueueAfterDelay(param0: com.google.firebase.firestore.util.AsyncQueue.TimerId, param1: number, param2: java.lang.Runnable): com.google.firebase.firestore.util.AsyncQueue.DelayedTask;
public enqueueAndInitiateShutdown(param0: java.lang.Runnable): com.google.android.gms.tasks.Task<java.lang.Void>;
public enqueue(param0: java.util.concurrent.Callable): com.google.android.gms.tasks.Task;
public isShuttingDown(): boolean;
public runSync(param0: java.lang.Runnable): void;
}
export module AsyncQueue {
export class DelayedTask {
public static class: java.lang.Class<com.google.firebase.firestore.util.AsyncQueue.DelayedTask>;
public cancel(): void;
}
export class SynchronizedShutdownAwareExecutor {
public static class: java.lang.Class<com.google.firebase.firestore.util.AsyncQueue.SynchronizedShutdownAwareExecutor>;
public execute(param0: java.lang.Runnable): void;
public executeEvenAfterShutdown(param0: java.lang.Runnable): void;
}
export module SynchronizedShutdownAwareExecutor {
export class DelayedStartFactory {
public static class: java.lang.Class<com.google.firebase.firestore.util.AsyncQueue.SynchronizedShutdownAwareExecutor.DelayedStartFactory>;
public run(): void;
public newThread(param0: java.lang.Runnable): java.lang.Thread;
}
}
export class TimerId {
public static class: java.lang.Class<com.google.firebase.firestore.util.AsyncQueue.TimerId>;
public static ALL: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static LISTEN_STREAM_IDLE: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static LISTEN_STREAM_CONNECTION_BACKOFF: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static WRITE_STREAM_IDLE: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static WRITE_STREAM_CONNECTION_BACKOFF: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static ONLINE_STATE_TIMEOUT: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static GARBAGE_COLLECTION: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static RETRY_TRANSACTION: com.google.firebase.firestore.util.AsyncQueue.TimerId;
public static values(): native.Array<com.google.firebase.firestore.util.AsyncQueue.TimerId>;
public static valueOf(param0: string): com.google.firebase.firestore.util.AsyncQueue.TimerId;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class BackgroundQueue {
public static class: java.lang.Class<com.google.firebase.firestore.util.BackgroundQueue>;
public constructor();
public execute(param0: java.lang.Runnable): void;
public drain(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Consumer<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.util.Consumer<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.util.Consumer<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
accept(param0: T): void;
});
public constructor();
public accept(param0: T): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class CustomClassMapper {
public static class: java.lang.Class<com.google.firebase.firestore.util.CustomClassMapper>;
public constructor();
public static convertToCustomClass(param0: any, param1: java.lang.Class, param2: com.google.firebase.firestore.DocumentReference): any;
public static convertToPlainJavaTypes(param0: any): any;
public static convertToPlainJavaTypes(param0: java.util.Map<any,any>): java.util.Map<string,any>;
}
export module CustomClassMapper {
export class BeanMapper<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.util.CustomClassMapper.BeanMapper<any>>;
}
export class DeserializeContext {
public static class: java.lang.Class<com.google.firebase.firestore.util.CustomClassMapper.DeserializeContext>;
}
export class ErrorPath {
public static class: java.lang.Class<com.google.firebase.firestore.util.CustomClassMapper.ErrorPath>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Executors {
public static class: java.lang.Class<com.google.firebase.firestore.util.Executors>;
public static DEFAULT_CALLBACK_EXECUTOR: java.util.concurrent.Executor;
public static DIRECT_EXECUTOR: java.util.concurrent.Executor;
public static BACKGROUND_EXECUTOR: java.util.concurrent.Executor;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class ExponentialBackoff {
public static class: java.lang.Class<com.google.firebase.firestore.util.ExponentialBackoff>;
public static DEFAULT_BACKOFF_INITIAL_DELAY_MS: number;
public static DEFAULT_BACKOFF_FACTOR: number;
public static DEFAULT_BACKOFF_MAX_DELAY_MS: number;
public cancel(): void;
public constructor(param0: com.google.firebase.firestore.util.AsyncQueue, param1: com.google.firebase.firestore.util.AsyncQueue.TimerId);
public constructor(param0: com.google.firebase.firestore.util.AsyncQueue, param1: com.google.firebase.firestore.util.AsyncQueue.TimerId, param2: number, param3: number, param4: number);
public resetToMax(): void;
public backoffAndRun(param0: java.lang.Runnable): void;
public reset(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class FileUtil {
public static class: java.lang.Class<com.google.firebase.firestore.util.FileUtil>;
public constructor();
public static delete(param0: java.io.File): void;
}
export module FileUtil {
export class DefaultFileDeleter {
public static class: java.lang.Class<com.google.firebase.firestore.util.FileUtil.DefaultFileDeleter>;
public static delete(param0: java.io.File): void;
}
export class LegacyFileDeleter {
public static class: java.lang.Class<com.google.firebase.firestore.util.FileUtil.LegacyFileDeleter>;
public static delete(param0: java.io.File): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Listener<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.util.Listener<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.util.Listener<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onValue(param0: T): void;
});
public constructor();
public onValue(param0: T): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Logger {
public static class: java.lang.Class<com.google.firebase.firestore.util.Logger>;
public constructor();
public static setLogLevel(param0: com.google.firebase.firestore.util.Logger.Level): void;
public static isDebugEnabled(): boolean;
public static debug(param0: string, param1: string, param2: native.Array<any>): void;
public static warn(param0: string, param1: string, param2: native.Array<any>): void;
}
export module Logger {
export class Level {
public static class: java.lang.Class<com.google.firebase.firestore.util.Logger.Level>;
public static DEBUG: com.google.firebase.firestore.util.Logger.Level;
public static WARN: com.google.firebase.firestore.util.Logger.Level;
public static NONE: com.google.firebase.firestore.util.Logger.Level;
public static valueOf(param0: string): com.google.firebase.firestore.util.Logger.Level;
public static values(): native.Array<com.google.firebase.firestore.util.Logger.Level>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Supplier<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.firestore.util.Supplier<any>>;
/**
* Constructs a new instance of the com.google.firebase.firestore.util.Supplier<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
get(): T;
});
public constructor();
public get(): T;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class ThrottledForwardingExecutor {
public static class: java.lang.Class<com.google.firebase.firestore.util.ThrottledForwardingExecutor>;
public execute(param0: java.lang.Runnable): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module firestore {
export module util {
export class Util {
public static class: java.lang.Class<com.google.firebase.firestore.util.Util>;
public static collectUpdateArguments(param0: number, param1: any, param2: any, param3: native.Array<any>): java.util.List<any>;
public static compareIntegers(param0: number, param1: number): number;
public constructor();
public static crashMainThread(param0: java.lang.RuntimeException): void;
public static compareInts(param0: number, param1: number): number;
public static convertThrowableToException(param0: java.lang.Throwable): java.lang.Exception;
public static voidErrorTransformer(): com.google.android.gms.tasks.Continuation<java.lang.Void,java.lang.Void>;
public static comparator(): java.util.Comparator;
public static exceptionFromStatus(param0: io.grpc.Status): com.google.firebase.firestore.FirebaseFirestoreException;
public static compareMixed(param0: number, param1: number): number;
public static compareLongs(param0: number, param1: number): number;
public static compareDoubles(param0: number, param1: number): number;
public static toDebugString(param0: com.google.protobuf.ByteString): string;
public static autoId(): string;
public static compareBooleans(param0: boolean, param1: boolean): number;
public static typeName(param0: any): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ArrayValue extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ArrayValue,com.google.firestore.v1.ArrayValue.Builder> implements com.google.firestore.v1.ArrayValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ArrayValue>;
public static VALUES_FIELD_NUMBER: number;
public static newBuilder(): com.google.firestore.v1.ArrayValue.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ArrayValue;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ArrayValue>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ArrayValue;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ArrayValue;
public getValues(param0: number): com.google.firestore.v1.Value;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ArrayValue;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ArrayValue;
public static newBuilder(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.ArrayValue.Builder;
public getValuesCount(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ArrayValue;
public getValuesOrBuilder(param0: number): com.google.firestore.v1.ValueOrBuilder;
public static getDefaultInstance(): com.google.firestore.v1.ArrayValue;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ArrayValue;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ArrayValue;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ArrayValue;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ArrayValue;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
public getValuesOrBuilderList(): java.util.List<any>;
}
export module ArrayValue {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ArrayValue,com.google.firestore.v1.ArrayValue.Builder> implements com.google.firestore.v1.ArrayValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ArrayValue.Builder>;
public addAllValues(param0: java.lang.Iterable<any>): com.google.firestore.v1.ArrayValue.Builder;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
public addValues(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.ArrayValue.Builder;
public removeValues(param0: number): com.google.firestore.v1.ArrayValue.Builder;
public getValues(param0: number): com.google.firestore.v1.Value;
public setValues(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.ArrayValue.Builder;
public addValues(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.ArrayValue.Builder;
public setValues(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.ArrayValue.Builder;
public addValues(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.ArrayValue.Builder;
public getValuesCount(): number;
public addValues(param0: com.google.firestore.v1.Value): com.google.firestore.v1.ArrayValue.Builder;
public clearValues(): com.google.firestore.v1.ArrayValue.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ArrayValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ArrayValueOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ArrayValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getValuesList(): java.util.List<com.google.firestore.v1.Value>;
getValues(param0: number): com.google.firestore.v1.Value;
getValuesCount(): number;
});
public constructor();
public getValues(param0: number): com.google.firestore.v1.Value;
public getValuesCount(): number;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BatchGetDocumentsRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.BatchGetDocumentsRequest,com.google.firestore.v1.BatchGetDocumentsRequest.Builder> implements com.google.firestore.v1.BatchGetDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static DOCUMENTS_FIELD_NUMBER: number;
public static MASK_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static NEW_TRANSACTION_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsRequest;
public getTransaction(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.BatchGetDocumentsRequest;
public getDocuments(param0: number): string;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.BatchGetDocumentsRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.BatchGetDocumentsRequest>;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsRequest;
public getDatabase(): string;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public getDocumentsCount(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.BatchGetDocumentsRequest;
public getMask(): com.google.firestore.v1.DocumentMask;
public getDocumentsList(): java.util.List<string>;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.BatchGetDocumentsRequest;
public static newBuilder(param0: com.google.firestore.v1.BatchGetDocumentsRequest): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getSerializedSize(): number;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsRequest;
public getConsistencySelectorCase(): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public hasMask(): boolean;
public static getDefaultInstance(): com.google.firestore.v1.BatchGetDocumentsRequest;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsRequest;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static newBuilder(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
}
export module BatchGetDocumentsRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.BatchGetDocumentsRequest,com.google.firestore.v1.BatchGetDocumentsRequest.Builder> implements com.google.firestore.v1.BatchGetDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsRequest.Builder>;
public setNewTransaction(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public clearConsistencySelector(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getMask(): com.google.firestore.v1.DocumentMask;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public setDocuments(param0: number, param1: string): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public clearDatabase(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public addDocuments(param0: string): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public clearTransaction(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public setNewTransaction(param0: com.google.firestore.v1.TransactionOptions.Builder): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getDocuments(param0: number): string;
public setMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public clearNewTransaction(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public clearMask(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public clearDocuments(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getConsistencySelectorCase(): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public getDatabase(): string;
public mergeNewTransaction(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public setMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public addAllDocuments(param0: java.lang.Iterable<string>): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getDocumentsCount(): number;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public mergeMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public addDocumentsBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public hasMask(): boolean;
public clearReadTime(): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
public getDocumentsList(): java.util.List<string>;
public setDatabase(param0: string): com.google.firestore.v1.BatchGetDocumentsRequest.Builder;
}
export class ConsistencySelectorCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase>;
public static TRANSACTION: com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static NEW_TRANSACTION: com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static READ_TIME: com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static CONSISTENCYSELECTOR_NOT_SET: com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static valueOf(param0: string): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static valueOf(param0: number): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static forNumber(param0: number): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public static values(): native.Array<com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase>;
public getNumber(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BatchGetDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.BatchGetDocumentsRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
getDocumentsList(): java.util.List<string>;
getDocumentsCount(): number;
getDocuments(param0: number): string;
getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
hasMask(): boolean;
getMask(): com.google.firestore.v1.DocumentMask;
getTransaction(): com.google.protobuf.ByteString;
getNewTransaction(): com.google.firestore.v1.TransactionOptions;
getReadTime(): com.google.protobuf.Timestamp;
getConsistencySelectorCase(): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
});
public constructor();
public getDatabase(): string;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public getMask(): com.google.firestore.v1.DocumentMask;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public getConsistencySelectorCase(): com.google.firestore.v1.BatchGetDocumentsRequest.ConsistencySelectorCase;
public hasMask(): boolean;
public getDocumentsList(): java.util.List<string>;
public getDocumentsCount(): number;
public getTransaction(): com.google.protobuf.ByteString;
public getDocuments(param0: number): string;
public getReadTime(): com.google.protobuf.Timestamp;
public getDatabaseBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BatchGetDocumentsResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.BatchGetDocumentsResponse,com.google.firestore.v1.BatchGetDocumentsResponse.Builder> implements com.google.firestore.v1.BatchGetDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsResponse>;
public static FOUND_FIELD_NUMBER: number;
public static MISSING_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsResponse;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.BatchGetDocumentsResponse;
public getMissingBytes(): com.google.protobuf.ByteString;
public getTransaction(): com.google.protobuf.ByteString;
public getFound(): com.google.firestore.v1.Document;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.BatchGetDocumentsResponse;
public static getDefaultInstance(): com.google.firestore.v1.BatchGetDocumentsResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.BatchGetDocumentsResponse>;
public getMissing(): string;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.BatchGetDocumentsResponse;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsResponse;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.BatchGetDocumentsResponse;
public static newBuilder(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsResponse;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsResponse;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsResponse;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BatchGetDocumentsResponse;
public static newBuilder(param0: com.google.firestore.v1.BatchGetDocumentsResponse): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public hasReadTime(): boolean;
public getResultCase(): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
}
export module BatchGetDocumentsResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.BatchGetDocumentsResponse,com.google.firestore.v1.BatchGetDocumentsResponse.Builder> implements com.google.firestore.v1.BatchGetDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsResponse.Builder>;
public getMissingBytes(): com.google.protobuf.ByteString;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public getResultCase(): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public clearReadTime(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public setMissingBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public mergeFound(param0: com.google.firestore.v1.Document): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public clearTransaction(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public clearFound(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public hasReadTime(): boolean;
public setFound(param0: com.google.firestore.v1.Document): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public setFound(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public getMissing(): string;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public clearResult(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public clearMissing(): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public setMissing(param0: string): com.google.firestore.v1.BatchGetDocumentsResponse.Builder;
public getFound(): com.google.firestore.v1.Document;
public getTransaction(): com.google.protobuf.ByteString;
}
export class ResultCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase>;
public static FOUND: com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public static MISSING: com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public static RESULT_NOT_SET: com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public static values(): native.Array<com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase>;
public static valueOf(param0: number): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
public static forNumber(param0: number): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BatchGetDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BatchGetDocumentsResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.BatchGetDocumentsResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFound(): com.google.firestore.v1.Document;
getMissing(): string;
getMissingBytes(): com.google.protobuf.ByteString;
getTransaction(): com.google.protobuf.ByteString;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
getResultCase(): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
});
public constructor();
public getMissingBytes(): com.google.protobuf.ByteString;
public getTransaction(): com.google.protobuf.ByteString;
public getFound(): com.google.firestore.v1.Document;
public getReadTime(): com.google.protobuf.Timestamp;
public hasReadTime(): boolean;
public getMissing(): string;
public getResultCase(): com.google.firestore.v1.BatchGetDocumentsResponse.ResultCase;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BeginTransactionRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.BeginTransactionRequest,com.google.firestore.v1.BeginTransactionRequest.Builder> implements com.google.firestore.v1.BeginTransactionRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static OPTIONS_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionRequest;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.BeginTransactionRequest>;
public getSerializedSize(): number;
public static newBuilder(param0: com.google.firestore.v1.BeginTransactionRequest): com.google.firestore.v1.BeginTransactionRequest.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionRequest;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.BeginTransactionRequest;
public getDatabase(): string;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.BeginTransactionRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.BeginTransactionRequest;
public static getDefaultInstance(): com.google.firestore.v1.BeginTransactionRequest;
public hasOptions(): boolean;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.BeginTransactionRequest;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BeginTransactionRequest;
public static newBuilder(): com.google.firestore.v1.BeginTransactionRequest.Builder;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getOptions(): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionRequest;
}
export module BeginTransactionRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.BeginTransactionRequest,com.google.firestore.v1.BeginTransactionRequest.Builder> implements com.google.firestore.v1.BeginTransactionRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionRequest.Builder>;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public hasOptions(): boolean;
public getOptions(): com.google.firestore.v1.TransactionOptions;
public mergeOptions(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.BeginTransactionRequest.Builder;
public getDatabase(): string;
public clearOptions(): com.google.firestore.v1.BeginTransactionRequest.Builder;
public clearDatabase(): com.google.firestore.v1.BeginTransactionRequest.Builder;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BeginTransactionRequest.Builder;
public setOptions(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.BeginTransactionRequest.Builder;
public setDatabase(param0: string): com.google.firestore.v1.BeginTransactionRequest.Builder;
public setOptions(param0: com.google.firestore.v1.TransactionOptions.Builder): com.google.firestore.v1.BeginTransactionRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BeginTransactionRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.BeginTransactionRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
hasOptions(): boolean;
getOptions(): com.google.firestore.v1.TransactionOptions;
});
public constructor();
public getDatabase(): string;
public hasOptions(): boolean;
public getOptions(): com.google.firestore.v1.TransactionOptions;
public getDatabaseBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BeginTransactionResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.BeginTransactionResponse,com.google.firestore.v1.BeginTransactionResponse.Builder> implements com.google.firestore.v1.BeginTransactionResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionResponse>;
public static TRANSACTION_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.BeginTransactionResponse;
public getTransaction(): com.google.protobuf.ByteString;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.BeginTransactionResponse;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionResponse;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionResponse;
public static getDefaultInstance(): com.google.firestore.v1.BeginTransactionResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionResponse;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BeginTransactionResponse;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.BeginTransactionResponse;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.BeginTransactionResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.BeginTransactionResponse>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(param0: com.google.firestore.v1.BeginTransactionResponse): com.google.firestore.v1.BeginTransactionResponse.Builder;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static newBuilder(): com.google.firestore.v1.BeginTransactionResponse.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.BeginTransactionResponse;
}
export module BeginTransactionResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.BeginTransactionResponse,com.google.firestore.v1.BeginTransactionResponse.Builder> implements com.google.firestore.v1.BeginTransactionResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionResponse.Builder>;
public clearTransaction(): com.google.firestore.v1.BeginTransactionResponse.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.BeginTransactionResponse.Builder;
public getTransaction(): com.google.protobuf.ByteString;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class BeginTransactionResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.BeginTransactionResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.BeginTransactionResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTransaction(): com.google.protobuf.ByteString;
});
public constructor();
public getTransaction(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CommitRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.CommitRequest,com.google.firestore.v1.CommitRequest.Builder> implements com.google.firestore.v1.CommitRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static WRITES_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.CommitRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.CommitRequest>;
public getTransaction(): com.google.protobuf.ByteString;
public static getDefaultInstance(): com.google.firestore.v1.CommitRequest;
public getDatabase(): string;
public getWritesOrBuilderList(): java.util.List<any>;
public getWritesCount(): number;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.CommitRequest;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitRequest;
public static newBuilder(param0: com.google.firestore.v1.CommitRequest): com.google.firestore.v1.CommitRequest.Builder;
public static newBuilder(): com.google.firestore.v1.CommitRequest.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getWritesOrBuilder(param0: number): com.google.firestore.v1.WriteOrBuilder;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitRequest;
public getWrites(param0: number): com.google.firestore.v1.Write;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.CommitRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.CommitRequest;
public getSerializedSize(): number;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CommitRequest;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitRequest;
}
export module CommitRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.CommitRequest,com.google.firestore.v1.CommitRequest.Builder> implements com.google.firestore.v1.CommitRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitRequest.Builder>;
public getWritesCount(): number;
public getWrites(param0: number): com.google.firestore.v1.Write;
public addWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firestore.v1.CommitRequest.Builder;
public setDatabase(param0: string): com.google.firestore.v1.CommitRequest.Builder;
public clearWrites(): com.google.firestore.v1.CommitRequest.Builder;
public getDatabase(): string;
public addWrites(param0: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.CommitRequest.Builder;
public setWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firestore.v1.CommitRequest.Builder;
public setWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.CommitRequest.Builder;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CommitRequest.Builder;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public addWrites(param0: com.google.firestore.v1.Write): com.google.firestore.v1.CommitRequest.Builder;
public clearDatabase(): com.google.firestore.v1.CommitRequest.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CommitRequest.Builder;
public addWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.CommitRequest.Builder;
public clearTransaction(): com.google.firestore.v1.CommitRequest.Builder;
public addAllWrites(param0: java.lang.Iterable<any>): com.google.firestore.v1.CommitRequest.Builder;
public removeWrites(param0: number): com.google.firestore.v1.CommitRequest.Builder;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getTransaction(): com.google.protobuf.ByteString;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CommitRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.CommitRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
getWritesList(): java.util.List<com.google.firestore.v1.Write>;
getWrites(param0: number): com.google.firestore.v1.Write;
getWritesCount(): number;
getTransaction(): com.google.protobuf.ByteString;
});
public constructor();
public getDatabase(): string;
public getWritesCount(): number;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getTransaction(): com.google.protobuf.ByteString;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public getWrites(param0: number): com.google.firestore.v1.Write;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CommitResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.CommitResponse,com.google.firestore.v1.CommitResponse.Builder> implements com.google.firestore.v1.CommitResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitResponse>;
public static WRITE_RESULTS_FIELD_NUMBER: number;
public static COMMIT_TIME_FIELD_NUMBER: number;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.CommitResponse;
public getSerializedSize(): number;
public static newBuilder(): com.google.firestore.v1.CommitResponse.Builder;
public static newBuilder(param0: com.google.firestore.v1.CommitResponse): com.google.firestore.v1.CommitResponse.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.CommitResponse;
public getWriteResultsOrBuilderList(): java.util.List<any>;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.CommitResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitResponse;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.CommitResponse;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitResponse;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.CommitResponse>;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitResponse;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CommitResponse;
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public getWriteResultsCount(): number;
public getWriteResultsOrBuilder(param0: number): com.google.firestore.v1.WriteResultOrBuilder;
public hasCommitTime(): boolean;
public getCommitTime(): com.google.protobuf.Timestamp;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CommitResponse;
public static getDefaultInstance(): com.google.firestore.v1.CommitResponse;
}
export module CommitResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.CommitResponse,com.google.firestore.v1.CommitResponse.Builder> implements com.google.firestore.v1.CommitResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitResponse.Builder>;
public clearCommitTime(): com.google.firestore.v1.CommitResponse.Builder;
public removeWriteResults(param0: number): com.google.firestore.v1.CommitResponse.Builder;
public getCommitTime(): com.google.protobuf.Timestamp;
public addWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.CommitResponse.Builder;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public mergeCommitTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.CommitResponse.Builder;
public setCommitTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.CommitResponse.Builder;
public addWriteResults(param0: com.google.firestore.v1.WriteResult): com.google.firestore.v1.CommitResponse.Builder;
public setCommitTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.CommitResponse.Builder;
public getWriteResultsCount(): number;
public addWriteResults(param0: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.CommitResponse.Builder;
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public addAllWriteResults(param0: java.lang.Iterable<any>): com.google.firestore.v1.CommitResponse.Builder;
public setWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.CommitResponse.Builder;
public setWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult): com.google.firestore.v1.CommitResponse.Builder;
public addWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult): com.google.firestore.v1.CommitResponse.Builder;
public clearWriteResults(): com.google.firestore.v1.CommitResponse.Builder;
public hasCommitTime(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CommitResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CommitResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.CommitResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
getWriteResultsCount(): number;
hasCommitTime(): boolean;
getCommitTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public getWriteResultsCount(): number;
public hasCommitTime(): boolean;
public getCommitTime(): com.google.protobuf.Timestamp;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CommonProto {
public static class: java.lang.Class<com.google.firestore.v1.CommonProto>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CreateDocumentRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.CreateDocumentRequest,com.google.firestore.v1.CreateDocumentRequest.Builder> implements com.google.firestore.v1.CreateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CreateDocumentRequest>;
public static PARENT_FIELD_NUMBER: number;
public static COLLECTION_ID_FIELD_NUMBER: number;
public static DOCUMENT_ID_FIELD_NUMBER: number;
public static DOCUMENT_FIELD_NUMBER: number;
public static MASK_FIELD_NUMBER: number;
public getDocumentId(): string;
public static newBuilder(param0: com.google.firestore.v1.CreateDocumentRequest): com.google.firestore.v1.CreateDocumentRequest.Builder;
public static newBuilder(): com.google.firestore.v1.CreateDocumentRequest.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CreateDocumentRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.CreateDocumentRequest;
public hasDocument(): boolean;
public static getDefaultInstance(): com.google.firestore.v1.CreateDocumentRequest;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CreateDocumentRequest;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.CreateDocumentRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getDocument(): com.google.firestore.v1.Document;
public getDocumentIdBytes(): com.google.protobuf.ByteString;
public getMask(): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.CreateDocumentRequest;
public getSerializedSize(): number;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.CreateDocumentRequest;
public hasMask(): boolean;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CreateDocumentRequest;
public getCollectionId(): string;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CreateDocumentRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.CreateDocumentRequest>;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.CreateDocumentRequest;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CreateDocumentRequest;
}
export module CreateDocumentRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.CreateDocumentRequest,com.google.firestore.v1.CreateDocumentRequest.Builder> implements com.google.firestore.v1.CreateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CreateDocumentRequest.Builder>;
public clearParent(): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setDocumentIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setDocument(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.CreateDocumentRequest.Builder;
public getCollectionId(): string;
public setDocumentId(param0: string): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.CreateDocumentRequest.Builder;
public getParent(): string;
public getMask(): com.google.firestore.v1.DocumentMask;
public mergeMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.CreateDocumentRequest.Builder;
public clearDocument(): com.google.firestore.v1.CreateDocumentRequest.Builder;
public getParentBytes(): com.google.protobuf.ByteString;
public getDocumentIdBytes(): com.google.protobuf.ByteString;
public mergeDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.CreateDocumentRequest.Builder;
public hasDocument(): boolean;
public getDocument(): com.google.firestore.v1.Document;
public getDocumentId(): string;
public clearDocumentId(): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setParentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CreateDocumentRequest.Builder;
public clearCollectionId(): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setCollectionIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.CreateDocumentRequest.Builder;
public hasMask(): boolean;
public setParent(param0: string): com.google.firestore.v1.CreateDocumentRequest.Builder;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public setCollectionId(param0: string): com.google.firestore.v1.CreateDocumentRequest.Builder;
public setDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.CreateDocumentRequest.Builder;
public clearMask(): com.google.firestore.v1.CreateDocumentRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CreateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CreateDocumentRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.CreateDocumentRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParent(): string;
getParentBytes(): com.google.protobuf.ByteString;
getCollectionId(): string;
getCollectionIdBytes(): com.google.protobuf.ByteString;
getDocumentId(): string;
getDocumentIdBytes(): com.google.protobuf.ByteString;
hasDocument(): boolean;
getDocument(): com.google.firestore.v1.Document;
hasMask(): boolean;
getMask(): com.google.firestore.v1.DocumentMask;
});
public constructor();
public getDocumentId(): string;
public getMask(): com.google.firestore.v1.DocumentMask;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public hasMask(): boolean;
public getCollectionId(): string;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public getDocument(): com.google.firestore.v1.Document;
public hasDocument(): boolean;
public getDocumentIdBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Cursor extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Cursor,com.google.firestore.v1.Cursor.Builder> implements com.google.firestore.v1.CursorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Cursor>;
public static VALUES_FIELD_NUMBER: number;
public static BEFORE_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Cursor;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Cursor;
public static newBuilder(): com.google.firestore.v1.Cursor.Builder;
public static getDefaultInstance(): com.google.firestore.v1.Cursor;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Cursor;
public getBefore(): boolean;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Cursor;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Cursor;
public getValues(param0: number): com.google.firestore.v1.Value;
public static newBuilder(param0: com.google.firestore.v1.Cursor): com.google.firestore.v1.Cursor.Builder;
public getValuesCount(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Cursor>;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Cursor;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Cursor;
public getValuesOrBuilder(param0: number): com.google.firestore.v1.ValueOrBuilder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Cursor;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Cursor;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Cursor;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
public getValuesOrBuilderList(): java.util.List<any>;
}
export module Cursor {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Cursor,com.google.firestore.v1.Cursor.Builder> implements com.google.firestore.v1.CursorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Cursor.Builder>;
public clearValues(): com.google.firestore.v1.Cursor.Builder;
public removeValues(param0: number): com.google.firestore.v1.Cursor.Builder;
public setValues(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.Cursor.Builder;
public addValues(param0: com.google.firestore.v1.Value): com.google.firestore.v1.Cursor.Builder;
public getValuesCount(): number;
public setBefore(param0: boolean): com.google.firestore.v1.Cursor.Builder;
public addValues(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.Cursor.Builder;
public addValues(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Cursor.Builder;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
public addValues(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.Cursor.Builder;
public getValues(param0: number): com.google.firestore.v1.Value;
public setValues(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Cursor.Builder;
public clearBefore(): com.google.firestore.v1.Cursor.Builder;
public addAllValues(param0: java.lang.Iterable<any>): com.google.firestore.v1.Cursor.Builder;
public getBefore(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class CursorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.CursorOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.CursorOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getValuesList(): java.util.List<com.google.firestore.v1.Value>;
getValues(param0: number): com.google.firestore.v1.Value;
getValuesCount(): number;
getBefore(): boolean;
});
public constructor();
public getBefore(): boolean;
public getValues(param0: number): com.google.firestore.v1.Value;
public getValuesCount(): number;
public getValuesList(): java.util.List<com.google.firestore.v1.Value>;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DeleteDocumentRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DeleteDocumentRequest,com.google.firestore.v1.DeleteDocumentRequest.Builder> implements com.google.firestore.v1.DeleteDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DeleteDocumentRequest>;
public static NAME_FIELD_NUMBER: number;
public static CURRENT_DOCUMENT_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DeleteDocumentRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DeleteDocumentRequest;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DeleteDocumentRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DeleteDocumentRequest;
public getSerializedSize(): number;
public getNameBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DeleteDocumentRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DeleteDocumentRequest>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DeleteDocumentRequest;
public static newBuilder(param0: com.google.firestore.v1.DeleteDocumentRequest): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public hasCurrentDocument(): boolean;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DeleteDocumentRequest;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DeleteDocumentRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DeleteDocumentRequest;
public getName(): string;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DeleteDocumentRequest;
public static getDefaultInstance(): com.google.firestore.v1.DeleteDocumentRequest;
public static newBuilder(): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
}
export module DeleteDocumentRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DeleteDocumentRequest,com.google.firestore.v1.DeleteDocumentRequest.Builder> implements com.google.firestore.v1.DeleteDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DeleteDocumentRequest.Builder>;
public setNameBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public hasCurrentDocument(): boolean;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition.Builder): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public mergeCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public setName(param0: string): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public clearCurrentDocument(): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.DeleteDocumentRequest.Builder;
public getNameBytes(): com.google.protobuf.ByteString;
public getName(): string;
public clearName(): com.google.firestore.v1.DeleteDocumentRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DeleteDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DeleteDocumentRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DeleteDocumentRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
getNameBytes(): com.google.protobuf.ByteString;
hasCurrentDocument(): boolean;
getCurrentDocument(): com.google.firestore.v1.Precondition;
});
public constructor();
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public getName(): string;
public getNameBytes(): com.google.protobuf.ByteString;
public hasCurrentDocument(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Document extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Document,com.google.firestore.v1.Document.Builder> implements com.google.firestore.v1.DocumentOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Document>;
public static NAME_FIELD_NUMBER: number;
public static FIELDS_FIELD_NUMBER: number;
public static CREATE_TIME_FIELD_NUMBER: number;
public static UPDATE_TIME_FIELD_NUMBER: number;
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Document;
public getFieldsCount(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Document>;
public getUpdateTime(): com.google.protobuf.Timestamp;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Document;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Document;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Document;
public static newBuilder(param0: com.google.firestore.v1.Document): com.google.firestore.v1.Document.Builder;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Document;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(): com.google.firestore.v1.Document.Builder;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
public getCreateTime(): com.google.protobuf.Timestamp;
public getSerializedSize(): number;
public getNameBytes(): com.google.protobuf.ByteString;
public containsFields(param0: string): boolean;
public hasCreateTime(): boolean;
public hasUpdateTime(): boolean;
public static getDefaultInstance(): com.google.firestore.v1.Document;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Document;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Document;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public getName(): string;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Document;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Document;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Document;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
}
export module Document {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Document,com.google.firestore.v1.Document.Builder> implements com.google.firestore.v1.DocumentOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Document.Builder>;
public setUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Document.Builder;
public putAllFields(param0: java.util.Map<string,com.google.firestore.v1.Value>): com.google.firestore.v1.Document.Builder;
public getName(): string;
public getCreateTime(): com.google.protobuf.Timestamp;
public clearName(): com.google.firestore.v1.Document.Builder;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
public mergeCreateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Document.Builder;
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public getNameBytes(): com.google.protobuf.ByteString;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
public removeFields(param0: string): com.google.firestore.v1.Document.Builder;
public clearUpdateTime(): com.google.firestore.v1.Document.Builder;
public setName(param0: string): com.google.firestore.v1.Document.Builder;
public setUpdateTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.Document.Builder;
public mergeUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Document.Builder;
public setCreateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Document.Builder;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public getUpdateTime(): com.google.protobuf.Timestamp;
public hasCreateTime(): boolean;
public hasUpdateTime(): boolean;
public setNameBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Document.Builder;
public setCreateTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.Document.Builder;
public containsFields(param0: string): boolean;
public putFields(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Document.Builder;
public getFieldsCount(): number;
public clearFields(): com.google.firestore.v1.Document.Builder;
public clearCreateTime(): com.google.firestore.v1.Document.Builder;
}
export class FieldsDefaultEntryHolder {
public static class: java.lang.Class<com.google.firestore.v1.Document.FieldsDefaultEntryHolder>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentChange extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentChange,com.google.firestore.v1.DocumentChange.Builder> implements com.google.firestore.v1.DocumentChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentChange>;
public static DOCUMENT_FIELD_NUMBER: number;
public static TARGET_IDS_FIELD_NUMBER: number;
public static REMOVED_TARGET_IDS_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentChange;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public static newBuilder(): com.google.firestore.v1.DocumentChange.Builder;
public static getDefaultInstance(): com.google.firestore.v1.DocumentChange;
public hasDocument(): boolean;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentChange>;
public getRemovedTargetIdsCount(): number;
public getRemovedTargetIds(param0: number): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentChange;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getDocument(): com.google.firestore.v1.Document;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentChange;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentChange;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentChange;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentChange;
public getTargetIdsCount(): number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentChange;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentChange;
public getTargetIds(param0: number): number;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentChange;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentChange;
public static newBuilder(param0: com.google.firestore.v1.DocumentChange): com.google.firestore.v1.DocumentChange.Builder;
}
export module DocumentChange {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentChange,com.google.firestore.v1.DocumentChange.Builder> implements com.google.firestore.v1.DocumentChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentChange.Builder>;
public getDocument(): com.google.firestore.v1.Document;
public addRemovedTargetIds(param0: number): com.google.firestore.v1.DocumentChange.Builder;
public clearTargetIds(): com.google.firestore.v1.DocumentChange.Builder;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public clearRemovedTargetIds(): com.google.firestore.v1.DocumentChange.Builder;
public getTargetIds(param0: number): number;
public addTargetIds(param0: number): com.google.firestore.v1.DocumentChange.Builder;
public mergeDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.DocumentChange.Builder;
public addAllRemovedTargetIds(param0: java.lang.Iterable<any>): com.google.firestore.v1.DocumentChange.Builder;
public setTargetIds(param0: number, param1: number): com.google.firestore.v1.DocumentChange.Builder;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public setRemovedTargetIds(param0: number, param1: number): com.google.firestore.v1.DocumentChange.Builder;
public clearDocument(): com.google.firestore.v1.DocumentChange.Builder;
public getRemovedTargetIds(param0: number): number;
public addAllTargetIds(param0: java.lang.Iterable<any>): com.google.firestore.v1.DocumentChange.Builder;
public getTargetIdsCount(): number;
public hasDocument(): boolean;
public setDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.DocumentChange.Builder;
public setDocument(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.DocumentChange.Builder;
public getRemovedTargetIdsCount(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentChangeOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentChangeOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasDocument(): boolean;
getDocument(): com.google.firestore.v1.Document;
getTargetIdsList(): java.util.List<java.lang.Integer>;
getTargetIdsCount(): number;
getTargetIds(param0: number): number;
getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
getRemovedTargetIdsCount(): number;
getRemovedTargetIds(param0: number): number;
});
public constructor();
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public getRemovedTargetIdsCount(): number;
public getRemovedTargetIds(param0: number): number;
public getTargetIds(param0: number): number;
public getDocument(): com.google.firestore.v1.Document;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public hasDocument(): boolean;
public getTargetIdsCount(): number;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentDelete extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentDelete,com.google.firestore.v1.DocumentDelete.Builder> implements com.google.firestore.v1.DocumentDeleteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentDelete>;
public static DOCUMENT_FIELD_NUMBER: number;
public static REMOVED_TARGET_IDS_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public getDocumentBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentDelete;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentDelete;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentDelete;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentDelete;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentDelete;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentDelete;
public getDocument(): string;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentDelete;
public getSerializedSize(): number;
public static newBuilder(): com.google.firestore.v1.DocumentDelete.Builder;
public static getDefaultInstance(): com.google.firestore.v1.DocumentDelete;
public getRemovedTargetIdsCount(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentDelete>;
public getRemovedTargetIds(param0: number): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentDelete;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentDelete;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentDelete;
public static newBuilder(param0: com.google.firestore.v1.DocumentDelete): com.google.firestore.v1.DocumentDelete.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public hasReadTime(): boolean;
}
export module DocumentDelete {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentDelete,com.google.firestore.v1.DocumentDelete.Builder> implements com.google.firestore.v1.DocumentDeleteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentDelete.Builder>;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public addAllRemovedTargetIds(param0: java.lang.Iterable<any>): com.google.firestore.v1.DocumentDelete.Builder;
public clearReadTime(): com.google.firestore.v1.DocumentDelete.Builder;
public setRemovedTargetIds(param0: number, param1: number): com.google.firestore.v1.DocumentDelete.Builder;
public getDocument(): string;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.DocumentDelete.Builder;
public getDocumentBytes(): com.google.protobuf.ByteString;
public clearRemovedTargetIds(): com.google.firestore.v1.DocumentDelete.Builder;
public addRemovedTargetIds(param0: number): com.google.firestore.v1.DocumentDelete.Builder;
public setDocument(param0: string): com.google.firestore.v1.DocumentDelete.Builder;
public clearDocument(): com.google.firestore.v1.DocumentDelete.Builder;
public hasReadTime(): boolean;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.DocumentDelete.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public getRemovedTargetIds(param0: number): number;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.DocumentDelete.Builder;
public setDocumentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentDelete.Builder;
public getRemovedTargetIdsCount(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentDeleteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentDeleteOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentDeleteOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDocument(): string;
getDocumentBytes(): com.google.protobuf.ByteString;
getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
getRemovedTargetIdsCount(): number;
getRemovedTargetIds(param0: number): number;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getDocumentBytes(): com.google.protobuf.ByteString;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public getRemovedTargetIdsCount(): number;
public getDocument(): string;
public getRemovedTargetIds(param0: number): number;
public getReadTime(): com.google.protobuf.Timestamp;
public hasReadTime(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentMask extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentMask,com.google.firestore.v1.DocumentMask.Builder> implements com.google.firestore.v1.DocumentMaskOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentMask>;
public static FIELD_PATHS_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentMask;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentMask;
public static newBuilder(): com.google.firestore.v1.DocumentMask.Builder;
public getFieldPathsCount(): number;
public static getDefaultInstance(): com.google.firestore.v1.DocumentMask;
public getFieldPathsList(): java.util.List<string>;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentMask;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentMask>;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentMask;
public static newBuilder(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.DocumentMask.Builder;
public getFieldPathsBytes(param0: number): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentMask;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentMask;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentMask;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getFieldPaths(param0: number): string;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentMask;
}
export module DocumentMask {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentMask,com.google.firestore.v1.DocumentMask.Builder> implements com.google.firestore.v1.DocumentMaskOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentMask.Builder>;
public getFieldPathsList(): java.util.List<string>;
public clearFieldPaths(): com.google.firestore.v1.DocumentMask.Builder;
public getFieldPathsBytes(param0: number): com.google.protobuf.ByteString;
public getFieldPaths(param0: number): string;
public setFieldPaths(param0: number, param1: string): com.google.firestore.v1.DocumentMask.Builder;
public addFieldPaths(param0: string): com.google.firestore.v1.DocumentMask.Builder;
public addFieldPathsBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentMask.Builder;
public addAllFieldPaths(param0: java.lang.Iterable<string>): com.google.firestore.v1.DocumentMask.Builder;
public getFieldPathsCount(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentMaskOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentMaskOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentMaskOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFieldPathsList(): java.util.List<string>;
getFieldPathsCount(): number;
getFieldPaths(param0: number): string;
getFieldPathsBytes(param0: number): com.google.protobuf.ByteString;
});
public constructor();
public getFieldPathsBytes(param0: number): com.google.protobuf.ByteString;
public getFieldPathsCount(): number;
public getFieldPaths(param0: number): string;
public getFieldPathsList(): java.util.List<string>;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
getNameBytes(): com.google.protobuf.ByteString;
getFieldsCount(): number;
containsFields(param0: string): boolean;
getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
hasCreateTime(): boolean;
getCreateTime(): com.google.protobuf.Timestamp;
hasUpdateTime(): boolean;
getUpdateTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public getUpdateTime(): com.google.protobuf.Timestamp;
public getFieldsCount(): number;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public getName(): string;
public getCreateTime(): com.google.protobuf.Timestamp;
public getNameBytes(): com.google.protobuf.ByteString;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
public containsFields(param0: string): boolean;
public hasCreateTime(): boolean;
public hasUpdateTime(): boolean;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentProto {
public static class: java.lang.Class<com.google.firestore.v1.DocumentProto>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentRemove extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentRemove,com.google.firestore.v1.DocumentRemove.Builder> implements com.google.firestore.v1.DocumentRemoveOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentRemove>;
public static DOCUMENT_FIELD_NUMBER: number;
public static REMOVED_TARGET_IDS_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public getDocumentBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentRemove;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentRemove;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentRemove;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentRemove;
public static newBuilder(param0: com.google.firestore.v1.DocumentRemove): com.google.firestore.v1.DocumentRemove.Builder;
public getDocument(): string;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentRemove;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentRemove;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentRemove;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentRemove;
public static newBuilder(): com.google.firestore.v1.DocumentRemove.Builder;
public static getDefaultInstance(): com.google.firestore.v1.DocumentRemove;
public getRemovedTargetIdsCount(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentRemove;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentRemove>;
public getRemovedTargetIds(param0: number): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentRemove;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public hasReadTime(): boolean;
}
export module DocumentRemove {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentRemove,com.google.firestore.v1.DocumentRemove.Builder> implements com.google.firestore.v1.DocumentRemoveOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentRemove.Builder>;
public clearReadTime(): com.google.firestore.v1.DocumentRemove.Builder;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public addAllRemovedTargetIds(param0: java.lang.Iterable<any>): com.google.firestore.v1.DocumentRemove.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.DocumentRemove.Builder;
public getDocument(): string;
public clearRemovedTargetIds(): com.google.firestore.v1.DocumentRemove.Builder;
public getDocumentBytes(): com.google.protobuf.ByteString;
public setDocument(param0: string): com.google.firestore.v1.DocumentRemove.Builder;
public setRemovedTargetIds(param0: number, param1: number): com.google.firestore.v1.DocumentRemove.Builder;
public hasReadTime(): boolean;
public setDocumentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentRemove.Builder;
public addRemovedTargetIds(param0: number): com.google.firestore.v1.DocumentRemove.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.DocumentRemove.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.DocumentRemove.Builder;
public clearDocument(): com.google.firestore.v1.DocumentRemove.Builder;
public getRemovedTargetIds(param0: number): number;
public getRemovedTargetIdsCount(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentRemoveOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentRemoveOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentRemoveOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDocument(): string;
getDocumentBytes(): com.google.protobuf.ByteString;
getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
getRemovedTargetIdsCount(): number;
getRemovedTargetIds(param0: number): number;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getDocumentBytes(): com.google.protobuf.ByteString;
public getRemovedTargetIdsList(): java.util.List<java.lang.Integer>;
public getRemovedTargetIdsCount(): number;
public getDocument(): string;
public getRemovedTargetIds(param0: number): number;
public getReadTime(): com.google.protobuf.Timestamp;
public hasReadTime(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentTransform extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentTransform,com.google.firestore.v1.DocumentTransform.Builder> implements com.google.firestore.v1.DocumentTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform>;
public static DOCUMENT_FIELD_NUMBER: number;
public static FIELD_TRANSFORMS_FIELD_NUMBER: number;
public getDocumentBytes(): com.google.protobuf.ByteString;
public getFieldTransformsOrBuilder(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransformOrBuilder;
public getFieldTransformsCount(): number;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform;
public getDocument(): string;
public getSerializedSize(): number;
public static newBuilder(): com.google.firestore.v1.DocumentTransform.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentTransform;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentTransform;
public getFieldTransformsOrBuilderList(): java.util.List<any>;
public getFieldTransforms(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentTransform>;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentTransform;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentTransform;
public static newBuilder(param0: com.google.firestore.v1.DocumentTransform): com.google.firestore.v1.DocumentTransform.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform;
public getFieldTransformsList(): java.util.List<com.google.firestore.v1.DocumentTransform.FieldTransform>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentTransform;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform;
public static getDefaultInstance(): com.google.firestore.v1.DocumentTransform;
}
export module DocumentTransform {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentTransform,com.google.firestore.v1.DocumentTransform.Builder> implements com.google.firestore.v1.DocumentTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.Builder>;
public getFieldTransformsCount(): number;
public getDocument(): string;
public addFieldTransforms(param0: com.google.firestore.v1.DocumentTransform.FieldTransform.Builder): com.google.firestore.v1.DocumentTransform.Builder;
public getDocumentBytes(): com.google.protobuf.ByteString;
public addFieldTransforms(param0: number, param1: com.google.firestore.v1.DocumentTransform.FieldTransform): com.google.firestore.v1.DocumentTransform.Builder;
public getFieldTransformsList(): java.util.List<com.google.firestore.v1.DocumentTransform.FieldTransform>;
public addFieldTransforms(param0: number, param1: com.google.firestore.v1.DocumentTransform.FieldTransform.Builder): com.google.firestore.v1.DocumentTransform.Builder;
public removeFieldTransforms(param0: number): com.google.firestore.v1.DocumentTransform.Builder;
public getFieldTransforms(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform;
public clearDocument(): com.google.firestore.v1.DocumentTransform.Builder;
public setFieldTransforms(param0: number, param1: com.google.firestore.v1.DocumentTransform.FieldTransform): com.google.firestore.v1.DocumentTransform.Builder;
public setFieldTransforms(param0: number, param1: com.google.firestore.v1.DocumentTransform.FieldTransform.Builder): com.google.firestore.v1.DocumentTransform.Builder;
public addFieldTransforms(param0: com.google.firestore.v1.DocumentTransform.FieldTransform): com.google.firestore.v1.DocumentTransform.Builder;
public setDocument(param0: string): com.google.firestore.v1.DocumentTransform.Builder;
public setDocumentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentTransform.Builder;
public addAllFieldTransforms(param0: java.lang.Iterable<any>): com.google.firestore.v1.DocumentTransform.Builder;
public clearFieldTransforms(): com.google.firestore.v1.DocumentTransform.Builder;
}
export class FieldTransform extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.DocumentTransform.FieldTransform,com.google.firestore.v1.DocumentTransform.FieldTransform.Builder> implements com.google.firestore.v1.DocumentTransform.FieldTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.FieldTransform>;
public static FIELD_PATH_FIELD_NUMBER: number;
public static SET_TO_SERVER_VALUE_FIELD_NUMBER: number;
public static INCREMENT_FIELD_NUMBER: number;
public static MAXIMUM_FIELD_NUMBER: number;
public static MINIMUM_FIELD_NUMBER: number;
public static APPEND_MISSING_ELEMENTS_FIELD_NUMBER: number;
public static REMOVE_ALL_FROM_ARRAY_FIELD_NUMBER: number;
public getMinimum(): com.google.firestore.v1.Value;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getSetToServerValue(): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static getDefaultInstance(): com.google.firestore.v1.DocumentTransform.FieldTransform;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getSetToServerValueValue(): number;
public getIncrement(): com.google.firestore.v1.Value;
public getRemoveAllFromArray(): com.google.firestore.v1.ArrayValue;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.DocumentTransform.FieldTransform;
public getFieldPathBytes(): com.google.protobuf.ByteString;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.DocumentTransform.FieldTransform>;
public static newBuilder(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform.FieldTransform;
public getSerializedSize(): number;
public getFieldPath(): string;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentTransform.FieldTransform;
public static newBuilder(param0: com.google.firestore.v1.DocumentTransform.FieldTransform): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getMaximum(): com.google.firestore.v1.Value;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.DocumentTransform.FieldTransform;
public getTransformTypeCase(): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public getAppendMissingElements(): com.google.firestore.v1.ArrayValue;
}
export module FieldTransform {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.DocumentTransform.FieldTransform,com.google.firestore.v1.DocumentTransform.FieldTransform.Builder> implements com.google.firestore.v1.DocumentTransform.FieldTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.FieldTransform.Builder>;
public setIncrement(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getMinimum(): com.google.firestore.v1.Value;
public setMinimum(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getTransformTypeCase(): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public clearIncrement(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getMaximum(): com.google.firestore.v1.Value;
public clearSetToServerValue(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getFieldPathBytes(): com.google.protobuf.ByteString;
public getRemoveAllFromArray(): com.google.firestore.v1.ArrayValue;
public clearRemoveAllFromArray(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public mergeIncrement(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public clearFieldPath(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getIncrement(): com.google.firestore.v1.Value;
public setMaximum(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getFieldPath(): string;
public mergeMaximum(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public clearMaximum(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setRemoveAllFromArray(param0: com.google.firestore.v1.ArrayValue.Builder): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setIncrement(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public mergeAppendMissingElements(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setRemoveAllFromArray(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public clearTransformType(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public mergeMinimum(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setFieldPathBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getAppendMissingElements(): com.google.firestore.v1.ArrayValue;
public setSetToServerValueValue(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setMinimum(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setMaximum(param0: com.google.firestore.v1.Value): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setSetToServerValue(param0: com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setAppendMissingElements(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public clearAppendMissingElements(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public setAppendMissingElements(param0: com.google.firestore.v1.ArrayValue.Builder): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getSetToServerValue(): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public clearMinimum(): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public mergeRemoveAllFromArray(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
public getSetToServerValueValue(): number;
public setFieldPath(param0: string): com.google.firestore.v1.DocumentTransform.FieldTransform.Builder;
}
export class ServerValue extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue>;
public static SERVER_VALUE_UNSPECIFIED: com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static REQUEST_TIME: com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static UNRECOGNIZED: com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static SERVER_VALUE_UNSPECIFIED_VALUE: number;
public static REQUEST_TIME_VALUE: number;
public static valueOf(param0: string): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static forNumber(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue>;
public static valueOf(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue>;
}
export class TransformTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase>;
public static SET_TO_SERVER_VALUE: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static INCREMENT: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static MAXIMUM: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static MINIMUM: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static APPEND_MISSING_ELEMENTS: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static REMOVE_ALL_FROM_ARRAY: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static TRANSFORMTYPE_NOT_SET: com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public static valueOf(param0: string): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase>;
public static forNumber(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
}
}
export class FieldTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransform.FieldTransformOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentTransform$FieldTransformOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFieldPath(): string;
getFieldPathBytes(): com.google.protobuf.ByteString;
getSetToServerValueValue(): number;
getSetToServerValue(): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
getIncrement(): com.google.firestore.v1.Value;
getMaximum(): com.google.firestore.v1.Value;
getMinimum(): com.google.firestore.v1.Value;
getAppendMissingElements(): com.google.firestore.v1.ArrayValue;
getRemoveAllFromArray(): com.google.firestore.v1.ArrayValue;
getTransformTypeCase(): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
});
public constructor();
public getMinimum(): com.google.firestore.v1.Value;
public getFieldPath(): string;
public getSetToServerValueValue(): number;
public getFieldPathBytes(): com.google.protobuf.ByteString;
public getSetToServerValue(): com.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue;
public getIncrement(): com.google.firestore.v1.Value;
public getRemoveAllFromArray(): com.google.firestore.v1.ArrayValue;
public getMaximum(): com.google.firestore.v1.Value;
public getTransformTypeCase(): com.google.firestore.v1.DocumentTransform.FieldTransform.TransformTypeCase;
public getAppendMissingElements(): com.google.firestore.v1.ArrayValue;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class DocumentTransformOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.DocumentTransformOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.DocumentTransformOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDocument(): string;
getDocumentBytes(): com.google.protobuf.ByteString;
getFieldTransformsList(): java.util.List<com.google.firestore.v1.DocumentTransform.FieldTransform>;
getFieldTransforms(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform;
getFieldTransformsCount(): number;
});
public constructor();
public getFieldTransforms(param0: number): com.google.firestore.v1.DocumentTransform.FieldTransform;
public getDocumentBytes(): com.google.protobuf.ByteString;
public getFieldTransformsCount(): number;
public getDocument(): string;
public getFieldTransformsList(): java.util.List<com.google.firestore.v1.DocumentTransform.FieldTransform>;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ExistenceFilter extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ExistenceFilter,com.google.firestore.v1.ExistenceFilter.Builder> implements com.google.firestore.v1.ExistenceFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ExistenceFilter>;
public static TARGET_ID_FIELD_NUMBER: number;
public static COUNT_FIELD_NUMBER: number;
public getCount(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ExistenceFilter>;
public getTargetId(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ExistenceFilter;
public getSerializedSize(): number;
public static newBuilder(param0: com.google.firestore.v1.ExistenceFilter): com.google.firestore.v1.ExistenceFilter.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ExistenceFilter;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ExistenceFilter;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static getDefaultInstance(): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ExistenceFilter;
public static newBuilder(): com.google.firestore.v1.ExistenceFilter.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ExistenceFilter;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ExistenceFilter;
}
export module ExistenceFilter {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ExistenceFilter,com.google.firestore.v1.ExistenceFilter.Builder> implements com.google.firestore.v1.ExistenceFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ExistenceFilter.Builder>;
public getTargetId(): number;
public setTargetId(param0: number): com.google.firestore.v1.ExistenceFilter.Builder;
public clearTargetId(): com.google.firestore.v1.ExistenceFilter.Builder;
public clearCount(): com.google.firestore.v1.ExistenceFilter.Builder;
public getCount(): number;
public setCount(param0: number): com.google.firestore.v1.ExistenceFilter.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ExistenceFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ExistenceFilterOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ExistenceFilterOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTargetId(): number;
getCount(): number;
});
public constructor();
public getCount(): number;
public getTargetId(): number;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class FirestoreGrpc {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc>;
public static SERVICE_NAME: string;
public static getGetDocumentMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.GetDocumentRequest,com.google.firestore.v1.Document>;
public static getCommitMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.CommitRequest,com.google.firestore.v1.CommitResponse>;
public static newStub(param0: io.grpc.Channel): com.google.firestore.v1.FirestoreGrpc.FirestoreStub;
public static getBatchGetDocumentsMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.BatchGetDocumentsRequest,com.google.firestore.v1.BatchGetDocumentsResponse>;
public static getUpdateDocumentMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.UpdateDocumentRequest,com.google.firestore.v1.Document>;
public static getRunQueryMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.RunQueryRequest,com.google.firestore.v1.RunQueryResponse>;
public static getListenMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.ListenRequest,com.google.firestore.v1.ListenResponse>;
public static newBlockingStub(param0: io.grpc.Channel): com.google.firestore.v1.FirestoreGrpc.FirestoreBlockingStub;
public static getListDocumentsMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.ListDocumentsRequest,com.google.firestore.v1.ListDocumentsResponse>;
public static getDeleteDocumentMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.DeleteDocumentRequest,com.google.protobuf.Empty>;
public static getListCollectionIdsMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.ListCollectionIdsRequest,com.google.firestore.v1.ListCollectionIdsResponse>;
public static getCreateDocumentMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.CreateDocumentRequest,com.google.firestore.v1.Document>;
public static getRollbackMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.RollbackRequest,com.google.protobuf.Empty>;
public static getServiceDescriptor(): io.grpc.ServiceDescriptor;
public static newFutureStub(param0: io.grpc.Channel): com.google.firestore.v1.FirestoreGrpc.FirestoreFutureStub;
public static getBeginTransactionMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.BeginTransactionRequest,com.google.firestore.v1.BeginTransactionResponse>;
public static getWriteMethod(): io.grpc.MethodDescriptor<com.google.firestore.v1.WriteRequest,com.google.firestore.v1.WriteResponse>;
}
export module FirestoreGrpc {
export class FirestoreBlockingStub extends io.grpc.stub.AbstractStub<com.google.firestore.v1.FirestoreGrpc.FirestoreBlockingStub> {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc.FirestoreBlockingStub>;
public build(param0: io.grpc.Channel, param1: io.grpc.CallOptions): com.google.firestore.v1.FirestoreGrpc.FirestoreBlockingStub;
public rollback(param0: com.google.firestore.v1.RollbackRequest): com.google.protobuf.Empty;
public deleteDocument(param0: com.google.firestore.v1.DeleteDocumentRequest): com.google.protobuf.Empty;
public listCollectionIds(param0: com.google.firestore.v1.ListCollectionIdsRequest): com.google.firestore.v1.ListCollectionIdsResponse;
public updateDocument(param0: com.google.firestore.v1.UpdateDocumentRequest): com.google.firestore.v1.Document;
public listDocuments(param0: com.google.firestore.v1.ListDocumentsRequest): com.google.firestore.v1.ListDocumentsResponse;
public commit(param0: com.google.firestore.v1.CommitRequest): com.google.firestore.v1.CommitResponse;
public getDocument(param0: com.google.firestore.v1.GetDocumentRequest): com.google.firestore.v1.Document;
public createDocument(param0: com.google.firestore.v1.CreateDocumentRequest): com.google.firestore.v1.Document;
public batchGetDocuments(param0: com.google.firestore.v1.BatchGetDocumentsRequest): java.util.Iterator<com.google.firestore.v1.BatchGetDocumentsResponse>;
public beginTransaction(param0: com.google.firestore.v1.BeginTransactionRequest): com.google.firestore.v1.BeginTransactionResponse;
public runQuery(param0: com.google.firestore.v1.RunQueryRequest): java.util.Iterator<com.google.firestore.v1.RunQueryResponse>;
}
export class FirestoreFutureStub extends io.grpc.stub.AbstractStub<com.google.firestore.v1.FirestoreGrpc.FirestoreFutureStub> {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc.FirestoreFutureStub>;
public deleteDocument(param0: com.google.firestore.v1.DeleteDocumentRequest): com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>;
public rollback(param0: com.google.firestore.v1.RollbackRequest): com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>;
public build(param0: io.grpc.Channel, param1: io.grpc.CallOptions): com.google.firestore.v1.FirestoreGrpc.FirestoreFutureStub;
public commit(param0: com.google.firestore.v1.CommitRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.CommitResponse>;
public createDocument(param0: com.google.firestore.v1.CreateDocumentRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.Document>;
public getDocument(param0: com.google.firestore.v1.GetDocumentRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.Document>;
public listCollectionIds(param0: com.google.firestore.v1.ListCollectionIdsRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.ListCollectionIdsResponse>;
public updateDocument(param0: com.google.firestore.v1.UpdateDocumentRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.Document>;
public listDocuments(param0: com.google.firestore.v1.ListDocumentsRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.ListDocumentsResponse>;
public beginTransaction(param0: com.google.firestore.v1.BeginTransactionRequest): com.google.common.util.concurrent.ListenableFuture<com.google.firestore.v1.BeginTransactionResponse>;
}
export abstract class FirestoreImplBase {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc.FirestoreImplBase>;
public updateDocument(param0: com.google.firestore.v1.UpdateDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public runQuery(param0: com.google.firestore.v1.RunQueryRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.RunQueryResponse>): void;
public constructor();
public rollback(param0: com.google.firestore.v1.RollbackRequest, param1: io.grpc.stub.StreamObserver<com.google.protobuf.Empty>): void;
public bindService(): io.grpc.ServerServiceDefinition;
public listDocuments(param0: com.google.firestore.v1.ListDocumentsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListDocumentsResponse>): void;
public createDocument(param0: com.google.firestore.v1.CreateDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public beginTransaction(param0: com.google.firestore.v1.BeginTransactionRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.BeginTransactionResponse>): void;
public write(param0: io.grpc.stub.StreamObserver<com.google.firestore.v1.WriteResponse>): io.grpc.stub.StreamObserver<com.google.firestore.v1.WriteRequest>;
public deleteDocument(param0: com.google.firestore.v1.DeleteDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.protobuf.Empty>): void;
public listCollectionIds(param0: com.google.firestore.v1.ListCollectionIdsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListCollectionIdsResponse>): void;
public getDocument(param0: com.google.firestore.v1.GetDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public batchGetDocuments(param0: com.google.firestore.v1.BatchGetDocumentsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.BatchGetDocumentsResponse>): void;
public listen(param0: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListenResponse>): io.grpc.stub.StreamObserver<com.google.firestore.v1.ListenRequest>;
public commit(param0: com.google.firestore.v1.CommitRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.CommitResponse>): void;
}
export class FirestoreStub extends io.grpc.stub.AbstractStub<com.google.firestore.v1.FirestoreGrpc.FirestoreStub> {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc.FirestoreStub>;
public updateDocument(param0: com.google.firestore.v1.UpdateDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public runQuery(param0: com.google.firestore.v1.RunQueryRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.RunQueryResponse>): void;
public rollback(param0: com.google.firestore.v1.RollbackRequest, param1: io.grpc.stub.StreamObserver<com.google.protobuf.Empty>): void;
public listDocuments(param0: com.google.firestore.v1.ListDocumentsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListDocumentsResponse>): void;
public createDocument(param0: com.google.firestore.v1.CreateDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public beginTransaction(param0: com.google.firestore.v1.BeginTransactionRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.BeginTransactionResponse>): void;
public write(param0: io.grpc.stub.StreamObserver<com.google.firestore.v1.WriteResponse>): io.grpc.stub.StreamObserver<com.google.firestore.v1.WriteRequest>;
public build(param0: io.grpc.Channel, param1: io.grpc.CallOptions): com.google.firestore.v1.FirestoreGrpc.FirestoreStub;
public deleteDocument(param0: com.google.firestore.v1.DeleteDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.protobuf.Empty>): void;
public listCollectionIds(param0: com.google.firestore.v1.ListCollectionIdsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListCollectionIdsResponse>): void;
public getDocument(param0: com.google.firestore.v1.GetDocumentRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.Document>): void;
public batchGetDocuments(param0: com.google.firestore.v1.BatchGetDocumentsRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.BatchGetDocumentsResponse>): void;
public listen(param0: io.grpc.stub.StreamObserver<com.google.firestore.v1.ListenResponse>): io.grpc.stub.StreamObserver<com.google.firestore.v1.ListenRequest>;
public commit(param0: com.google.firestore.v1.CommitRequest, param1: io.grpc.stub.StreamObserver<com.google.firestore.v1.CommitResponse>): void;
}
export class MethodHandlers<Req, Resp> extends java.lang.Object {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreGrpc.MethodHandlers<any,any>>;
public invoke(param0: io.grpc.stub.StreamObserver<Resp>): io.grpc.stub.StreamObserver<Req>;
public invoke(param0: Req, param1: io.grpc.stub.StreamObserver<Resp>): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class FirestoreProto {
public static class: java.lang.Class<com.google.firestore.v1.FirestoreProto>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class GetDocumentRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.GetDocumentRequest,com.google.firestore.v1.GetDocumentRequest.Builder> implements com.google.firestore.v1.GetDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.GetDocumentRequest>;
public static NAME_FIELD_NUMBER: number;
public static MASK_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public getMask(): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.GetDocumentRequest;
public getTransaction(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.GetDocumentRequest;
public getSerializedSize(): number;
public getNameBytes(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.GetDocumentRequest;
public static getDefaultInstance(): com.google.firestore.v1.GetDocumentRequest;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.GetDocumentRequest;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.GetDocumentRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.GetDocumentRequest;
public hasMask(): boolean;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.GetDocumentRequest>;
public getConsistencySelectorCase(): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public getName(): string;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.GetDocumentRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(param0: com.google.firestore.v1.GetDocumentRequest): com.google.firestore.v1.GetDocumentRequest.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.GetDocumentRequest;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.GetDocumentRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.GetDocumentRequest;
public static newBuilder(): com.google.firestore.v1.GetDocumentRequest.Builder;
}
export module GetDocumentRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.GetDocumentRequest,com.google.firestore.v1.GetDocumentRequest.Builder> implements com.google.firestore.v1.GetDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.GetDocumentRequest.Builder>;
public setNameBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.GetDocumentRequest.Builder;
public clearMask(): com.google.firestore.v1.GetDocumentRequest.Builder;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.GetDocumentRequest.Builder;
public getName(): string;
public getMask(): com.google.firestore.v1.DocumentMask;
public hasMask(): boolean;
public clearName(): com.google.firestore.v1.GetDocumentRequest.Builder;
public clearReadTime(): com.google.firestore.v1.GetDocumentRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.GetDocumentRequest.Builder;
public mergeMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.GetDocumentRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.GetDocumentRequest.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.GetDocumentRequest.Builder;
public setName(param0: string): com.google.firestore.v1.GetDocumentRequest.Builder;
public clearTransaction(): com.google.firestore.v1.GetDocumentRequest.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.GetDocumentRequest.Builder;
public clearConsistencySelector(): com.google.firestore.v1.GetDocumentRequest.Builder;
public getConsistencySelectorCase(): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public getNameBytes(): com.google.protobuf.ByteString;
public getTransaction(): com.google.protobuf.ByteString;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.GetDocumentRequest.Builder;
}
export class ConsistencySelectorCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase>;
public static TRANSACTION: com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public static READ_TIME: com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public static CONSISTENCYSELECTOR_NOT_SET: com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public static valueOf(param0: string): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public static forNumber(param0: number): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase>;
public static valueOf(param0: number): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class GetDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.GetDocumentRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.GetDocumentRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getName(): string;
getNameBytes(): com.google.protobuf.ByteString;
hasMask(): boolean;
getMask(): com.google.firestore.v1.DocumentMask;
getTransaction(): com.google.protobuf.ByteString;
getReadTime(): com.google.protobuf.Timestamp;
getConsistencySelectorCase(): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
});
public constructor();
public getMask(): com.google.firestore.v1.DocumentMask;
public hasMask(): boolean;
public getName(): string;
public getConsistencySelectorCase(): com.google.firestore.v1.GetDocumentRequest.ConsistencySelectorCase;
public getTransaction(): com.google.protobuf.ByteString;
public getNameBytes(): com.google.protobuf.ByteString;
public getReadTime(): com.google.protobuf.Timestamp;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListCollectionIdsRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListCollectionIdsRequest,com.google.firestore.v1.ListCollectionIdsRequest.Builder> implements com.google.firestore.v1.ListCollectionIdsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsRequest>;
public static PARENT_FIELD_NUMBER: number;
public static PAGE_SIZE_FIELD_NUMBER: number;
public static PAGE_TOKEN_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsRequest;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListCollectionIdsRequest;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getPageToken(): string;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListCollectionIdsRequest;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsRequest;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsRequest;
public static getDefaultInstance(): com.google.firestore.v1.ListCollectionIdsRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListCollectionIdsRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListCollectionIdsRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getPageSize(): number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsRequest;
public getPageTokenBytes(): com.google.protobuf.ByteString;
public static newBuilder(param0: com.google.firestore.v1.ListCollectionIdsRequest): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsRequest;
public static newBuilder(): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListCollectionIdsRequest>;
}
export module ListCollectionIdsRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListCollectionIdsRequest,com.google.firestore.v1.ListCollectionIdsRequest.Builder> implements com.google.firestore.v1.ListCollectionIdsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsRequest.Builder>;
public setParentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public clearPageSize(): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public getPageTokenBytes(): com.google.protobuf.ByteString;
public clearParent(): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public clearPageToken(): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public setPageSize(param0: number): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public getParent(): string;
public setParent(param0: string): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public getPageToken(): string;
public setPageToken(param0: string): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
public getParentBytes(): com.google.protobuf.ByteString;
public getPageSize(): number;
public setPageTokenBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListCollectionIdsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListCollectionIdsRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParent(): string;
getParentBytes(): com.google.protobuf.ByteString;
getPageSize(): number;
getPageToken(): string;
getPageTokenBytes(): com.google.protobuf.ByteString;
});
public constructor();
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getPageToken(): string;
public getPageSize(): number;
public getPageTokenBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListCollectionIdsResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListCollectionIdsResponse,com.google.firestore.v1.ListCollectionIdsResponse.Builder> implements com.google.firestore.v1.ListCollectionIdsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsResponse>;
public static COLLECTION_IDS_FIELD_NUMBER: number;
public static NEXT_PAGE_TOKEN_FIELD_NUMBER: number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListCollectionIdsResponse>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsResponse;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListCollectionIdsResponse;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsResponse;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsResponse;
public getCollectionIdsCount(): number;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListCollectionIdsResponse;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsResponse;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListCollectionIdsResponse;
public getCollectionIdsBytes(param0: number): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListCollectionIdsResponse;
public static newBuilder(): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListCollectionIdsResponse;
public static newBuilder(param0: com.google.firestore.v1.ListCollectionIdsResponse): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getCollectionIdsList(): java.util.List<string>;
public getCollectionIds(param0: number): string;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getNextPageToken(): string;
public static getDefaultInstance(): com.google.firestore.v1.ListCollectionIdsResponse;
}
export module ListCollectionIdsResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListCollectionIdsResponse,com.google.firestore.v1.ListCollectionIdsResponse.Builder> implements com.google.firestore.v1.ListCollectionIdsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsResponse.Builder>;
public clearNextPageToken(): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public getCollectionIdsBytes(param0: number): com.google.protobuf.ByteString;
public getCollectionIds(param0: number): string;
public setNextPageTokenBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public clearCollectionIds(): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public getCollectionIdsCount(): number;
public addAllCollectionIds(param0: java.lang.Iterable<string>): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public addCollectionIds(param0: string): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public setCollectionIds(param0: number, param1: string): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public getCollectionIdsList(): java.util.List<string>;
public getNextPageToken(): string;
public addCollectionIdsBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
public setNextPageToken(param0: string): com.google.firestore.v1.ListCollectionIdsResponse.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListCollectionIdsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListCollectionIdsResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListCollectionIdsResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getCollectionIdsList(): java.util.List<string>;
getCollectionIdsCount(): number;
getCollectionIds(param0: number): string;
getCollectionIdsBytes(param0: number): com.google.protobuf.ByteString;
getNextPageToken(): string;
getNextPageTokenBytes(): com.google.protobuf.ByteString;
});
public constructor();
public getCollectionIdsBytes(param0: number): com.google.protobuf.ByteString;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public getCollectionIdsList(): java.util.List<string>;
public getCollectionIds(param0: number): string;
public getNextPageToken(): string;
public getCollectionIdsCount(): number;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListDocumentsRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListDocumentsRequest,com.google.firestore.v1.ListDocumentsRequest.Builder> implements com.google.firestore.v1.ListDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsRequest>;
public static PARENT_FIELD_NUMBER: number;
public static COLLECTION_ID_FIELD_NUMBER: number;
public static PAGE_SIZE_FIELD_NUMBER: number;
public static PAGE_TOKEN_FIELD_NUMBER: number;
public static ORDER_BY_FIELD_NUMBER: number;
public static MASK_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static SHOW_MISSING_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsRequest;
public static newBuilder(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListDocumentsRequest;
public static getDefaultInstance(): com.google.firestore.v1.ListDocumentsRequest;
public static newBuilder(param0: com.google.firestore.v1.ListDocumentsRequest): com.google.firestore.v1.ListDocumentsRequest.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsRequest;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getConsistencySelectorCase(): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListDocumentsRequest;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsRequest;
public getOrderByBytes(): com.google.protobuf.ByteString;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getPageTokenBytes(): com.google.protobuf.ByteString;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListDocumentsRequest>;
public getMask(): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListDocumentsRequest;
public getOrderBy(): string;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsRequest;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListDocumentsRequest;
public getPageToken(): string;
public hasMask(): boolean;
public getCollectionId(): string;
public getShowMissing(): boolean;
public getPageSize(): number;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
}
export module ListDocumentsRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListDocumentsRequest,com.google.firestore.v1.ListDocumentsRequest.Builder> implements com.google.firestore.v1.ListDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsRequest.Builder>;
public mergeMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getConsistencySelectorCase(): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearConsistencySelector(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getCollectionId(): string;
public clearShowMissing(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setParent(param0: string): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getOrderByBytes(): com.google.protobuf.ByteString;
public getParent(): string;
public getMask(): com.google.firestore.v1.DocumentMask;
public getShowMissing(): boolean;
public setCollectionId(param0: string): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public setShowMissing(param0: boolean): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearOrderBy(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getParentBytes(): com.google.protobuf.ByteString;
public clearCollectionId(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getPageSize(): number;
public setPageToken(param0: string): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearPageToken(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getOrderBy(): string;
public setMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getPageTokenBytes(): com.google.protobuf.ByteString;
public setPageTokenBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setOrderByBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearParent(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearReadTime(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setPageSize(param0: number): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setOrderBy(param0: string): com.google.firestore.v1.ListDocumentsRequest.Builder;
public hasMask(): boolean;
public setCollectionIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getPageToken(): string;
public clearTransaction(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.ListDocumentsRequest.Builder;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public setParentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearPageSize(): com.google.firestore.v1.ListDocumentsRequest.Builder;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.ListDocumentsRequest.Builder;
public clearMask(): com.google.firestore.v1.ListDocumentsRequest.Builder;
}
export class ConsistencySelectorCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase>;
public static TRANSACTION: com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static READ_TIME: com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static CONSISTENCYSELECTOR_NOT_SET: com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static valueOf(param0: string): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static forNumber(param0: number): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public static valueOf(param0: number): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListDocumentsRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListDocumentsRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParent(): string;
getParentBytes(): com.google.protobuf.ByteString;
getCollectionId(): string;
getCollectionIdBytes(): com.google.protobuf.ByteString;
getPageSize(): number;
getPageToken(): string;
getPageTokenBytes(): com.google.protobuf.ByteString;
getOrderBy(): string;
getOrderByBytes(): com.google.protobuf.ByteString;
hasMask(): boolean;
getMask(): com.google.firestore.v1.DocumentMask;
getTransaction(): com.google.protobuf.ByteString;
getReadTime(): com.google.protobuf.Timestamp;
getShowMissing(): boolean;
getConsistencySelectorCase(): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
});
public constructor();
public getMask(): com.google.firestore.v1.DocumentMask;
public getOrderBy(): string;
public getTransaction(): com.google.protobuf.ByteString;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getPageToken(): string;
public hasMask(): boolean;
public getConsistencySelectorCase(): com.google.firestore.v1.ListDocumentsRequest.ConsistencySelectorCase;
public getCollectionId(): string;
public getOrderByBytes(): com.google.protobuf.ByteString;
public getShowMissing(): boolean;
public getPageSize(): number;
public getReadTime(): com.google.protobuf.Timestamp;
public getPageTokenBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListDocumentsResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListDocumentsResponse,com.google.firestore.v1.ListDocumentsResponse.Builder> implements com.google.firestore.v1.ListDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsResponse>;
public static DOCUMENTS_FIELD_NUMBER: number;
public static NEXT_PAGE_TOKEN_FIELD_NUMBER: number;
public static getDefaultInstance(): com.google.firestore.v1.ListDocumentsResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsResponse;
public static newBuilder(): com.google.firestore.v1.ListDocumentsResponse.Builder;
public getDocumentsOrBuilderList(): java.util.List<any>;
public getDocuments(param0: number): com.google.firestore.v1.Document;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public getDocumentsList(): java.util.List<com.google.firestore.v1.Document>;
public static newBuilder(param0: com.google.firestore.v1.ListDocumentsResponse): com.google.firestore.v1.ListDocumentsResponse.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsResponse;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListDocumentsResponse;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListDocumentsResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListDocumentsResponse>;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsResponse;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsResponse;
public getDocumentsOrBuilder(param0: number): com.google.firestore.v1.DocumentOrBuilder;
public getDocumentsCount(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsResponse;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListDocumentsResponse;
public getNextPageToken(): string;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListDocumentsResponse;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListDocumentsResponse;
}
export module ListDocumentsResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListDocumentsResponse,com.google.firestore.v1.ListDocumentsResponse.Builder> implements com.google.firestore.v1.ListDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsResponse.Builder>;
public addAllDocuments(param0: java.lang.Iterable<any>): com.google.firestore.v1.ListDocumentsResponse.Builder;
public setDocuments(param0: number, param1: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.ListDocumentsResponse.Builder;
public getDocumentsCount(): number;
public getDocumentsList(): java.util.List<com.google.firestore.v1.Document>;
public getDocuments(param0: number): com.google.firestore.v1.Document;
public clearDocuments(): com.google.firestore.v1.ListDocumentsResponse.Builder;
public removeDocuments(param0: number): com.google.firestore.v1.ListDocumentsResponse.Builder;
public setNextPageToken(param0: string): com.google.firestore.v1.ListDocumentsResponse.Builder;
public setNextPageTokenBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListDocumentsResponse.Builder;
public setDocuments(param0: number, param1: com.google.firestore.v1.Document): com.google.firestore.v1.ListDocumentsResponse.Builder;
public addDocuments(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.ListDocumentsResponse.Builder;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public addDocuments(param0: number, param1: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.ListDocumentsResponse.Builder;
public clearNextPageToken(): com.google.firestore.v1.ListDocumentsResponse.Builder;
public addDocuments(param0: com.google.firestore.v1.Document): com.google.firestore.v1.ListDocumentsResponse.Builder;
public addDocuments(param0: number, param1: com.google.firestore.v1.Document): com.google.firestore.v1.ListDocumentsResponse.Builder;
public getNextPageToken(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListDocumentsResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListDocumentsResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListDocumentsResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDocumentsList(): java.util.List<com.google.firestore.v1.Document>;
getDocuments(param0: number): com.google.firestore.v1.Document;
getDocumentsCount(): number;
getNextPageToken(): string;
getNextPageTokenBytes(): com.google.protobuf.ByteString;
});
public constructor();
public getDocuments(param0: number): com.google.firestore.v1.Document;
public getNextPageTokenBytes(): com.google.protobuf.ByteString;
public getDocumentsList(): java.util.List<com.google.firestore.v1.Document>;
public getDocumentsCount(): number;
public getNextPageToken(): string;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListenRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListenRequest,com.google.firestore.v1.ListenRequest.Builder> implements com.google.firestore.v1.ListenRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static ADD_TARGET_FIELD_NUMBER: number;
public static REMOVE_TARGET_FIELD_NUMBER: number;
public static LABELS_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListenRequest;
public getAddTarget(): com.google.firestore.v1.Target;
public getRemoveTarget(): number;
public getLabelsOrDefault(param0: string, param1: string): string;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenRequest;
public getLabelsMap(): java.util.Map<string,string>;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListenRequest;
public getLabels(): java.util.Map<string,string>;
public getDatabase(): string;
public static newBuilder(param0: com.google.firestore.v1.ListenRequest): com.google.firestore.v1.ListenRequest.Builder;
public getLabelsOrThrow(param0: string): string;
public getLabelsCount(): number;
public containsLabels(param0: string): boolean;
public getTargetChangeCase(): com.google.firestore.v1.ListenRequest.TargetChangeCase;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static getDefaultInstance(): com.google.firestore.v1.ListenRequest;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListenRequest;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListenRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListenRequest;
public static newBuilder(): com.google.firestore.v1.ListenRequest.Builder;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListenRequest>;
}
export module ListenRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListenRequest,com.google.firestore.v1.ListenRequest.Builder> implements com.google.firestore.v1.ListenRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenRequest.Builder>;
public getRemoveTarget(): number;
public setRemoveTarget(param0: number): com.google.firestore.v1.ListenRequest.Builder;
public setAddTarget(param0: com.google.firestore.v1.Target): com.google.firestore.v1.ListenRequest.Builder;
public clearAddTarget(): com.google.firestore.v1.ListenRequest.Builder;
public clearDatabase(): com.google.firestore.v1.ListenRequest.Builder;
public getLabelsOrThrow(param0: string): string;
public putAllLabels(param0: java.util.Map<string,string>): com.google.firestore.v1.ListenRequest.Builder;
public clearTargetChange(): com.google.firestore.v1.ListenRequest.Builder;
public getAddTarget(): com.google.firestore.v1.Target;
public getLabelsOrDefault(param0: string, param1: string): string;
public getTargetChangeCase(): com.google.firestore.v1.ListenRequest.TargetChangeCase;
public setAddTarget(param0: com.google.firestore.v1.Target.Builder): com.google.firestore.v1.ListenRequest.Builder;
public setDatabase(param0: string): com.google.firestore.v1.ListenRequest.Builder;
public putLabels(param0: string, param1: string): com.google.firestore.v1.ListenRequest.Builder;
public getDatabase(): string;
public getLabelsCount(): number;
public getLabels(): java.util.Map<string,string>;
public clearLabels(): com.google.firestore.v1.ListenRequest.Builder;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListenRequest.Builder;
public removeLabels(param0: string): com.google.firestore.v1.ListenRequest.Builder;
public mergeAddTarget(param0: com.google.firestore.v1.Target): com.google.firestore.v1.ListenRequest.Builder;
public getLabelsMap(): java.util.Map<string,string>;
public clearRemoveTarget(): com.google.firestore.v1.ListenRequest.Builder;
public containsLabels(param0: string): boolean;
}
export class LabelsDefaultEntryHolder {
public static class: java.lang.Class<com.google.firestore.v1.ListenRequest.LabelsDefaultEntryHolder>;
}
export class TargetChangeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.ListenRequest.TargetChangeCase>;
public static ADD_TARGET: com.google.firestore.v1.ListenRequest.TargetChangeCase;
public static REMOVE_TARGET: com.google.firestore.v1.ListenRequest.TargetChangeCase;
public static TARGETCHANGE_NOT_SET: com.google.firestore.v1.ListenRequest.TargetChangeCase;
public static valueOf(param0: string): com.google.firestore.v1.ListenRequest.TargetChangeCase;
public static values(): native.Array<com.google.firestore.v1.ListenRequest.TargetChangeCase>;
public static valueOf(param0: number): com.google.firestore.v1.ListenRequest.TargetChangeCase;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.ListenRequest.TargetChangeCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListenRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListenRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
getAddTarget(): com.google.firestore.v1.Target;
getRemoveTarget(): number;
getLabelsCount(): number;
containsLabels(param0: string): boolean;
getLabels(): java.util.Map<string,string>;
getLabelsMap(): java.util.Map<string,string>;
getLabelsOrDefault(param0: string, param1: string): string;
getLabelsOrThrow(param0: string): string;
getTargetChangeCase(): com.google.firestore.v1.ListenRequest.TargetChangeCase;
});
public constructor();
public getDatabase(): string;
public getAddTarget(): com.google.firestore.v1.Target;
public getRemoveTarget(): number;
public getLabelsOrDefault(param0: string, param1: string): string;
public getLabelsOrThrow(param0: string): string;
public getLabelsCount(): number;
public containsLabels(param0: string): boolean;
public getTargetChangeCase(): com.google.firestore.v1.ListenRequest.TargetChangeCase;
public getLabelsMap(): java.util.Map<string,string>;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public getLabels(): java.util.Map<string,string>;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListenResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.ListenResponse,com.google.firestore.v1.ListenResponse.Builder> implements com.google.firestore.v1.ListenResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenResponse>;
public static TARGET_CHANGE_FIELD_NUMBER: number;
public static DOCUMENT_CHANGE_FIELD_NUMBER: number;
public static DOCUMENT_DELETE_FIELD_NUMBER: number;
public static DOCUMENT_REMOVE_FIELD_NUMBER: number;
public static FILTER_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.ListenResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.ListenResponse>;
public getTargetChange(): com.google.firestore.v1.TargetChange;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.ListenResponse;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenResponse;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenResponse;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenResponse;
public getDocumentChange(): com.google.firestore.v1.DocumentChange;
public getResponseTypeCase(): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public getFilter(): com.google.firestore.v1.ExistenceFilter;
public static newBuilder(): com.google.firestore.v1.ListenResponse.Builder;
public static getDefaultInstance(): com.google.firestore.v1.ListenResponse;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.ListenResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenResponse;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.ListenResponse;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.ListenResponse;
public static newBuilder(param0: com.google.firestore.v1.ListenResponse): com.google.firestore.v1.ListenResponse.Builder;
public getDocumentDelete(): com.google.firestore.v1.DocumentDelete;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getDocumentRemove(): com.google.firestore.v1.DocumentRemove;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.ListenResponse;
}
export module ListenResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.ListenResponse,com.google.firestore.v1.ListenResponse.Builder> implements com.google.firestore.v1.ListenResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenResponse.Builder>;
public setTargetChange(param0: com.google.firestore.v1.TargetChange): com.google.firestore.v1.ListenResponse.Builder;
public clearDocumentChange(): com.google.firestore.v1.ListenResponse.Builder;
public clearFilter(): com.google.firestore.v1.ListenResponse.Builder;
public mergeDocumentDelete(param0: com.google.firestore.v1.DocumentDelete): com.google.firestore.v1.ListenResponse.Builder;
public mergeDocumentChange(param0: com.google.firestore.v1.DocumentChange): com.google.firestore.v1.ListenResponse.Builder;
public getDocumentChange(): com.google.firestore.v1.DocumentChange;
public mergeDocumentRemove(param0: com.google.firestore.v1.DocumentRemove): com.google.firestore.v1.ListenResponse.Builder;
public getDocumentRemove(): com.google.firestore.v1.DocumentRemove;
public clearDocumentDelete(): com.google.firestore.v1.ListenResponse.Builder;
public clearTargetChange(): com.google.firestore.v1.ListenResponse.Builder;
public setFilter(param0: com.google.firestore.v1.ExistenceFilter.Builder): com.google.firestore.v1.ListenResponse.Builder;
public getResponseTypeCase(): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public clearResponseType(): com.google.firestore.v1.ListenResponse.Builder;
public clearDocumentRemove(): com.google.firestore.v1.ListenResponse.Builder;
public setTargetChange(param0: com.google.firestore.v1.TargetChange.Builder): com.google.firestore.v1.ListenResponse.Builder;
public setDocumentChange(param0: com.google.firestore.v1.DocumentChange.Builder): com.google.firestore.v1.ListenResponse.Builder;
public setDocumentRemove(param0: com.google.firestore.v1.DocumentRemove): com.google.firestore.v1.ListenResponse.Builder;
public getFilter(): com.google.firestore.v1.ExistenceFilter;
public setDocumentDelete(param0: com.google.firestore.v1.DocumentDelete): com.google.firestore.v1.ListenResponse.Builder;
public getDocumentDelete(): com.google.firestore.v1.DocumentDelete;
public setDocumentDelete(param0: com.google.firestore.v1.DocumentDelete.Builder): com.google.firestore.v1.ListenResponse.Builder;
public setDocumentChange(param0: com.google.firestore.v1.DocumentChange): com.google.firestore.v1.ListenResponse.Builder;
public getTargetChange(): com.google.firestore.v1.TargetChange;
public mergeTargetChange(param0: com.google.firestore.v1.TargetChange): com.google.firestore.v1.ListenResponse.Builder;
public setDocumentRemove(param0: com.google.firestore.v1.DocumentRemove.Builder): com.google.firestore.v1.ListenResponse.Builder;
public setFilter(param0: com.google.firestore.v1.ExistenceFilter): com.google.firestore.v1.ListenResponse.Builder;
public mergeFilter(param0: com.google.firestore.v1.ExistenceFilter): com.google.firestore.v1.ListenResponse.Builder;
}
export class ResponseTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.ListenResponse.ResponseTypeCase>;
public static TARGET_CHANGE: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static DOCUMENT_CHANGE: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static DOCUMENT_DELETE: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static DOCUMENT_REMOVE: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static FILTER: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static RESPONSETYPE_NOT_SET: com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static forNumber(param0: number): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.ListenResponse.ResponseTypeCase>;
public static valueOf(param0: string): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ListenResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ListenResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ListenResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTargetChange(): com.google.firestore.v1.TargetChange;
getDocumentChange(): com.google.firestore.v1.DocumentChange;
getDocumentDelete(): com.google.firestore.v1.DocumentDelete;
getDocumentRemove(): com.google.firestore.v1.DocumentRemove;
getFilter(): com.google.firestore.v1.ExistenceFilter;
getResponseTypeCase(): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
});
public constructor();
public getTargetChange(): com.google.firestore.v1.TargetChange;
public getFilter(): com.google.firestore.v1.ExistenceFilter;
public getDocumentChange(): com.google.firestore.v1.DocumentChange;
public getDocumentDelete(): com.google.firestore.v1.DocumentDelete;
public getDocumentRemove(): com.google.firestore.v1.DocumentRemove;
public getResponseTypeCase(): com.google.firestore.v1.ListenResponse.ResponseTypeCase;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class MapValue extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.MapValue,com.google.firestore.v1.MapValue.Builder> implements com.google.firestore.v1.MapValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.MapValue>;
public static FIELDS_FIELD_NUMBER: number;
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.MapValue;
public getFieldsCount(): number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.MapValue;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.MapValue;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.MapValue;
public getSerializedSize(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.MapValue;
public containsFields(param0: string): boolean;
public static newBuilder(param0: com.google.firestore.v1.MapValue): com.google.firestore.v1.MapValue.Builder;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.MapValue;
public static getDefaultInstance(): com.google.firestore.v1.MapValue;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.MapValue;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.MapValue;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.MapValue>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static newBuilder(): com.google.firestore.v1.MapValue.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.MapValue;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.MapValue;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
}
export module MapValue {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.MapValue,com.google.firestore.v1.MapValue.Builder> implements com.google.firestore.v1.MapValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.MapValue.Builder>;
public containsFields(param0: string): boolean;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
public getFieldsCount(): number;
public clearFields(): com.google.firestore.v1.MapValue.Builder;
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public putAllFields(param0: java.util.Map<string,com.google.firestore.v1.Value>): com.google.firestore.v1.MapValue.Builder;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public putFields(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.MapValue.Builder;
public removeFields(param0: string): com.google.firestore.v1.MapValue.Builder;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
}
export class FieldsDefaultEntryHolder {
public static class: java.lang.Class<com.google.firestore.v1.MapValue.FieldsDefaultEntryHolder>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class MapValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.MapValueOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.MapValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFieldsCount(): number;
containsFields(param0: string): boolean;
getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
});
public constructor();
public getFieldsOrDefault(param0: string, param1: com.google.firestore.v1.Value): com.google.firestore.v1.Value;
public getFieldsCount(): number;
public getFieldsMap(): java.util.Map<string,com.google.firestore.v1.Value>;
public getFields(): java.util.Map<string,com.google.firestore.v1.Value>;
public containsFields(param0: string): boolean;
public getFieldsOrThrow(param0: string): com.google.firestore.v1.Value;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Precondition extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Precondition,com.google.firestore.v1.Precondition.Builder> implements com.google.firestore.v1.PreconditionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Precondition>;
public static EXISTS_FIELD_NUMBER: number;
public static UPDATE_TIME_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Precondition;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Precondition;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Precondition;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Precondition;
public static getDefaultInstance(): com.google.firestore.v1.Precondition;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Precondition>;
public getUpdateTime(): com.google.protobuf.Timestamp;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Precondition;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Precondition;
public static newBuilder(): com.google.firestore.v1.Precondition.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Precondition;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Precondition;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Precondition;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Precondition;
public static newBuilder(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.Precondition.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getExists(): boolean;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getConditionTypeCase(): com.google.firestore.v1.Precondition.ConditionTypeCase;
}
export module Precondition {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Precondition,com.google.firestore.v1.Precondition.Builder> implements com.google.firestore.v1.PreconditionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Precondition.Builder>;
public clearExists(): com.google.firestore.v1.Precondition.Builder;
public clearConditionType(): com.google.firestore.v1.Precondition.Builder;
public getExists(): boolean;
public setExists(param0: boolean): com.google.firestore.v1.Precondition.Builder;
public setUpdateTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.Precondition.Builder;
public clearUpdateTime(): com.google.firestore.v1.Precondition.Builder;
public setUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Precondition.Builder;
public mergeUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Precondition.Builder;
public getUpdateTime(): com.google.protobuf.Timestamp;
public getConditionTypeCase(): com.google.firestore.v1.Precondition.ConditionTypeCase;
}
export class ConditionTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Precondition.ConditionTypeCase>;
public static EXISTS: com.google.firestore.v1.Precondition.ConditionTypeCase;
public static UPDATE_TIME: com.google.firestore.v1.Precondition.ConditionTypeCase;
public static CONDITIONTYPE_NOT_SET: com.google.firestore.v1.Precondition.ConditionTypeCase;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.Precondition.ConditionTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.Precondition.ConditionTypeCase;
public static forNumber(param0: number): com.google.firestore.v1.Precondition.ConditionTypeCase;
public static values(): native.Array<com.google.firestore.v1.Precondition.ConditionTypeCase>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class PreconditionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.PreconditionOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.PreconditionOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getExists(): boolean;
getUpdateTime(): com.google.protobuf.Timestamp;
getConditionTypeCase(): com.google.firestore.v1.Precondition.ConditionTypeCase;
});
public constructor();
public getUpdateTime(): com.google.protobuf.Timestamp;
public getExists(): boolean;
public getConditionTypeCase(): com.google.firestore.v1.Precondition.ConditionTypeCase;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class QueryProto {
public static class: java.lang.Class<com.google.firestore.v1.QueryProto>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RollbackRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.RollbackRequest,com.google.firestore.v1.RollbackRequest.Builder> implements com.google.firestore.v1.RollbackRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RollbackRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RollbackRequest;
public getTransaction(): com.google.protobuf.ByteString;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.RollbackRequest;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RollbackRequest;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public static newBuilder(param0: com.google.firestore.v1.RollbackRequest): com.google.firestore.v1.RollbackRequest.Builder;
public getDatabase(): string;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RollbackRequest;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RollbackRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.RollbackRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RollbackRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.RollbackRequest>;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.RollbackRequest;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RollbackRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static getDefaultInstance(): com.google.firestore.v1.RollbackRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.RollbackRequest;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static newBuilder(): com.google.firestore.v1.RollbackRequest.Builder;
}
export module RollbackRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.RollbackRequest,com.google.firestore.v1.RollbackRequest.Builder> implements com.google.firestore.v1.RollbackRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RollbackRequest.Builder>;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RollbackRequest.Builder;
public getDatabase(): string;
public clearTransaction(): com.google.firestore.v1.RollbackRequest.Builder;
public setDatabase(param0: string): com.google.firestore.v1.RollbackRequest.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public clearDatabase(): com.google.firestore.v1.RollbackRequest.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RollbackRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RollbackRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RollbackRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.RollbackRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
getTransaction(): com.google.protobuf.ByteString;
});
public constructor();
public getDatabase(): string;
public getTransaction(): com.google.protobuf.ByteString;
public getDatabaseBytes(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RunQueryRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.RunQueryRequest,com.google.firestore.v1.RunQueryRequest.Builder> implements com.google.firestore.v1.RunQueryRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryRequest>;
public static PARENT_FIELD_NUMBER: number;
public static STRUCTURED_QUERY_FIELD_NUMBER: number;
public static TRANSACTION_FIELD_NUMBER: number;
public static NEW_TRANSACTION_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public getQueryTypeCase(): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public getTransaction(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.RunQueryRequest;
public static newBuilder(): com.google.firestore.v1.RunQueryRequest.Builder;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryRequest;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryRequest;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.RunQueryRequest;
public static newBuilder(param0: com.google.firestore.v1.RunQueryRequest): com.google.firestore.v1.RunQueryRequest.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryRequest;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.RunQueryRequest>;
public getSerializedSize(): number;
public static getDefaultInstance(): com.google.firestore.v1.RunQueryRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.RunQueryRequest;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.RunQueryRequest;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getConsistencySelectorCase(): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RunQueryRequest;
}
export module RunQueryRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.RunQueryRequest,com.google.firestore.v1.RunQueryRequest.Builder> implements com.google.firestore.v1.RunQueryRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryRequest.Builder>;
public getConsistencySelectorCase(): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public setStructuredQuery(param0: com.google.firestore.v1.StructuredQuery): com.google.firestore.v1.RunQueryRequest.Builder;
public setNewTransaction(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.RunQueryRequest.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RunQueryRequest.Builder;
public getParent(): string;
public setParent(param0: string): com.google.firestore.v1.RunQueryRequest.Builder;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.RunQueryRequest.Builder;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public setStructuredQuery(param0: com.google.firestore.v1.StructuredQuery.Builder): com.google.firestore.v1.RunQueryRequest.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public getParentBytes(): com.google.protobuf.ByteString;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public clearNewTransaction(): com.google.firestore.v1.RunQueryRequest.Builder;
public setNewTransaction(param0: com.google.firestore.v1.TransactionOptions.Builder): com.google.firestore.v1.RunQueryRequest.Builder;
public clearConsistencySelector(): com.google.firestore.v1.RunQueryRequest.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.RunQueryRequest.Builder;
public clearParent(): com.google.firestore.v1.RunQueryRequest.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.RunQueryRequest.Builder;
public setParentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RunQueryRequest.Builder;
public clearTransaction(): com.google.firestore.v1.RunQueryRequest.Builder;
public clearReadTime(): com.google.firestore.v1.RunQueryRequest.Builder;
public clearQueryType(): com.google.firestore.v1.RunQueryRequest.Builder;
public clearStructuredQuery(): com.google.firestore.v1.RunQueryRequest.Builder;
public mergeNewTransaction(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.RunQueryRequest.Builder;
public getQueryTypeCase(): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public mergeStructuredQuery(param0: com.google.firestore.v1.StructuredQuery): com.google.firestore.v1.RunQueryRequest.Builder;
}
export class ConsistencySelectorCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase>;
public static TRANSACTION: com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static NEW_TRANSACTION: com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static READ_TIME: com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static CONSISTENCYSELECTOR_NOT_SET: com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static forNumber(param0: number): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public static values(): native.Array<com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase>;
public static valueOf(param0: string): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
public getNumber(): number;
public static valueOf(param0: number): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
}
export class QueryTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryRequest.QueryTypeCase>;
public static STRUCTURED_QUERY: com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public static QUERYTYPE_NOT_SET: com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public static forNumber(param0: number): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public static values(): native.Array<com.google.firestore.v1.RunQueryRequest.QueryTypeCase>;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RunQueryRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.RunQueryRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParent(): string;
getParentBytes(): com.google.protobuf.ByteString;
getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
getTransaction(): com.google.protobuf.ByteString;
getNewTransaction(): com.google.firestore.v1.TransactionOptions;
getReadTime(): com.google.protobuf.Timestamp;
getQueryTypeCase(): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
getConsistencySelectorCase(): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
});
public constructor();
public getQueryTypeCase(): com.google.firestore.v1.RunQueryRequest.QueryTypeCase;
public getParent(): string;
public getParentBytes(): com.google.protobuf.ByteString;
public getNewTransaction(): com.google.firestore.v1.TransactionOptions;
public getTransaction(): com.google.protobuf.ByteString;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public getReadTime(): com.google.protobuf.Timestamp;
public getConsistencySelectorCase(): com.google.firestore.v1.RunQueryRequest.ConsistencySelectorCase;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RunQueryResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.RunQueryResponse,com.google.firestore.v1.RunQueryResponse.Builder> implements com.google.firestore.v1.RunQueryResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryResponse>;
public static TRANSACTION_FIELD_NUMBER: number;
public static DOCUMENT_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static SKIPPED_RESULTS_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.RunQueryResponse;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.RunQueryResponse;
public getTransaction(): com.google.protobuf.ByteString;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryResponse;
public getSerializedSize(): number;
public static getDefaultInstance(): com.google.firestore.v1.RunQueryResponse;
public hasDocument(): boolean;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.RunQueryResponse;
public static newBuilder(param0: com.google.firestore.v1.RunQueryResponse): com.google.firestore.v1.RunQueryResponse.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryResponse;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RunQueryResponse;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryResponse;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getDocument(): com.google.firestore.v1.Document;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.RunQueryResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.RunQueryResponse>;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryResponse;
public static newBuilder(): com.google.firestore.v1.RunQueryResponse.Builder;
public hasReadTime(): boolean;
public getSkippedResults(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.RunQueryResponse;
}
export module RunQueryResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.RunQueryResponse,com.google.firestore.v1.RunQueryResponse.Builder> implements com.google.firestore.v1.RunQueryResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryResponse.Builder>;
public getDocument(): com.google.firestore.v1.Document;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.RunQueryResponse.Builder;
public clearReadTime(): com.google.firestore.v1.RunQueryResponse.Builder;
public setTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.RunQueryResponse.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.RunQueryResponse.Builder;
public getSkippedResults(): number;
public setDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.RunQueryResponse.Builder;
public clearTransaction(): com.google.firestore.v1.RunQueryResponse.Builder;
public clearDocument(): com.google.firestore.v1.RunQueryResponse.Builder;
public hasReadTime(): boolean;
public getReadTime(): com.google.protobuf.Timestamp;
public setSkippedResults(param0: number): com.google.firestore.v1.RunQueryResponse.Builder;
public setDocument(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.RunQueryResponse.Builder;
public mergeDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.RunQueryResponse.Builder;
public getTransaction(): com.google.protobuf.ByteString;
public hasDocument(): boolean;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.RunQueryResponse.Builder;
public clearSkippedResults(): com.google.firestore.v1.RunQueryResponse.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class RunQueryResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.RunQueryResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.RunQueryResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTransaction(): com.google.protobuf.ByteString;
hasDocument(): boolean;
getDocument(): com.google.firestore.v1.Document;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
getSkippedResults(): number;
});
public constructor();
public getTransaction(): com.google.protobuf.ByteString;
public getDocument(): com.google.firestore.v1.Document;
public getReadTime(): com.google.protobuf.Timestamp;
public hasDocument(): boolean;
public hasReadTime(): boolean;
public getSkippedResults(): number;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class StructuredQuery extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery,com.google.firestore.v1.StructuredQuery.Builder> implements com.google.firestore.v1.StructuredQueryOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery>;
public static SELECT_FIELD_NUMBER: number;
public static FROM_FIELD_NUMBER: number;
public static WHERE_FIELD_NUMBER: number;
public static ORDER_BY_FIELD_NUMBER: number;
public static START_AT_FIELD_NUMBER: number;
public static END_AT_FIELD_NUMBER: number;
public static OFFSET_FIELD_NUMBER: number;
public static LIMIT_FIELD_NUMBER: number;
public getWhere(): com.google.firestore.v1.StructuredQuery.Filter;
public getFromList(): java.util.List<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
public getOffset(): number;
public hasEndAt(): boolean;
public getOrderByCount(): number;
public getFromOrBuilder(param0: number): com.google.firestore.v1.StructuredQuery.CollectionSelectorOrBuilder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery;
public hasLimit(): boolean;
public getLimit(): com.google.protobuf.Int32Value;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery>;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery;
public getOrderByList(): java.util.List<com.google.firestore.v1.StructuredQuery.Order>;
public getOrderByOrBuilderList(): java.util.List<any>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.Builder;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery): com.google.firestore.v1.StructuredQuery.Builder;
public getFrom(param0: number): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery;
public getStartAt(): com.google.firestore.v1.Cursor;
public getOrderByOrBuilder(param0: number): com.google.firestore.v1.StructuredQuery.OrderOrBuilder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery;
public hasSelect(): boolean;
public getOrderBy(param0: number): com.google.firestore.v1.StructuredQuery.Order;
public getFromOrBuilderList(): java.util.List<any>;
public hasWhere(): boolean;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery;
public getSelect(): com.google.firestore.v1.StructuredQuery.Projection;
public getEndAt(): com.google.firestore.v1.Cursor;
public getFromCount(): number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery;
public hasStartAt(): boolean;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery;
}
export module StructuredQuery {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery,com.google.firestore.v1.StructuredQuery.Builder> implements com.google.firestore.v1.StructuredQueryOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Builder>;
public mergeEndAt(param0: com.google.firestore.v1.Cursor): com.google.firestore.v1.StructuredQuery.Builder;
public addOrderBy(param0: number, param1: com.google.firestore.v1.StructuredQuery.Order.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public setSelect(param0: com.google.firestore.v1.StructuredQuery.Projection): com.google.firestore.v1.StructuredQuery.Builder;
public setOffset(param0: number): com.google.firestore.v1.StructuredQuery.Builder;
public getWhere(): com.google.firestore.v1.StructuredQuery.Filter;
public setEndAt(param0: com.google.firestore.v1.Cursor.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public hasWhere(): boolean;
public hasStartAt(): boolean;
public addOrderBy(param0: com.google.firestore.v1.StructuredQuery.Order): com.google.firestore.v1.StructuredQuery.Builder;
public mergeStartAt(param0: com.google.firestore.v1.Cursor): com.google.firestore.v1.StructuredQuery.Builder;
public getFrom(param0: number): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public getFromCount(): number;
public setWhere(param0: com.google.firestore.v1.StructuredQuery.Filter.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public getEndAt(): com.google.firestore.v1.Cursor;
public addOrderBy(param0: com.google.firestore.v1.StructuredQuery.Order.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public setWhere(param0: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.Builder;
public getFromList(): java.util.List<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
public mergeWhere(param0: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.Builder;
public setLimit(param0: com.google.protobuf.Int32Value): com.google.firestore.v1.StructuredQuery.Builder;
public setLimit(param0: com.google.protobuf.Int32Value.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public clearSelect(): com.google.firestore.v1.StructuredQuery.Builder;
public removeFrom(param0: number): com.google.firestore.v1.StructuredQuery.Builder;
public clearLimit(): com.google.firestore.v1.StructuredQuery.Builder;
public clearOffset(): com.google.firestore.v1.StructuredQuery.Builder;
public setStartAt(param0: com.google.firestore.v1.Cursor): com.google.firestore.v1.StructuredQuery.Builder;
public hasEndAt(): boolean;
public setFrom(param0: number, param1: com.google.firestore.v1.StructuredQuery.CollectionSelector): com.google.firestore.v1.StructuredQuery.Builder;
public mergeLimit(param0: com.google.protobuf.Int32Value): com.google.firestore.v1.StructuredQuery.Builder;
public setSelect(param0: com.google.firestore.v1.StructuredQuery.Projection.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public clearEndAt(): com.google.firestore.v1.StructuredQuery.Builder;
public addFrom(param0: com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public clearFrom(): com.google.firestore.v1.StructuredQuery.Builder;
public setOrderBy(param0: number, param1: com.google.firestore.v1.StructuredQuery.Order): com.google.firestore.v1.StructuredQuery.Builder;
public addFrom(param0: number, param1: com.google.firestore.v1.StructuredQuery.CollectionSelector): com.google.firestore.v1.StructuredQuery.Builder;
public addOrderBy(param0: number, param1: com.google.firestore.v1.StructuredQuery.Order): com.google.firestore.v1.StructuredQuery.Builder;
public getOrderBy(param0: number): com.google.firestore.v1.StructuredQuery.Order;
public setEndAt(param0: com.google.firestore.v1.Cursor): com.google.firestore.v1.StructuredQuery.Builder;
public setOrderBy(param0: number, param1: com.google.firestore.v1.StructuredQuery.Order.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public getOrderByList(): java.util.List<com.google.firestore.v1.StructuredQuery.Order>;
public mergeSelect(param0: com.google.firestore.v1.StructuredQuery.Projection): com.google.firestore.v1.StructuredQuery.Builder;
public clearOrderBy(): com.google.firestore.v1.StructuredQuery.Builder;
public getStartAt(): com.google.firestore.v1.Cursor;
public hasSelect(): boolean;
public removeOrderBy(param0: number): com.google.firestore.v1.StructuredQuery.Builder;
public hasLimit(): boolean;
public getLimit(): com.google.protobuf.Int32Value;
public setFrom(param0: number, param1: com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public addAllOrderBy(param0: java.lang.Iterable<any>): com.google.firestore.v1.StructuredQuery.Builder;
public clearStartAt(): com.google.firestore.v1.StructuredQuery.Builder;
public addAllFrom(param0: java.lang.Iterable<any>): com.google.firestore.v1.StructuredQuery.Builder;
public addFrom(param0: number, param1: com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public clearWhere(): com.google.firestore.v1.StructuredQuery.Builder;
public getOffset(): number;
public addFrom(param0: com.google.firestore.v1.StructuredQuery.CollectionSelector): com.google.firestore.v1.StructuredQuery.Builder;
public getSelect(): com.google.firestore.v1.StructuredQuery.Projection;
public setStartAt(param0: com.google.firestore.v1.Cursor.Builder): com.google.firestore.v1.StructuredQuery.Builder;
public getOrderByCount(): number;
}
export class CollectionSelector extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.CollectionSelector,com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder> implements com.google.firestore.v1.StructuredQuery.CollectionSelectorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
public static COLLECTION_ID_FIELD_NUMBER: number;
public static ALL_DESCENDANTS_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public getCollectionId(): string;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public getAllDescendants(): boolean;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.CollectionSelector): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CollectionSelector;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.CollectionSelector;
}
export module CollectionSelector {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.CollectionSelector,com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder> implements com.google.firestore.v1.StructuredQuery.CollectionSelectorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder>;
public getAllDescendants(): boolean;
public getCollectionId(): string;
public setCollectionIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public clearCollectionId(): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public clearAllDescendants(): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public setCollectionId(param0: string): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public setAllDescendants(param0: boolean): com.google.firestore.v1.StructuredQuery.CollectionSelector.Builder;
public getCollectionIdBytes(): com.google.protobuf.ByteString;
}
}
export class CollectionSelectorOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CollectionSelectorOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$CollectionSelectorOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getCollectionId(): string;
getCollectionIdBytes(): com.google.protobuf.ByteString;
getAllDescendants(): boolean;
});
public constructor();
public getCollectionIdBytes(): com.google.protobuf.ByteString;
public getAllDescendants(): boolean;
public getCollectionId(): string;
}
export class CompositeFilter extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.CompositeFilter,com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder> implements com.google.firestore.v1.StructuredQuery.CompositeFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CompositeFilter>;
public static OP_FIELD_NUMBER: number;
public static FILTERS_FIELD_NUMBER: number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public getOp(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getOpValue(): number;
public getSerializedSize(): number;
public getFiltersOrBuilderList(): java.util.List<any>;
public getFiltersOrBuilder(param0: number): com.google.firestore.v1.StructuredQuery.FilterOrBuilder;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.CompositeFilter>;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.CompositeFilter): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public getFiltersList(): java.util.List<com.google.firestore.v1.StructuredQuery.Filter>;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public getFilters(param0: number): com.google.firestore.v1.StructuredQuery.Filter;
public getFiltersCount(): number;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.CompositeFilter;
}
export module CompositeFilter {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.CompositeFilter,com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder> implements com.google.firestore.v1.StructuredQuery.CompositeFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder>;
public addFilters(param0: com.google.firestore.v1.StructuredQuery.Filter.Builder): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public getOp(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public setOp(param0: com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public clearFilters(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public removeFilters(param0: number): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public setFilters(param0: number, param1: com.google.firestore.v1.StructuredQuery.Filter.Builder): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public addFilters(param0: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public getOpValue(): number;
public setOpValue(param0: number): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public addFilters(param0: number, param1: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public addAllFilters(param0: java.lang.Iterable<any>): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public getFilters(param0: number): com.google.firestore.v1.StructuredQuery.Filter;
public addFilters(param0: number, param1: com.google.firestore.v1.StructuredQuery.Filter.Builder): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public clearOp(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
public getFiltersList(): java.util.List<com.google.firestore.v1.StructuredQuery.Filter>;
public getFiltersCount(): number;
public setFilters(param0: number, param1: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder;
}
export class Operator extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator>;
public static OPERATOR_UNSPECIFIED: com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public static AND: com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public static UNRECOGNIZED: com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public static OPERATOR_UNSPECIFIED_VALUE: number;
public static AND_VALUE: number;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator>;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator>;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
}
}
export class CompositeFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.CompositeFilterOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$CompositeFilterOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getOpValue(): number;
getOp(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
getFiltersList(): java.util.List<com.google.firestore.v1.StructuredQuery.Filter>;
getFilters(param0: number): com.google.firestore.v1.StructuredQuery.Filter;
getFiltersCount(): number;
});
public constructor();
public getFiltersList(): java.util.List<com.google.firestore.v1.StructuredQuery.Filter>;
public getOp(): com.google.firestore.v1.StructuredQuery.CompositeFilter.Operator;
public getFilters(param0: number): com.google.firestore.v1.StructuredQuery.Filter;
public getFiltersCount(): number;
public getOpValue(): number;
}
export class Direction extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Direction>;
public static DIRECTION_UNSPECIFIED: com.google.firestore.v1.StructuredQuery.Direction;
public static ASCENDING: com.google.firestore.v1.StructuredQuery.Direction;
public static DESCENDING: com.google.firestore.v1.StructuredQuery.Direction;
public static UNRECOGNIZED: com.google.firestore.v1.StructuredQuery.Direction;
public static DIRECTION_UNSPECIFIED_VALUE: number;
public static ASCENDING_VALUE: number;
public static DESCENDING_VALUE: number;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.Direction;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.StructuredQuery.Direction>;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.Direction;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.Direction;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.Direction>;
}
export class FieldFilter extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.FieldFilter,com.google.firestore.v1.StructuredQuery.FieldFilter.Builder> implements com.google.firestore.v1.StructuredQuery.FieldFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldFilter>;
public static FIELD_FIELD_NUMBER: number;
public static OP_FIELD_NUMBER: number;
public static VALUE_FIELD_NUMBER: number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldFilter;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldFilter;
public hasValue(): boolean;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getOp(): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.FieldFilter): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getOpValue(): number;
public getSerializedSize(): number;
public hasField(): boolean;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getValue(): com.google.firestore.v1.Value;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.FieldFilter>;
}
export module FieldFilter {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.FieldFilter,com.google.firestore.v1.StructuredQuery.FieldFilter.Builder> implements com.google.firestore.v1.StructuredQuery.FieldFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldFilter.Builder>;
public setValue(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public setOpValue(param0: number): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public hasValue(): boolean;
public clearField(): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public hasField(): boolean;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public mergeField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public setOp(param0: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public clearValue(): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public getOpValue(): number;
public setValue(param0: com.google.firestore.v1.Value): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public getOp(): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public mergeValue(param0: com.google.firestore.v1.Value): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public clearOp(): com.google.firestore.v1.StructuredQuery.FieldFilter.Builder;
public getValue(): com.google.firestore.v1.Value;
}
export class Operator extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldFilter.Operator>;
public static OPERATOR_UNSPECIFIED: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static LESS_THAN: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static LESS_THAN_OR_EQUAL: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static GREATER_THAN: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static GREATER_THAN_OR_EQUAL: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static EQUAL: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static ARRAY_CONTAINS: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static IN: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static ARRAY_CONTAINS_ANY: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static UNRECOGNIZED: com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static OPERATOR_UNSPECIFIED_VALUE: number;
public static LESS_THAN_VALUE: number;
public static LESS_THAN_OR_EQUAL_VALUE: number;
public static GREATER_THAN_VALUE: number;
public static GREATER_THAN_OR_EQUAL_VALUE: number;
public static EQUAL_VALUE: number;
public static ARRAY_CONTAINS_VALUE: number;
public static IN_VALUE: number;
public static ARRAY_CONTAINS_ANY_VALUE: number;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.StructuredQuery.FieldFilter.Operator>;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.FieldFilter.Operator>;
}
}
export class FieldFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldFilterOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$FieldFilterOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasField(): boolean;
getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
getOpValue(): number;
getOp(): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
hasValue(): boolean;
getValue(): com.google.firestore.v1.Value;
});
public constructor();
public hasField(): boolean;
public hasValue(): boolean;
public getOp(): com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
public getValue(): com.google.firestore.v1.Value;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public getOpValue(): number;
}
export class FieldReference extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.FieldReference,com.google.firestore.v1.StructuredQuery.FieldReference.Builder> implements com.google.firestore.v1.StructuredQuery.FieldReferenceOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldReference>;
public static FIELD_PATH_FIELD_NUMBER: number;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.FieldReference.Builder;
public getFieldPathBytes(): com.google.protobuf.ByteString;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.FieldReference>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.FieldReference;
public getSerializedSize(): number;
public getFieldPath(): string;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldReference;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.FieldReference;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.FieldReference.Builder;
}
export module FieldReference {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.FieldReference,com.google.firestore.v1.StructuredQuery.FieldReference.Builder> implements com.google.firestore.v1.StructuredQuery.FieldReferenceOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldReference.Builder>;
public setFieldPath(param0: string): com.google.firestore.v1.StructuredQuery.FieldReference.Builder;
public getFieldPath(): string;
public clearFieldPath(): com.google.firestore.v1.StructuredQuery.FieldReference.Builder;
public setFieldPathBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.FieldReference.Builder;
public getFieldPathBytes(): com.google.protobuf.ByteString;
}
}
export class FieldReferenceOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FieldReferenceOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$FieldReferenceOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFieldPath(): string;
getFieldPathBytes(): com.google.protobuf.ByteString;
});
public constructor();
public getFieldPath(): string;
public getFieldPathBytes(): com.google.protobuf.ByteString;
}
export class Filter extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.Filter,com.google.firestore.v1.StructuredQuery.Filter.Builder> implements com.google.firestore.v1.StructuredQuery.FilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Filter>;
public static COMPOSITE_FILTER_FIELD_NUMBER: number;
public static FIELD_FILTER_FIELD_NUMBER: number;
public static UNARY_FILTER_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Filter;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Filter;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Filter;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.Filter>;
public getSerializedSize(): number;
public getCompositeFilter(): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public getUnaryFilter(): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public getFieldFilter(): com.google.firestore.v1.StructuredQuery.FieldFilter;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Filter;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Filter;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.Filter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Filter;
public getFilterTypeCase(): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
}
export module Filter {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.Filter,com.google.firestore.v1.StructuredQuery.Filter.Builder> implements com.google.firestore.v1.StructuredQuery.FilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Filter.Builder>;
public setFieldFilter(param0: com.google.firestore.v1.StructuredQuery.FieldFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public mergeFieldFilter(param0: com.google.firestore.v1.StructuredQuery.FieldFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public mergeUnaryFilter(param0: com.google.firestore.v1.StructuredQuery.UnaryFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public getFieldFilter(): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getUnaryFilter(): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public setCompositeFilter(param0: com.google.firestore.v1.StructuredQuery.CompositeFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public clearUnaryFilter(): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public getFilterTypeCase(): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public clearFieldFilter(): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public getCompositeFilter(): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public setUnaryFilter(param0: com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public setFieldFilter(param0: com.google.firestore.v1.StructuredQuery.FieldFilter.Builder): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public setCompositeFilter(param0: com.google.firestore.v1.StructuredQuery.CompositeFilter.Builder): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public clearFilterType(): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public mergeCompositeFilter(param0: com.google.firestore.v1.StructuredQuery.CompositeFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public clearCompositeFilter(): com.google.firestore.v1.StructuredQuery.Filter.Builder;
public setUnaryFilter(param0: com.google.firestore.v1.StructuredQuery.UnaryFilter): com.google.firestore.v1.StructuredQuery.Filter.Builder;
}
export class FilterTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase>;
public static COMPOSITE_FILTER: com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static FIELD_FILTER: com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static UNARY_FILTER: com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static FILTERTYPE_NOT_SET: com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase>;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
public getNumber(): number;
}
}
export class FilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.FilterOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$FilterOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getCompositeFilter(): com.google.firestore.v1.StructuredQuery.CompositeFilter;
getFieldFilter(): com.google.firestore.v1.StructuredQuery.FieldFilter;
getUnaryFilter(): com.google.firestore.v1.StructuredQuery.UnaryFilter;
getFilterTypeCase(): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
});
public constructor();
public getCompositeFilter(): com.google.firestore.v1.StructuredQuery.CompositeFilter;
public getUnaryFilter(): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public getFieldFilter(): com.google.firestore.v1.StructuredQuery.FieldFilter;
public getFilterTypeCase(): com.google.firestore.v1.StructuredQuery.Filter.FilterTypeCase;
}
export class Order extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.Order,com.google.firestore.v1.StructuredQuery.Order.Builder> implements com.google.firestore.v1.StructuredQuery.OrderOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Order>;
public static FIELD_FIELD_NUMBER: number;
public static DIRECTION_FIELD_NUMBER: number;
public getDirection(): com.google.firestore.v1.StructuredQuery.Direction;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Order;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Order;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.Order.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Order;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.Order>;
public getDirectionValue(): number;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.Order): com.google.firestore.v1.StructuredQuery.Order.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.Order;
public getSerializedSize(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Order;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Order;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.Order;
public hasField(): boolean;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.Order;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Order;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Order;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.Order;
}
export module Order {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.Order,com.google.firestore.v1.StructuredQuery.Order.Builder> implements com.google.firestore.v1.StructuredQuery.OrderOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Order.Builder>;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.Order.Builder;
public mergeField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.Order.Builder;
public setDirectionValue(param0: number): com.google.firestore.v1.StructuredQuery.Order.Builder;
public getDirection(): com.google.firestore.v1.StructuredQuery.Direction;
public getDirectionValue(): number;
public hasField(): boolean;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.Order.Builder;
public setDirection(param0: com.google.firestore.v1.StructuredQuery.Direction): com.google.firestore.v1.StructuredQuery.Order.Builder;
public clearDirection(): com.google.firestore.v1.StructuredQuery.Order.Builder;
public clearField(): com.google.firestore.v1.StructuredQuery.Order.Builder;
}
}
export class OrderOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.OrderOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$OrderOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasField(): boolean;
getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
getDirectionValue(): number;
getDirection(): com.google.firestore.v1.StructuredQuery.Direction;
});
public constructor();
public hasField(): boolean;
public getDirection(): com.google.firestore.v1.StructuredQuery.Direction;
public getDirectionValue(): number;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
}
export class Projection extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.Projection,com.google.firestore.v1.StructuredQuery.Projection.Builder> implements com.google.firestore.v1.StructuredQuery.ProjectionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Projection>;
public static FIELDS_FIELD_NUMBER: number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.Projection>;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Projection;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Projection;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Projection;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Projection;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.Projection): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.Projection;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Projection;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.Projection;
public getFieldsOrBuilder(param0: number): com.google.firestore.v1.StructuredQuery.FieldReferenceOrBuilder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.Projection;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getSerializedSize(): number;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public getFieldsList(): java.util.List<com.google.firestore.v1.StructuredQuery.FieldReference>;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.Projection;
public getFieldsCount(): number;
public getFieldsOrBuilderList(): java.util.List<any>;
public getFields(param0: number): com.google.firestore.v1.StructuredQuery.FieldReference;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.Projection;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.Projection;
}
export module Projection {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.Projection,com.google.firestore.v1.StructuredQuery.Projection.Builder> implements com.google.firestore.v1.StructuredQuery.ProjectionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.Projection.Builder>;
public addFields(param0: number, param1: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public addAllFields(param0: java.lang.Iterable<any>): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public addFields(param0: number, param1: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public getFields(param0: number): com.google.firestore.v1.StructuredQuery.FieldReference;
public addFields(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public clearFields(): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public getFieldsCount(): number;
public addFields(param0: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public getFieldsList(): java.util.List<com.google.firestore.v1.StructuredQuery.FieldReference>;
public removeFields(param0: number): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public setFields(param0: number, param1: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.Projection.Builder;
public setFields(param0: number, param1: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.Projection.Builder;
}
}
export class ProjectionOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.ProjectionOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$ProjectionOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getFieldsList(): java.util.List<com.google.firestore.v1.StructuredQuery.FieldReference>;
getFields(param0: number): com.google.firestore.v1.StructuredQuery.FieldReference;
getFieldsCount(): number;
});
public constructor();
public getFieldsList(): java.util.List<com.google.firestore.v1.StructuredQuery.FieldReference>;
public getFieldsCount(): number;
public getFields(param0: number): com.google.firestore.v1.StructuredQuery.FieldReference;
}
export class UnaryFilter extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.StructuredQuery.UnaryFilter,com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder> implements com.google.firestore.v1.StructuredQuery.UnaryFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.UnaryFilter>;
public static OP_FIELD_NUMBER: number;
public static FIELD_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static newBuilder(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public getOp(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static getDefaultInstance(): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public getOperandTypeCase(): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getOpValue(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static newBuilder(param0: com.google.firestore.v1.StructuredQuery.UnaryFilter): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.StructuredQuery.UnaryFilter;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.StructuredQuery.UnaryFilter>;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
}
export module UnaryFilter {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.StructuredQuery.UnaryFilter,com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder> implements com.google.firestore.v1.StructuredQuery.UnaryFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder>;
public getOpValue(): number;
public setOp(param0: com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference.Builder): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public mergeField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public clearOp(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public getOperandTypeCase(): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
public setField(param0: com.google.firestore.v1.StructuredQuery.FieldReference): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public clearOperandType(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public getOp(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public clearField(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
public setOpValue(param0: number): com.google.firestore.v1.StructuredQuery.UnaryFilter.Builder;
}
export class OperandTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase>;
public static FIELD: com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public static OPERANDTYPE_NOT_SET: com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase>;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
}
export class Operator extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator>;
public static OPERATOR_UNSPECIFIED: com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static IS_NAN: com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static IS_NULL: com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static UNRECOGNIZED: com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static OPERATOR_UNSPECIFIED_VALUE: number;
public static IS_NAN_VALUE: number;
public static IS_NULL_VALUE: number;
public static values(): native.Array<com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator>;
public static valueOf(param0: string): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator>;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public static valueOf(param0: number): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
}
}
export class UnaryFilterOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQuery.UnaryFilterOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQuery$UnaryFilterOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getOpValue(): number;
getOp(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
getOperandTypeCase(): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
});
public constructor();
public getOp(): com.google.firestore.v1.StructuredQuery.UnaryFilter.Operator;
public getOperandTypeCase(): com.google.firestore.v1.StructuredQuery.UnaryFilter.OperandTypeCase;
public getOpValue(): number;
public getField(): com.google.firestore.v1.StructuredQuery.FieldReference;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class StructuredQueryOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.StructuredQueryOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.StructuredQueryOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasSelect(): boolean;
getSelect(): com.google.firestore.v1.StructuredQuery.Projection;
getFromList(): java.util.List<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
getFrom(param0: number): com.google.firestore.v1.StructuredQuery.CollectionSelector;
getFromCount(): number;
hasWhere(): boolean;
getWhere(): com.google.firestore.v1.StructuredQuery.Filter;
getOrderByList(): java.util.List<com.google.firestore.v1.StructuredQuery.Order>;
getOrderBy(param0: number): com.google.firestore.v1.StructuredQuery.Order;
getOrderByCount(): number;
hasStartAt(): boolean;
getStartAt(): com.google.firestore.v1.Cursor;
hasEndAt(): boolean;
getEndAt(): com.google.firestore.v1.Cursor;
getOffset(): number;
hasLimit(): boolean;
getLimit(): com.google.protobuf.Int32Value;
});
public constructor();
public getWhere(): com.google.firestore.v1.StructuredQuery.Filter;
public getStartAt(): com.google.firestore.v1.Cursor;
public hasSelect(): boolean;
public getFromList(): java.util.List<com.google.firestore.v1.StructuredQuery.CollectionSelector>;
public getOffset(): number;
public getOrderBy(param0: number): com.google.firestore.v1.StructuredQuery.Order;
public hasWhere(): boolean;
public hasEndAt(): boolean;
public getOrderByCount(): number;
public hasLimit(): boolean;
public getLimit(): com.google.protobuf.Int32Value;
public getSelect(): com.google.firestore.v1.StructuredQuery.Projection;
public getEndAt(): com.google.firestore.v1.Cursor;
public getFromCount(): number;
public getOrderByList(): java.util.List<com.google.firestore.v1.StructuredQuery.Order>;
public hasStartAt(): boolean;
public getFrom(param0: number): com.google.firestore.v1.StructuredQuery.CollectionSelector;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Target extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Target,com.google.firestore.v1.Target.Builder> implements com.google.firestore.v1.TargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target>;
public static QUERY_FIELD_NUMBER: number;
public static DOCUMENTS_FIELD_NUMBER: number;
public static RESUME_TOKEN_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static TARGET_ID_FIELD_NUMBER: number;
public static ONCE_FIELD_NUMBER: number;
public static newBuilder(param0: com.google.firestore.v1.Target): com.google.firestore.v1.Target.Builder;
public static getDefaultInstance(): com.google.firestore.v1.Target;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target;
public getResumeTypeCase(): com.google.firestore.v1.Target.ResumeTypeCase;
public getTargetId(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Target>;
public getTargetTypeCase(): com.google.firestore.v1.Target.TargetTypeCase;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Target;
public getResumeToken(): com.google.protobuf.ByteString;
public static newBuilder(): com.google.firestore.v1.Target.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Target;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Target;
public getOnce(): boolean;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Target;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
}
export module Target {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Target,com.google.firestore.v1.Target.Builder> implements com.google.firestore.v1.TargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.Builder>;
public getTargetTypeCase(): com.google.firestore.v1.Target.TargetTypeCase;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.Target.Builder;
public getOnce(): boolean;
public clearQuery(): com.google.firestore.v1.Target.Builder;
public setQuery(param0: com.google.firestore.v1.Target.QueryTarget.Builder): com.google.firestore.v1.Target.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Target.Builder;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
public clearOnce(): com.google.firestore.v1.Target.Builder;
public clearTargetId(): com.google.firestore.v1.Target.Builder;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Target.Builder;
public mergeDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firestore.v1.Target.Builder;
public getTargetId(): number;
public setQuery(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firestore.v1.Target.Builder;
public getReadTime(): com.google.protobuf.Timestamp;
public setResumeToken(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target.Builder;
public clearTargetType(): com.google.firestore.v1.Target.Builder;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public clearReadTime(): com.google.firestore.v1.Target.Builder;
public clearDocuments(): com.google.firestore.v1.Target.Builder;
public setDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firestore.v1.Target.Builder;
public mergeQuery(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firestore.v1.Target.Builder;
public clearResumeToken(): com.google.firestore.v1.Target.Builder;
public setOnce(param0: boolean): com.google.firestore.v1.Target.Builder;
public getResumeToken(): com.google.protobuf.ByteString;
public getResumeTypeCase(): com.google.firestore.v1.Target.ResumeTypeCase;
public clearResumeType(): com.google.firestore.v1.Target.Builder;
public setTargetId(param0: number): com.google.firestore.v1.Target.Builder;
public setDocuments(param0: com.google.firestore.v1.Target.DocumentsTarget.Builder): com.google.firestore.v1.Target.Builder;
}
export class DocumentsTarget extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Target.DocumentsTarget,com.google.firestore.v1.Target.DocumentsTarget.Builder> implements com.google.firestore.v1.Target.DocumentsTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.DocumentsTarget>;
public static DOCUMENTS_FIELD_NUMBER: number;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Target.DocumentsTarget;
public static getDefaultInstance(): com.google.firestore.v1.Target.DocumentsTarget;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Target.DocumentsTarget;
public getDocumentsCount(): number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Target.DocumentsTarget>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.DocumentsTarget;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target.DocumentsTarget;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.DocumentsTarget;
public static newBuilder(): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public getDocumentsList(): java.util.List<string>;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.DocumentsTarget;
public getDocuments(param0: number): string;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Target.DocumentsTarget;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.DocumentsTarget;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Target.DocumentsTarget;
public static newBuilder(param0: com.google.firestore.v1.Target.DocumentsTarget): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.DocumentsTarget;
}
export module DocumentsTarget {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Target.DocumentsTarget,com.google.firestore.v1.Target.DocumentsTarget.Builder> implements com.google.firestore.v1.Target.DocumentsTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.DocumentsTarget.Builder>;
public addDocuments(param0: string): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public addDocumentsBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public getDocumentsCount(): number;
public getDocumentsList(): java.util.List<string>;
public clearDocuments(): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public setDocuments(param0: number, param1: string): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public addAllDocuments(param0: java.lang.Iterable<string>): com.google.firestore.v1.Target.DocumentsTarget.Builder;
public getDocuments(param0: number): string;
}
}
export class DocumentsTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.DocumentsTargetOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.Target$DocumentsTargetOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDocumentsList(): java.util.List<string>;
getDocumentsCount(): number;
getDocuments(param0: number): string;
getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
});
public constructor();
public getDocumentsList(): java.util.List<string>;
public getDocumentsBytes(param0: number): com.google.protobuf.ByteString;
public getDocumentsCount(): number;
public getDocuments(param0: number): string;
}
export class QueryTarget extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Target.QueryTarget,com.google.firestore.v1.Target.QueryTarget.Builder> implements com.google.firestore.v1.Target.QueryTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.QueryTarget>;
public static PARENT_FIELD_NUMBER: number;
public static STRUCTURED_QUERY_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target.QueryTarget;
public getQueryTypeCase(): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Target.QueryTarget;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.QueryTarget;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Target.QueryTarget>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static newBuilder(): com.google.firestore.v1.Target.QueryTarget.Builder;
public getParent(): string;
public getSerializedSize(): number;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.QueryTarget;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Target.QueryTarget;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Target.QueryTarget;
public static newBuilder(param0: com.google.firestore.v1.Target.QueryTarget): com.google.firestore.v1.Target.QueryTarget.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.QueryTarget;
public getParentBytes(): com.google.protobuf.ByteString;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.QueryTarget;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Target.QueryTarget;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Target.QueryTarget;
public static getDefaultInstance(): com.google.firestore.v1.Target.QueryTarget;
}
export module QueryTarget {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Target.QueryTarget,com.google.firestore.v1.Target.QueryTarget.Builder> implements com.google.firestore.v1.Target.QueryTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.QueryTarget.Builder>;
public setParentBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Target.QueryTarget.Builder;
public getParent(): string;
public getQueryTypeCase(): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public clearQueryType(): com.google.firestore.v1.Target.QueryTarget.Builder;
public getParentBytes(): com.google.protobuf.ByteString;
public clearParent(): com.google.firestore.v1.Target.QueryTarget.Builder;
public setParent(param0: string): com.google.firestore.v1.Target.QueryTarget.Builder;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public setStructuredQuery(param0: com.google.firestore.v1.StructuredQuery.Builder): com.google.firestore.v1.Target.QueryTarget.Builder;
public setStructuredQuery(param0: com.google.firestore.v1.StructuredQuery): com.google.firestore.v1.Target.QueryTarget.Builder;
public mergeStructuredQuery(param0: com.google.firestore.v1.StructuredQuery): com.google.firestore.v1.Target.QueryTarget.Builder;
public clearStructuredQuery(): com.google.firestore.v1.Target.QueryTarget.Builder;
}
export class QueryTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Target.QueryTarget.QueryTypeCase>;
public static STRUCTURED_QUERY: com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public static QUERYTYPE_NOT_SET: com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public static values(): native.Array<com.google.firestore.v1.Target.QueryTarget.QueryTypeCase>;
public static valueOf(param0: string): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
}
}
export class QueryTargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Target.QueryTargetOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.Target$QueryTargetOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParent(): string;
getParentBytes(): com.google.protobuf.ByteString;
getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
getQueryTypeCase(): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
});
public constructor();
public getQueryTypeCase(): com.google.firestore.v1.Target.QueryTarget.QueryTypeCase;
public getStructuredQuery(): com.google.firestore.v1.StructuredQuery;
public getParentBytes(): com.google.protobuf.ByteString;
public getParent(): string;
}
export class ResumeTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Target.ResumeTypeCase>;
public static RESUME_TOKEN: com.google.firestore.v1.Target.ResumeTypeCase;
public static READ_TIME: com.google.firestore.v1.Target.ResumeTypeCase;
public static RESUMETYPE_NOT_SET: com.google.firestore.v1.Target.ResumeTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.Target.ResumeTypeCase;
public static values(): native.Array<com.google.firestore.v1.Target.ResumeTypeCase>;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.Target.ResumeTypeCase;
public static valueOf(param0: string): com.google.firestore.v1.Target.ResumeTypeCase;
}
export class TargetTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Target.TargetTypeCase>;
public static QUERY: com.google.firestore.v1.Target.TargetTypeCase;
public static DOCUMENTS: com.google.firestore.v1.Target.TargetTypeCase;
public static TARGETTYPE_NOT_SET: com.google.firestore.v1.Target.TargetTypeCase;
public static valueOf(param0: string): com.google.firestore.v1.Target.TargetTypeCase;
public static valueOf(param0: number): com.google.firestore.v1.Target.TargetTypeCase;
public static forNumber(param0: number): com.google.firestore.v1.Target.TargetTypeCase;
public getNumber(): number;
public static values(): native.Array<com.google.firestore.v1.Target.TargetTypeCase>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class TargetChange extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.TargetChange,com.google.firestore.v1.TargetChange.Builder> implements com.google.firestore.v1.TargetChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TargetChange>;
public static TARGET_CHANGE_TYPE_FIELD_NUMBER: number;
public static TARGET_IDS_FIELD_NUMBER: number;
public static CAUSE_FIELD_NUMBER: number;
public static RESUME_TOKEN_FIELD_NUMBER: number;
public static READ_TIME_FIELD_NUMBER: number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.TargetChange>;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TargetChange;
public static getDefaultInstance(): com.google.firestore.v1.TargetChange;
public getCause(): com.google.rpc.Status;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.TargetChange;
public static newBuilder(): com.google.firestore.v1.TargetChange.Builder;
public getResumeToken(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TargetChange;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.TargetChange;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public hasCause(): boolean;
public hasReadTime(): boolean;
public getTargetChangeType(): com.google.firestore.v1.TargetChange.TargetChangeType;
public getSerializedSize(): number;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TargetChange;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TargetChange;
public getTargetIdsCount(): number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TargetChange;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.TargetChange;
public getTargetChangeTypeValue(): number;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.TargetChange;
public getTargetIds(param0: number): number;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public getReadTime(): com.google.protobuf.Timestamp;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TargetChange;
public static newBuilder(param0: com.google.firestore.v1.TargetChange): com.google.firestore.v1.TargetChange.Builder;
}
export module TargetChange {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.TargetChange,com.google.firestore.v1.TargetChange.Builder> implements com.google.firestore.v1.TargetChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TargetChange.Builder>;
public hasCause(): boolean;
public setCause(param0: com.google.rpc.Status.Builder): com.google.firestore.v1.TargetChange.Builder;
public clearTargetIds(): com.google.firestore.v1.TargetChange.Builder;
public setTargetChangeType(param0: com.google.firestore.v1.TargetChange.TargetChangeType): com.google.firestore.v1.TargetChange.Builder;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public getReadTime(): com.google.protobuf.Timestamp;
public getCause(): com.google.rpc.Status;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.TargetChange.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.TargetChange.Builder;
public setTargetIds(param0: number, param1: number): com.google.firestore.v1.TargetChange.Builder;
public setResumeToken(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TargetChange.Builder;
public addAllTargetIds(param0: java.lang.Iterable<any>): com.google.firestore.v1.TargetChange.Builder;
public getTargetIds(param0: number): number;
public setCause(param0: com.google.rpc.Status): com.google.firestore.v1.TargetChange.Builder;
public mergeCause(param0: com.google.rpc.Status): com.google.firestore.v1.TargetChange.Builder;
public clearReadTime(): com.google.firestore.v1.TargetChange.Builder;
public clearCause(): com.google.firestore.v1.TargetChange.Builder;
public clearResumeToken(): com.google.firestore.v1.TargetChange.Builder;
public setTargetChangeTypeValue(param0: number): com.google.firestore.v1.TargetChange.Builder;
public hasReadTime(): boolean;
public clearTargetChangeType(): com.google.firestore.v1.TargetChange.Builder;
public getResumeToken(): com.google.protobuf.ByteString;
public addTargetIds(param0: number): com.google.firestore.v1.TargetChange.Builder;
public getTargetChangeTypeValue(): number;
public getTargetChangeType(): com.google.firestore.v1.TargetChange.TargetChangeType;
public getTargetIdsCount(): number;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.TargetChange.Builder;
}
export class TargetChangeType extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.TargetChange.TargetChangeType>;
public static NO_CHANGE: com.google.firestore.v1.TargetChange.TargetChangeType;
public static ADD: com.google.firestore.v1.TargetChange.TargetChangeType;
public static REMOVE: com.google.firestore.v1.TargetChange.TargetChangeType;
public static CURRENT: com.google.firestore.v1.TargetChange.TargetChangeType;
public static RESET: com.google.firestore.v1.TargetChange.TargetChangeType;
public static UNRECOGNIZED: com.google.firestore.v1.TargetChange.TargetChangeType;
public static NO_CHANGE_VALUE: number;
public static ADD_VALUE: number;
public static REMOVE_VALUE: number;
public static CURRENT_VALUE: number;
public static RESET_VALUE: number;
public static valueOf(param0: string): com.google.firestore.v1.TargetChange.TargetChangeType;
public static values(): native.Array<com.google.firestore.v1.TargetChange.TargetChangeType>;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.TargetChange.TargetChangeType;
public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.firestore.v1.TargetChange.TargetChangeType>;
public static valueOf(param0: number): com.google.firestore.v1.TargetChange.TargetChangeType;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class TargetChangeOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TargetChangeOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.TargetChangeOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getTargetChangeTypeValue(): number;
getTargetChangeType(): com.google.firestore.v1.TargetChange.TargetChangeType;
getTargetIdsList(): java.util.List<java.lang.Integer>;
getTargetIdsCount(): number;
getTargetIds(param0: number): number;
hasCause(): boolean;
getCause(): com.google.rpc.Status;
getResumeToken(): com.google.protobuf.ByteString;
hasReadTime(): boolean;
getReadTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getTargetChangeTypeValue(): number;
public getResumeToken(): com.google.protobuf.ByteString;
public getTargetChangeType(): com.google.firestore.v1.TargetChange.TargetChangeType;
public getTargetIds(param0: number): number;
public getCause(): com.google.rpc.Status;
public getTargetIdsList(): java.util.List<java.lang.Integer>;
public getReadTime(): com.google.protobuf.Timestamp;
public getTargetIdsCount(): number;
public hasCause(): boolean;
public hasReadTime(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class TargetOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TargetOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.TargetOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getQuery(): com.google.firestore.v1.Target.QueryTarget;
getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
getResumeToken(): com.google.protobuf.ByteString;
getReadTime(): com.google.protobuf.Timestamp;
getTargetId(): number;
getOnce(): boolean;
getTargetTypeCase(): com.google.firestore.v1.Target.TargetTypeCase;
getResumeTypeCase(): com.google.firestore.v1.Target.ResumeTypeCase;
});
public constructor();
public getResumeToken(): com.google.protobuf.ByteString;
public getOnce(): boolean;
public getResumeTypeCase(): com.google.firestore.v1.Target.ResumeTypeCase;
public getTargetId(): number;
public getTargetTypeCase(): com.google.firestore.v1.Target.TargetTypeCase;
public getQuery(): com.google.firestore.v1.Target.QueryTarget;
public getReadTime(): com.google.protobuf.Timestamp;
public getDocuments(): com.google.firestore.v1.Target.DocumentsTarget;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class TransactionOptions extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.TransactionOptions,com.google.firestore.v1.TransactionOptions.Builder> implements com.google.firestore.v1.TransactionOptionsOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions>;
public static READ_ONLY_FIELD_NUMBER: number;
public static READ_WRITE_FIELD_NUMBER: number;
public getReadWrite(): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TransactionOptions;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.TransactionOptions>;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.TransactionOptions;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.TransactionOptions;
public static newBuilder(): com.google.firestore.v1.TransactionOptions.Builder;
public getModeCase(): com.google.firestore.v1.TransactionOptions.ModeCase;
public static newBuilder(param0: com.google.firestore.v1.TransactionOptions): com.google.firestore.v1.TransactionOptions.Builder;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions;
public getReadOnly(): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static getDefaultInstance(): com.google.firestore.v1.TransactionOptions;
}
export module TransactionOptions {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.TransactionOptions,com.google.firestore.v1.TransactionOptions.Builder> implements com.google.firestore.v1.TransactionOptionsOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.Builder>;
public clearMode(): com.google.firestore.v1.TransactionOptions.Builder;
public mergeReadOnly(param0: com.google.firestore.v1.TransactionOptions.ReadOnly): com.google.firestore.v1.TransactionOptions.Builder;
public getReadOnly(): com.google.firestore.v1.TransactionOptions.ReadOnly;
public getModeCase(): com.google.firestore.v1.TransactionOptions.ModeCase;
public clearReadWrite(): com.google.firestore.v1.TransactionOptions.Builder;
public setReadOnly(param0: com.google.firestore.v1.TransactionOptions.ReadOnly): com.google.firestore.v1.TransactionOptions.Builder;
public clearReadOnly(): com.google.firestore.v1.TransactionOptions.Builder;
public setReadWrite(param0: com.google.firestore.v1.TransactionOptions.ReadWrite.Builder): com.google.firestore.v1.TransactionOptions.Builder;
public mergeReadWrite(param0: com.google.firestore.v1.TransactionOptions.ReadWrite): com.google.firestore.v1.TransactionOptions.Builder;
public getReadWrite(): com.google.firestore.v1.TransactionOptions.ReadWrite;
public setReadOnly(param0: com.google.firestore.v1.TransactionOptions.ReadOnly.Builder): com.google.firestore.v1.TransactionOptions.Builder;
public setReadWrite(param0: com.google.firestore.v1.TransactionOptions.ReadWrite): com.google.firestore.v1.TransactionOptions.Builder;
}
export class ModeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ModeCase>;
public static READ_ONLY: com.google.firestore.v1.TransactionOptions.ModeCase;
public static READ_WRITE: com.google.firestore.v1.TransactionOptions.ModeCase;
public static MODE_NOT_SET: com.google.firestore.v1.TransactionOptions.ModeCase;
public static valueOf(param0: number): com.google.firestore.v1.TransactionOptions.ModeCase;
public static forNumber(param0: number): com.google.firestore.v1.TransactionOptions.ModeCase;
public getNumber(): number;
public static valueOf(param0: string): com.google.firestore.v1.TransactionOptions.ModeCase;
public static values(): native.Array<com.google.firestore.v1.TransactionOptions.ModeCase>;
}
export class ReadOnly extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.TransactionOptions.ReadOnly,com.google.firestore.v1.TransactionOptions.ReadOnly.Builder> implements com.google.firestore.v1.TransactionOptions.ReadOnlyOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadOnly>;
public static READ_TIME_FIELD_NUMBER: number;
public static newBuilder(param0: com.google.firestore.v1.TransactionOptions.ReadOnly): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadOnly;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.TransactionOptions.ReadOnly;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static newBuilder(): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public getConsistencySelectorCase(): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public getSerializedSize(): number;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.TransactionOptions.ReadOnly>;
public getReadTime(): com.google.protobuf.Timestamp;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static getDefaultInstance(): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadOnly;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TransactionOptions.ReadOnly;
}
export module ReadOnly {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.TransactionOptions.ReadOnly,com.google.firestore.v1.TransactionOptions.ReadOnly.Builder> implements com.google.firestore.v1.TransactionOptions.ReadOnlyOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadOnly.Builder>;
public getReadTime(): com.google.protobuf.Timestamp;
public mergeReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public getConsistencySelectorCase(): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public clearConsistencySelector(): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public clearReadTime(): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
public setReadTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.TransactionOptions.ReadOnly.Builder;
}
export class ConsistencySelectorCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase>;
public static READ_TIME: com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public static CONSISTENCYSELECTOR_NOT_SET: com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public static values(): native.Array<com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase>;
public static valueOf(param0: string): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public static forNumber(param0: number): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
public getNumber(): number;
public static valueOf(param0: number): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
}
}
export class ReadOnlyOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadOnlyOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.TransactionOptions$ReadOnlyOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getReadTime(): com.google.protobuf.Timestamp;
getConsistencySelectorCase(): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
});
public constructor();
public getReadTime(): com.google.protobuf.Timestamp;
public getConsistencySelectorCase(): com.google.firestore.v1.TransactionOptions.ReadOnly.ConsistencySelectorCase;
}
export class ReadWrite extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.TransactionOptions.ReadWrite,com.google.firestore.v1.TransactionOptions.ReadWrite.Builder> implements com.google.firestore.v1.TransactionOptions.ReadWriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadWrite>;
public static RETRY_TRANSACTION_FIELD_NUMBER: number;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static getDefaultInstance(): com.google.firestore.v1.TransactionOptions.ReadWrite;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static newBuilder(): com.google.firestore.v1.TransactionOptions.ReadWrite.Builder;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.TransactionOptions.ReadWrite>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions.ReadWrite;
public getSerializedSize(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadWrite;
public getRetryTransaction(): com.google.protobuf.ByteString;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static newBuilder(param0: com.google.firestore.v1.TransactionOptions.ReadWrite): com.google.firestore.v1.TransactionOptions.ReadWrite.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.TransactionOptions.ReadWrite;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.TransactionOptions.ReadWrite;
}
export module ReadWrite {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.TransactionOptions.ReadWrite,com.google.firestore.v1.TransactionOptions.ReadWrite.Builder> implements com.google.firestore.v1.TransactionOptions.ReadWriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadWrite.Builder>;
public clearRetryTransaction(): com.google.firestore.v1.TransactionOptions.ReadWrite.Builder;
public setRetryTransaction(param0: com.google.protobuf.ByteString): com.google.firestore.v1.TransactionOptions.ReadWrite.Builder;
public getRetryTransaction(): com.google.protobuf.ByteString;
}
}
export class ReadWriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptions.ReadWriteOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.TransactionOptions$ReadWriteOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getRetryTransaction(): com.google.protobuf.ByteString;
});
public constructor();
public getRetryTransaction(): com.google.protobuf.ByteString;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class TransactionOptionsOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.TransactionOptionsOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.TransactionOptionsOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getReadOnly(): com.google.firestore.v1.TransactionOptions.ReadOnly;
getReadWrite(): com.google.firestore.v1.TransactionOptions.ReadWrite;
getModeCase(): com.google.firestore.v1.TransactionOptions.ModeCase;
});
public constructor();
public getReadWrite(): com.google.firestore.v1.TransactionOptions.ReadWrite;
public getModeCase(): com.google.firestore.v1.TransactionOptions.ModeCase;
public getReadOnly(): com.google.firestore.v1.TransactionOptions.ReadOnly;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class UpdateDocumentRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.UpdateDocumentRequest,com.google.firestore.v1.UpdateDocumentRequest.Builder> implements com.google.firestore.v1.UpdateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.UpdateDocumentRequest>;
public static DOCUMENT_FIELD_NUMBER: number;
public static UPDATE_MASK_FIELD_NUMBER: number;
public static MASK_FIELD_NUMBER: number;
public static CURRENT_DOCUMENT_FIELD_NUMBER: number;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.UpdateDocumentRequest;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.UpdateDocumentRequest;
public static getDefaultInstance(): com.google.firestore.v1.UpdateDocumentRequest;
public hasDocument(): boolean;
public hasCurrentDocument(): boolean;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.UpdateDocumentRequest;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public hasUpdateMask(): boolean;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.UpdateDocumentRequest;
public getDocument(): com.google.firestore.v1.Document;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.UpdateDocumentRequest;
public getMask(): com.google.firestore.v1.DocumentMask;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.UpdateDocumentRequest;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.UpdateDocumentRequest;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.UpdateDocumentRequest;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.UpdateDocumentRequest;
public getSerializedSize(): number;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.UpdateDocumentRequest;
public static newBuilder(): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.UpdateDocumentRequest>;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public hasMask(): boolean;
public static newBuilder(param0: com.google.firestore.v1.UpdateDocumentRequest): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
}
export module UpdateDocumentRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.UpdateDocumentRequest,com.google.firestore.v1.UpdateDocumentRequest.Builder> implements com.google.firestore.v1.UpdateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.UpdateDocumentRequest.Builder>;
public getDocument(): com.google.firestore.v1.Document;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public setUpdateMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public getMask(): com.google.firestore.v1.DocumentMask;
public setUpdateMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public mergeMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public clearDocument(): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public hasMask(): boolean;
public setMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public hasCurrentDocument(): boolean;
public clearUpdateMask(): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public mergeUpdateMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public setMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public setDocument(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public setDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public clearMask(): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public mergeDocument(param0: com.google.firestore.v1.Document): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public hasUpdateMask(): boolean;
public mergeCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition.Builder): com.google.firestore.v1.UpdateDocumentRequest.Builder;
public hasDocument(): boolean;
public clearCurrentDocument(): com.google.firestore.v1.UpdateDocumentRequest.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class UpdateDocumentRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.UpdateDocumentRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.UpdateDocumentRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasDocument(): boolean;
getDocument(): com.google.firestore.v1.Document;
hasUpdateMask(): boolean;
getUpdateMask(): com.google.firestore.v1.DocumentMask;
hasMask(): boolean;
getMask(): com.google.firestore.v1.DocumentMask;
hasCurrentDocument(): boolean;
getCurrentDocument(): com.google.firestore.v1.Precondition;
});
public constructor();
public getMask(): com.google.firestore.v1.DocumentMask;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public hasMask(): boolean;
public hasUpdateMask(): boolean;
public getDocument(): com.google.firestore.v1.Document;
public hasDocument(): boolean;
public hasCurrentDocument(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Value extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Value,com.google.firestore.v1.Value.Builder> implements com.google.firestore.v1.ValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Value>;
public static NULL_VALUE_FIELD_NUMBER: number;
public static BOOLEAN_VALUE_FIELD_NUMBER: number;
public static INTEGER_VALUE_FIELD_NUMBER: number;
public static DOUBLE_VALUE_FIELD_NUMBER: number;
public static TIMESTAMP_VALUE_FIELD_NUMBER: number;
public static STRING_VALUE_FIELD_NUMBER: number;
public static BYTES_VALUE_FIELD_NUMBER: number;
public static REFERENCE_VALUE_FIELD_NUMBER: number;
public static GEO_POINT_VALUE_FIELD_NUMBER: number;
public static ARRAY_VALUE_FIELD_NUMBER: number;
public static MAP_VALUE_FIELD_NUMBER: number;
public getNullValue(): com.google.protobuf.NullValue;
public getDoubleValue(): number;
public getReferenceValue(): string;
public getMapValue(): com.google.firestore.v1.MapValue;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Value;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Value;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Value;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Value;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Value;
public static getDefaultInstance(): com.google.firestore.v1.Value;
public getGeoPointValue(): com.google.type.LatLng;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Value;
public getValueTypeCase(): com.google.firestore.v1.Value.ValueTypeCase;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Value;
public getTimestampValue(): com.google.protobuf.Timestamp;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Value>;
public getStringValueBytes(): com.google.protobuf.ByteString;
public getIntegerValue(): number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Value;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Value;
public getBooleanValue(): boolean;
public static newBuilder(): com.google.firestore.v1.Value.Builder;
public getReferenceValueBytes(): com.google.protobuf.ByteString;
public static newBuilder(param0: com.google.firestore.v1.Value): com.google.firestore.v1.Value.Builder;
public getNullValueValue(): number;
public getSerializedSize(): number;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Value;
public getArrayValue(): com.google.firestore.v1.ArrayValue;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public getBytesValue(): com.google.protobuf.ByteString;
public getStringValue(): string;
}
export module Value {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Value,com.google.firestore.v1.Value.Builder> implements com.google.firestore.v1.ValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Value.Builder>;
public setDoubleValue(param0: number): com.google.firestore.v1.Value.Builder;
public clearValueType(): com.google.firestore.v1.Value.Builder;
public getStringValueBytes(): com.google.protobuf.ByteString;
public getDoubleValue(): number;
public clearNullValue(): com.google.firestore.v1.Value.Builder;
public clearBooleanValue(): com.google.firestore.v1.Value.Builder;
public getReferenceValueBytes(): com.google.protobuf.ByteString;
public clearIntegerValue(): com.google.firestore.v1.Value.Builder;
public getTimestampValue(): com.google.protobuf.Timestamp;
public clearBytesValue(): com.google.firestore.v1.Value.Builder;
public setArrayValue(param0: com.google.firestore.v1.ArrayValue.Builder): com.google.firestore.v1.Value.Builder;
public getMapValue(): com.google.firestore.v1.MapValue;
public getGeoPointValue(): com.google.type.LatLng;
public getIntegerValue(): number;
public getReferenceValue(): string;
public setGeoPointValue(param0: com.google.type.LatLng.Builder): com.google.firestore.v1.Value.Builder;
public mergeArrayValue(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.Value.Builder;
public setArrayValue(param0: com.google.firestore.v1.ArrayValue): com.google.firestore.v1.Value.Builder;
public getNullValueValue(): number;
public setTimestampValue(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Value.Builder;
public clearReferenceValue(): com.google.firestore.v1.Value.Builder;
public clearStringValue(): com.google.firestore.v1.Value.Builder;
public getStringValue(): string;
public mergeMapValue(param0: com.google.firestore.v1.MapValue): com.google.firestore.v1.Value.Builder;
public getArrayValue(): com.google.firestore.v1.ArrayValue;
public setGeoPointValue(param0: com.google.type.LatLng): com.google.firestore.v1.Value.Builder;
public getBytesValue(): com.google.protobuf.ByteString;
public mergeGeoPointValue(param0: com.google.type.LatLng): com.google.firestore.v1.Value.Builder;
public setNullValue(param0: com.google.protobuf.NullValue): com.google.firestore.v1.Value.Builder;
public setStringValue(param0: string): com.google.firestore.v1.Value.Builder;
public clearDoubleValue(): com.google.firestore.v1.Value.Builder;
public setNullValueValue(param0: number): com.google.firestore.v1.Value.Builder;
public clearMapValue(): com.google.firestore.v1.Value.Builder;
public getBooleanValue(): boolean;
public setStringValueBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Value.Builder;
public setBytesValue(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Value.Builder;
public getValueTypeCase(): com.google.firestore.v1.Value.ValueTypeCase;
public getNullValue(): com.google.protobuf.NullValue;
public setReferenceValueBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Value.Builder;
public setIntegerValue(param0: number): com.google.firestore.v1.Value.Builder;
public clearGeoPointValue(): com.google.firestore.v1.Value.Builder;
public clearArrayValue(): com.google.firestore.v1.Value.Builder;
public mergeTimestampValue(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.Value.Builder;
public setMapValue(param0: com.google.firestore.v1.MapValue.Builder): com.google.firestore.v1.Value.Builder;
public clearTimestampValue(): com.google.firestore.v1.Value.Builder;
public setReferenceValue(param0: string): com.google.firestore.v1.Value.Builder;
public setMapValue(param0: com.google.firestore.v1.MapValue): com.google.firestore.v1.Value.Builder;
public setBooleanValue(param0: boolean): com.google.firestore.v1.Value.Builder;
public setTimestampValue(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.Value.Builder;
}
export class ValueTypeCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Value.ValueTypeCase>;
public static NULL_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static BOOLEAN_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static INTEGER_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static DOUBLE_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static TIMESTAMP_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static STRING_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static BYTES_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static REFERENCE_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static GEO_POINT_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static ARRAY_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static MAP_VALUE: com.google.firestore.v1.Value.ValueTypeCase;
public static VALUETYPE_NOT_SET: com.google.firestore.v1.Value.ValueTypeCase;
public static values(): native.Array<com.google.firestore.v1.Value.ValueTypeCase>;
public static valueOf(param0: number): com.google.firestore.v1.Value.ValueTypeCase;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.Value.ValueTypeCase;
public static valueOf(param0: string): com.google.firestore.v1.Value.ValueTypeCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class ValueOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.ValueOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.ValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getNullValueValue(): number;
getNullValue(): com.google.protobuf.NullValue;
getBooleanValue(): boolean;
getIntegerValue(): number;
getDoubleValue(): number;
getTimestampValue(): com.google.protobuf.Timestamp;
getStringValue(): string;
getStringValueBytes(): com.google.protobuf.ByteString;
getBytesValue(): com.google.protobuf.ByteString;
getReferenceValue(): string;
getReferenceValueBytes(): com.google.protobuf.ByteString;
getGeoPointValue(): com.google.type.LatLng;
getArrayValue(): com.google.firestore.v1.ArrayValue;
getMapValue(): com.google.firestore.v1.MapValue;
getValueTypeCase(): com.google.firestore.v1.Value.ValueTypeCase;
});
public constructor();
public getNullValue(): com.google.protobuf.NullValue;
public getIntegerValue(): number;
public getDoubleValue(): number;
public getReferenceValue(): string;
public getMapValue(): com.google.firestore.v1.MapValue;
public getBooleanValue(): boolean;
public getReferenceValueBytes(): com.google.protobuf.ByteString;
public getNullValueValue(): number;
public getGeoPointValue(): com.google.type.LatLng;
public getValueTypeCase(): com.google.firestore.v1.Value.ValueTypeCase;
public getArrayValue(): com.google.firestore.v1.ArrayValue;
public getTimestampValue(): com.google.protobuf.Timestamp;
public getStringValueBytes(): com.google.protobuf.ByteString;
public getBytesValue(): com.google.protobuf.ByteString;
public getStringValue(): string;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class Write extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.Write,com.google.firestore.v1.Write.Builder> implements com.google.firestore.v1.WriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Write>;
public static UPDATE_FIELD_NUMBER: number;
public static DELETE_FIELD_NUMBER: number;
public static TRANSFORM_FIELD_NUMBER: number;
public static UPDATE_MASK_FIELD_NUMBER: number;
public static CURRENT_DOCUMENT_FIELD_NUMBER: number;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Write;
public hasCurrentDocument(): boolean;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public getUpdate(): com.google.firestore.v1.Document;
public getOperationCase(): com.google.firestore.v1.Write.OperationCase;
public hasUpdateMask(): boolean;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public static getDefaultInstance(): com.google.firestore.v1.Write;
public static newBuilder(): com.google.firestore.v1.Write.Builder;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.Write;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.Write;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Write;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.Write;
public getDeleteBytes(): com.google.protobuf.ByteString;
public getDelete(): string;
public getSerializedSize(): number;
public getTransform(): com.google.firestore.v1.DocumentTransform;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Write;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.Write>;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.Write;
public static newBuilder(param0: com.google.firestore.v1.Write): com.google.firestore.v1.Write.Builder;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Write;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Write;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.Write;
}
export module Write {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.Write,com.google.firestore.v1.Write.Builder> implements com.google.firestore.v1.WriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.Write.Builder>;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition.Builder): com.google.firestore.v1.Write.Builder;
public setUpdate(param0: com.google.firestore.v1.Document.Builder): com.google.firestore.v1.Write.Builder;
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public mergeUpdate(param0: com.google.firestore.v1.Document): com.google.firestore.v1.Write.Builder;
public setDelete(param0: string): com.google.firestore.v1.Write.Builder;
public setTransform(param0: com.google.firestore.v1.DocumentTransform): com.google.firestore.v1.Write.Builder;
public setUpdateMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.Write.Builder;
public clearOperation(): com.google.firestore.v1.Write.Builder;
public setCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.Write.Builder;
public hasCurrentDocument(): boolean;
public getOperationCase(): com.google.firestore.v1.Write.OperationCase;
public getDelete(): string;
public clearUpdateMask(): com.google.firestore.v1.Write.Builder;
public clearUpdate(): com.google.firestore.v1.Write.Builder;
public hasUpdateMask(): boolean;
public getTransform(): com.google.firestore.v1.DocumentTransform;
public mergeCurrentDocument(param0: com.google.firestore.v1.Precondition): com.google.firestore.v1.Write.Builder;
public clearCurrentDocument(): com.google.firestore.v1.Write.Builder;
public setUpdateMask(param0: com.google.firestore.v1.DocumentMask.Builder): com.google.firestore.v1.Write.Builder;
public clearDelete(): com.google.firestore.v1.Write.Builder;
public getUpdate(): com.google.firestore.v1.Document;
public setDeleteBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.Write.Builder;
public setTransform(param0: com.google.firestore.v1.DocumentTransform.Builder): com.google.firestore.v1.Write.Builder;
public mergeTransform(param0: com.google.firestore.v1.DocumentTransform): com.google.firestore.v1.Write.Builder;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public clearTransform(): com.google.firestore.v1.Write.Builder;
public setUpdate(param0: com.google.firestore.v1.Document): com.google.firestore.v1.Write.Builder;
public getDeleteBytes(): com.google.protobuf.ByteString;
public mergeUpdateMask(param0: com.google.firestore.v1.DocumentMask): com.google.firestore.v1.Write.Builder;
}
export class OperationCase extends com.google.protobuf.Internal.EnumLite {
public static class: java.lang.Class<com.google.firestore.v1.Write.OperationCase>;
public static UPDATE: com.google.firestore.v1.Write.OperationCase;
public static DELETE: com.google.firestore.v1.Write.OperationCase;
public static TRANSFORM: com.google.firestore.v1.Write.OperationCase;
public static OPERATION_NOT_SET: com.google.firestore.v1.Write.OperationCase;
public static values(): native.Array<com.google.firestore.v1.Write.OperationCase>;
public static valueOf(param0: string): com.google.firestore.v1.Write.OperationCase;
public static valueOf(param0: number): com.google.firestore.v1.Write.OperationCase;
public getNumber(): number;
public static forNumber(param0: number): com.google.firestore.v1.Write.OperationCase;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.WriteOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getUpdate(): com.google.firestore.v1.Document;
getDelete(): string;
getDeleteBytes(): com.google.protobuf.ByteString;
getTransform(): com.google.firestore.v1.DocumentTransform;
hasUpdateMask(): boolean;
getUpdateMask(): com.google.firestore.v1.DocumentMask;
hasCurrentDocument(): boolean;
getCurrentDocument(): com.google.firestore.v1.Precondition;
getOperationCase(): com.google.firestore.v1.Write.OperationCase;
});
public constructor();
public getCurrentDocument(): com.google.firestore.v1.Precondition;
public getUpdateMask(): com.google.firestore.v1.DocumentMask;
public getUpdate(): com.google.firestore.v1.Document;
public getDeleteBytes(): com.google.protobuf.ByteString;
public getOperationCase(): com.google.firestore.v1.Write.OperationCase;
public getDelete(): string;
public hasUpdateMask(): boolean;
public getTransform(): com.google.firestore.v1.DocumentTransform;
public hasCurrentDocument(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteProto {
public static class: java.lang.Class<com.google.firestore.v1.WriteProto>;
public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteRequest extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.WriteRequest,com.google.firestore.v1.WriteRequest.Builder> implements com.google.firestore.v1.WriteRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteRequest>;
public static DATABASE_FIELD_NUMBER: number;
public static STREAM_ID_FIELD_NUMBER: number;
public static WRITES_FIELD_NUMBER: number;
public static STREAM_TOKEN_FIELD_NUMBER: number;
public static LABELS_FIELD_NUMBER: number;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteRequest;
public getLabelsOrDefault(param0: string, param1: string): string;
public getLabelsMap(): java.util.Map<string,string>;
public getLabels(): java.util.Map<string,string>;
public getDatabase(): string;
public getWritesOrBuilderList(): java.util.List<any>;
public getWritesCount(): number;
public getLabelsOrThrow(param0: string): string;
public getLabelsCount(): number;
public containsLabels(param0: string): boolean;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getWritesOrBuilder(param0: number): com.google.firestore.v1.WriteOrBuilder;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteRequest;
public getStreamToken(): com.google.protobuf.ByteString;
public getWrites(param0: number): com.google.firestore.v1.Write;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.WriteRequest;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.WriteRequest;
public static newBuilder(param0: com.google.firestore.v1.WriteRequest): com.google.firestore.v1.WriteRequest.Builder;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteRequest;
public getSerializedSize(): number;
public static getDefaultInstance(): com.google.firestore.v1.WriteRequest;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public getStreamId(): string;
public static newBuilder(): com.google.firestore.v1.WriteRequest.Builder;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteRequest;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteRequest;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteRequest;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteRequest;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.WriteRequest>;
}
export module WriteRequest {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.WriteRequest,com.google.firestore.v1.WriteRequest.Builder> implements com.google.firestore.v1.WriteRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteRequest.Builder>;
public setDatabase(param0: string): com.google.firestore.v1.WriteRequest.Builder;
public getWritesCount(): number;
public setWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firestore.v1.WriteRequest.Builder;
public clearWrites(): com.google.firestore.v1.WriteRequest.Builder;
public getWrites(param0: number): com.google.firestore.v1.Write;
public removeWrites(param0: number): com.google.firestore.v1.WriteRequest.Builder;
public getStreamId(): string;
public addAllWrites(param0: java.lang.Iterable<any>): com.google.firestore.v1.WriteRequest.Builder;
public putAllLabels(param0: java.util.Map<string,string>): com.google.firestore.v1.WriteRequest.Builder;
public clearLabels(): com.google.firestore.v1.WriteRequest.Builder;
public clearStreamId(): com.google.firestore.v1.WriteRequest.Builder;
public setStreamIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteRequest.Builder;
public addWrites(param0: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.WriteRequest.Builder;
public getLabelsOrThrow(param0: string): string;
public setStreamToken(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteRequest.Builder;
public addWrites(param0: com.google.firestore.v1.Write): com.google.firestore.v1.WriteRequest.Builder;
public putLabels(param0: string, param1: string): com.google.firestore.v1.WriteRequest.Builder;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getLabelsOrDefault(param0: string, param1: string): string;
public getStreamToken(): com.google.protobuf.ByteString;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public getDatabase(): string;
public getLabelsCount(): number;
public clearStreamToken(): com.google.firestore.v1.WriteRequest.Builder;
public getLabels(): java.util.Map<string,string>;
public addWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.WriteRequest.Builder;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public setDatabaseBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteRequest.Builder;
public setWrites(param0: number, param1: com.google.firestore.v1.Write.Builder): com.google.firestore.v1.WriteRequest.Builder;
public clearDatabase(): com.google.firestore.v1.WriteRequest.Builder;
public addWrites(param0: number, param1: com.google.firestore.v1.Write): com.google.firestore.v1.WriteRequest.Builder;
public getLabelsMap(): java.util.Map<string,string>;
public removeLabels(param0: string): com.google.firestore.v1.WriteRequest.Builder;
public containsLabels(param0: string): boolean;
public setStreamId(param0: string): com.google.firestore.v1.WriteRequest.Builder;
}
export class LabelsDefaultEntryHolder {
public static class: java.lang.Class<com.google.firestore.v1.WriteRequest.LabelsDefaultEntryHolder>;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteRequestOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteRequestOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.WriteRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getDatabase(): string;
getDatabaseBytes(): com.google.protobuf.ByteString;
getStreamId(): string;
getStreamIdBytes(): com.google.protobuf.ByteString;
getWritesList(): java.util.List<com.google.firestore.v1.Write>;
getWrites(param0: number): com.google.firestore.v1.Write;
getWritesCount(): number;
getStreamToken(): com.google.protobuf.ByteString;
getLabelsCount(): number;
containsLabels(param0: string): boolean;
getLabels(): java.util.Map<string,string>;
getLabelsMap(): java.util.Map<string,string>;
getLabelsOrDefault(param0: string, param1: string): string;
getLabelsOrThrow(param0: string): string;
});
public constructor();
public getLabelsOrDefault(param0: string, param1: string): string;
public getLabelsMap(): java.util.Map<string,string>;
public getDatabaseBytes(): com.google.protobuf.ByteString;
public getStreamId(): string;
public getLabels(): java.util.Map<string,string>;
public getDatabase(): string;
public getWritesCount(): number;
public getLabelsOrThrow(param0: string): string;
public getWritesList(): java.util.List<com.google.firestore.v1.Write>;
public getLabelsCount(): number;
public containsLabels(param0: string): boolean;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public getStreamToken(): com.google.protobuf.ByteString;
public getWrites(param0: number): com.google.firestore.v1.Write;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteResponse extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.WriteResponse,com.google.firestore.v1.WriteResponse.Builder> implements com.google.firestore.v1.WriteResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResponse>;
public static STREAM_ID_FIELD_NUMBER: number;
public static STREAM_TOKEN_FIELD_NUMBER: number;
public static WRITE_RESULTS_FIELD_NUMBER: number;
public static COMMIT_TIME_FIELD_NUMBER: number;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResponse;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public getWriteResultsCount(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResponse;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResponse;
public hasCommitTime(): boolean;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getStreamToken(): com.google.protobuf.ByteString;
public static newBuilder(param0: com.google.firestore.v1.WriteResponse): com.google.firestore.v1.WriteResponse.Builder;
public static newBuilder(): com.google.firestore.v1.WriteResponse.Builder;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.WriteResponse;
public getSerializedSize(): number;
public getStreamId(): string;
public getWriteResultsOrBuilderList(): java.util.List<any>;
public static getDefaultInstance(): com.google.firestore.v1.WriteResponse;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.WriteResponse>;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteResponse;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResponse;
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public getWriteResultsOrBuilder(param0: number): com.google.firestore.v1.WriteResultOrBuilder;
public getCommitTime(): com.google.protobuf.Timestamp;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteResponse;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResponse;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteResponse;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.WriteResponse;
}
export module WriteResponse {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.WriteResponse,com.google.firestore.v1.WriteResponse.Builder> implements com.google.firestore.v1.WriteResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResponse.Builder>;
public addWriteResults(param0: com.google.firestore.v1.WriteResult): com.google.firestore.v1.WriteResponse.Builder;
public getStreamId(): string;
public mergeCommitTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.WriteResponse.Builder;
public setCommitTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.WriteResponse.Builder;
public clearWriteResults(): com.google.firestore.v1.WriteResponse.Builder;
public setWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult): com.google.firestore.v1.WriteResponse.Builder;
public setStreamIdBytes(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteResponse.Builder;
public setStreamToken(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteResponse.Builder;
public addWriteResults(param0: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.WriteResponse.Builder;
public removeWriteResults(param0: number): com.google.firestore.v1.WriteResponse.Builder;
public hasCommitTime(): boolean;
public clearCommitTime(): com.google.firestore.v1.WriteResponse.Builder;
public setCommitTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.WriteResponse.Builder;
public setWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.WriteResponse.Builder;
public getStreamToken(): com.google.protobuf.ByteString;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public addWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult): com.google.firestore.v1.WriteResponse.Builder;
public getCommitTime(): com.google.protobuf.Timestamp;
public setStreamId(param0: string): com.google.firestore.v1.WriteResponse.Builder;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public addWriteResults(param0: number, param1: com.google.firestore.v1.WriteResult.Builder): com.google.firestore.v1.WriteResponse.Builder;
public clearStreamToken(): com.google.firestore.v1.WriteResponse.Builder;
public getWriteResultsCount(): number;
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public clearStreamId(): com.google.firestore.v1.WriteResponse.Builder;
public addAllWriteResults(param0: java.lang.Iterable<any>): com.google.firestore.v1.WriteResponse.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteResponseOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResponseOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.WriteResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getStreamId(): string;
getStreamIdBytes(): com.google.protobuf.ByteString;
getStreamToken(): com.google.protobuf.ByteString;
getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
getWriteResultsCount(): number;
hasCommitTime(): boolean;
getCommitTime(): com.google.protobuf.Timestamp;
});
public constructor();
public getWriteResultsList(): java.util.List<com.google.firestore.v1.WriteResult>;
public getWriteResults(param0: number): com.google.firestore.v1.WriteResult;
public getWriteResultsCount(): number;
public hasCommitTime(): boolean;
public getCommitTime(): com.google.protobuf.Timestamp;
public getStreamIdBytes(): com.google.protobuf.ByteString;
public getStreamId(): string;
public getStreamToken(): com.google.protobuf.ByteString;
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteResult extends com.google.protobuf.GeneratedMessageLite<com.google.firestore.v1.WriteResult,com.google.firestore.v1.WriteResult.Builder> implements com.google.firestore.v1.WriteResultOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResult>;
public static UPDATE_TIME_FIELD_NUMBER: number;
public static TRANSFORM_RESULTS_FIELD_NUMBER: number;
public static parser(): com.google.protobuf.Parser<com.google.firestore.v1.WriteResult>;
public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firestore.v1.WriteResult;
public static getDefaultInstance(): com.google.firestore.v1.WriteResult;
public static newBuilder(param0: com.google.firestore.v1.WriteResult): com.google.firestore.v1.WriteResult.Builder;
public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResult;
public getSerializedSize(): number;
public getTransformResultsOrBuilder(param0: number): com.google.firestore.v1.ValueOrBuilder;
public static newBuilder(): com.google.firestore.v1.WriteResult.Builder;
public hasUpdateTime(): boolean;
public getTransformResultsCount(): number;
public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firestore.v1.WriteResult;
public getUpdateTime(): com.google.protobuf.Timestamp;
public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResult;
public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResult;
public getTransformResultsOrBuilderList(): java.util.List<any>;
public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResult;
public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firestore.v1.WriteResult;
public getTransformResultsList(): java.util.List<com.google.firestore.v1.Value>;
public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any;
public getTransformResults(param0: number): com.google.firestore.v1.Value;
public writeTo(param0: com.google.protobuf.CodedOutputStream): void;
public static parseFrom(param0: native.Array<number>): com.google.firestore.v1.WriteResult;
public static parseFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteResult;
public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firestore.v1.WriteResult;
}
export module WriteResult {
export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firestore.v1.WriteResult,com.google.firestore.v1.WriteResult.Builder> implements com.google.firestore.v1.WriteResultOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResult.Builder>;
public getTransformResultsList(): java.util.List<com.google.firestore.v1.Value>;
public getTransformResults(param0: number): com.google.firestore.v1.Value;
public addTransformResults(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.WriteResult.Builder;
public setTransformResults(param0: number, param1: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.WriteResult.Builder;
public getTransformResultsCount(): number;
public setUpdateTime(param0: com.google.protobuf.Timestamp.Builder): com.google.firestore.v1.WriteResult.Builder;
public getUpdateTime(): com.google.protobuf.Timestamp;
public removeTransformResults(param0: number): com.google.firestore.v1.WriteResult.Builder;
public hasUpdateTime(): boolean;
public clearTransformResults(): com.google.firestore.v1.WriteResult.Builder;
public setTransformResults(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.WriteResult.Builder;
public addAllTransformResults(param0: java.lang.Iterable<any>): com.google.firestore.v1.WriteResult.Builder;
public mergeUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.WriteResult.Builder;
public addTransformResults(param0: com.google.firestore.v1.Value.Builder): com.google.firestore.v1.WriteResult.Builder;
public addTransformResults(param0: com.google.firestore.v1.Value): com.google.firestore.v1.WriteResult.Builder;
public clearUpdateTime(): com.google.firestore.v1.WriteResult.Builder;
public setUpdateTime(param0: com.google.protobuf.Timestamp): com.google.firestore.v1.WriteResult.Builder;
public addTransformResults(param0: number, param1: com.google.firestore.v1.Value): com.google.firestore.v1.WriteResult.Builder;
}
}
}
}
}
}
declare module com {
export module google {
export module firestore {
export module v1 {
export class WriteResultOrBuilder {
public static class: java.lang.Class<com.google.firestore.v1.WriteResultOrBuilder>;
/**
* Constructs a new instance of the com.google.firestore.v1.WriteResultOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
hasUpdateTime(): boolean;
getUpdateTime(): com.google.protobuf.Timestamp;
getTransformResultsList(): java.util.List<com.google.firestore.v1.Value>;
getTransformResults(param0: number): com.google.firestore.v1.Value;
getTransformResultsCount(): number;
});
public constructor();
public getUpdateTime(): com.google.protobuf.Timestamp;
public getTransformResultsList(): java.util.List<com.google.firestore.v1.Value>;
public getTransformResults(param0: number): com.google.firestore.v1.Value;
public hasUpdateTime(): boolean;
public getTransformResultsCount(): number;
}
}
}
}
}
//Generics information:
//com.google.firebase.firestore.EventListener:1
//com.google.firebase.firestore.Transaction.Function:1
//com.google.firebase.firestore.core.AsyncEventListener:1
//com.google.firebase.firestore.core.TransactionRunner:1
//com.google.firebase.firestore.model.BasePath:1
//com.google.firebase.firestore.remote.AbstractStream:3
//com.google.firebase.firestore.remote.IncomingStreamObserver:1
//com.google.firebase.firestore.remote.Stream:1
//com.google.firebase.firestore.util.Consumer:1
//com.google.firebase.firestore.util.CustomClassMapper.BeanMapper:1
//com.google.firebase.firestore.util.Listener:1
//com.google.firebase.firestore.util.Supplier:1
//com.google.firestore.v1.FirestoreGrpc.MethodHandlers:2 | the_stack |
import { EventFieldInfo } from './EventFieldInfo';
import { eventNameAliasRegisteredCallbacks, getBrowserEventName, getEventNameAliases, getEventTypeOptions } from './EventTypes';
import { dispatchEvent } from '../WebRendererInteropMethods';
const nonBubblingEvents = toLookup([
'abort',
'blur',
'canplay',
'canplaythrough',
'change',
'cuechange',
'durationchange',
'emptied',
'ended',
'error',
'focus',
'load',
'loadeddata',
'loadedmetadata',
'loadend',
'loadstart',
'mouseenter',
'mouseleave',
'pause',
'play',
'playing',
'progress',
'ratechange',
'reset',
'scroll',
'seeked',
'seeking',
'stalled',
'submit',
'suspend',
'timeupdate',
'toggle',
'unload',
'volumechange',
'waiting',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemovedFromDocument',
]);
const alwaysPreventDefaultEvents: { [eventType: string]: boolean } = { submit: true };
const disableableEventNames = toLookup(['click', 'dblclick', 'mousedown', 'mousemove', 'mouseup']);
// Responsible for adding/removing the eventInfo on an expando property on DOM elements, and
// calling an EventInfoStore that deals with registering/unregistering the underlying delegated
// event listeners as required (and also maps actual events back to the given callback).
export class EventDelegator {
private static nextEventDelegatorId = 0;
private readonly eventsCollectionKey: string;
private readonly afterClickCallbacks: ((event: MouseEvent) => void)[] = [];
private eventInfoStore: EventInfoStore;
constructor(private browserRendererId: number) {
const eventDelegatorId = ++EventDelegator.nextEventDelegatorId;
this.eventsCollectionKey = `_blazorEvents_${eventDelegatorId}`;
this.eventInfoStore = new EventInfoStore(this.onGlobalEvent.bind(this));
}
public setListener(element: Element, eventName: string, eventHandlerId: number, renderingComponentId: number) {
const infoForElement = this.getEventHandlerInfosForElement(element, true)!;
const existingHandler = infoForElement.getHandler(eventName);
if (existingHandler) {
// We can cheaply update the info on the existing object and don't need any other housekeeping
// Note that this also takes care of updating the eventHandlerId on the existing handler object
this.eventInfoStore.update(existingHandler.eventHandlerId, eventHandlerId);
} else {
// Go through the whole flow which might involve registering a new global handler
const newInfo = { element, eventName, eventHandlerId, renderingComponentId };
this.eventInfoStore.add(newInfo);
infoForElement.setHandler(eventName, newInfo);
}
}
public getHandler(eventHandlerId: number) {
return this.eventInfoStore.get(eventHandlerId);
}
public removeListener(eventHandlerId: number) {
// This method gets called whenever the .NET-side code reports that a certain event handler
// has been disposed. However we will already have disposed the info about that handler if
// the eventHandlerId for the (element,eventName) pair was replaced during diff application.
const info = this.eventInfoStore.remove(eventHandlerId);
if (info) {
// Looks like this event handler wasn't already disposed
// Remove the associated data from the DOM element
const element = info.element;
const elementEventInfos = this.getEventHandlerInfosForElement(element, false);
if (elementEventInfos) {
elementEventInfos.removeHandler(info.eventName);
}
}
}
public notifyAfterClick(callback: (event: MouseEvent) => void) {
// This is extremely special-case. It's needed so that navigation link click interception
// can be sure to run *after* our synthetic bubbling process. If a need arises, we can
// generalise this, but right now it's a purely internal detail.
this.afterClickCallbacks.push(callback);
this.eventInfoStore.addGlobalListener('click'); // Ensure we always listen for this
}
public setStopPropagation(element: Element, eventName: string, value: boolean) {
const infoForElement = this.getEventHandlerInfosForElement(element, true)!;
infoForElement.stopPropagation(eventName, value);
}
public setPreventDefault(element: Element, eventName: string, value: boolean) {
const infoForElement = this.getEventHandlerInfosForElement(element, true)!;
infoForElement.preventDefault(eventName, value);
}
private onGlobalEvent(evt: Event) {
if (!(evt.target instanceof Element)) {
return;
}
// Always dispatch to any listeners for the original underlying browser event name
this.dispatchGlobalEventToAllElements(evt.type, evt);
// If this event name has aliases, dispatch for those listeners too
const eventNameAliases = getEventNameAliases(evt.type);
eventNameAliases && eventNameAliases.forEach(alias =>
this.dispatchGlobalEventToAllElements(alias, evt));
// Special case for navigation interception
if (evt.type === 'click') {
this.afterClickCallbacks.forEach(callback => callback(evt as MouseEvent));
}
}
private dispatchGlobalEventToAllElements(eventName: string, browserEvent: Event) {
// Note that 'eventName' can be an alias. For example, eventName may be 'click.special'
// while browserEvent.type may be 'click'.
// Use the event's 'path' rather than the chain of parent nodes, since the path gives
// visibility into shadow roots.
const path = browserEvent.composedPath();
// Scan up the element hierarchy, looking for any matching registered event handlers
let candidateEventTarget = path.shift();
let eventArgs: any = null; // Populate lazily
let eventArgsIsPopulated = false;
const eventIsNonBubbling = nonBubblingEvents.hasOwnProperty(eventName);
let stopPropagationWasRequested = false;
while (candidateEventTarget) {
const candidateElement = candidateEventTarget as Element;
const handlerInfos = this.getEventHandlerInfosForElement(candidateElement, false);
if (handlerInfos) {
const handlerInfo = handlerInfos.getHandler(eventName);
if (handlerInfo && !eventIsDisabledOnElement(candidateElement, browserEvent.type)) {
// We are going to raise an event for this element, so prepare info needed by the .NET code
if (!eventArgsIsPopulated) {
const eventOptionsIfRegistered = getEventTypeOptions(eventName);
// For back-compat, if there's no registered createEventArgs, we supply empty event args (not null).
// But if there is a registered createEventArgs, it can supply anything (including null).
eventArgs = eventOptionsIfRegistered?.createEventArgs
? eventOptionsIfRegistered.createEventArgs(browserEvent)
: {};
eventArgsIsPopulated = true;
}
// For certain built-in events, having any .NET handler implicitly means we will prevent
// the browser's default behavior. This has to be based on the original browser event type name,
// not any alias (e.g., if you create a custom 'submit' variant, it should still preventDefault).
if (alwaysPreventDefaultEvents.hasOwnProperty(browserEvent.type)) {
browserEvent.preventDefault();
}
dispatchEvent(this.browserRendererId, {
eventHandlerId: handlerInfo.eventHandlerId,
eventName: eventName,
eventFieldInfo: EventFieldInfo.fromEvent(handlerInfo.renderingComponentId, browserEvent)
}, eventArgs);
}
if (handlerInfos.stopPropagation(eventName)) {
stopPropagationWasRequested = true;
}
if (handlerInfos.preventDefault(eventName)) {
browserEvent.preventDefault();
}
}
candidateEventTarget = (eventIsNonBubbling || stopPropagationWasRequested) ? undefined : path.shift();
}
}
private getEventHandlerInfosForElement(element: Element, createIfNeeded: boolean): EventHandlerInfosForElement | null {
if (element.hasOwnProperty(this.eventsCollectionKey)) {
return element[this.eventsCollectionKey];
} else if (createIfNeeded) {
return (element[this.eventsCollectionKey] = new EventHandlerInfosForElement());
} else {
return null;
}
}
}
// Responsible for adding and removing the global listener when the number of listeners
// for a given event name changes between zero and nonzero
class EventInfoStore {
private infosByEventHandlerId: { [eventHandlerId: number]: EventHandlerInfo } = {};
private countByEventName: { [eventName: string]: number } = {};
constructor(private globalListener: EventListener) {
eventNameAliasRegisteredCallbacks.push(this.handleEventNameAliasAdded.bind(this));
}
public add(info: EventHandlerInfo) {
if (this.infosByEventHandlerId[info.eventHandlerId]) {
// Should never happen, but we want to know if it does
throw new Error(`Event ${info.eventHandlerId} is already tracked`);
}
this.infosByEventHandlerId[info.eventHandlerId] = info;
this.addGlobalListener(info.eventName);
}
public get(eventHandlerId: number) {
return this.infosByEventHandlerId[eventHandlerId];
}
public addGlobalListener(eventName: string) {
// If this event name is an alias, update the global listener for the corresponding browser event
eventName = getBrowserEventName(eventName);
if (this.countByEventName.hasOwnProperty(eventName)) {
this.countByEventName[eventName]++;
} else {
this.countByEventName[eventName] = 1;
// To make delegation work with non-bubbling events, register a 'capture' listener.
// We preserve the non-bubbling behavior by only dispatching such events to the targeted element.
const useCapture = nonBubblingEvents.hasOwnProperty(eventName);
document.addEventListener(eventName, this.globalListener, useCapture);
}
}
public update(oldEventHandlerId: number, newEventHandlerId: number) {
if (this.infosByEventHandlerId.hasOwnProperty(newEventHandlerId)) {
// Should never happen, but we want to know if it does
throw new Error(`Event ${newEventHandlerId} is already tracked`);
}
// Since we're just updating the event handler ID, there's no need to update the global counts
const info = this.infosByEventHandlerId[oldEventHandlerId];
delete this.infosByEventHandlerId[oldEventHandlerId];
info.eventHandlerId = newEventHandlerId;
this.infosByEventHandlerId[newEventHandlerId] = info;
}
public remove(eventHandlerId: number): EventHandlerInfo {
const info = this.infosByEventHandlerId[eventHandlerId];
if (info) {
delete this.infosByEventHandlerId[eventHandlerId];
// If this event name is an alias, update the global listener for the corresponding browser event
const eventName = getBrowserEventName(info.eventName);
if (--this.countByEventName[eventName] === 0) {
delete this.countByEventName[eventName];
document.removeEventListener(eventName, this.globalListener);
}
}
return info;
}
private handleEventNameAliasAdded(aliasEventName, browserEventName) {
// If an event name alias gets registered later, we need to update the global listener
// registrations to match. This makes it equivalent to the alias having been registered
// before the elements with event handlers got rendered.
if (this.countByEventName.hasOwnProperty(aliasEventName)) {
// Delete old
const countByAliasEventName = this.countByEventName[aliasEventName];
delete this.countByEventName[aliasEventName];
document.removeEventListener(aliasEventName, this.globalListener);
// Ensure corresponding count is added to new
this.addGlobalListener(browserEventName);
this.countByEventName[browserEventName] += countByAliasEventName - 1;
}
}
}
class EventHandlerInfosForElement {
// Although we *could* track multiple event handlers per (element, eventName) pair
// (since they have distinct eventHandlerId values), there's no point doing so because
// our programming model is that you declare event handlers as attributes. An element
// can only have one attribute with a given name, hence only one event handler with
// that name at any one time.
// So to keep things simple, only track one EventHandlerInfo per (element, eventName)
private handlers: { [eventName: string]: EventHandlerInfo } = {};
private preventDefaultFlags: { [eventName: string]: boolean } | null = null;
private stopPropagationFlags: { [eventName: string]: boolean } | null = null;
public getHandler(eventName: string): EventHandlerInfo | null {
return this.handlers.hasOwnProperty(eventName) ? this.handlers[eventName] : null;
}
public setHandler(eventName: string, handler: EventHandlerInfo) {
this.handlers[eventName] = handler;
}
public removeHandler(eventName: string) {
delete this.handlers[eventName];
}
public preventDefault(eventName: string, setValue?: boolean): boolean {
if (setValue !== undefined) {
this.preventDefaultFlags = this.preventDefaultFlags || {};
this.preventDefaultFlags[eventName] = setValue;
}
return this.preventDefaultFlags ? this.preventDefaultFlags[eventName] : false;
}
public stopPropagation(eventName: string, setValue?: boolean): boolean {
if (setValue !== undefined) {
this.stopPropagationFlags = this.stopPropagationFlags || {};
this.stopPropagationFlags[eventName] = setValue;
}
return this.stopPropagationFlags ? this.stopPropagationFlags[eventName] : false;
}
}
export interface EventDescriptor {
eventHandlerId: number;
eventName: string;
eventFieldInfo: EventFieldInfo | null;
}
interface EventHandlerInfo {
element: Element;
eventName: string;
eventHandlerId: number;
// The component whose tree includes the event handler attribute frame, *not* necessarily the
// same component that will be re-rendered after the event is handled (since we re-render the
// component that supplied the delegate, not the one that rendered the event handler frame)
renderingComponentId: number;
}
function toLookup(items: string[]): { [key: string]: boolean } {
const result = {};
items.forEach(value => {
result[value] = true;
});
return result;
}
function eventIsDisabledOnElement(element: Element, rawBrowserEventName: string): boolean {
// We want to replicate the normal DOM event behavior that, for 'interactive' elements
// with a 'disabled' attribute, certain mouse events are suppressed
return (element instanceof HTMLButtonElement || element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement)
&& disableableEventNames.hasOwnProperty(rawBrowserEventName)
&& element.disabled;
} | the_stack |
import { getElementsWithGivenOffset, updateAsciiValue, getElementsOffset } from "./util";
import { ByteData } from "./byteData";
import { messageHandler, virtualHexDocument } from "./hexEdit";
import { SelectHandler } from "./selectHandler";
interface DocumentEdit {
offset: number;
previousValue: string | undefined;
newValue: string | undefined;
element: HTMLSpanElement | undefined;
}
// This is what an edit to/from the extension host looks like
export interface EditMessage {
readonly oldValue: number | undefined;
readonly newValue: number | undefined;
readonly offset: number;
readonly sameOnDisk: boolean;
}
/**
* @description Class responsible for handling edits within the virtual document
*/
export class EditHandler {
private pendingEdit: DocumentEdit | undefined;
constructor() {
this.pendingEdit = undefined;
}
/**
* @description Handles when a user starts typing on a hex element
* @param {HTMLSpanElement} element The element which the keypress was fired on
* @param {string} keyPressed The key which was pressed
*/
public async editHex(element: HTMLSpanElement, keyPressed: string): Promise<void> {
// If the user presses escape and there is a current edit then we just revert the cell as if no edit has happened
if (keyPressed === "Escape" && this.pendingEdit && this.pendingEdit.previousValue) {
element.innerText = this.pendingEdit.previousValue;
element.classList.remove("editing");
this.pendingEdit = undefined;
}
// If it's not a valid hex input or delete we ignore it
const regex = new RegExp(/^[a-fA-F0-9]$/gm);
if (keyPressed.match(regex) === null && keyPressed !== "Delete") {
return;
}
const offset: number = getElementsOffset(element);
if (!this.pendingEdit || this.pendingEdit.offset != offset) {
this.pendingEdit = {
offset: offset,
previousValue: element.innerText === "+" ? undefined : element.innerText,
newValue: "",
element: element
};
}
element.classList.add("editing");
element.innerText = element.innerText.trimRight();
// When the user hits delete
if (keyPressed === "Delete") {
element.innerText = " ";
} else {
// This handles when the user presses the first character erasing the old value vs adding to the currently edited value
element.innerText = element.innerText.length !== 1 || element.innerText === "+" ? `${keyPressed.toUpperCase()} ` : element.innerText + keyPressed.toUpperCase();
}
this.pendingEdit.newValue = element.innerText;
if (element.innerText.trimRight().length == 2) {
element.classList.remove("add-cell");
// Not really an edit if nothing changed
if (this.pendingEdit.newValue == this.pendingEdit.previousValue) {
this.pendingEdit = undefined;
return;
}
await this.sendEditToExtHost([this.pendingEdit]);
this.updateAscii(element.innerText, offset);
element.classList.add("edited");
// Means the last cell of the document was filled in so we add another placeholder afterwards
if (!this.pendingEdit.previousValue) {
virtualHexDocument.createAddCell();
}
this.pendingEdit = undefined;
}
}
/**
* @description Handles when the user starts typing on an ascii element
* @param {HTMLSpanElement} element The element which the keystroke was fired on
* @param {string} keyPressed The key which was pressed
*/
public async editAscii(element: HTMLSpanElement, keyPressed: string): Promise<void> {
// We don't want to do anything if the user presses a key such as home etc which will register as greater than 1 char
if (keyPressed.length != 1) return;
const offset: number = getElementsOffset(element);
const hexElement = getElementsWithGivenOffset(offset)[0];
const newValueHex = keyPressed.charCodeAt(0).toString(16).toUpperCase();
// No need to call it edited if it's the same value. The comparison is done on hex values because '+' and '.' have additional meaning on ASCII panel
if(hexElement.innerText === newValueHex){
return;
}
// We store all pending edits as hex as ascii isn't always representative due to control characters
this.pendingEdit = {
offset: offset,
previousValue: hexElement.innerText === "+" ? undefined : hexElement.innerText,
newValue: newValueHex,
element: element
};
element.classList.remove("add-cell");
element.classList.add("editing");
element.classList.add("edited");
this.updateAscii(this.pendingEdit.newValue, offset);
this.updateHex(keyPressed, offset);
await this.sendEditToExtHost([this.pendingEdit]);
// Means the last cell of the document was filled in so we add another placeholder afterwards
if (!this.pendingEdit.previousValue) {
virtualHexDocument.createAddCell();
}
this.pendingEdit = undefined;
}
/**
* @description Given a hex value updates the respective ascii value
* @param {string | undefined} hexValue The hex value to convert to ascii
* @param {number} offset The offset of the ascii value to update
*/
private updateAscii(hexValue: string | undefined, offset: number): void {
// For now if it's undefined we will just ignore it, but this would be the delete case
if (!hexValue) return;
// The way the DOM is constructed the ascii element will always be the second one
const ascii = getElementsWithGivenOffset(offset)[1];
ascii.classList.remove("add-cell");
updateAsciiValue(new ByteData(parseInt(hexValue, 16)), ascii);
ascii.classList.add("edited");
}
/**
* @description Given an ascii value updates the respective hex value
* @param {string} asciiValue The ascii value to convert to hex
* @param {number} offset The offset of the hex value to update
*/
private updateHex(asciiValue: string, offset: number): void {
// The way the DOM is constructed the hex element will always be the first one
const hex = getElementsWithGivenOffset(offset)[0];
hex.innerText = asciiValue.charCodeAt(0).toString(16).toUpperCase();
hex.classList.remove("add-cell");
hex.classList.add("edited");
}
/**
* @description Completes the current edit, this is used if the user navigates off the cell and it wasn't done being edited
*/
public async completePendingEdits(): Promise<void> {
if (this.pendingEdit && this.pendingEdit.element && this.pendingEdit.newValue) {
// We don't want to stop the edit if it is selected as that can mean the user will be making further edits
if (this.pendingEdit.element.classList.contains("selected")) return;
// Ensure the hex value has 2 characters, if not we add a 0 in front
this.pendingEdit.newValue = "00" + this.pendingEdit.newValue.trimRight();
this.pendingEdit.newValue = this.pendingEdit.newValue.slice(this.pendingEdit.newValue.length - 2);
this.pendingEdit.element.classList.remove("editing");
this.pendingEdit.element.innerText = this.pendingEdit.newValue;
// No edit really happened so we don't want it to update the ext host
if (this.pendingEdit.newValue === this.pendingEdit.previousValue) {
return;
}
this.updateAscii(this.pendingEdit.newValue, this.pendingEdit.offset);
this.pendingEdit.element.classList.add("edited");
this.pendingEdit.element.classList.remove("add-cell");
await this.sendEditToExtHost([this.pendingEdit]);
if (!this.pendingEdit.previousValue) {
virtualHexDocument.createAddCell();
}
this.pendingEdit = undefined;
}
}
/**
* @description Given a list of edits sends it to the exthost so that the ext host and webview are in sync
* @param {DocumentEdit} edits The edits to send to the exthost
*/
private async sendEditToExtHost(edits: DocumentEdit[]): Promise<void> {
const extHostMessage: EditMessage[] = [];
for (const edit of edits) {
// The ext host only accepts 8bit unsigned ints, so we must convert the edits back into that representation
const oldValue = edit.previousValue ? parseInt(edit.previousValue, 16) : undefined;
const newValue = edit.newValue ? parseInt(edit.newValue, 16) : undefined;
const currentMessage = {
offset: edit.offset,
oldValue,
newValue,
sameOnDisk: false
};
extHostMessage.push(currentMessage);
}
try {
const syncedFileSize = (await messageHandler.postMessageWithResponse("edit", extHostMessage)).fileSize;
virtualHexDocument.updateDocumentSize(syncedFileSize);
} catch {
// Empty catch because we just don't do anything if for some reason the exthost doesn't respond with the new fileSize,
// we just sync at the next available opportunity
return;
}
}
/**
* @description Given a list of edits undoes them from the document
* @param {EditMessage[]} edits The list of edits to undo
*/
public undo(edits: EditMessage[]): void {
// We want to process the highest offset first as we only support removing cells from the end of the document
// So if we need to remove 3 cells we can't remove them in arbitrary order it needs to be outermost cell first
if (edits.length > 1 && edits[0].offset < edits[edits.length - 1].offset) {
edits = edits.reverse();
}
for (const edit of edits) {
// This is the delete case
if (edit.oldValue === undefined) {
virtualHexDocument.focusElementWithGivenOffset(virtualHexDocument.documentSize);
virtualHexDocument.removeLastCell();
continue;
}
const elements = getElementsWithGivenOffset(edit.offset);
// We're executing an undo and the elements aren't on the DOM so there's no point in doing anything
if (elements.length != 2) return;
if (edit.sameOnDisk) {
elements[0].classList.remove("edited");
elements[1].classList.remove("edited");
} else {
elements[0].classList.add("edited");
elements[1].classList.add("edited");
}
elements[0].innerText = edit.oldValue.toString(16).toUpperCase();
elements[0].innerText = elements[0].innerText.length == 2 ? elements[0].innerText : `0${elements[0].innerText}`;
updateAsciiValue(new ByteData(edit.oldValue), elements[1]);
virtualHexDocument.focusElementWithGivenOffset(edit.offset);
}
}
/**
* @description Given a list of edits reapplies them to the document
* @param {EditMessage[]} edits The list of edits to redo
*/
public redo(edits: EditMessage[]): void {
for (const edit of edits) {
if (edit.newValue === undefined) continue;
const elements = getElementsWithGivenOffset(edit.offset);
// We're executing an redo and the elements aren't on the DOM so there's no point in doing anything
if (elements.length != 2) continue;
elements[0].classList.remove("add-cell");
elements[1].classList.remove("add-cell");
if (edit.sameOnDisk) {
elements[0].classList.remove("edited");
elements[1].classList.remove("edited");
} else {
elements[0].classList.add("edited");
elements[1].classList.add("edited");
}
elements[0].innerText = edit.newValue.toString(16).toUpperCase();
elements[0].innerText = elements[0].innerText.length == 2 ? elements[0].innerText : `0${elements[0].innerText}`;
updateAsciiValue(new ByteData(edit.newValue), elements[1]);
// If no add cells are left we need to add more as this means we just replaced the end
if (document.getElementsByClassName("add-cell").length === 0 && edit.oldValue === undefined) {
// We are going to estimate the filesize and it will be resynced at the end if wrong
// This is because we add 1 cell at a time therefore if we paste the filesize is larger than whats rendered breaking the plus cell logic
// This causes issues so this is a quick fix, another fix would be to apply all cells at once
virtualHexDocument.updateDocumentSize(virtualHexDocument.documentSize + 1);
virtualHexDocument.createAddCell();
}
virtualHexDocument.focusElementWithGivenOffset(edit.offset);
}
}
/**
* @description Handles when a user copies
* @param {ClipboardEvent} event The clibpoard event passed to a copy event handler
*/
public copy(event: ClipboardEvent): void {
event.clipboardData?.setData("text/json", JSON.stringify(SelectHandler.getSelectedHex()));
event.clipboardData?.setData("text/plain", SelectHandler.getSelectedValue());
event.preventDefault();
}
/**
* @description Handles when a user pastes
* @param {ClipboardEvent} event The clibpoard event passed to a paste event handler
*/
public async paste(event: ClipboardEvent): Promise<void> {
// If what's on the clipboard isn't json we won't try to past it in
if (!event.clipboardData || event.clipboardData.types.indexOf("text/json") < 0) return;
const hexData = JSON.parse(event.clipboardData.getData("text/json"));
// We do Array.from() as this makes it so the array no longer is tied to the dom who's selection may change during this paste
const selected = Array.from(document.getElementsByClassName("selected hex") as HTMLCollectionOf<HTMLSpanElement>);
const edits: DocumentEdit[] = [];
// We apply as much of the hex data as we can based on the selection
for (let i = 0; i < selected.length && i < hexData.length; i++) {
const element = selected[i];
const offset: number = getElementsOffset(element);
const currentEdit: DocumentEdit = {
offset: offset,
previousValue: element.innerText === "+" ? undefined : element.innerText,
newValue: hexData[i],
element: element
};
element.classList.remove("add-cell");
// Not really an edit if nothing changed
if (currentEdit.newValue == currentEdit.previousValue) {
continue;
}
element.innerText = hexData[i];
this.updateAscii(element.innerText, offset);
element.classList.add("edited");
// Means the last cell of the document was filled in so we add another placeholder afterwards
if (currentEdit.previousValue === undefined) {
// Since we don't send all the edits until the end we need to estimate what the current file size is during this operation or the last cells won't be added correctly
virtualHexDocument.updateDocumentSize(virtualHexDocument.documentSize + 1);
virtualHexDocument.createAddCell();
selected.push(getElementsWithGivenOffset(virtualHexDocument.documentSize)[0]);
}
edits.push(currentEdit);
}
await this.sendEditToExtHost(edits);
event.preventDefault();
}
/**
* @description Called when the user executes the revert command or when the document changes on disk and there are no unsaved edits
*/
public revert(): void {
virtualHexDocument.reRequestChunks();
}
} | the_stack |
import { assert } from "@fluidframework/common-utils";
import * as MergeTree from "@fluidframework/merge-tree";
import { SharedString } from "@fluidframework/sequence";
import { IFluidDataStoreContext } from "@fluidframework/runtime-definitions";
/**
* - Create a new object from the passed SharedString.
* - Modify the methods that insert / remove / annotate the properties of the SharedString to call
* the propertyInterceptionCallback to get new properties.
* - Use these new properties to call the underlying SharedString.
* - The propertyInterceptionCallback and the call to the underlying SharedString are wrapped around an
* orderSequentially call to batch any operations that might happen in the callback.
*
* @param sharedString - The underlying SharedString
* @param context - The IFluidDataStoreContext that will be used to call orderSequentially
* @param propertyInterceptionCallback - The interception callback to be called
*
* @returns A new SharedString that intercepts the methods modifying the SharedString properties.
*/
export function createSharedStringWithInterception(
sharedString: SharedString,
context: IFluidDataStoreContext,
propertyInterceptionCallback: (props?: MergeTree.PropertySet) => MergeTree.PropertySet): SharedString {
const sharedStringWithInterception = Object.create(sharedString);
// executingCallback keeps track of whether a method on this wrapper object is called recursively
// from the propertyInterceptionCallback.
let executingCallback: boolean = false;
/**
* Inserts a marker at a relative position.
*
* @param relativePos1 - The relative position to insert the marker at
* @param refType - The reference type of the marker
* @param props - The properties of the marker
*/
sharedStringWithInterception.insertMarkerRelative = (
relativePos1: MergeTree.IRelativePosition,
refType: MergeTree.ReferenceType,
props?: MergeTree.PropertySet) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c1 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.insertMarkerRelative(relativePos1, refType, propertyInterceptionCallback(props));
} finally {
executingCallback = false;
}
});
};
/**
* Inserts a marker at the position.
*
* @param pos - The position to insert the marker at
* @param refType - The reference type of the marker
* @param props - The properties of the marker
*/
sharedStringWithInterception.insertMarker = (
pos: number,
refType: MergeTree.ReferenceType,
props?: MergeTree.PropertySet) => {
let insertOp;
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c2 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
insertOp = sharedString.insertMarker(pos, refType, propertyInterceptionCallback(props));
} finally {
executingCallback = false;
}
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return insertOp;
};
/**
* Inserts the text at a relative position.
*
* @param relativePos1 - The relative position to insert the text at
* @param text - The text to insert
* @param props - The properties of text
*/
sharedStringWithInterception.insertTextRelative = (
relativePos1: MergeTree.IRelativePosition,
text: string,
props?: MergeTree.PropertySet) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c3 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.insertTextRelative(relativePos1, text, propertyInterceptionCallback(props));
} finally {
executingCallback = false;
}
});
};
/**
* Inserts the text at the position.
*
* @param pos - The position to insert the text at
* @param text - The text to insert
* @param props - The properties of text
*/
sharedStringWithInterception.insertText = (pos: number, text: string, props?: MergeTree.PropertySet) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c4 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.insertText(pos, text, propertyInterceptionCallback(props));
} finally {
executingCallback = false;
}
});
};
/**
* Replaces a range with the provided text.
*
* @param start - The inclusive start of the range to replace
* @param end - The exclusive end of the range to replace
* @param text - The text to replace the range with
* @param props - Optional. The properties of the replacement text
*/
sharedStringWithInterception.replaceText = (
start: number,
end: number,
text: string,
props?: MergeTree.PropertySet) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c5 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.replaceText(start, end, text, propertyInterceptionCallback(props));
} finally {
executingCallback = false;
}
});
};
/**
* Annotates the marker with the provided properties and calls the callback on concensus.
*
* @param marker - The marker to annotate
* @param props - The properties to annotate the marker with
* @param consensusCallback - The callback called when consensus is reached
*/
sharedStringWithInterception.annotateMarkerNotifyConsensus = (
marker: MergeTree.Marker,
props: MergeTree.PropertySet,
callback: (m: MergeTree.Marker) => void) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c6 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.annotateMarkerNotifyConsensus(marker, propertyInterceptionCallback(props), callback);
} finally {
executingCallback = false;
}
});
};
/**
* Annotates the marker with the provided properties.
*
* @param marker - The marker to annotate
* @param props - The properties to annotate the marker with
* @param combiningOp - Optional. Specifies how to combine values for the property, such as "incr" for increment.
*/
sharedStringWithInterception.annotateMarker = (
marker: MergeTree.Marker,
props: MergeTree.PropertySet,
combiningOp?: MergeTree.ICombiningOp) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c7 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.annotateMarker(marker, propertyInterceptionCallback(props), combiningOp);
} finally {
executingCallback = false;
}
});
};
/**
* Annotates the range with the provided properties.
*
* @param start - The inclusive start position of the range to annotate
* @param end - The exclusive end position of the range to annotate
* @param props - The properties to annotate the range with
* @param combiningOp - Optional. Specifies how to combine values for the property, such as "incr" for increment.
*
*/
sharedStringWithInterception.annotateRange = (
start: number,
end: number,
props: MergeTree.PropertySet,
combiningOp?: MergeTree.ICombiningOp) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c8 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
sharedString.annotateRange(start, end, propertyInterceptionCallback(props), combiningOp);
} finally {
executingCallback = false;
}
});
};
/**
* Inserts the segment at the given position
*
* @param pos - The position to insert the segment at
* @param segment - The segment to insert
*/
sharedStringWithInterception.insertAtReferencePosition = (
pos: MergeTree.ReferencePosition,
segment: MergeTree.TextSegment) => {
// Wrapper methods should not be called from the interception callback as this will lead to
// infinite recursion.
assert(executingCallback === false,
0x0c9 /* "Interception wrapper methods called recursively from the interception callback" */);
context.containerRuntime.orderSequentially(() => {
executingCallback = true;
try {
segment.properties = propertyInterceptionCallback(segment.properties);
sharedString.insertAtReferencePosition(pos, segment);
} finally {
executingCallback = false;
}
});
};
return sharedStringWithInterception as SharedString;
} | the_stack |
import { BigNumber, BigNumberish } from "ethers/utils";
import { JsonRpcNotification, JsonRpcResponse, Rpc } from "rpc-server";
import { OutcomeType } from ".";
import {
AppABIEncodings,
AppInstanceJson,
AppInstanceProposal
} from "./data-types";
import { SolidityValueType } from "./simple-types";
export interface IRpcNodeProvider {
onMessage(callback: (message: JsonRpcResponse | JsonRpcNotification) => void);
sendMessage(message: Rpc);
}
export namespace Node {
/**
* The message type for Nodes to communicate with each other.
*/
export type NodeMessage = {
from: string;
type: EventName;
};
// This is used instead of the ethers `Transaction` because that type
// requires the nonce and chain ID to be specified, when sometimes those
// arguments are not known at the time of creating a transaction.
export type MinimalTransaction = {
to: string;
value: BigNumberish;
data: string;
};
export interface ServiceFactory {
connect?(host: string, port: string): ServiceFactory;
auth?(email: string, password: string): Promise<void>;
createMessagingService?(messagingServiceKey: string): IMessagingService;
createStoreService?(storeServiceKey: string): IStoreService;
}
export interface IMessagingService {
send(to: string, msg: Node.NodeMessage): Promise<void>;
onReceive(address: string, callback: (msg: Node.NodeMessage) => void);
}
/**
* An interface for a stateful storage service with an API very similar to Firebase's API.
* Values are addressed by paths, which are separated by the forward slash separator `/`.
* `get` must return values whose paths have prefixes that match the provided path,
* keyed by the remaining path.
* `set` allows multiple values and paths to be atomically set. In Firebase, passing `null`
* as `value` deletes the entry at the given prefix, and passing objects with null subvalues
* deletes entries at the path extended by the subvalue's path within the object. `set` must
* have the same behaviour if the `allowDelete` flag is passed; otherwise, any null values or
* subvalues throws an error.
*/
export interface IStoreService {
get(path: string): Promise<any>;
set(
pairs: { path: string; value: any }[],
allowDelete?: Boolean
): Promise<void>;
reset?(): Promise<void>;
}
export interface IPrivateKeyGenerator {
(s: string): Promise<string>;
}
/**
* Centralized locking service (i.e. redis)
*/
export interface ILockService {
acquireLock(
lockName: string,
callback: (...args: any[]) => any,
timeout: number
): Promise<any>;
}
export enum ErrorType {
ERROR = "error"
}
// SOURCE: https://github.com/counterfactual/monorepo/blob/master/packages/cf.js/API_REFERENCE.md#public-methods
export enum MethodName {
ACCEPT_STATE = "acceptState",
GET_PROPOSED_APP_INSTANCE = "getProposedAppInstance"
}
export enum RpcMethodName {
CREATE_CHANNEL = "chan_create",
DEPOSIT = "chan_deposit",
DEPLOY_STATE_DEPOSIT_HOLDER = "chan_deployStateDepositHolder",
GET_CHANNEL_ADDRESSES = "chan_getChannelAddresses",
GET_APP_INSTANCE_DETAILS = "chan_getAppInstance",
GET_APP_INSTANCES = "chan_getAppInstances",
GET_STATE_DEPOSIT_HOLDER_ADDRESS = "chan_getStateDepositHolderAddress",
GET_FREE_BALANCE_STATE = "chan_getFreeBalanceState",
GET_TOKEN_INDEXED_FREE_BALANCE_STATES = "chan_getTokenIndexedFreeBalanceStates",
GET_PROPOSED_APP_INSTANCES = "chan_getProposedAppInstances",
GET_STATE = "chan_getState",
GET_STATE_CHANNEL = "chan_getStateChannel",
INSTALL = "chan_install",
INSTALL_VIRTUAL = "chan_installVirtual",
PROPOSE_INSTALL = "chan_proposeInstall",
PROPOSE_STATE = "chan_proposeState",
REJECT_INSTALL = "chan_rejectInstall",
REJECT_STATE = "chan_rejectState",
UPDATE_STATE = "chan_updateState",
TAKE_ACTION = "chan_takeAction",
UNINSTALL = "chan_uninstall",
UNINSTALL_VIRTUAL = "chan_uninstallVirtual",
WITHDRAW = "chan_withdraw",
WITHDRAW_COMMITMENT = "chan_withdrawCommitment"
}
// SOURCE: https://github.com/counterfactual/monorepo/blob/master/packages/cf.js/API_REFERENCE.md#events
export enum EventName {
COUNTER_DEPOSIT_CONFIRMED = "counterDepositConfirmed",
CREATE_CHANNEL = "createChannelEvent",
DEPOSIT_CONFIRMED = "depositConfirmedEvent",
DEPOSIT_FAILED = "depositFailed",
DEPOSIT_STARTED = "depositStartedEvent",
INSTALL = "installEvent",
INSTALL_VIRTUAL = "installVirtualEvent",
PROPOSE_STATE = "proposeStateEvent",
REJECT_INSTALL = "rejectInstallEvent",
REJECT_STATE = "rejectStateEvent",
UNINSTALL = "uninstallEvent",
UNINSTALL_VIRTUAL = "uninstallVirtualEvent",
UPDATE_STATE = "updateStateEvent",
WITHDRAWAL_CONFIRMED = "withdrawalConfirmedEvent",
WITHDRAWAL_FAILED = "withdrawalFailed",
WITHDRAWAL_STARTED = "withdrawalStartedEvent",
PROPOSE_INSTALL = "proposeInstallEvent",
PROTOCOL_MESSAGE_EVENT = "protocolMessageEvent",
WITHDRAW_EVENT = "withdrawEvent",
REJECT_INSTALL_VIRTUAL = "rejectInstallEvent"
}
export type CreateChannelParams = {
owners: string[];
};
export type CreateChannelResult = {
multisigAddress: string;
owners: string[];
counterpartyXpub: string;
};
export type CreateChannelTransactionResult = {
multisigAddress: string;
};
export type CreateMultisigParams = {
owners: string[];
};
export type CreateMultisigResult = {
multisigAddress: string;
};
export type DeployStateDepositHolderParams = {
multisigAddress: string;
retryCount?: number;
};
export type DeployStateDepositHolderResult = {
transactionHash: string;
};
export type DepositParams = {
multisigAddress: string;
amount: BigNumber;
tokenAddress?: string;
};
export type DepositResult = {
multisigBalance: BigNumber;
};
export type GetAppInstanceDetailsParams = {
appInstanceId: string;
};
export type GetAppInstanceDetailsResult = {
appInstance: AppInstanceJson;
};
export type GetStateDepositHolderAddressParams = {
owners: string[];
};
export type GetStateDepositHolderAddressResult = {
address: string;
};
export type GetAppInstancesParams = {};
export type GetAppInstancesResult = {
appInstances: AppInstanceJson[];
};
export type GetChannelAddressesParams = {};
export type GetChannelAddressesResult = {
multisigAddresses: string[];
};
export type GetFreeBalanceStateParams = {
multisigAddress: string;
tokenAddress?: string;
};
export type GetFreeBalanceStateResult = {
[s: string]: BigNumber;
};
export type GetTokenIndexedFreeBalanceStatesParams = {
multisigAddress: string;
};
export type GetTokenIndexedFreeBalanceStatesResult = {
[tokenAddress: string]: {
[s: string]: BigNumber;
};
};
export type GetProposedAppInstancesParams = {};
export type GetProposedAppInstancesResult = {
appInstances: AppInstanceProposal[];
};
export type GetProposedAppInstanceParams = {
appInstanceId: string;
};
export type GetProposedAppInstanceResult = {
appInstance: AppInstanceProposal;
};
export type GetStateParams = {
appInstanceId: string;
};
export type GetStateResult = {
state: SolidityValueType;
};
export type InstallParams = {
appInstanceId: string;
};
export type InstallResult = {
appInstance: AppInstanceJson;
};
export type InstallVirtualParams = InstallParams & {
intermediaryIdentifier: string;
};
export type InstallVirtualResult = InstallResult;
export type ProposeInstallParams = {
appDefinition: string;
abiEncodings: AppABIEncodings;
initiatorDeposit: BigNumber;
initiatorDepositTokenAddress?: string;
responderDeposit: BigNumber;
responderDepositTokenAddress?: string;
timeout: BigNumber;
initialState: SolidityValueType;
proposedToIdentifier: string;
outcomeType: OutcomeType;
};
export type ProposeInstallVirtualParams = ProposeInstallParams & {
intermediaryIdentifier: string;
};
export type ProposeInstallVirtualResult = ProposeInstallResult;
export type ProposeInstallResult = {
appInstanceId: string;
};
export type RejectInstallParams = {
appInstanceId: string;
};
export type RejectInstallResult = {};
export type TakeActionParams = {
appInstanceId: string;
action: SolidityValueType;
};
export type TakeActionResult = {
newState: SolidityValueType;
};
export type UninstallParams = {
appInstanceId: string;
};
export type UninstallResult = {};
export type UninstallVirtualParams = UninstallParams & {
intermediaryIdentifier: string;
};
export type UninstallVirtualResult = UninstallResult;
export type UpdateStateParams = {
appInstanceId: string;
newState: SolidityValueType;
};
export type UpdateStateResult = {
newState: SolidityValueType;
};
export type WithdrawParams = {
multisigAddress: string;
recipient?: string;
amount: BigNumber;
tokenAddress?: string;
};
export type WithdrawResult = {
recipient: string;
txHash: string;
};
export type WithdrawCommitmentParams = WithdrawParams;
export type WithdrawCommitmentResult = {
transaction: MinimalTransaction;
};
export type MethodParams =
| GetAppInstancesParams
| GetProposedAppInstancesParams
| ProposeInstallParams
| ProposeInstallVirtualParams
| RejectInstallParams
| InstallParams
| InstallVirtualParams
| GetStateParams
| GetAppInstanceDetailsParams
| TakeActionParams
| UninstallParams
| CreateChannelParams
| GetChannelAddressesParams
| DeployStateDepositHolderParams;
export type MethodResult =
| GetAppInstancesResult
| GetProposedAppInstancesResult
| ProposeInstallResult
| ProposeInstallVirtualResult
| RejectInstallResult
| InstallResult
| InstallVirtualResult
| GetStateResult
| GetAppInstanceDetailsResult
| TakeActionResult
| UninstallResult
| CreateChannelResult
| GetChannelAddressesResult
| DeployStateDepositHolderResult;
export type CreateMultisigEventData = {
owners: string[];
multisigAddress: string;
};
export type InstallEventData = {
appInstanceId: string;
};
export type RejectInstallEventData = {
appInstance: AppInstanceProposal;
};
export type UninstallEventData = {
appInstanceId: string;
};
export type UpdateStateEventData = {
appInstanceId: string;
newState: SolidityValueType;
action?: SolidityValueType;
};
export type WithdrawEventData = {
amount: BigNumber;
};
export type EventData =
| InstallEventData
| RejectInstallEventData
| UpdateStateEventData
| UninstallEventData
| CreateMultisigEventData;
export type MethodMessage = {
type: MethodName;
requestId: string;
};
export type MethodRequest = MethodMessage & {
params: MethodParams;
};
export type MethodResponse = MethodMessage & {
result: MethodResult;
};
export type Event = {
type: EventName;
data: EventData;
};
export type Error = {
type: ErrorType;
requestId?: string;
data: {
errorName: string;
message?: string;
appInstanceId?: string;
extra?: { [k: string]: string | number | boolean | object };
};
};
export type Message = MethodRequest | MethodResponse | Event | Error;
} | the_stack |
import { Emitter, TextEditor, Grammar } from "atom";
import { observable, action, computed } from "mobx";
import isEqual from "lodash/isEqual";
import {
log,
focus,
msgSpecToNotebookFormat,
msgSpecV4toV5,
INSPECTOR_URI,
executionTime,
} from "./utils";
import store from "./store";
import WatchesStore from "./store/watches";
import OutputStore from "./store/output";
import HydrogenKernel from "./plugin-api/hydrogen-kernel";
import type {
HydrogenKernelMiddlewareThunk,
HydrogenKernelMiddleware,
} from "./plugin-api/hydrogen-types";
import InputView from "./input-view";
import KernelTransport from "./kernel-transport";
import type { ResultsCallback } from "./kernel-transport";
import type { Kernel as JupyterlabKernel } from "@jupyterlab/services";
import type { Message } from "./hydrogen";
import type { KernelspecMetadata } from "@nteract/types";
function protectFromInvalidMessages(
onResults: ResultsCallback
): ResultsCallback {
const wrappedOnResults: ResultsCallback = (message, channel) => {
if (!message) {
log("Invalid message: null");
return;
}
if (!message.content) {
log("Invalid message: Missing content");
return;
}
if (message.content.execution_state === "starting") {
// Kernels send a starting status message with an empty parent_header
log("Dropped starting status IO message");
return;
}
if (!message.parent_header) {
log("Invalid message: Missing parent_header");
return;
}
if (!message.parent_header.msg_id) {
log("Invalid message: Missing parent_header.msg_id");
return;
}
if (!message.parent_header.msg_type) {
log("Invalid message: Missing parent_header.msg_type");
return;
}
if (!message.header) {
log("Invalid message: Missing header");
return;
}
if (!message.header.msg_id) {
log("Invalid message: Missing header.msg_id");
return;
}
if (!message.header.msg_type) {
log("Invalid message: Missing header.msg_type");
return;
}
onResults(message, channel);
};
return wrappedOnResults;
} // Adapts middleware objects provided by plugins to an internal interface. In
// particular, this implements fallthrough logic for when a plugin defines some
// methods (e.g. execute) but doesn't implement others (e.g. interrupt). Note
// that HydrogenKernelMiddleware objects are mutable: they may lose/gain methods
// at any time, including in the middle of processing a request. This class also
// adds basic checks that messages passed via the `onResults` callbacks are not
// missing key mandatory fields specified in the Jupyter messaging spec.
class MiddlewareAdapter implements HydrogenKernelMiddlewareThunk {
_middleware: HydrogenKernelMiddleware;
_next: MiddlewareAdapter | KernelTransport;
constructor(
middleware: HydrogenKernelMiddleware,
next: MiddlewareAdapter | KernelTransport
) {
this._middleware = middleware;
this._next = next;
}
// The return value of this method gets passed to plugins! For now we just
// return the MiddlewareAdapter object itself, which is why all private
// functionality is prefixed with _, and why MiddlewareAdapter is marked as
// implementing HydrogenKernelMiddlewareThunk. Once multiple plugin API
// versions exist, we may want to generate a HydrogenKernelMiddlewareThunk
// specialized for a particular plugin API version.
get _nextAsPluginType(): HydrogenKernelMiddlewareThunk {
if (this._next instanceof KernelTransport) {
throw new Error(
"MiddlewareAdapter: _nextAsPluginType must never be called when _next is KernelTransport"
);
}
return this._next;
}
interrupt(): void {
if (this._middleware.interrupt) {
this._middleware.interrupt(this._nextAsPluginType);
} else {
this._next.interrupt();
}
}
shutdown(): void {
if (this._middleware.shutdown) {
this._middleware.shutdown(this._nextAsPluginType);
} else {
this._next.shutdown();
}
}
restart(
onRestarted: ((...args: Array<any>) => any) | null | undefined
): void {
if (this._middleware.restart) {
this._middleware.restart(this._nextAsPluginType, onRestarted);
} else {
this._next.restart(onRestarted);
}
}
execute(code: string, onResults: ResultsCallback): void {
// We don't want to repeatedly wrap the onResults callback every time we
// fall through, but we need to do it at least once before delegating to
// the KernelTransport.
const safeOnResults =
this._middleware.execute || this._next instanceof KernelTransport
? protectFromInvalidMessages(onResults)
: onResults;
if (this._middleware.execute) {
this._middleware.execute(this._nextAsPluginType, code, safeOnResults);
} else {
this._next.execute(code, safeOnResults);
}
}
complete(code: string, onResults: ResultsCallback): void {
const safeOnResults =
this._middleware.complete || this._next instanceof KernelTransport
? protectFromInvalidMessages(onResults)
: onResults;
if (this._middleware.complete) {
this._middleware.complete(this._nextAsPluginType, code, safeOnResults);
} else {
this._next.complete(code, safeOnResults);
}
}
inspect(code: string, cursorPos: number, onResults: ResultsCallback): void {
const safeOnResults =
this._middleware.inspect || this._next instanceof KernelTransport
? protectFromInvalidMessages(onResults)
: onResults;
if (this._middleware.inspect) {
this._middleware.inspect(
this._nextAsPluginType,
code,
cursorPos,
safeOnResults
);
} else {
this._next.inspect(code, cursorPos, safeOnResults);
}
}
}
export default class Kernel {
@observable
inspector = {
bundle: {},
};
outputStore = new OutputStore();
watchesStore: WatchesStore;
watchCallbacks: Array<(...args: Array<any>) => any> = [];
emitter = new Emitter();
pluginWrapper: HydrogenKernel | null = null;
transport: KernelTransport;
// Invariant: the `._next` of each entry in this array must point to the next
// element of the array. The `._next` of the last element must point to
// `this.transport`.
middleware: Array<MiddlewareAdapter>;
constructor(kernel: KernelTransport) {
this.transport = kernel;
this.watchesStore = new WatchesStore(this);
// A MiddlewareAdapter that forwards all requests to `this.transport`.
// Needed to terminate the middleware chain in a way such that the `next`
// object passed to the last middleware is not the KernelTransport instance
// itself (which would be violate isolation of internals from plugins).
const delegateToTransport = new MiddlewareAdapter({}, this.transport);
this.middleware = [delegateToTransport];
}
get kernelSpec(): JupyterlabKernel.ISpecModel | KernelspecMetadata {
return this.transport.kernelSpec;
}
get grammar(): Grammar {
return this.transport.grammar;
}
get language(): string {
return this.transport.language;
}
get displayName(): string {
return this.transport.displayName;
}
get firstMiddlewareAdapter(): MiddlewareAdapter {
return this.middleware[0];
}
addMiddleware(middleware: HydrogenKernelMiddleware) {
this.middleware.unshift(
new MiddlewareAdapter(middleware, this.middleware[0])
);
}
@computed
get executionState(): string {
return this.transport.executionState;
}
setExecutionState(state: string) {
this.transport.setExecutionState(state);
}
@computed
get executionCount(): number {
return this.transport.executionCount;
}
setExecutionCount(count: number) {
this.transport.setExecutionCount(count);
}
@computed
get lastExecutionTime(): string {
return this.transport.lastExecutionTime;
}
setLastExecutionTime(timeString: string) {
this.transport.setLastExecutionTime(timeString);
}
@action
async setInspectorResult(
bundle: Record<string, any>,
editor: TextEditor | null | undefined
) {
if (isEqual(this.inspector.bundle, bundle)) {
await atom.workspace.toggle(INSPECTOR_URI);
} else if (bundle.size !== 0) {
this.inspector.bundle = bundle;
await atom.workspace.open(INSPECTOR_URI, {
searchAllPanes: true,
});
}
focus(editor);
}
getPluginWrapper() {
if (!this.pluginWrapper) {
this.pluginWrapper = new HydrogenKernel(this);
}
return this.pluginWrapper;
}
addWatchCallback(watchCallback: (...args: Array<any>) => any) {
this.watchCallbacks.push(watchCallback);
}
interrupt() {
this.firstMiddlewareAdapter.interrupt();
}
shutdown() {
this.firstMiddlewareAdapter.shutdown();
}
restart(onRestarted?: ((...args: Array<any>) => any) | null | undefined) {
this.firstMiddlewareAdapter.restart(onRestarted);
this.setExecutionCount(0);
this.setLastExecutionTime("No execution");
}
execute(code: string, onResults: (...args: Array<any>) => any) {
const wrappedOnResults = this._wrapExecutionResultsCallback(onResults);
this.firstMiddlewareAdapter.execute(
code,
(message: Message, channel: string) => {
wrappedOnResults(message, channel);
const { msg_type } = message.header;
if (msg_type === "execute_input") {
this.setLastExecutionTime("Running ...");
}
if (msg_type === "execute_reply") {
const count = message.content.execution_count;
this.setExecutionCount(count);
const timeString = executionTime(message);
this.setLastExecutionTime(timeString);
}
const { execution_state } = message.content;
if (
channel == "iopub" &&
msg_type === "status" &&
execution_state === "idle"
) {
this._callWatchCallbacks();
}
}
);
}
executeWatch(code: string, onResults: (...args: Array<any>) => any) {
this.firstMiddlewareAdapter.execute(
code,
this._wrapExecutionResultsCallback(onResults)
);
}
_callWatchCallbacks() {
this.watchCallbacks.forEach((watchCallback) => watchCallback());
}
/*
* Takes a callback that accepts execution results in a hydrogen-internal
* format and wraps it to accept Jupyter message/channel pairs instead.
* Kernels and plugins all operate on types specified by the Jupyter messaging
* protocol in order to maximize compatibility, but hydrogen internally uses
* its own types.
*/
_wrapExecutionResultsCallback(onResults: (...args: Array<any>) => any) {
return (message: Message, channel: string) => {
if (channel === "shell") {
const { status } = message.content;
if (status === "error" || status === "ok") {
onResults({
data: status,
stream: "status",
});
} else {
log("Kernel: ignoring unexpected value for message.content.status");
}
} else if (channel === "iopub") {
if (message.header.msg_type === "execute_input") {
onResults({
data: message.content.execution_count,
stream: "execution_count",
});
}
// TODO(nikita): Consider converting to V5 elsewhere, so that plugins
// never have to deal with messages in the V4 format
const result = msgSpecToNotebookFormat(msgSpecV4toV5(message));
onResults(result);
} else if (channel === "stdin") {
if (message.header.msg_type !== "input_request") {
return;
}
const { prompt, password } = message.content;
// TODO(nikita): perhaps it would make sense to install middleware for
// sending input replies
const inputView = new InputView(
{
prompt,
password,
},
(input: string) => this.transport.inputReply(input)
);
inputView.attach();
}
};
}
complete(code: string, onResults: (...args: Array<any>) => any) {
this.firstMiddlewareAdapter.complete(
code,
(message: Message, channel: string) => {
if (channel !== "shell") {
log("Invalid reply: wrong channel");
return;
}
onResults(message.content);
}
);
}
inspect(
code: string,
cursorPos: number,
onResults: (...args: Array<any>) => any
) {
this.firstMiddlewareAdapter.inspect(
code,
cursorPos,
(message: Message, channel: string) => {
if (channel !== "shell") {
log("Invalid reply: wrong channel");
return;
}
onResults({
data: message.content.data,
found: message.content.found,
});
}
);
}
destroy() {
log("Kernel: Destroying");
// This is for cleanup to improve performance
this.watchesStore.destroy();
store.deleteKernel(this);
this.transport.destroy();
if (this.pluginWrapper) {
this.pluginWrapper.destroyed = true;
}
this.emitter.emit("did-destroy");
this.emitter.dispose();
}
} | the_stack |
Components.utils.import('resource://gre/modules/AddonManager.jsm')
declare const AddonManager: any
declare const Zotero: IZotero
declare const Components: any
declare const ZoteroPane: any
import { patch as $patch$ } from './monkey-patch'
import { debug } from './debug'
import { htmlencode, plaintext, getField } from './util'
interface Tallies {
doi: string
contrasting: number // NOTE: The API returns contradicting, we map this manually
mentioning: number
supporting: number
total: number
unclassified: number
citingPublications: number
}
const shortToLongDOIMap = {}
const longToShortDOIMap = {}
const usingXULTree = typeof Zotero.ItemTreeView !== 'undefined'
const MAX_DOI_BATCH_SIZE = 500 // tslint:disable-line:no-magic-numbers
function getDOI(doi, extra) {
if (doi) return doi.toLowerCase().trim()
if (!extra) return ''
const dois = extra.split('\n').map(line => line.match(/^DOI:\s*(.+)/i)).filter(line => line).map(line => line[1].trim())
return dois[0]?.toLowerCase().trim() || ''
}
function isShortDoi(doi) {
return doi.match(/10\/[^\s]*[^\s\.,]/)
}
async function getLongDoi(shortDoi) {
try {
if (!shortDoi) {
return ''
}
// If it starts with 10/, it is short
// otherwise, treat it as long and just return
shortDoi = shortDoi.toLowerCase().trim()
if (!isShortDoi(shortDoi)) {
// This is probably a long DOI then!
return shortDoi
}
if (shortDoi in shortToLongDOIMap) {
debug(`shortToLongDOIMap cache hit ${shortDoi}`)
return shortToLongDOIMap[shortDoi]
}
const res = await Zotero.HTTP.request('GET', `https://doi.org/api/handles/${shortDoi}`)
const doiRes = res?.response ? JSON.parse(res.response).values : []
const longDoi = (doiRes && doiRes.length && doiRes.length > 1) ? doiRes[1].data.value.toLowerCase().trim() : ''
if (!longDoi) {
debug(`Unable to resolve shortDoi ${shortDoi} to longDoi`)
// I guess just return the shortDoi for now...?
return shortDoi
}
// Use these to minimize API calls and easily go back and forth
shortToLongDOIMap[shortDoi] = longDoi
longToShortDOIMap[longDoi] = shortDoi
debug(`Converted shortDoi (${shortDoi}) to longDoi (${longDoi})`)
return longDoi
} catch (err) {
Zotero.logError(`ERR_getLongDoi(${shortDoi}): ${err}`)
return shortDoi
}
}
const itemTreeViewWaiting: Record<string, boolean> = {}
const sciteItemCols = new Set(['zotero-items-column-supporting', 'zotero-items-column-contrasting', 'zotero-items-column-mentioning', 'zotero-items-column-total', 'zotero-items-column-citingPublications'])
function getCellX(tree, row, col, field) {
if (usingXULTree && !sciteItemCols.has(col.id)) return ''
if (!usingXULTree && !sciteItemCols.has(col.dataKey)) return ''
const key = usingXULTree ? col.id.split('-').pop() : col.dataKey.split('-').pop()
const item = tree.getRow(row).ref
if (item.isNote() || item.isAttachment()) return ''
if (Scite.ready.isPending()) { // tslint:disable-line:no-use-before-declare
const id = `${field}.${item.id}`
if (!itemTreeViewWaiting[id]) {
// tslint:disable-next-line:no-use-before-declare
if (usingXULTree) {
Scite.ready.then(() => tree._treebox.invalidateCell(row, col))
} else {
Scite.ready.then(() => tree.tree.invalidateRow(row))
}
itemTreeViewWaiting[id] = true
}
switch (field) {
case 'image':
return 'chrome://zotero-scite/skin/loading.jpg'
case 'properties':
return ' scite-state-loading'
case 'text':
return ''
}
}
const doi = getDOI(getField(item, 'DOI'), getField(item, 'extra'))
// This will work regardless of whether the doi is short or long, because the
// service will store them by both forms if it was originally a shortDOI.
const tallies = Scite.tallies[doi]
if (!tallies) {
debug(`No tallies found for ${doi}`)
}
const value = tallies ? tallies[key].toLocaleString() : '-'
switch (field) {
case 'text':
return value
case 'properties':
return ` scite-state-${key}`
}
}
const sciteColumns = [
{
dataKey: 'zotero-items-column-supporting',
label: 'Supporting',
flex: '1',
zoteroPersist: new Set(['width', 'hidden', 'sortDirection']),
},
{
dataKey: 'zotero-items-column-contrasting',
label: 'Contrasting',
flex: '1',
zoteroPersist: new Set(['width', 'hidden', 'sortDirection']),
},
{
dataKey: 'zotero-items-column-mentioning',
label: 'Mentioning',
flex: '1',
zoteroPersist: new Set(['width', 'hidden', 'sortDirection']),
},
{
dataKey: 'zotero-items-column-total',
label: 'Total Smart Citations',
flex: '1',
zoteroPersist: new Set(['width', 'hidden', 'sortDirection']),
},
{
dataKey: 'zotero-items-column-citingPublications',
label: 'Total Distinct Citing Publications',
flex: '1',
zoteroPersist: new Set(['width', 'hidden', 'sortDirection']),
},
]
if (usingXULTree) {
/**
* Backwards compatibility for the old XUL based tree, see:
* - https://github.com/scitedotai/scite-zotero-plugin/pull/26
* - https://groups.google.com/g/zotero-dev/c/yi4olucA_vY/m/pTY4QCzTAQAJ?pli=1
*/
$patch$(Zotero.ItemTreeView.prototype, 'getCellProperties', original => function Zotero_ItemTreeView_prototype_getCellProperties(row, col, prop) {
return (original.apply(this, arguments) + getCellX(this, row, col, 'properties')).trim()
})
$patch$(Zotero.ItemTreeView.prototype, 'getCellText', original => function Zotero_ItemTreeView_prototype_getCellText(row, col) {
if (!sciteItemCols.has(col.id)) return original.apply(this, arguments)
return getCellX(this, row, col, 'text')
})
} else {
/**
* If using a newer version of Zotero with HTML tree,
* patch using itemTree instead of itemTreeView.
*/
const itemTree = require('zotero/itemTree')
$patch$(itemTree.prototype, 'getColumns', original => function Zotero_ItemTree_prototype_getColumns() {
const columns = original.apply(this, arguments)
const insertAfter = columns.findIndex(column => column.dataKey === 'title')
columns.splice(insertAfter + 1, 0, ...sciteColumns)
return columns
})
$patch$(itemTree.prototype, '_renderCell', original => function Zotero_ItemTree_prototype_renderCell(index, data, column) {
if (!sciteItemCols.has(column.dataKey)) return original.apply(this, arguments)
if (Scite.ready.isPending()) {
const loadingIcon = document.createElementNS('http://www.w3.org/1999/xhtml', 'span')
loadingIcon.className = 'zotero-items-column-loading icon icon-bg cell-icon'
const loadingSpan = document.createElementNS('http://www.w3.org/1999/xhtml', 'span')
loadingSpan.className = `cell ${column.className} scite-cell`
loadingSpan.append(loadingIcon)
return loadingSpan
}
const icon = document.createElementNS('http://www.w3.org/1999/xhtml', 'span')
icon.className = `${column.dataKey} icon icon-bg cell-icon`
const textSpan = document.createElementNS('http://www.w3.org/1999/xhtml', 'span')
textSpan.className = 'cell-text'
textSpan.innerText = data
const span = document.createElementNS('http://www.w3.org/1999/xhtml', 'span')
span.className = `cell ${column.className} scite-cell`
span.append(icon, textSpan)
return span
})
}
$patch$(Zotero.Item.prototype, 'getField', original => function Zotero_Item_prototype_getField(field, unformatted, includeBaseMapped) {
try {
const colID = usingXULTree ? `zotero-items-column-${field}` : field
if (sciteItemCols.has(colID)) {
if (Scite.ready.isPending()) return '-' // tslint:disable-line:no-use-before-declare
const doi = getDOI(getField(this, 'DOI'), getField(this, 'extra'))
if (!doi || !Scite.tallies[doi]) return 0
const tallies = Scite.tallies[doi]
return tallies[field]
}
} catch (err) {
Zotero.logError(`err in scite patched getField: ${err}`)
return 0
}
return original.apply(this, arguments)
})
const ready = Zotero.Promise.defer()
class CScite { // tslint:disable-line:variable-name
public ready: any = ready.promise
public tallies: { [DOI: string]: Tallies } = {}
public uninstalled: boolean = false
private bundle: any
private started = false
constructor() {
this.bundle = Components.classes['@mozilla.org/intl/stringbundle;1'].getService(Components.interfaces.nsIStringBundleService).createBundle('chrome://zotero-scite/locale/zotero-scite.properties')
}
public async start() {
if (this.started) return
this.started = true
await Zotero.Schema.schemaUpdatePromise
await this.refresh()
ready.resolve(true)
Zotero.Notifier.registerObserver(this, ['item'], 'Scite', 1)
if (!usingXULTree) {
$patch$(Zotero.getActiveZoteroPane().itemsView, '_getRowData', original => function Zotero_ItemTree_prototype_getRowData(index) {
const row = original.apply(this, arguments)
for (const column of sciteColumns) {
row[column.dataKey] = getCellX(this, index, column, 'text')
}
return row
})
}
if (!usingXULTree) ZoteroPane.itemsView.refreshAndMaintainSelection()
}
public getString(name, params = {}, html = false) {
if (!this.bundle || typeof this.bundle.GetStringFromName !== 'function') {
Zotero.logError(`Scite.getString(${name}): getString called before strings were loaded`)
return name
}
let template = name
try {
template = this.bundle.GetStringFromName(name)
} catch (err) {
Zotero.logError(`Scite.getString(${name}): ${err}`)
}
const encode = html ? htmlencode : plaintext
return template.replace(/{{(.*?)}}/g, (match, param) => encode(params[param] || ''))
}
public async viewSciteReport(doi) {
try {
if (isShortDoi(doi)) {
doi = await getLongDoi(doi)
}
const zoteroPane = Zotero.getActiveZoteroPane()
zoteroPane.loadURI(`https://scite.ai/reports/${doi}`)
} catch (err) {
Zotero.logError(`Scite.viewSciteReport(${doi}): ${err}`)
alert(err)
}
}
public async refreshTallies(doi) {
try {
if (isShortDoi(doi)) {
doi = await getLongDoi(doi)
}
const data = await Zotero.HTTP.request('GET', `https://api.scite.ai/tallies/${doi.toLowerCase().trim()}`)
const tallies = data?.response
if (!tallies) {
Zotero.logError(`Scite.refreshTallies: No tallies found for: (${doi})`)
return {}
}
const tallyData = JSON.parse(tallies)
this.tallies[doi] = {
...tallyData,
contrasting: tallyData.contradicting,
}
// Also set it for the short DOI equivalent
const shortDoi = longToShortDOIMap[doi]
if (shortDoi) {
this.tallies[shortDoi] = {
...tallyData,
contrasting: tallyData.contradicting,
}
}
return tallyData
} catch (err) {
Zotero.logError(`Scite.refreshTallies(${doi}): ${err}`)
alert(err)
}
}
public async bulkRefreshDois(doisToFetch) {
try {
const res = await Zotero.HTTP.request('POST', 'https://api.scite.ai/tallies', {
body: JSON.stringify(doisToFetch.map(doi => doi.toLowerCase().trim())),
responseType: 'json',
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
})
const doiTallies = res?.response ? res.response.tallies : {}
for (const doi of Object.keys(doiTallies)) {
debug(`scite bulk DOI refresh: ${doi}`)
const tallies = doiTallies[doi]
this.tallies[doi] = {
...tallies,
contrasting: tallies.contradicting,
}
// Also set it for the short DOI equivalent if present
const shortDoi = longToShortDOIMap[doi]
if (shortDoi) {
this.tallies[shortDoi] = {
...tallies,
contrasting: tallies.contradicting,
}
}
}
} catch (err) {
Zotero.logError(`Scite.bulkRefreshDois(${doisToFetch}): ${err}`)
}
}
public async get(dois, options: { refresh?: boolean } = {}) {
let doisToFetch = options.refresh ? dois : dois.filter(doi => !this.tallies[doi])
doisToFetch = await Promise.all(doisToFetch.map(async doi => {
const longDoi = await getLongDoi(doi)
return longDoi
}))
const numDois = doisToFetch.length
if (!numDois) {
return
}
if (numDois <= MAX_DOI_BATCH_SIZE) {
await this.bulkRefreshDois(doisToFetch)
} else {
// Do them in chunks of MAX_DOI_BATCH_SIZE due to server limits
const chunks = []
let i = 0
while (i < numDois) {
chunks.push(doisToFetch.slice(i, i += MAX_DOI_BATCH_SIZE))
}
// Properly wait for each chunk to finish before returning!
await chunks.reduce(async (promise, chunk) => {
await promise
await this.bulkRefreshDois(chunk)
}, Promise.resolve())
}
return dois.map(doi => this.tallies[doi])
}
private async refresh() {
const query = `
SELECT DISTINCT fields.fieldName, itemDataValues.value
FROM fields
JOIN itemData on fields.fieldID = itemData.fieldID
JOIN itemDataValues on itemData.valueID = itemDataValues.valueID
WHERE fieldname IN ('extra', 'DOI')
`.replace(/[\s\n]+/g, ' ').trim()
let dois = []
for (const doi of await Zotero.DB.queryAsync(query)) {
switch (doi.fieldName) {
case 'extra':
dois = dois.concat(doi.value.split('\n').map(line => line.match(/^DOI:\s*(.+)/i)).filter(line => line).map(line => line[1].trim()))
break
case 'DOI':
dois.push(doi.value)
break
}
}
await this.get(dois, { refresh: true })
setTimeout(this.refresh.bind(this), 24 * 60 * 60 * 1000) // tslint:disable-line:no-magic-numbers
}
protected async notify(action, type, ids, extraData) {
if (type !== 'item' || (action !== 'modify' && action !== 'add')) return
const dois = []
for (const item of (await Zotero.Items.getAsync(ids))) {
const doi = getDOI(getField(item, 'DOI'), getField(item, 'extra'))
if (doi && !dois.includes(doi)) dois.push(doi)
}
// this list of dois can include a mix of short and long
if (dois.length) await this.get(dois)
}
}
const Scite = new CScite // tslint:disable-line:variable-name
// used in zoteroPane.ts
AddonManager.addAddonListener({
onUninstalling(addon, needsRestart) {
if (addon.id === 'scite@scite.ai') Scite.uninstalled = true
},
onDisabling(addon, needsRestart) { this.onUninstalling(addon, needsRestart) },
onOperationCancelled(addon, needsRestart) {
if (addon.id !== 'scite@scite.ai') return null
// tslint:disable-next-line:no-bitwise
if (addon.pendingOperations & (AddonManager.PENDING_UNINSTALL | AddonManager.PENDING_DISABLE)) return null
delete Zotero.Scite.uninstalled
},
})
export = Scite | the_stack |
import '../setup'
/* External Imports */
import * as assert from 'assert'
import { DB, newInMemoryDB } from '@pigi/core-db'
import {
bufToHexString,
ChecksumAgnosticIdentityVerifier,
NULL_ADDRESS,
} from '@pigi/core-utils'
/* Internal Imports */
import {
AGGREGATOR_ADDRESS,
ALICE_ADDRESS,
ALICE_GENESIS_STATE_INDEX,
BOB_ADDRESS,
UNISWAP_GENESIS_STATE_INDEX,
} from '../helpers'
import {
UNI_TOKEN_TYPE,
UNISWAP_ADDRESS,
PIGI_TOKEN_TYPE,
DefaultRollupStateValidator,
RollupStateValidator,
LocalFraudProof,
CreateAndTransferTransition,
StateSnapshot,
TransferTransition,
State,
SwapTransition,
RollupBlock,
ValidationOutOfOrderError,
AggregatorUnsupportedError,
ContractFraudProof,
DefaultRollupStateMachine,
} from '../../src'
/***********
* HELPERS *
***********/
const BOB_GENESIS_STATE_INDEX = 3
function getMultiBalanceGenesis(
aliceAddress: string = ALICE_ADDRESS,
bobAddress: string = BOB_ADDRESS
): State[] {
return [
{
pubkey: UNISWAP_ADDRESS,
balances: {
[UNI_TOKEN_TYPE]: 650_000,
[PIGI_TOKEN_TYPE]: 650_000,
},
},
{
pubkey: aliceAddress,
balances: {
[UNI_TOKEN_TYPE]: 5_000,
[PIGI_TOKEN_TYPE]: 5_000,
},
},
{
pubkey: AGGREGATOR_ADDRESS,
balances: {
[UNI_TOKEN_TYPE]: 1_000_000,
[PIGI_TOKEN_TYPE]: 1_000_000,
},
},
{
pubkey: bobAddress,
balances: {
[UNI_TOKEN_TYPE]: 5_000,
[PIGI_TOKEN_TYPE]: 5_000,
},
},
]
}
/*********
* TESTS *
*********/
describe('RollupStateValidator', () => {
let rollupGuard: DefaultRollupStateValidator
let stateDb: DB
beforeEach(async () => {
stateDb = newInMemoryDB()
const rollupStateMachine: DefaultRollupStateMachine = (await DefaultRollupStateMachine.create(
getMultiBalanceGenesis(),
stateDb,
AGGREGATOR_ADDRESS,
ChecksumAgnosticIdentityVerifier.instance()
)) as DefaultRollupStateMachine
rollupGuard = new DefaultRollupStateValidator(rollupStateMachine)
})
afterEach(async () => {
await stateDb.close()
})
describe('initialization', () => {
it('should create Guarder with a rollup machine', async () => {
rollupGuard.rollupMachine.should.not.be.undefined
})
})
describe('getInputStateSnapshots', () => {
it('should get right inclusion proof for a swap', async () => {
// pull initial root to compare later
const genesisStateRootBuf: Buffer = await rollupGuard.rollupMachine.getStateRoot()
const genesisStateRoot: string = bufToHexString(genesisStateRootBuf)
// construct a swap transition
const swapTransition: SwapTransition = {
stateRoot: 'DOESNT_MATTER',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
const snaps: StateSnapshot[] = await rollupGuard.getInputStateSnapshots(
swapTransition
)
// make sure the right root was pulled
snaps[0].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
snaps[1].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
// make sure the right pubkeys were pulled
snaps[0].state.pubkey.should.equal(ALICE_ADDRESS)
snaps[1].state.pubkey.should.equal(UNISWAP_ADDRESS)
})
it('should get right inclusion proof for a non creation transfer', async () => {
// pull initial root to compare later
const genesisStateRootBuf: Buffer = await rollupGuard.rollupMachine.getStateRoot()
const genesisStateRoot: string = bufToHexString(genesisStateRootBuf)
// construct a transfer transition
const transferTransition: TransferTransition = {
stateRoot: 'DOESNT_MATTER',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
amount: 10,
signature: ALICE_ADDRESS,
}
const snaps: StateSnapshot[] = await rollupGuard.getInputStateSnapshots(
transferTransition
)
// make sure the right root was pulled
snaps[0].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
snaps[1].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
// make sure the right pubkeys were pulled
snaps[0].state.pubkey.should.equal(ALICE_ADDRESS)
snaps[1].state.pubkey.should.equal(BOB_ADDRESS)
})
it('should get right inclusion proof for a createAndTransfer', async () => {
// pull initial root to compare later
const genesisStateRootBuf: Buffer = await rollupGuard.rollupMachine.getStateRoot()
const genesisStateRoot: string = bufToHexString(genesisStateRootBuf)
// construct a transfer transition
const creationTransition: CreateAndTransferTransition = {
stateRoot: 'DOESNT_MATTER',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: 40,
tokenType: UNI_TOKEN_TYPE,
amount: 10,
signature: ALICE_ADDRESS,
createdAccountPubkey: BOB_ADDRESS,
}
const snaps: StateSnapshot[] = await rollupGuard.getInputStateSnapshots(
creationTransition
)
// make sure the right root was pulled
snaps[0].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
snaps[1].stateRoot.should.equal(genesisStateRoot.replace('0x', ''))
// make sure the right pubkeys were pulled
snaps[0].state.pubkey.should.equal(ALICE_ADDRESS)
assert(
snaps[1].state.should.deep.equal({
pubkey: NULL_ADDRESS,
balances: { [UNI_TOKEN_TYPE]: 0, [PIGI_TOKEN_TYPE]: 0 },
}),
'Empty slot should give a default state.'
)
})
})
describe('checkNextTransition', () => {
it('should return no fraud if correct root for transfer', async () => {
// create a valid transfer from genesis
const transitionAliceToBob: TransferTransition = {
stateRoot:
'0x68cb03c6cace1db3a6f7e58db36e8e480ade32e1cba9451a0a63a750b8c48e1a',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
}
// test checking this individual transition
const res: LocalFraudProof = await rollupGuard.checkNextTransition(
transitionAliceToBob
)
assert(
res === undefined,
'Fraud should not be detected for this valid transition.'
)
})
it('should return no fraud if correct root for swap', async () => {
// create a valid swap from genesis
const transitionAliceSwap: SwapTransition = {
stateRoot:
'0x351f9762c0826a3c53eb990d3b69f6f27d6a8793b29f2edf825658065f7a991e',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
// test checking this individual transition
const res: LocalFraudProof = await rollupGuard.checkNextTransition(
transitionAliceSwap
)
assert(
res === undefined,
'Fraud should not be detected for this valid transition.'
)
})
it('should return no fraud if correct root for creation transition', async () => {
// create a valid create-and-transfer transition from genesis
const transitionAliceToCreatedBob: CreateAndTransferTransition = {
stateRoot:
'0x24a9c3fdd45a8fadb92d89ab74bb249edbe9a415f1d82a488c2efc5372979710',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: 4, // genesis fills first few
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
createdAccountPubkey: '0x0100000000000000000000000000000000000000',
}
// test checking this individual transition
const res: LocalFraudProof = await rollupGuard.checkNextTransition(
transitionAliceToCreatedBob
)
assert(
res === undefined,
'Fraud should not be detected for this valid transition.'
)
})
it('should return positive for fraud if transition has invalid root', async () => {
// create an invalid deadbeef post root transition
const transitionAliceSwap: SwapTransition = {
stateRoot:
'0xdeadbeefb833c9e1086ded944c9fbe011248203e586d81f9fe0922434632dcde',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
// test checking this individual transition
const res: LocalFraudProof = await rollupGuard.checkNextTransition(
transitionAliceSwap
)
res.should.not.equal(undefined)
})
it("should let us know we can't currently validate if accounts are not created sequentially", async () => {
// create a transition which we can't generate a fraud proof yet
const outOfOrderCreation: CreateAndTransferTransition = {
stateRoot:
'0x8bb6f1bd59e26928f8f1531af52224d59d76d6951db31c403bf1e215c99372e6',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: 300, // not suported yet, only sequential
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
createdAccountPubkey: '0x0100000000000000000000000000000000000000',
}
try {
await rollupGuard.checkNextTransition(outOfOrderCreation)
} catch (error) {
// Make sure we recognized the right error
error.should.be.instanceOf(AggregatorUnsupportedError)
return
}
false.should.equal(true) // we should never get here!
})
})
describe('checkNextBlock', () => {
it('should throw if it recieves blocks out of order', async () => {
// create a block with num =/= 0 which cannot be processed before 0-4
const blockNumber: number = 5
const wrongOrderBlock: RollupBlock = {
blockNumber,
transitions: undefined,
}
// store the block
await rollupGuard.storeBlock(wrongOrderBlock)
// try to validate it
try {
await rollupGuard.validateStoredBlock(blockNumber)
} catch (e) {
e.should.be.an.instanceOf(ValidationOutOfOrderError)
}
})
it('should successfully validate a send followed by a swap', async () => {
// create a svalid end
const transitionAliceToBob: TransferTransition = {
stateRoot:
'0x68cb03c6cace1db3a6f7e58db36e8e480ade32e1cba9451a0a63a750b8c48e1a',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
}
// create a valid swap
const transitionAliceSwap: SwapTransition = {
stateRoot:
'0x0ae582fd70c6fa55ced00cc5a7f5a0f0e0d68447ee7ece74d841548142ba9d32',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
// create the block
const blockNumber: number = 1
const sendThenSwapBlock: RollupBlock = {
blockNumber,
transitions: [transitionAliceToBob, transitionAliceSwap],
}
// store the block
await rollupGuard.storeBlock(sendThenSwapBlock)
// validate it
const res: ContractFraudProof = await rollupGuard.validateStoredBlock(
blockNumber
)
assert(
res === undefined,
'Fraud should not be detected for this valid transition.'
)
})
it('should successfully get a fraud proof for a valid transition followed by another with invalid root', async () => {
// create valid transition from genesis
const transitionAliceToBob: TransferTransition = {
stateRoot:
'0x68cb03c6cace1db3a6f7e58db36e8e480ade32e1cba9451a0a63a750b8c48e1a',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
}
// create transition with deadbeef post root
const transitionAliceSwap: SwapTransition = {
stateRoot:
'0xdeadbeef3b1531efd3fa80ce5698f5838e45c62efca5ecde0152f9b165ce6813',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
// create block
const blockNumber: number = 1
const sendThenSwapBlock: RollupBlock = {
blockNumber,
transitions: [transitionAliceToBob, transitionAliceSwap],
}
// store it
await rollupGuard.storeBlock(sendThenSwapBlock)
// check it, expecting fraud
const res: ContractFraudProof = await rollupGuard.validateStoredBlock(
blockNumber
)
res.should.not.equal(undefined)
})
it('should return a fraud proof for a block with an invalid initial tx', async () => {
// create a valid transaction for block 0
const transitionAliceToBob: TransferTransition = {
stateRoot:
'0x68cb03c6cace1db3a6f7e58db36e8e480ade32e1cba9451a0a63a750b8c48e1a',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
}
// create another valid transaction for block 0
const transitionAliceSwap: SwapTransition = {
stateRoot:
'0x0ae582fd70c6fa55ced00cc5a7f5a0f0e0d68447ee7ece74d841548142ba9d32',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
uniswapSlotIndex: UNISWAP_GENESIS_STATE_INDEX,
tokenType: UNI_TOKEN_TYPE,
inputAmount: 100,
minOutputAmount: 20,
timeout: 10,
signature: ALICE_ADDRESS,
}
// create valid block 0
const validFirstBlock: RollupBlock = {
blockNumber: 1,
transitions: [transitionAliceToBob, transitionAliceSwap],
}
// create an invalid state transition for block 1
const invalidSendTransition: TransferTransition = {
stateRoot:
'0xdeadbeef000000efd3fa80ce5698f5838e45c62efca5ecde0152f9b165ce6813',
senderSlotIndex: ALICE_GENESIS_STATE_INDEX,
recipientSlotIndex: BOB_GENESIS_STATE_INDEX,
tokenType: 0,
amount: 100,
signature: ALICE_ADDRESS,
}
// create invalid block 1
const invalidFirstTransitionBlock: RollupBlock = {
blockNumber: 2,
transitions: [
invalidSendTransition,
invalidSendTransition, // there could be multiple invalid transitions, but we need to confirm we get the first.
invalidSendTransition,
],
}
// store and validate the first valid block 0
await rollupGuard.storeBlock(validFirstBlock)
await rollupGuard.validateStoredBlock(1)
// store and validate the invalid block 1
await rollupGuard.storeBlock(invalidFirstTransitionBlock)
const res: ContractFraudProof = await rollupGuard.validateStoredBlock(2)
// Fraud roof should give last transition of block 0 and the first transition of block 1
res[0].inclusionProof.transitionIndex.should.equal(1)
res[0].inclusionProof.blockNumber.should.equal(1)
res[1].inclusionProof.transitionIndex.should.equal(0)
res[1].inclusionProof.blockNumber.should.equal(2)
})
})
}) | the_stack |
export function analyzeModuleSyntax (_str) {
str = _str;
let err = null;
try {
baseParse();
}
catch (e) {
err = e;
}
return [oImports, oExports, err];
}
// State:
// (for perf, works because this runs sync)
let i, charCode, str,
lastTokenIndex,
lastOpenTokenIndex,
lastTokenIndexStack,
dynamicImportStack,
braceDepth,
templateDepth,
templateStack,
oImports,
oExports;
function baseParse () {
lastTokenIndex = lastOpenTokenIndex = -1;
oImports = [];
oExports = [];
braceDepth = 0;
templateDepth = 0;
templateStack = [];
lastTokenIndexStack = [];
dynamicImportStack = [];
i = -1;
/*
* This is just the simple loop:
*
* while (charCode = str.charCodeAt(++i)) {
* // reads into the first non-ws / comment token
* commentWhitespace();
* // reads one token at a time
* parseNext();
* // stores the last (non ws/comment) token for division operator backtracking checks
* // (including on lastTokenIndexStack as we nest structures)
* lastTokenIndex = i;
* }
*
* Optimized by:
* - Inlining comment whitespace to avoid repeated "/" checks (minor perf saving)
* - Inlining the division operator check from "parseNext" into this loop
* - Having "regularExpression()" start on the initial index (different to other parse functions)
*/
while (charCode = str.charCodeAt(++i)) {
// reads into the first non-ws / comment token
if (isBrOrWs(charCode))
continue;
if (charCode === 47/*/*/) {
charCode = str.charCodeAt(++i);
if (charCode === 47/*/*/)
lineComment();
else if (charCode === 42/***/)
blockComment();
else {
/*
* Division / regex ambiguity handling
* based on checking backtrack analysis of:
* - what token came previously (lastTokenIndex)
* - what token came before the opening paren or brace (lastOpenTokenIndex)
*
* Only known unhandled ambiguities are cases of regexes immediately followed
* by division, another regex or brace:
*
* /regex/ / x
*
* /regex/
* {}
* /regex/
*
* And those cases only show errors when containing "'/` in the regex
*
* Could be fixed tracking stack of last regex, but doesn't seem worth it, and bad for perf
*/
const lastTokenCode = str.charCodeAt(lastTokenIndex);
if (!lastTokenCode || isExpressionKeyword(lastTokenIndex) ||
isExpressionPunctuator(lastTokenCode) ||
lastTokenCode === 41/*)*/ && isParenKeyword(lastOpenTokenIndex) ||
lastTokenCode === 125/*}*/ && isExpressionTerminator(lastOpenTokenIndex)) {
// TODO: perf improvement
// it may be possible to precompute isParenKeyword and isExpressionTerminator checks
// when they are added to the token stack, not here
// this way we only need to store a stack of "regexTokenDepthStack" and "regexTokenDepth"
// where depth is the combined brace and paren depth count
// when leaving a brace or paren, this stack would be cleared automatically (if a match)
// this check then becomes curDepth === regexTokenDepth for the lastTokenCode )|} case
regularExpression();
}
lastTokenIndex = i;
}
}
else {
parseNext();
lastTokenIndex = i;
}
}
if (braceDepth || templateDepth || lastTokenIndexStack.length)
syntaxError();
}
function parseNext () {
switch (charCode) {
case 123/*{*/:
// dynamic import followed by { is not a dynamic import (so remove)
// this is a sneaky way to get around { import () {} } v { import () } block / object ambiguity without a parser (assuming source is valid)
if (oImports.length && oImports[oImports.length - 1].d === lastTokenIndex)
oImports.pop();
braceDepth++;
// fallthrough
case 40/*(*/:
lastTokenIndexStack.push(lastTokenIndex);
return;
case 125/*}*/:
if (braceDepth-- === templateDepth) {
templateDepth = templateStack.pop();
templateString();
return;
}
if (braceDepth < templateDepth)
syntaxError();
// fallthrough
case 41/*)*/:
if (!lastTokenIndexStack)
syntaxError();
lastOpenTokenIndex = lastTokenIndexStack.pop();
if (dynamicImportStack.length && lastOpenTokenIndex == dynamicImportStack[dynamicImportStack.length - 1]) {
let imptIndex = oImports.length;
while (oImports[--imptIndex] && oImports[imptIndex].e > lastOpenTokenIndex);
imptIndex++;
oImports[imptIndex].d = lastTokenIndex + 1;
}
return;
case 39/*'*/:
singleQuoteString();
return;
case 34/*"*/:
doubleQuoteString();
return;
case 96/*`*/:
templateString();
return;
case 105/*i*/: {
if (readPrecedingKeyword(i + 5) !== 'import' || readToWsOrPunctuator(i + 6) !== '' && str.charCodeAt(i + 6) !== 46/*.*/)
return;
const start = i;
charCode = str.charCodeAt(i += 6);
commentWhitespace();
switch (charCode) {
// dynamic import
case 40/*(*/:
lastTokenIndexStack.push(start);
if (str.charCodeAt(lastTokenIndex) === 46/*.*/)
return;
// dynamic import indicated by positive d, which will be set to closing paren index
dynamicImportStack.push(start);
oImports.push({ s: start, e: i + 1, d: undefined });
return;
// import.meta
case 46/*.*/:
charCode = str.charCodeAt(++i);
commentWhitespace();
// import.meta indicated by d === -2
if (readToWsOrPunctuator(i) === 'meta' && str.charCodeAt(lastTokenIndex) !== 46/*.*/)
oImports.push({ s: start, e: i + 4, d: -2 });
return;
}
// import statement (only permitted at base-level)
if (lastTokenIndexStack.length === 0) {
readSourceString();
return;
}
}
case 101/*e*/: {
if (lastTokenIndexStack.length !== 0 || readPrecedingKeyword(i + 5) !== 'export' || readToWsOrPunctuator(i + 6) !== '')
return;
let name;
charCode = str.charCodeAt(i += 6);
commentWhitespace();
switch (charCode) {
// export default ...
case 100/*d*/:
oExports.push('default');
return;
// export async? function*? name () {
case 97/*a*/:
charCode = str.charCodeAt(i += 5);
commentWhitespace();
// fallthrough
case 102/*f*/:
charCode = str.charCodeAt(i += 8);
commentWhitespace();
if (charCode === 42/***/) {
charCode = str.charCodeAt(++i);
commentWhitespace();
}
oExports.push(readToWsOrPunctuator(i));
return;
case 99/*c*/:
if (readToWsOrPunctuator(i + 1) === 'lass') {
charCode = str.charCodeAt(i += 5);
commentWhitespace();
oExports.push(readToWsOrPunctuator(i));
return;
}
i += 2;
// fallthrough
// export var/let/const name = ...(, name = ...)+
case 118/*v*/:
case 108/*l*/:
/*
* destructured initializations not currently supported (skipped for { or [)
* also, lexing names after variable equals is skipped (export var p = function () { ... }, q = 5 skips "q")
*/
do {
charCode = str.charCodeAt(i += 3);
commentWhitespace();
name = readToWsOrPunctuator(i);
// stops on [ { destructurings
if (!name.length)
return;
oExports.push(name);
charCode = str.charCodeAt(i += name.length);
commentWhitespace();
} while (charCode === 44/*,*/);
return;
// export {...}
case 123/*{*/:
charCode = str.charCodeAt(++i);
commentWhitespace();
do {
name = readToWsOrPunctuator(i);
charCode = str.charCodeAt(i += name.length);
commentWhitespace();
// as
if (charCode === 97/*a*/) {
charCode = str.charCodeAt(i += 2);
commentWhitespace();
name = readToWsOrPunctuator(i);
charCode = str.charCodeAt(i += name.length);
commentWhitespace();
}
// ,
if (charCode === 44) {
charCode = str.charCodeAt(++i);
commentWhitespace();
}
oExports.push(name);
if (!charCode)
syntaxError();
} while (charCode !== 125/*}*/);
// fallthrough
// export *
case 42/***/:
charCode = str.charCodeAt(++i);
commentWhitespace();
if (charCode === 102 && str.slice(i + 1, i + 4) === 'rom') {
charCode = str.charCodeAt(i += 4);
readSourceString();
}
}
}
}
}
/*
* Helper functions
*/
// seeks through whitespace, comments and multiline comments
function commentWhitespace () {
do {
if (charCode === 47/*/*/) {
const nextCharCode = str.charCodeAt(i + 1);
if (nextCharCode === 47/*/*/) {
charCode = nextCharCode;
i++;
lineComment();
}
else if (nextCharCode === 42/***/) {
charCode = nextCharCode;
i++;
blockComment();
}
else {
return;
}
}
else if (!isBrOrWs(charCode)) {
return;
}
} while (charCode = str.charCodeAt(++i));
}
function templateString () {
while (charCode = str.charCodeAt(++i)) {
if (charCode === 36/*$*/) {
charCode = str.charCodeAt(++i);
if (charCode === 123/*{*/) {
templateStack.push(templateDepth);
templateDepth = ++braceDepth;
return;
}
}
else if (charCode === 96/*`*/) {
return;
}
else if (charCode === 92/*\*/) {
charCode = str.charCodeAt(++i);
}
}
syntaxError();
}
function readSourceString () {
let start;
do {
if (charCode === 39/*'*/) {
start = i + 1;
singleQuoteString();
oImports.push({ s: start, e: i, d: -1 });
return;
}
if (charCode === 34/*"*/) {
start = i + 1;
doubleQuoteString();
oImports.push({ s: start, e: i, d: -1 });
return;
}
} while (charCode = str.charCodeAt(++i))
syntaxError();
}
export function isWs () {
// Note there are even more than this - https://en.wikipedia.org/wiki/Whitespace_character#Unicode
return charCode === 32/* */ || charCode === 9/*\t*/ || charCode === 12/*\f*/ || charCode === 11/*\v*/ || charCode === 160/*\u00A0*/ || charCode === 65279/*\ufeff*/;
}
export function isBr () {
// (8232 <LS> and 8233 <PS> omitted for now)
return charCode === 10/*\n*/ || charCode === 13/*\r*/;
}
export function isBrOrWs (charCode) {
return charCode > 8 && charCode < 14 || charCode === 32 || charCode === 160 || charCode === 65279;
}
export function blockComment () {
charCode = str.charCodeAt(++i);
while (charCode) {
if (charCode === 42/***/) {
charCode = str.charCodeAt(++i);
if (charCode === 47/*/*/)
return;
continue;
}
charCode = str.charCodeAt(++i);
}
}
export function lineComment () {
while (charCode = str.charCodeAt(++i)) {
if (isBr())
return;
}
}
export function singleQuoteString () {
while (charCode = str.charCodeAt(++i)) {
if (charCode === 39/*'*/)
return;
if (charCode === 92/*\*/)
i++;
else if (isBr())
syntaxError();
}
syntaxError();
}
export function doubleQuoteString () {
while (charCode = str.charCodeAt(++i)) {
if (charCode === 34/*"*/)
return;
if (charCode === 92/*\*/)
i++;
else if (isBr())
syntaxError();
}
syntaxError();
}
export function regexCharacterClass () {
while (charCode = str.charCodeAt(++i)) {
if (charCode === 93/*]*/)
return;
if (charCode === 92/*\*/)
i++;
else if (isBr())
syntaxError();
}
syntaxError();
}
export function regularExpression () {
do {
if (charCode === 47/*/*/)
return;
if (charCode === 91/*[*/)
regexCharacterClass();
else if (charCode === 92/*\*/)
i++;
else if (isBr())
syntaxError();
} while (charCode = str.charCodeAt(++i));
syntaxError();
}
export function readPrecedingKeyword (endIndex) {
let startIndex = endIndex;
let nextChar = str.charCodeAt(startIndex);
while (nextChar && nextChar > 96/*a*/ && nextChar < 123/*z*/)
nextChar = str.charCodeAt(--startIndex);
// must be preceded by punctuator or whitespace
if (nextChar && !isBrOrWs(nextChar) && !isPunctuator(nextChar) || nextChar === 46/*.*/)
return '';
return str.slice(startIndex + 1, endIndex + 1);
}
export function readToWsOrPunctuator (startIndex) {
let endIndex = startIndex;
let nextChar = str.charCodeAt(endIndex);
while (nextChar && !isBrOrWs(nextChar) && !isPunctuator(nextChar))
nextChar = str.charCodeAt(++endIndex);
return str.slice(startIndex, endIndex);
}
const expressionKeywords = {
case: 1,
debugger: 1,
delete: 1,
do: 1,
else: 1,
in: 1,
instanceof: 1,
new: 1,
return: 1,
throw: 1,
typeof: 1,
void: 1,
yield: 1,
await: 1
};
export function isExpressionKeyword (lastTokenIndex) {
return expressionKeywords[readPrecedingKeyword(lastTokenIndex)];
}
export function isParenKeyword (lastTokenIndex) {
const precedingKeyword = readPrecedingKeyword(lastTokenIndex);
return precedingKeyword === 'while' || precedingKeyword === 'for' || precedingKeyword === 'if';
}
function isPunctuator (charCode) {
// 23 possible punctuator endings: !%&()*+,-./:;<=>?[]^{}|~
return charCode === 33 || charCode === 37 || charCode === 38 ||
charCode > 39 && charCode < 48 || charCode > 57 && charCode < 64 ||
charCode === 91 || charCode === 93 || charCode === 94 ||
charCode > 122 && charCode < 127;
}
export function isExpressionPunctuator (charCode) {
return isPunctuator(charCode) && charCode !== 93/*]*/ && charCode !== 41/*)*/ && charCode !== 125/*}*/;
}
export function isExpressionTerminator (lastTokenIndex) {
// detects:
// ; ) -1 finally
// as all of these followed by a { will indicate a statement brace
// in future we will need: "catch" (optional catch parameters)
// "do" (do expressions)
switch (str.charCodeAt(lastTokenIndex)) {
case 59/*;*/:
case 41/*)*/:
case NaN:
return true;
case 121/*y*/:
return readPrecedingKeyword(lastTokenIndex) === 'finally';
}
return false;
}
export function syntaxError () {
// we just need the stack
// this isn't shown to users, only for diagnostics
throw new Error();
} | the_stack |
import {
ArgumentValue,
CdmArgumentDefinition,
CdmCollection,
CdmConstantEntityDefinition,
CdmCorpusContext,
cdmDataFormat,
CdmEntityReference,
cdmLogCode,
CdmObject,
CdmObjectDefinition,
CdmObjectReference,
cdmObjectType,
CdmTraitCollection,
CdmTraitGroupReference,
CdmTraitReference,
CdmTypeAttributeDefinition,
constants,
Logger,
ResolvedTrait
} from '../internal';
const traitToListOfProperties: Map<string, string[]> =
new Map([
['is.CDM.entityVersion', ['version']],
['is.CDM.attributeGroup', ['cdmSchemas']],
['is.CDM.sourceNamed', ['sourceName']],
['is.localized.displayedAs', ['displayName']],
['is.localized.describedAs', ['description']],
['is.CDS.ordered', ['sourceOrdering']],
['is.readOnly', ['isReadOnly']],
['is.nullable', ['isNullable']],
['is.constrainedList', ['valueConstrainedToList']],
['is.constrained', ['maximumValue', 'minimumValue', 'maximumLength']]
]);
const dataFormatTraitNames: string[] = [
'is.dataFormat.integer',
'is.dataFormat.small',
'is.dataFormat.big',
'is.dataFormat.floatingPoint',
'is.dataFormat.guid',
'is.dataFormat.character',
'is.dataFormat.array',
'is.dataFormat.byte',
'is.dataFormat.time',
'is.dataFormat.date',
'is.dataFormat.timeOffset',
'is.dataFormat.boolean',
'is.dataFormat.numeric.shaped',
'means.content.text.JSON'
];
/**
* @internal
* attribute and entity traits that are represented as properties
* this entire class is gross. it is a different abstraction level than all of the rest of this om.
* however, it does make it easier to work with the consumption object model so ... i will hold my nose.
*/
export class traitToPropertyMap {
private TAG: string = traitToPropertyMap.name;
private host: CdmObject;
private get ctx(): CdmCorpusContext {
return this.host.ctx;
}
private get traits(): CdmTraitCollection {
if ('appliedTraits' in this.host) {
return (this.host as CdmObjectReference).appliedTraits;
}
if ('exhibitsTraits' in this.host) {
return (this.host as CdmObjectDefinition).exhibitsTraits;
}
}
constructor(host: CdmObject) {
this.host = host;
}
/**
* @internal
*/
public updatePropertyValue(propertyName: string, newValue: any | ArgumentValue | string[]): void {
const traitName: string = this.mapTraitName(propertyName);
const listOfProps: string[] = traitToListOfProperties.get(traitName);
const multipleProperties: boolean = listOfProps && listOfProps.length > 1;
if (newValue === undefined && !multipleProperties) {
this.removeTrait(traitName);
} else {
switch (propertyName) {
case 'version':
this.updateTraitArgument('is.CDM.entityVersion', 'versionNumber', newValue as ArgumentValue);
break;
case 'cdmSchemas':
this.updateSingleAttributeTraitTable('is.CDM.attributeGroup', 'groupList', 'attributeGroupSet', newValue as string[]);
break;
case 'sourceName':
this.updateTraitArgument('is.CDS.sourceNamed', 'name', newValue as ArgumentValue);
break;
case 'displayName':
this.constructLocalizedTraitTable('is.localized.displayedAs', newValue as string);
break;
case 'description':
this.constructLocalizedTraitTable('is.localized.describedAs', newValue as string);
break;
case 'sourceOrdering':
this.updateTraitArgument('is.CDS.ordered', 'ordinal', newValue.toString());
break;
case 'isPrimaryKey':
this.updateTraitArgument('is.identifiedBy', '', newValue);
break;
case 'isReadOnly':
this.mapBooleanTrait('is.readOnly', newValue as boolean);
break;
case 'isNullable':
this.mapBooleanTrait('is.nullable', newValue as boolean);
break;
case 'valueConstrainedToList':
this.mapBooleanTrait('is.constrainedList', newValue as boolean);
break;
case 'maximumValue':
this.updateTraitArgument('is.constrained', 'maximumValue', newValue as ArgumentValue);
break;
case 'minimumValue':
this.updateTraitArgument('is.constrained', 'minimumValue', newValue as ArgumentValue);
break;
case 'maximumLength':
this.updateTraitArgument('is.constrained', 'maximumLength', newValue !== undefined ? newValue.toString() : undefined);
break;
case 'dataFormat':
this.dataFormatToTraits(newValue);
break;
case 'defaultValue':
this.updateDefaultValue(newValue);
break;
default:
}
}
}
/**
* @internal
*/
public fetchPropertyValue(propertyName: string, fromProperty: boolean = false): ArgumentValue | string[] | number | boolean | any {
switch (propertyName) {
case 'version':
return this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.CDM.entityVersion', fromProperty), 'versionNumber');
case 'sourceName':
return this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.CDS.sourceNamed', fromProperty), 'name');
case 'displayName':
return this.fetchLocalizedTraitTable('is.localized.displayedAs', fromProperty);
case 'description':
return this.fetchLocalizedTraitTable('is.localized.describedAs', fromProperty);
case 'cdmSchemas':
return this.fetchSingleAttTraittable('is.CDM.attributeGroup', 'groupList', fromProperty);
case 'sourceOrdering':
return parseInt(this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.CDS.ordered', fromProperty), 'ordinal') as string, 10);
case 'isPrimaryKey':
if (this.host instanceof CdmTypeAttributeDefinition) {
const typeAttribute: CdmTypeAttributeDefinition = this.host;
if (!fromProperty && typeAttribute.purpose && typeAttribute.purpose.namedReference === 'identifiedBy') {
return true;
}
}
return this.fetchTraitReference('is.identifiedBy', fromProperty) !== undefined;
case 'isNullable':
return this.fetchTraitReference('is.nullable', fromProperty) !== undefined;
case 'isReadOnly':
return this.fetchTraitReference('is.readOnly', fromProperty) !== undefined;
case 'isResolved':
const trait = this.fetchTraitReference('has.entitySchemaAbstractionLevel', fromProperty)
return trait?.arguments?.fetchValue('level') === 'resolved'
case 'valueConstrainedToList':
return this.fetchTraitReference('is.constrainedList', fromProperty) !== undefined;
case 'maximumValue':
return this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.constrained', fromProperty), 'maximumValue');
case 'minimumValue':
return this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.constrained', fromProperty), 'minimumValue');
case 'maximumLength':
const temp: string = this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.constrained', fromProperty), 'maximumLength') as string;
if (temp !== undefined) {
return parseInt(temp, 10);
}
break;
case 'dataFormat':
return this.traitsToDataFormat(fromProperty);
case 'primaryKey':
const attRef: ArgumentValue = this.fetchTraitReferenceArgumentValue(this.fetchTraitReference('is.identifiedBy', fromProperty), 'attribute');
if (attRef) {
if (typeof attRef === 'string' || attRef instanceof String) {
return attRef;
}
return (attRef as CdmObject).fetchObjectDefinitionName();
}
break;
case 'defaultValue':
return this.fetchDefaultValue(fromProperty);
case 'isIncremental':
return this.fetchTraitReference(constants.INCREMENTAL_TRAIT_NAME) !== undefined;
default:
}
}
/**
* @internal
*/
public fetchTraitReference(traitName: string, fromProperty: boolean = false): CdmTraitReference {
const traitIndex: number = this.traits === undefined ? -1 : this.traits.indexOf(traitName, fromProperty);
return traitIndex !== -1 ? this.traits.allItems[traitIndex] as CdmTraitReference : undefined;
}
/**
* @internal
*/
public removeTrait(traitName: string): void {
this.traits.remove(traitName, true);
}
/**
* @internal
*/
public mapBooleanTrait(traitName: string, value: boolean): void {
if (value === true) {
this.fetchOrCreateTrait(traitName, true);
} else {
this.removeTrait(traitName);
}
}
/**
* @internal
*/
public dataFormatToTraits(dataFormat: cdmDataFormat): void {
// reset the current dataFormat
for (const traitName of dataFormatTraitNames) {
this.removeTrait(traitName);
}
switch (dataFormat) {
case cdmDataFormat.int16:
this.fetchOrCreateTrait('is.dataFormat.integer', true);
this.fetchOrCreateTrait('is.dataFormat.small', true);
break;
case cdmDataFormat.int32:
this.fetchOrCreateTrait('is.dataFormat.integer', true);
break;
case cdmDataFormat.int64:
this.fetchOrCreateTrait('is.dataFormat.integer', true);
this.fetchOrCreateTrait('is.dataFormat.big', true);
break;
case cdmDataFormat.float:
this.fetchOrCreateTrait('is.dataFormat.floatingPoint', true);
break;
case cdmDataFormat.double:
this.fetchOrCreateTrait('is.dataFormat.floatingPoint', true);
this.fetchOrCreateTrait('is.dataFormat.big', true);
break;
case cdmDataFormat.guid:
this.fetchOrCreateTrait('is.dataFormat.guid', true);
this.fetchOrCreateTrait('is.dataFormat.character', true);
this.fetchOrCreateTrait('is.dataFormat.array', true);
break;
case cdmDataFormat.string:
this.fetchOrCreateTrait('is.dataFormat.character', true);
this.fetchOrCreateTrait('is.dataFormat.array', true);
break;
case cdmDataFormat.char:
this.fetchOrCreateTrait('is.dataFormat.character', true);
this.fetchOrCreateTrait('is.dataFormat.big', true);
break;
case cdmDataFormat.byte:
this.fetchOrCreateTrait('is.dataFormat.byte', true);
break;
case cdmDataFormat.binary:
this.fetchOrCreateTrait('is.dataFormat.byte', true);
this.fetchOrCreateTrait('is.dataFormat.array', true);
break;
case cdmDataFormat.time:
this.fetchOrCreateTrait('is.dataFormat.time', true);
break;
case cdmDataFormat.date:
this.fetchOrCreateTrait('is.dataFormat.date', true);
break;
case cdmDataFormat.dateTime:
this.fetchOrCreateTrait('is.dataFormat.time', true);
this.fetchOrCreateTrait('is.dataFormat.date', true);
break;
case cdmDataFormat.dateTimeOffset:
this.fetchOrCreateTrait('is.dataFormat.time', true);
this.fetchOrCreateTrait('is.dataFormat.date', true);
this.fetchOrCreateTrait('is.dataFormat.timeOffset', true);
break;
case cdmDataFormat.boolean:
this.fetchOrCreateTrait('is.dataFormat.boolean', true);
break;
case cdmDataFormat.decimal:
this.fetchOrCreateTrait('is.dataFormat.numeric.shaped', true);
break;
case cdmDataFormat.json:
this.fetchOrCreateTrait('is.dataFormat.array', true);
this.fetchOrCreateTrait('means.content.text.JSON', true);
break;
default:
}
}
/**
* @internal
*/
public mapTraitName(propertyName: string): string {
switch (propertyName) {
case 'version':
return 'is.CDM.entityVersion';
case 'cdmSchemas':
return 'is.CDM.attributeGroup';
case 'sourceName':
return 'is.CDS.sourceNamed';
case 'displayName':
return 'is.localized.displayedAs';
case 'description':
return 'is.localized.describedAs';
case 'sourceOrdering':
return 'is.CDS.ordered';
case 'isPrimaryKey':
return 'is.identifiedBy';
case 'isReadOnly':
return 'is.readOnly';
case 'isNullable':
return 'is.nullable';
case 'valueConstrainedToList':
return 'is.constrainedList';
case 'maximumValue':
case 'minimumValue':
case 'maximumLength':
return 'is.constrained';
default:
return propertyName;
}
}
/**
* @internal
*/
public traitsToDataFormat(onlyFromProperty: boolean = false): cdmDataFormat {
let isArray: boolean = false;
let isBig: boolean = false;
let isSmall: boolean = false;
let isInteger: boolean = false;
let probablyJson: boolean = false;
if (!this.traits) {
return undefined;
}
let baseType: cdmDataFormat = 0;
for (const trait of this.traits) {
if (onlyFromProperty &&
(trait instanceof CdmTraitGroupReference || !(trait as CdmTraitReference).isFromProperty)) {
continue;
}
const traitName: string = trait.fetchObjectDefinitionName();
// tslint:disable:switch-default
switch (traitName) {
case 'is.dataFormat.array':
isArray = true;
break;
case 'is.dataFormat.big':
isBig = true;
break;
case 'is.dataFormat.small':
isSmall = true;
break;
case 'is.dataFormat.integer':
isInteger = true;
break;
case 'is.dataFormat.floatingPoint':
baseType = cdmDataFormat.float;
break;
case 'is.dataFormat.character':
baseType = baseType !== cdmDataFormat.guid ? cdmDataFormat.char : baseType;
break;
case 'is.dataFormat.byte':
baseType = cdmDataFormat.byte;
break;
case 'is.dataFormat.date':
baseType = baseType === cdmDataFormat.time ? cdmDataFormat.dateTime : cdmDataFormat.date;
break;
case 'is.dataFormat.time':
baseType = baseType === cdmDataFormat.date ? cdmDataFormat.dateTime : cdmDataFormat.time;
break;
case 'is.dataFormat.timeOffset':
baseType = baseType === cdmDataFormat.dateTime ? cdmDataFormat.dateTimeOffset : baseType;
break;
case 'is.dataFormat.boolean':
baseType = cdmDataFormat.boolean;
break;
case 'is.dataFormat.numeric.shaped':
baseType = cdmDataFormat.decimal;
break;
case 'is.dataFormat.guid':
baseType = cdmDataFormat.guid;
break;
case 'means.content.text.JSON':
baseType = isArray ? cdmDataFormat.json : cdmDataFormat.unknown;
probablyJson = true;
}
}
if (isArray) {
if (probablyJson) {
baseType = cdmDataFormat.json;
} else if (baseType === cdmDataFormat.char) {
baseType = cdmDataFormat.string;
} else if (baseType === cdmDataFormat.byte) {
baseType = cdmDataFormat.binary;
} else if (baseType !== cdmDataFormat.guid) {
baseType = cdmDataFormat.unknown;
}
}
if (baseType === cdmDataFormat.float && isBig) {
baseType = cdmDataFormat.double;
}
if (isInteger && isBig) {
baseType = cdmDataFormat.int64;
} else if (isInteger && isSmall) {
baseType = cdmDataFormat.int16;
} else if (isInteger) {
baseType = cdmDataFormat.int32;
}
return baseType;
}
/**
* @internal
*/
public fetchOrCreateTrait(traitName: string, simpleRef: boolean = false): CdmTraitReference {
let trait: CdmTraitReference = this.fetchTraitReference(traitName, true);
if (!trait) {
trait = this.ctx.corpus.MakeObject<CdmTraitReference>(cdmObjectType.traitRef, traitName);
this.traits.push(trait);
trait.isFromProperty = true;
}
return trait;
}
/**
* @internal
*/
public updateTraitArgument(traitName: string, argName: string, value: ArgumentValue): void {
const trait: CdmTraitReference = this.fetchOrCreateTrait(traitName, false);
const args: CdmCollection<CdmArgumentDefinition> = trait.arguments;
if (!args || !args.length) {
if (value !== undefined) {
trait.arguments.push(argName, value);
return;
} else {
this.removeTrait(traitName);
}
} else {
for (const arg of args) {
if (arg.getName() === argName) {
if (!value) {
args.remove(arg);
if (trait.arguments && trait.arguments.length === 0) {
this.removeTrait(traitName);
}
} else {
arg.setValue(value);
}
return;
}
}
}
if (value !== undefined) {
trait.arguments.push(argName, value);
}
}
/**
* @internal
*/
public updateTraitTable(traitName: string, argName: string, entityName: string,
action: (cEnt: CdmConstantEntityDefinition, created: boolean) => void): void {
const resultantTrait: CdmTraitReference = this.fetchOrCreateTrait(traitName, false);
if (!resultantTrait.arguments || !resultantTrait.arguments.length) {
// make the argument nothing but a ref to a constant entity
// safe since there is only one param for the trait and it looks cleaner
const cEnt: CdmConstantEntityDefinition =
this.ctx.corpus.MakeObject<CdmConstantEntityDefinition>(cdmObjectType.constantEntityDef);
cEnt.setEntityShape(this.ctx.corpus.MakeRef(cdmObjectType.entityRef, entityName, true));
action(cEnt, true);
resultantTrait.arguments.push(argName, this.ctx.corpus.MakeRef<CdmEntityReference>(cdmObjectType.entityRef, cEnt, false));
} else {
const locEntRef: CdmObject = this.fetchTraitReferenceArgumentValue(resultantTrait, argName) as CdmObject;
if (locEntRef) {
const locEnt: CdmConstantEntityDefinition = locEntRef.fetchObjectDefinition(undefined);
if (locEnt) {
action(locEnt, false);
}
}
}
}
/**
* @internal
*/
public fetchTraitTable(traitName: string, argName: string, fromProperty: boolean): CdmConstantEntityDefinition {
let trait: CdmTraitReference;
const traitIndex: number = this.traits.indexOf(traitName, fromProperty);
trait = traitIndex !== -1 ? this.traits.allItems[traitIndex] as CdmTraitReference : undefined;
const locEntRef: CdmObject = this.fetchTraitReferenceArgumentValue(trait, argName) as CdmObject;
if (locEntRef) {
return locEntRef.fetchObjectDefinition(undefined);
}
}
/**
* @internal
*/
public constructLocalizedTraitTable(traitName: string, sourceText: string): void {
this.updateTraitTable(
traitName,
'localizedDisplayText',
'localizedTable',
(cEnt: CdmConstantEntityDefinition, created: boolean) => {
if (created) {
cEnt.setConstantValues([['en', sourceText]]);
} else {
/**
* search for a match
* -1 or order gets us last row that matches. needed because inheritence
* chain with different descriptions stacks these up
* need to use ordinals because no binding done yet
*/
cEnt.updateConstantValue(undefined, 1, sourceText, 0, 'en', -1);
} // need to use ordinals because no binding done yet
});
}
/**
* @internal
*/
public fetchLocalizedTraitTable(traitName: string, fromProperty: boolean): string {
const cEnt: CdmConstantEntityDefinition = this.fetchTraitTable(traitName, 'localizedDisplayText', fromProperty);
if (cEnt) {
/**
* search for a match
* -1 or order gets us last row that matches. needed because inheritence
* chain with different descriptions stacks these up
* need to use ordinals because no binding done yet
*/
return cEnt.fetchConstantValue(undefined, 1, 0, 'en', -1);
}
}
/**
* @internal
*/
public updateSingleAttributeTraitTable(traitName: string, argName: string, entityName: string, sourceText: string[]): void {
this.updateTraitTable(traitName, argName, entityName, (cEnt: CdmConstantEntityDefinition, created: boolean) => {
// turn array of strings into array of array of strings;
const vals: (string[])[] = [];
sourceText.forEach((v: string) => { const r: string[] = []; r.push(v); vals.push(r); });
cEnt.setConstantValues(vals);
});
}
/**
* @internal
*/
public fetchSingleAttTraittable(traitName: string, argName: string, fromProperty: boolean): string[] {
const cEnt: CdmConstantEntityDefinition = this.fetchTraitTable(traitName, argName, fromProperty);
if (cEnt) {
// turn array of arrays into single array of strings
const result: (string)[] = [];
cEnt.getConstantValues()
.forEach((v: string[]) => { result.push(v[0]); });
return result;
}
}
/**
* @internal
*/
public fetchDefaultValue(fromProperty: boolean): any {
const trait: CdmTraitReference = this.fetchTraitReference('does.haveDefault', fromProperty);
if (trait) {
let defVal: any = this.fetchTraitReferenceArgumentValue(trait, 'default');
if (defVal !== undefined) {
if (typeof (defVal) === 'string') {
return defVal;
}
if (defVal.getObjectType() === cdmObjectType.entityRef) {
// no doc or directives should work ?
const cEnt: CdmConstantEntityDefinition = defVal.fetchObjectDefinition() as CdmConstantEntityDefinition;
if (cEnt) {
const esName: string = cEnt.getEntityShape()
.fetchObjectDefinitionName();
const corr: boolean = esName === 'listLookupCorrelatedValues';
const lookup: boolean = esName === 'listLookupValues';
if (esName === 'localizedTable' || lookup || corr) {
const result: (object)[] = [];
const rawValues: string[][] = cEnt.getConstantValues();
if (rawValues) {
const l: number = rawValues.length;
for (let i: number = 0; i < l; i++) {
const row: any = {};
const rawRow: string[] = rawValues[i];
if (rawRow.length === 2 || (lookup && rawRow.length === 4) || (corr && rawRow.length === 5)) {
row.languageTag = rawRow[0] !== undefined ? rawRow[0] : null;
row.displayText = rawRow[1] !== undefined ? rawRow[1] : null;
if (lookup || corr) {
row.attributeValue = rawRow[2] !== undefined ? rawRow[2] : null;
row.displayOrder = rawRow[3] !== undefined ? rawRow[3] : null;
if (corr) {
row.correlatedValue = rawRow[4] !== undefined ? rawRow[4] : null;
}
}
}
result.push(row);
}
return result;
}
} else {
// an unknown entity shape. only thing to do is serialize the object
defVal = defVal.copyData(undefined, undefined);
}
}
} else {
// is it a cdm object?
if (defVal.getObjectType !== undefined) {
defVal = defVal.copyData(undefined, undefined);
}
}
}
return defVal;
}
}
/**
* @internal
*/
public updateDefaultValue(newDefault: any): void {
if (newDefault instanceof Array) {
const a: any[] = newDefault;
const l: number = a.length;
if (l && a[0].languageTag !== undefined && a[0].displayText !== undefined) {
// looks like something we understand
const tab: (string[])[] = [];
const corr: boolean = (a[0].correlatedValue !== undefined);
const lookup: boolean = (a[0].displayOrder !== undefined && a[0].attributeValue !== undefined);
for (let i: number = 0; i < l; i++) {
const row: (string)[] = [];
row.push(a[i].languageTag);
row.push(a[i].displayText);
if (lookup || corr) {
row.push(a[i].attributeValue);
row.push(a[i].displayOrder);
if (corr) {
row.push(a[i].correlatedValue);
}
}
tab.push(row);
}
const cEnt: CdmConstantEntityDefinition =
this.ctx.corpus.MakeObject<CdmConstantEntityDefinition>(cdmObjectType.constantEntityDef);
cEnt.setEntityShape(
this.ctx.corpus.MakeRef(cdmObjectType.entityRef, corr ? 'listLookupCorrelatedValues' : 'listLookupValues', true));
cEnt.setConstantValues(tab);
newDefault = this.ctx.corpus.MakeRef(cdmObjectType.entityRef, cEnt, false);
this.updateTraitArgument('does.haveDefault', 'default', newDefault);
} else {
Logger.error(this.host.ctx, this.TAG, this.updateDefaultValue.name, null, cdmLogCode.ErrValdnMissingLanguageTag);
}
} else {
Logger.error(this.host.ctx, this.TAG, this.updateDefaultValue.name, null, cdmLogCode.ErrUnsupportedType);
}
}
private fetchTraitReferenceArgumentValue(tr: CdmTraitReference | ResolvedTrait, argName: string): ArgumentValue {
{
if (tr) {
let av: ArgumentValue;
if ((tr as ResolvedTrait).parameterValues) {
av = (tr as ResolvedTrait).parameterValues.fetchParameterValueByName(argName).value;
} else {
av = (tr as CdmTraitReference).arguments.fetchValue(argName);
}
return av;
}
}
}
} | the_stack |
import * as pathLib from "path";
import * as fs from "fs";
import { ACEngineManager } from "../ACEngineManager";
import { IConfigUnsupported } from "../api/IChecker";
import { IScanSummary } from "./ReportUtil";
import { genReport } from "./genReport";
declare var after;
/**
* This function is responsible for constructing the aChecker Reporter which will be used to, report
* the scan results, such as writing the page results and the summary to a HTML file. This reporter function
* is registered with Karma server and triggered based on events that are triggered by the karma communication.
*
* @param {Object} baseReporterDecorator - the base karma reporter, which had the base functions which we override
* @param {Object} this.Config - All the Karma this.Configuration, we will extract what we need from this over
* all object, we need the entire object so that we detect any changes in the object
* as other plugins are loaded and the object is updated dynamically.
* @param {Object} logger - logger object which is used to log debug/error/info messages
* @param {Object} emitter - emitter object which allows to listem on any event that is triggered and allow to execute
* custom code, to handle the event that was triggered.
*
* @return - N/A
*
* @memberOf this
*/
export class ACReporterHTML {
Config: IConfigUnsupported;
scanSummary: IScanSummary
constructor(config: IConfigUnsupported, scanSummary: IScanSummary) {
this.scanSummary = scanSummary;
this.Config = config;
this.Config.DEBUG && console.log("START ACReporter Constructor");
let myThis = this;
if (typeof(after) !== "undefined") {
after(function(done) {
myThis.onRunComplete();
done && done();
});
} else {
process.on('beforeExit', function() {
myThis.onRunComplete();
});
}
this.Config.DEBUG && console.log("END ACReporter Constructor");
}
// This emitter function is responsible for calling this function when the info event is detected
report(info) {
this.Config.DEBUG && console.log("START 'info' emitter function");
// Save the results of a single scan to a HTML file based on the label provided
this.savePageResults(info);
// Update the overall summary object count object to include the new scan that was performed
this.addToSummaryCount(info.summary.counts);
// Save the summary of this scan into global space of this reporter, to be logged
// once the whole scan is done.
this.addResultsToGlobal(info);
this.Config.DEBUG && console.log("END 'info' emitter function");
};
/**
* This function is responsible for performing any action when the entire karma run is done.
* Overrides onRunComplete function from baseReporterDecorator
*
* @override
*
* @memberOf this
*/
onRunComplete() {
this.Config.DEBUG && console.log("START 'ACReporterHTML:onRunComplete' function");
// Add End time when the whole karma run is done
// End time will be in milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now.
this.scanSummary.endReport = Date.now();
// Save summary object to a HTML file.
this.saveSummary(this.scanSummary);
this.Config.DEBUG && console.log("END 'ACReporterHTML:onRunComplete' function");
};
/**
* This function is responsible for indexing the results into global spaces based on label.
*
* @param {Object} results - Results object which will be provided to the user/wroten to the file.
* Refer to aChecker.buildReport function's return to figure out what the object
* will look like.
*
* @return - N/A - Global object is updated with the results
*
* @memberOf this
*/
addResultsToGlobal(results) {
this.Config.DEBUG && console.log("START 'addResultsToGlobal' function");
// Build the single page summary object to follow the following format:
// "label": "dependencies/tools-rules-html/v2/a11y/test/g471/Table-DataNoSummaryARIA.html",
// "counts": {
// "violation": 1,
// "potentialviolation": 0,
// "recommendation": 0,
// "potentialrecommendation": 0,
// "manual": 0
// }
let pageSummaryObject = {
label: results.label,
counts: results.summary.counts
}
this.Config.DEBUG && console.log("Adding following object to scanSummary.pageScanSummary: ");
this.Config.DEBUG && console.log(pageSummaryObject);
// Add the summary count for this scan to the pageScanSummary object which is in the global space
// Index this by the label.
this.scanSummary.pageScanSummary.push(pageSummaryObject);
this.Config.DEBUG && console.log("END 'addResultsToGlobal' function");
}
/**
* This function is responsible for updating/creating the global violation summary for the engine karma run
* for browser that it is running on. Will take the pageCount object which is part of the page object and
* add extract the values for each of the levels and add them to the global object. This will provide an overall
* summary of violations for all testcases run and all scans done.
*
* @param {Object} pageCount - Provide the page count object, in the following format:
*
* @return N/A - Global summary object is updated with the counts
*
* @memberOf this
*/
addToSummaryCount = function (pageCount) {
// Variable Decleration
let ACScanSummary = this.scanSummary.counts || {};
let addedToSummary = false;
// In the case ACScanSummary is empty, simply assign pageCount to ACScanSummary
if (Object.keys(ACScanSummary).length === 0) {
// Set pageCount as the summary count
ACScanSummary = pageCount;
addedToSummary = true;
}
// In the case that this is not first scan, handle adding up the summary
if (!addedToSummary) {
// Go through the pageCount object and for each of the levels, extract the value
// and add it to the aChecker violation summary object.
// This will keep track of an overall summary of the violations for all testscases, that
// were run for a single karma run.
for (let level in pageCount) {
ACScanSummary[level] += pageCount[level];
}
}
// Assign the new violation summary back to the global object
this.scanSummary.counts = ACScanSummary;
}
/**
* This function is responsible for saving a single scans results to a file as HTML. On a side note
* this function will also extract the label which will be the file names where the results will be
* saved.
*
* @param {Object} this.Config - Karma this.Config object, used to extrat the outputFolder from the ACthis.Config.
* @param {Object} results - Provide the scan results for a single page that should be saved.
*
* @memberOf this
*/
savePageResults(results) {
this.Config.DEBUG && console.log("START 'savePageResults' function");
// Extract the outputFolder from the ACthis.Config (this is the user this.Config that they provid)
let resultDir = this.Config.outputFolder;
this.Config.DEBUG && console.log("Results are going to be stored under results directory: \"" + resultDir + "\"");
// Build the full file name based on the label provide in the results and also the results dir specified in the
// this.Configuration.
let resultsFileName = pathLib.join(resultDir, results.label + '.html');
/**************************************************** DEBUG INFORMATION ***************************************************************
// Debug example which has label which has unix "/" in them.
let resultsFileName = pathLib.join(resultDir, "dependencies/tools-rules-html/v2/a11y/test/g471/Table-layoutMultiple.html.json");
// Debug example which has a label which has Windows "\" in them.
let resultsFileName = pathLib.join(resultDir, "dependencies\\tools-rules-html\\v2\\a11y\\test\\g471\\Table-layoutMultiple.html.json");
***************************************************************************************************************************************/
// Write the results object as HTML to a file.
this.writeObjectToFileAsHTML(resultsFileName, results);
this.Config.DEBUG && console.log("END 'savePageResults' function");
}
/**
* This function is responsible for converting a javascript object into HTML and then writing that to a
* json file.
*
* @param {String} fileName - Full path of file where the HTML object should be stored
* @param {String} content - The javascript object which should be converted and saved to file as HTML.
*
* @memberOf this
*/
writeObjectToFileAsHTML(fileName, content) {
const valueMap = {
"VIOLATION": {
"POTENTIAL": "Needs review",
"FAIL": "Violation",
"PASS": "Pass",
"MANUAL": "Needs review"
},
"RECOMMENDATION": {
"POTENTIAL": "Recommendation",
"FAIL": "Recommendation",
"PASS": "Pass",
"MANUAL": "Recommendation"
}
};
this.Config.DEBUG && console.log("START 'writeObjectToFileAsHTML' function");
// Extract the parent directory of the file name that is provided
let parentDir = pathLib.dirname(fileName);
this.Config.DEBUG && console.log("Parent Directoy: \"" + parentDir + "\"");
// In the case that the parent directoy does not exist, create the directories
if (!fs.existsSync(parentDir)) {
// Create the parent directory recerseivly if it does not exist.
fs.mkdirSync(parentDir, { recursive: true});
}
this.Config.DEBUG && console.log("Object will be written to file: \"" + fileName + "\"");
let outReport = {
report: {
timestamp: content.summary.startScan,
nls: content.nls,
results: content.results,
counts: {
total: {
All: 0
}
}
},
rulesets: ACEngineManager.getRulesets(),
tabURL: content.summary.URL
}
for (const item of content.results) {
let val = valueMap[item.value[0]][item.value[1]] || item.value[0] + "_" + item.value[1];
outReport.report.counts.total[val] = (outReport.report.counts.total[val] || 0) + 1;
++outReport.report.counts.total.All;
}
// Convert the Object into HTML string and write that to the file
// Make sure to use utf-8 encoding to avoid an issues specify to OS.
// In terms of the HTML string that is constructed use 4 spaces to format the HTML object, before
// writing it to the file.
fs.writeFileSync(fileName, genReport(outReport), { encoding: 'utf-8' });
this.Config.DEBUG && console.log("END 'writeObjectToFileAsHTML' function");
}
/**
* This function is responsible for saving the summary object of the while scan to a summary file.
*
* @param {Object} summary - The summary object that needs to be written to the summary file.
*
* @memberOf this
*/
saveSummary(summary) {
}
/**
* This function is responsible for checking if a number needs a leading 0, and if it is needed
* add the leading 0 and return that as the new number.
*
* @param {int} number - Provide a number to check if a leading 0 needs to be added or not.
*
* @return {String} number - Return the number with the leading 0 added back
*
* @memberOf this
*/
datePadding(number) {
this.Config.DEBUG && console.log("START 'datePadding' function");
// In the case that the number is less then 10 we need to add the leading '0' to the number.
number = number < 10 ? '0' + number : number;
this.Config.DEBUG && console.log("END 'datePadding' function");
return number;
}
}; | the_stack |
import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import dayjs from 'dayjs/esm';
import { ChangeDetectorRef, DebugElement } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgModel } from '@angular/forms';
import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap';
import { BehaviorSubject, of, Subject } from 'rxjs';
import * as ace from 'brace';
import { ArtemisTestModule } from '../../test.module';
import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';
import { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';
import { CommitState, DeleteFileChange, DomainType, EditorState, FileType, GitConflictState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';
import { buildLogs, extractedBuildLogErrors, extractedErrorFiles } from '../../helpers/sample/build-logs';
import { problemStatement } from '../../helpers/sample/problemStatement.json';
import { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service';
import { ProgrammingSubmissionService, ProgrammingSubmissionState, ProgrammingSubmissionStateObj } from 'app/exercises/programming/participate/programming-submission.service';
import { MockProgrammingSubmissionService } from '../../helpers/mocks/service/mock-programming-submission.service';
import { DeviceDetectorService } from 'ngx-device-detector';
import { GuidedTourService } from 'app/guided-tour/guided-tour.service';
import { GuidedTourMapping } from 'app/guided-tour/guided-tour-setting.model';
import { JhiWebsocketService } from 'app/core/websocket/websocket.service';
import { MockWebsocketService } from '../../helpers/mocks/service/mock-websocket.service';
import { Participation } from 'app/entities/participation/participation.model';
import { BuildLogEntryArray } from 'app/entities/build-log.model';
import { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service';
import { ResultService } from 'app/exercises/shared/result/result.service';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { Result } from 'app/entities/result.model';
import {
CodeEditorBuildLogService,
CodeEditorRepositoryFileService,
CodeEditorRepositoryService,
} from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';
import { Feedback } from 'app/entities/feedback.model';
import { DomainService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain.service';
import { ProgrammingSubmission } from 'app/entities/programming-submission.model';
import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';
import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { MockResultService } from '../../helpers/mocks/service/mock-result.service';
import { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service';
import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service';
import { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service';
import { CodeEditorContainerComponent } from 'app/exercises/programming/shared/code-editor/container/code-editor-container.component';
import { omit } from 'lodash-es';
import { ProgrammingLanguage, ProjectType } from 'app/entities/programming-exercise.model';
import { CodeEditorGridComponent } from 'app/exercises/programming/shared/code-editor/layout/code-editor-grid.component';
import { MockComponent, MockDirective, MockPipe } from 'ng-mocks';
import { CodeEditorActionsComponent } from 'app/exercises/programming/shared/code-editor/actions/code-editor-actions.component';
import { CodeEditorFileBrowserComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser.component';
import { CodeEditorAceComponent } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component';
import { CodeEditorInstructionsComponent } from 'app/exercises/programming/shared/code-editor/instructions/code-editor-instructions.component';
import { CodeEditorBuildOutputComponent } from 'app/exercises/programming/shared/code-editor/build-output/code-editor-build-output.component';
import { KeysPipe } from 'app/shared/pipes/keys.pipe';
import { FeatureToggleDirective } from 'app/shared/feature-toggle/feature-toggle.directive';
import { FeatureToggleLinkDirective } from 'app/shared/feature-toggle/feature-toggle-link.directive';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { CodeEditorFileBrowserCreateNodeComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-create-node.component';
import { CodeEditorStatusComponent } from 'app/exercises/programming/shared/code-editor/status/code-editor-status.component';
import { CodeEditorFileBrowserFolderComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-folder.component';
import { CodeEditorFileBrowserFileComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-file.component';
import { CodeEditorTutorAssessmentInlineFeedbackComponent } from 'app/exercises/programming/assess/code-editor-tutor-assessment-inline-feedback.component';
import { AceEditorModule } from 'app/shared/markdown-editor/ace-editor/ace-editor.module';
import { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';
import { TreeviewComponent } from 'app/exercises/programming/shared/code-editor/treeview/components/treeview/treeview.component';
import { TreeviewItemComponent } from 'app/exercises/programming/shared/code-editor/treeview/components/treeview-item/treeview-item.component';
describe('CodeEditorContainerIntegration', () => {
// needed to make sure ace is defined
ace.acequire('ace/ext/modelist');
let container: CodeEditorContainerComponent;
let containerFixture: ComponentFixture<CodeEditorContainerComponent>;
let containerDebugElement: DebugElement;
let conflictService: CodeEditorConflictStateService;
let domainService: DomainService;
let checkIfRepositoryIsCleanStub: jest.SpyInstance;
let getRepositoryContentStub: jest.SpyInstance;
let subscribeForLatestResultOfParticipationStub: jest.SpyInstance;
let getFeedbackDetailsForResultStub: jest.SpyInstance;
let getBuildLogsStub: jest.SpyInstance;
let getFileStub: jest.SpyInstance;
let saveFilesStub: jest.SpyInstance;
let commitStub: jest.SpyInstance;
let getStudentParticipationWithLatestResultStub: jest.SpyInstance;
let getLatestPendingSubmissionStub: jest.SpyInstance;
let guidedTourService: GuidedTourService;
let subscribeForLatestResultOfParticipationSubject: BehaviorSubject<Result | undefined>;
let getLatestPendingSubmissionSubject = new Subject<ProgrammingSubmissionStateObj>();
const result = { id: 3, successful: false, completionDate: dayjs().subtract(2, 'days') };
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule, AceEditorModule],
declarations: [
CodeEditorContainerComponent,
MockComponent(CodeEditorGridComponent),
MockComponent(CodeEditorInstructionsComponent),
KeysPipe,
MockDirective(FeatureToggleDirective),
MockDirective(FeatureToggleLinkDirective),
MockDirective(NgbDropdown),
MockDirective(NgModel),
MockPipe(ArtemisTranslatePipe),
CodeEditorActionsComponent,
CodeEditorFileBrowserComponent,
CodeEditorBuildOutputComponent,
CodeEditorAceComponent,
MockComponent(CodeEditorFileBrowserCreateNodeComponent),
MockComponent(CodeEditorFileBrowserFolderComponent),
MockComponent(CodeEditorFileBrowserFileComponent),
MockComponent(CodeEditorStatusComponent),
TreeviewComponent,
TreeviewItemComponent,
MockPipe(ArtemisDatePipe),
MockComponent(CodeEditorTutorAssessmentInlineFeedbackComponent),
],
providers: [
ChangeDetectorRef,
DeviceDetectorService,
CodeEditorConflictStateService,
{ provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },
{ provide: JhiWebsocketService, useClass: MockWebsocketService },
{ provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },
{ provide: ProgrammingExerciseParticipationService, useClass: MockProgrammingExerciseParticipationService },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: ResultService, useClass: MockResultService },
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: CodeEditorRepositoryService, useClass: MockCodeEditorRepositoryService },
{ provide: CodeEditorRepositoryFileService, useClass: MockCodeEditorRepositoryFileService },
{ provide: CodeEditorBuildLogService, useClass: MockCodeEditorBuildLogService },
{ provide: ResultService, useClass: MockResultService },
{ provide: ProgrammingSubmissionService, useClass: MockProgrammingSubmissionService },
],
})
.compileComponents()
.then(() => {
containerFixture = TestBed.createComponent(CodeEditorContainerComponent);
container = containerFixture.componentInstance;
containerDebugElement = containerFixture.debugElement;
guidedTourService = TestBed.inject(GuidedTourService);
const codeEditorRepositoryService = containerDebugElement.injector.get(CodeEditorRepositoryService);
const codeEditorRepositoryFileService = containerDebugElement.injector.get(CodeEditorRepositoryFileService);
const participationWebsocketService = containerDebugElement.injector.get(ParticipationWebsocketService);
const resultService = containerDebugElement.injector.get(ResultService);
const buildLogService = containerDebugElement.injector.get(CodeEditorBuildLogService);
const programmingExerciseParticipationService = containerDebugElement.injector.get(ProgrammingExerciseParticipationService);
conflictService = containerDebugElement.injector.get(CodeEditorConflictStateService);
domainService = containerDebugElement.injector.get(DomainService);
const submissionService = containerDebugElement.injector.get(ProgrammingSubmissionService);
subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | undefined>(undefined);
getLatestPendingSubmissionSubject = new Subject<ProgrammingSubmissionStateObj>();
checkIfRepositoryIsCleanStub = jest.spyOn(codeEditorRepositoryService, 'getStatus');
getRepositoryContentStub = jest.spyOn(codeEditorRepositoryFileService, 'getRepositoryContent');
subscribeForLatestResultOfParticipationStub = jest
.spyOn(participationWebsocketService, 'subscribeForLatestResultOfParticipation')
.mockReturnValue(subscribeForLatestResultOfParticipationSubject);
getFeedbackDetailsForResultStub = jest.spyOn(resultService, 'getFeedbackDetailsForResult');
getBuildLogsStub = jest.spyOn(buildLogService, 'getBuildLogs');
getFileStub = jest.spyOn(codeEditorRepositoryFileService, 'getFile');
saveFilesStub = jest.spyOn(codeEditorRepositoryFileService, 'updateFiles');
commitStub = jest.spyOn(codeEditorRepositoryService, 'commit');
getStudentParticipationWithLatestResultStub = jest.spyOn(programmingExerciseParticipationService, 'getStudentParticipationWithLatestResult');
getLatestPendingSubmissionStub = jest.spyOn(submissionService, 'getLatestPendingSubmissionByParticipationId').mockReturnValue(getLatestPendingSubmissionSubject);
});
});
afterEach(() => {
jest.restoreAllMocks();
subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | undefined>(undefined);
subscribeForLatestResultOfParticipationStub.mockReturnValue(subscribeForLatestResultOfParticipationSubject);
getLatestPendingSubmissionSubject = new Subject<ProgrammingSubmissionStateObj>();
getLatestPendingSubmissionStub.mockReturnValue(getLatestPendingSubmissionSubject);
});
const cleanInitialize = () => {
const exercise = { id: 1, problemStatement };
const participation = { id: 2, exercise, student: { id: 99 }, results: [result] } as StudentParticipation;
const isCleanSubject = new Subject();
const getRepositoryContentSubject = new Subject();
const getBuildLogsSubject = new Subject();
checkIfRepositoryIsCleanStub.mockReturnValue(isCleanSubject);
getRepositoryContentStub.mockReturnValue(getRepositoryContentSubject);
getFeedbackDetailsForResultStub.mockReturnValue(of([]));
getBuildLogsStub.mockReturnValue(getBuildLogsSubject);
getLatestPendingSubmissionStub.mockReturnValue(getLatestPendingSubmissionSubject);
container.participation = participation as any;
// TODO: This should be replaced by testing with route params.
domainService.setDomain([DomainType.PARTICIPATION, participation]);
containerFixture.detectChanges();
container.commitState = CommitState.UNDEFINED;
isCleanSubject.next({ repositoryStatus: CommitState.CLEAN });
getBuildLogsSubject.next(buildLogs);
getRepositoryContentSubject.next({ file: FileType.FILE, folder: FileType.FOLDER, file2: FileType.FILE });
getLatestPendingSubmissionSubject.next({ participationId: 1, submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined });
containerFixture.detectChanges();
// container
expect(container.commitState).toBe(CommitState.CLEAN);
expect(container.editorState).toBe(EditorState.CLEAN);
expect(container.buildOutput.isBuilding).toBeFalse();
expect(container.unsavedFiles).toStrictEqual({});
// file browser
expect(checkIfRepositoryIsCleanStub).toHaveBeenCalledOnce();
expect(getRepositoryContentStub).toHaveBeenCalledOnce();
expect(container.fileBrowser.errorFiles).toEqual(extractedErrorFiles);
expect(container.fileBrowser.unsavedFiles).toHaveLength(0);
// ace editor
expect(container.aceEditor.isLoading).toBeFalse();
expect(container.aceEditor.commitState).toBe(CommitState.CLEAN);
// actions
expect(container.actions.commitState).toBe(CommitState.CLEAN);
expect(container.actions.editorState).toBe(EditorState.CLEAN);
expect(container.actions.isBuilding).toBeFalse();
// status
expect(container.fileBrowser.status.commitState).toBe(CommitState.CLEAN);
expect(container.fileBrowser.status.editorState).toBe(EditorState.CLEAN);
// build output
expect(getBuildLogsStub).toHaveBeenCalledOnce();
expect(container.buildOutput.rawBuildLogs.extractErrors(ProgrammingLanguage.JAVA, ProjectType.PLAIN_MAVEN)).toEqual(extractedBuildLogErrors);
expect(container.buildOutput.isBuilding).toBeFalse();
// instructions
expect(container.instructions).not.toBe(undefined); // Have to use this as it's a component
// called by build output
expect(getFeedbackDetailsForResultStub).toHaveBeenCalledOnce();
expect(getFeedbackDetailsForResultStub).toHaveBeenCalledWith(participation.id!, participation.results![0].id);
};
const loadFile = (fileName: string, fileContent: string) => {
getFileStub.mockReturnValue(of({ fileContent }));
container.fileBrowser.selectedFile = fileName;
};
it('should initialize all components correctly if all server calls are successful', (done) => {
cleanInitialize();
setTimeout(() => {
expect(subscribeForLatestResultOfParticipationStub).toHaveBeenCalledOnce();
done();
}, 0);
});
it('should not load files and render other components correctly if the repository status cannot be retrieved', (done) => {
const exercise = { id: 1, problemStatement, course: { id: 2 } };
const participation = { id: 2, exercise, results: [result] } as StudentParticipation;
const isCleanSubject = new Subject();
const getBuildLogsSubject = new Subject();
checkIfRepositoryIsCleanStub.mockReturnValue(isCleanSubject);
subscribeForLatestResultOfParticipationStub.mockReturnValue(of(undefined));
getFeedbackDetailsForResultStub.mockReturnValue(of([]));
getBuildLogsStub.mockReturnValue(getBuildLogsSubject);
container.participation = participation;
// TODO: This should be replaced by testing with route params.
domainService.setDomain([DomainType.PARTICIPATION, participation]);
containerFixture.detectChanges();
container.commitState = CommitState.UNDEFINED;
isCleanSubject.error('fatal error');
getBuildLogsSubject.next(buildLogs);
getLatestPendingSubmissionSubject.next({ participationId: 1, submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: undefined });
containerFixture.detectChanges();
// container
expect(container.commitState).toBe(CommitState.COULD_NOT_BE_RETRIEVED);
expect(container.editorState).toBe(EditorState.CLEAN);
expect(container.buildOutput.isBuilding).toBeFalse();
expect(container.unsavedFiles).toStrictEqual({});
// file browser
expect(checkIfRepositoryIsCleanStub).toHaveBeenCalledOnce();
expect(getRepositoryContentStub).not.toHaveBeenCalled();
expect(container.fileBrowser.errorFiles).toEqual(extractedErrorFiles);
expect(container.fileBrowser.unsavedFiles).toHaveLength(0);
// ace editor
expect(container.aceEditor.isLoading).toBeFalse();
expect(container.aceEditor.annotationsArray.map((a) => omit(a, 'hash'))).toEqual(extractedBuildLogErrors);
expect(container.aceEditor.commitState).toBe(CommitState.COULD_NOT_BE_RETRIEVED);
// actions
expect(container.actions.commitState).toBe(CommitState.COULD_NOT_BE_RETRIEVED);
expect(container.actions.editorState).toBe(EditorState.CLEAN);
expect(container.actions.isBuilding).toBeFalse();
// status
expect(container.fileBrowser.status.commitState).toBe(CommitState.COULD_NOT_BE_RETRIEVED);
expect(container.fileBrowser.status.editorState).toBe(EditorState.CLEAN);
// build output
expect(getBuildLogsStub).toHaveBeenCalledOnce();
expect(container.buildOutput.rawBuildLogs.extractErrors(ProgrammingLanguage.JAVA, ProjectType.PLAIN_MAVEN)).toEqual(extractedBuildLogErrors);
expect(container.buildOutput.isBuilding).toBeFalse();
// instructions
expect(container.instructions).not.toBe(undefined); // Have to use this as it's a component
// called by build output & instructions
expect(getFeedbackDetailsForResultStub).toHaveBeenCalledOnce();
expect(getFeedbackDetailsForResultStub).toHaveBeenCalledWith(participation.id!, participation.results![0].id);
setTimeout(() => {
// called by build output
expect(subscribeForLatestResultOfParticipationStub).toHaveBeenCalledOnce();
done();
}, 0);
});
it('should update the file browser and ace editor on file selection', () => {
cleanInitialize();
const selectedFile = Object.keys(container.fileBrowser.repositoryFiles)[0];
const fileContent = 'lorem ipsum';
loadFile(selectedFile, fileContent);
containerFixture.detectChanges();
expect(container.selectedFile).toBe(selectedFile);
expect(container.aceEditor.selectedFile).toBe(selectedFile);
expect(container.aceEditor.isLoading).toBeFalse();
expect(container.aceEditor.fileSession).toContainKey(selectedFile);
expect(getFileStub).toHaveBeenCalledOnce();
expect(getFileStub).toHaveBeenCalledWith(selectedFile);
containerFixture.detectChanges();
expect(container.aceEditor.editor.getEditor().getSession().getValue()).toBe(fileContent);
});
it('should mark file to have unsaved changes in file tree if the file was changed in editor', () => {
cleanInitialize();
const selectedFile = Object.keys(container.fileBrowser.repositoryFiles)[0];
const fileContent = 'lorem ipsum';
const newFileContent = 'new lorem ipsum';
loadFile(selectedFile, fileContent);
containerFixture.detectChanges();
container.aceEditor.onFileTextChanged(newFileContent);
containerFixture.detectChanges();
expect(getFileStub).toHaveBeenCalledOnce();
expect(getFileStub).toHaveBeenCalledWith(selectedFile);
expect(container.unsavedFiles).toEqual({ [selectedFile]: newFileContent });
expect(container.fileBrowser.unsavedFiles).toEqual([selectedFile]);
expect(container.editorState).toBe(EditorState.UNSAVED_CHANGES);
expect(container.actions.editorState).toBe(EditorState.UNSAVED_CHANGES);
});
it('should save files and remove unsaved status of saved files afterwards', () => {
// setup
cleanInitialize();
const selectedFile = Object.keys(container.fileBrowser.repositoryFiles)[0];
const otherFileWithUnsavedChanges = Object.keys(container.fileBrowser.repositoryFiles)[2];
const fileContent = 'lorem ipsum';
const newFileContent = 'new lorem ipsum';
const saveFilesSubject = new Subject();
saveFilesStub.mockReturnValue(saveFilesSubject);
container.unsavedFiles = { [otherFileWithUnsavedChanges]: 'lorem ipsum dolet', [selectedFile]: newFileContent };
loadFile(selectedFile, fileContent);
containerFixture.detectChanges();
// init saving
container.actions.saveChangedFiles().subscribe();
expect(container.commitState).toBe(CommitState.UNCOMMITTED_CHANGES);
expect(container.editorState).toBe(EditorState.SAVING);
// emit saving result
saveFilesSubject.next({ [selectedFile]: undefined, [otherFileWithUnsavedChanges]: undefined });
containerFixture.detectChanges();
// check if saving result updates comps as expected
expect(container.unsavedFiles).toStrictEqual({});
expect(container.editorState).toBe(EditorState.CLEAN);
expect(container.commitState).toBe(CommitState.UNCOMMITTED_CHANGES);
expect(container.fileBrowser.unsavedFiles).toHaveLength(0);
expect(container.actions.editorState).toBe(EditorState.CLEAN);
});
it('should remove the unsaved changes flag in all components if the unsaved file is deleted', () => {
cleanInitialize();
const repositoryFiles = { file: FileType.FILE, file2: FileType.FILE, folder: FileType.FOLDER };
const expectedFilesAfterDelete = { file2: FileType.FILE, folder: FileType.FOLDER };
const unsavedChanges = { file: 'lorem ipsum' };
container.fileBrowser.repositoryFiles = repositoryFiles;
container.unsavedFiles = unsavedChanges;
containerFixture.detectChanges();
expect(container.fileBrowser.unsavedFiles).toEqual(Object.keys(unsavedChanges));
expect(container.actions.editorState).toBe(EditorState.UNSAVED_CHANGES);
container.fileBrowser.onFileDeleted(new DeleteFileChange(FileType.FILE, 'file'));
containerFixture.detectChanges();
expect(container.unsavedFiles).toStrictEqual({});
expect(container.fileBrowser.repositoryFiles).toEqual(expectedFilesAfterDelete);
expect(container.actions.editorState).toBe(EditorState.CLEAN);
});
it('should wait for build result after submission if no unsaved changes exist', () => {
cleanInitialize();
const successfulSubmission = { id: 1, buildFailed: false } as ProgrammingSubmission;
const successfulResult = { id: 4, successful: true, feedbacks: [] as Feedback[], participation: { id: 3 } } as Result;
successfulResult.submission = successfulSubmission;
const expectedBuildLog = new BuildLogEntryArray();
expect(container.unsavedFiles).toStrictEqual({});
container.commitState = CommitState.UNCOMMITTED_CHANGES;
containerFixture.detectChanges();
// commit
expect(container.actions.commitState).toBe(CommitState.UNCOMMITTED_CHANGES);
commitStub.mockReturnValue(of(undefined));
getLatestPendingSubmissionSubject.next({
submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION,
submission: {} as ProgrammingSubmission,
participationId: successfulResult!.participation!.id!,
});
container.actions.commit();
containerFixture.detectChanges();
// waiting for build successfulResult
expect(container.commitState).toBe(CommitState.CLEAN);
expect(container.buildOutput.isBuilding).toBeTrue();
getLatestPendingSubmissionSubject.next({
submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION,
submission: undefined,
participationId: successfulResult!.participation!.id!,
});
subscribeForLatestResultOfParticipationSubject.next(successfulResult);
containerFixture.detectChanges();
expect(container.buildOutput.isBuilding).toBeFalse();
expect(container.buildOutput.rawBuildLogs).toEqual(expectedBuildLog);
expect(container.fileBrowser.errorFiles).toHaveLength(0);
});
it('should first save unsaved files before triggering commit', fakeAsync(() => {
cleanInitialize();
const successfulSubmission = { id: 1, buildFailed: false } as ProgrammingSubmission;
const successfulResult = { id: 4, successful: true, feedbacks: [] as Feedback[], participation: { id: 3 } } as Result;
successfulResult.submission = successfulSubmission;
const expectedBuildLog = new BuildLogEntryArray();
const unsavedFile = Object.keys(container.fileBrowser.repositoryFiles)[0];
const saveFilesSubject = new Subject();
saveFilesStub.mockReturnValue(saveFilesSubject);
container.unsavedFiles = { [unsavedFile]: 'lorem ipsum' };
container.editorState = EditorState.UNSAVED_CHANGES;
container.commitState = CommitState.UNCOMMITTED_CHANGES;
containerFixture.detectChanges();
// trying to commit
container.actions.commit();
containerFixture.detectChanges();
// saving before commit
expect(saveFilesStub).toHaveBeenCalledOnce();
expect(saveFilesStub).toHaveBeenCalledWith([{ fileName: unsavedFile, fileContent: 'lorem ipsum' }], true);
expect(container.editorState).toBe(EditorState.SAVING);
expect(container.fileBrowser.status.editorState).toBe(EditorState.SAVING);
// committing
expect(commitStub).not.toHaveBeenCalled();
expect(container.commitState).toBe(CommitState.COMMITTING);
expect(container.fileBrowser.status.commitState).toBe(CommitState.COMMITTING);
saveFilesSubject.next({ [unsavedFile]: undefined });
expect(container.editorState).toBe(EditorState.CLEAN);
subscribeForLatestResultOfParticipationSubject.next(successfulResult);
getLatestPendingSubmissionSubject.next({
submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION,
submission: {} as ProgrammingSubmission,
participationId: successfulResult!.participation!.id!,
});
containerFixture.detectChanges();
tick();
// waiting for build result
expect(container.commitState).toBe(CommitState.CLEAN);
expect(container.buildOutput.isBuilding).toBeTrue();
getLatestPendingSubmissionSubject.next({
submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION,
submission: undefined,
participationId: successfulResult!.participation!.id!,
});
containerFixture.detectChanges();
expect(container.buildOutput.isBuilding).toBeFalse();
expect(container.buildOutput.rawBuildLogs).toEqual(expectedBuildLog);
expect(container.fileBrowser.errorFiles).toHaveLength(0);
containerFixture.destroy();
flush();
}));
it('should enter conflict mode if a git conflict between local and remote arises', fakeAsync(() => {
const guidedTourMapping = {} as GuidedTourMapping;
jest.spyOn<any, any>(guidedTourService, 'checkTourState').mockReturnValue(true);
guidedTourService.guidedTourMapping = guidedTourMapping;
const successfulResult = { id: 3, successful: false };
const participation = { id: 1, results: [successfulResult], exercise: { id: 99 } } as StudentParticipation;
const feedbacks = [{ id: 2 }] as Feedback[];
const findWithLatestResultSubject = new Subject<Participation>();
const isCleanSubject = new Subject();
getStudentParticipationWithLatestResultStub.mockReturnValue(findWithLatestResultSubject);
checkIfRepositoryIsCleanStub.mockReturnValue(isCleanSubject);
getFeedbackDetailsForResultStub.mockReturnValue(of(feedbacks));
getRepositoryContentStub.mockReturnValue(of([]));
container.participation = participation;
domainService.setDomain([DomainType.PARTICIPATION, participation]);
containerFixture.detectChanges();
findWithLatestResultSubject.next(participation);
containerFixture.detectChanges();
// Create conflict.
isCleanSubject.next({ repositoryStatus: CommitState.CONFLICT });
containerFixture.detectChanges();
expect(container.commitState).toBe(CommitState.CONFLICT);
expect(getRepositoryContentStub).not.toHaveBeenCalled();
// Resolve conflict.
conflictService.notifyConflictState(GitConflictState.OK);
tick();
containerFixture.detectChanges();
isCleanSubject.next({ repositoryStatus: CommitState.CLEAN });
containerFixture.detectChanges();
expect(container.commitState).toBe(CommitState.CLEAN);
expect(getRepositoryContentStub).toHaveBeenCalledOnce();
containerFixture.destroy();
flush();
}));
}); | the_stack |
import { contains, each, isArray, keys, map } from 'underscore';
import { Assert } from '../../misc/Assert';
import { Logger } from '../../misc/Logger';
import { IStringMap } from '../../rest/GenericParam';
import { $$, Dom } from '../../utils/Dom';
import { SVGIcons } from '../../utils/SVGIcons';
import { Utils } from '../../utils/Utils';
import { Template } from '../Templates/Template';
import { ComponentOptionLoader } from './ComponentOptionsLoader';
import { ComponentOptionsMerger } from './ComponentOptionsMerger';
import { ComponentOptionsPostProcessor } from './ComponentOptionsPostProcessor';
import { ComponentOptionsValidator } from './ComponentOptionsValidator';
import {
ComponentOptionsType,
IComponentJsonObjectOption,
IComponentLocalizedStringOptionArgs,
IComponentOptions,
IComponentOptionsChildHtmlElementOption,
IComponentOptionsChildHtmlElementOptionArgs,
IComponentOptionsCustomListOptionArgs,
IComponentOptionsFieldOptionArgs,
IComponentOptionsFieldsOptionArgs,
IComponentOptionsListOption,
IComponentOptionsListOptionArgs,
IComponentOptionsLoadOption,
IComponentOptionsNumberOption,
IComponentOptionsNumberOptionArgs,
IComponentOptionsObjectOptionArgs,
IComponentOptionsOption,
IFieldConditionOption,
IFieldOption,
IQueryExpression
} from './IComponentOptions';
import { IComponentOptionsTemplateOptionArgs, TemplateComponentOptions } from './TemplateComponentOptions';
const camelCaseToHyphenRegex = /([A-Z])|\W+(\w)/g;
const fieldsSeperator = /\s*,\s*/;
const localizer = /([a-zA-Z\-]+)\s*:\s*(([^,]|,\s*(?!([a-zA-Z\-]+)\s*:))+)/g;
/**
* The `ComponentOptions` static class contains methods allowing the Coveo JavaScript Search Framework to initialize
* component options.
*
* Typically, each [`Component`]{@link Component} that exposes a set of options contains a static `options` property.
*
* This property "builds" each option using the `ComponentOptions` method corresponding to its type (e.g.,
* [`buildBooleanOption`]{@link ComponentOptions.buildBooleanOption},
* [`buildFieldOption`]{@link ComponentOptions.buildFieldOption},
* [`buildStringOption`]{@link ComponentOptions.buildStringOption}, etc.)
*/
export class ComponentOptions {
static buildTemplateOption(optionArgs?: IComponentOptionsTemplateOptionArgs): Template {
return TemplateComponentOptions.buildTemplateOption(optionArgs);
}
/**
* Builds a boolean option.
*
* **Markup Examples:**
*
* > `data-foo="true"`
*
* > `data-foo="false"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {boolean} The resulting option value.
*/
static buildBooleanOption(optionArgs?: IComponentOptions<boolean>): boolean {
return ComponentOptions.buildOption<boolean>(ComponentOptionsType.BOOLEAN, ComponentOptions.loadBooleanOption, optionArgs);
}
/**
* Builds a number option.
*
* A number option can be an integer or a float in the markup.
*
* **Note:**
*
* > To build a float option, you need to set the `float` property in the [`IComponentOptionsNumberOptionArgs`]{@link IComponentOptionsNumberOptionArgs} to `true`.
*
* **Markup Examples:**
*
* > `data-foo="3"`
*
* > `data-foo="1.5"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {number} The resulting option value.
*/
static buildNumberOption(optionArgs?: IComponentOptionsNumberOptionArgs): number {
return ComponentOptions.buildOption<number>(ComponentOptionsType.NUMBER, ComponentOptions.loadNumberOption, optionArgs);
}
/**
* Builds a string option.
*
* A string option can be any arbitrary string in the markup.
*
* **Markup Example:**
*
* > `data-foo="bar"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildStringOption<T extends string>(optionArgs?: IComponentOptions<T>): T {
return ComponentOptions.buildOption<T>(ComponentOptionsType.STRING, ComponentOptions.loadStringOption, optionArgs);
}
/**
* Builds an icon option.
*
* This takes an SVG icon name, validates it and returns the name of the icon.
* **Markup Examples:**
*
* > `data-foo="search"`
*
* > `data-foo="facet-expand"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildIconOption(optionArgs?: IComponentOptions<string>): string {
return ComponentOptions.buildOption<string>(ComponentOptionsType.ICON, ComponentOptions.loadIconOption, optionArgs);
}
/**
* Builds a color option.
*
* Normally, this simply builds a string that matches a CSS color.
*
* **Note:**
*
* > In the markup, this offers no advantage over using a plain string. This is mostly useful for the Coveo JavaScript
* > Interface Editor.
*
* **Markup Examples:**
*
* > `data-foo="coveo-sprites-user"`
*
* > `data-foo="coveo-sprites-database"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildColorOption(optionArgs?: IComponentOptions<string>): string {
return ComponentOptions.buildOption<string>(ComponentOptionsType.COLOR, ComponentOptions.loadStringOption, optionArgs);
}
/**
* Builds a helper option.
*
* Normally, this simply builds a string that matches the name of a template helper.
*
* **Note:**
*
* > In the markup, this offers no advantage over using a plain string. This is mostly useful for the Coveo JavaScript
* > Interface Editor.
*
* **Markup Examples:**
*
* > `data-foo="date"`
*
* > `data-foo="dateTime"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildHelperOption(optionArgs?: IComponentOptions<string>): string {
return ComponentOptions.buildOption<string>(ComponentOptionsType.HELPER, ComponentOptions.loadStringOption, optionArgs);
}
/**
* Tries to parse a stringified JSON option.
*
* If unsuccessful (because of invalid syntax), the JSON option is ignored altogether, and the console displays a warning message.
*
* **Markup Example:**
*
* > `data-foo='{"bar" : "baz"}'`
*
* **Note:**
*
* A JSON option can always be set as a property in the `init` call of the framework rather than as a `data-` property in the corresponding HTMLElement markup.
*
* **Initialization Example:**
*
* ```
* Coveo.init(root, {
* Facet : {
* foo : {
* "bar" : "baz"
* }
* }
* })
* ```
* @param optionArgs The arguments to apply when building the option.
* @returns {T} The resulting option value.
*/
static buildJsonOption<T extends IStringMap<any>>(optionArgs?: IComponentJsonObjectOption<T>): T {
return ComponentOptions.buildOption(ComponentOptionsType.JSON, ComponentOptions.loadJsonObjectOption, optionArgs) as T;
}
/**
* @deprecated Use buildJsonOption instead
*
* @deprecatedsince [2017 Javascript Search Framework Releases](https://docs.coveo.com/en/373/#december-2017-release-v236794)
*/
static buildJsonObjectOption<T>(optionArgs?: IComponentJsonObjectOption<T>): T {
return ComponentOptions.buildJsonOption(optionArgs);
}
/**
* Builds a localized string option.
*
* A localized string option can be any arbitrary string.
*
* When parsing the value, the Coveo JavaScript Search Framework tries to load the localization for that string, if it
* is available.
*
* If it is not available, it returns the non-localized value.
*
* This should be used for options that will be rendered directly to the end users.
*
* **Markup Example:**
*
* > `data-foo="bar"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildLocalizedStringOption(optionArgs?: IComponentLocalizedStringOptionArgs): string {
return ComponentOptions.buildOption<string>(
ComponentOptionsType.LOCALIZED_STRING,
ComponentOptions.loadLocalizedStringOption,
optionArgs
);
}
/**
* Builds a field option.
*
* A field option validates whether the field has a valid name. This means that the string must start with the `@`
* character.
*
* **Markup Example:**
*
* > `data-foo="@bar"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string} The resulting option value.
*/
static buildFieldOption(optionArgs?: IComponentOptionsFieldOptionArgs): IFieldOption {
return ComponentOptions.buildOption<string>(ComponentOptionsType.FIELD, ComponentOptions.loadFieldOption, optionArgs);
}
/**
* Builds an array of fields option.
*
* As with all options that expect an array, you should use commas to delimit the different values.
*
* **Markup Example:**
*
* > `data-foo="@bar,@baz"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string[]} The resulting option value.
*/
static buildFieldsOption(optionArgs?: IComponentOptionsFieldsOptionArgs): IFieldOption[] {
return ComponentOptions.buildOption<string[]>(ComponentOptionsType.FIELDS, ComponentOptions.loadFieldsOption, optionArgs);
}
/**
* Builds a query expression option.
*
* The query expression option should follow the [Coveo Cloud Query Syntax Reference](https://docs.coveo.com/en/1552/).
*
* **Markup Example:**
*
* > `data-foo="@bar==baz"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {IQueryExpression} The resulting option value.
*/
static buildQueryExpressionOption(optionArgs?: IComponentOptions<string>): IQueryExpression {
return ComponentOptions.buildOption<string>(ComponentOptionsType.QUERY_EXPRESSION, ComponentOptions.loadStringOption, optionArgs);
}
/**
* Builds an array of strings option.
*
* As with all options that expect an array, you should use commas to delimit the different values.
*
* **Markup Example:**
*
* > `data-foo="bar,baz"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {string[]} The resulting option value.
*/
static buildListOption<T>(optionArgs?: IComponentOptionsListOptionArgs): T[] | string[] {
return ComponentOptions.buildOption<string[]>(ComponentOptionsType.LIST, ComponentOptions.loadListOption, optionArgs);
}
/**
* Builds an option that allow to select an HTMLElement.
*
* The option accepts a CSS selector matching the required HTMLElement. This selector can either be a class, or an ID
* selector.
*
* **Markup Examples:**
*
* > `data-foo-selector=".bar"`
*
* > `data-foo-selector="#bar"`
*
* @param optionArgs The arguments to apply when building the option.
* @returns {HTMLElement} The resulting option value.
*/
static buildSelectorOption(optionArgs?: IComponentOptions<HTMLElement>): HTMLElement {
return ComponentOptions.buildOption<HTMLElement>(ComponentOptionsType.SELECTOR, ComponentOptions.loadSelectorOption, optionArgs);
}
static buildChildHtmlElementOption(optionArgs?: IComponentOptionsChildHtmlElementOptionArgs): HTMLElement {
return ComponentOptions.buildOption<HTMLElement>(
ComponentOptionsType.CHILD_HTML_ELEMENT,
ComponentOptions.loadChildHtmlElementOption,
optionArgs
);
}
static buildCustomOption<T>(converter: (value: string) => T, optionArgs?: IComponentOptions<T>): T {
const loadOption: IComponentOptionsLoadOption<T> = (element: HTMLElement, name: string, option: IComponentOptionsOption<T>) => {
const stringvalue = ComponentOptions.loadStringOption(element, name, option);
if (!Utils.isNullOrEmptyString(stringvalue)) {
return converter(stringvalue);
}
};
return ComponentOptions.buildOption<T>(ComponentOptionsType.STRING, loadOption, optionArgs);
}
static buildCustomListOption<T>(converter: (value: string[]) => T, optionArgs?: IComponentOptionsCustomListOptionArgs<T>): T {
const loadOption: IComponentOptionsLoadOption<T> = (element: HTMLElement, name: string, option: any) => {
const stringvalue = ComponentOptions.loadListOption(element, name, option);
return converter(stringvalue);
};
return ComponentOptions.buildOption<any>(ComponentOptionsType.LIST, loadOption, optionArgs);
}
static buildObjectOption(optionArgs?: IComponentOptionsObjectOptionArgs): any {
const loadOption: IComponentOptionsLoadOption<{
[key: string]: any;
}> = (element: HTMLElement, name: string, option: IComponentOptionsOption<any>) => {
const extractedKeys = keys(optionArgs.subOptions);
const scopedOptions: {
[name: string]: IComponentOptionsOption<any>;
} = {};
const scopedValues: {
[name: string]: any;
} = {};
for (let i = 0; i < extractedKeys.length; i++) {
const key = extractedKeys[i];
const scopedkey = ComponentOptions.mergeCamelCase(name, key);
scopedOptions[scopedkey] = optionArgs.subOptions[key];
}
ComponentOptions.initOptions(element, scopedOptions, scopedValues, '');
const resultValues: {
[name: string]: any;
} = {};
let resultFound = false;
for (let i = 0; i < extractedKeys.length; i++) {
const key = extractedKeys[i];
const scopedkey = ComponentOptions.mergeCamelCase(name, key);
if (scopedValues[scopedkey] != null) {
resultValues[key] = scopedValues[scopedkey];
resultFound = true;
}
}
return resultFound ? resultValues : null;
};
return ComponentOptions.buildOption<{
[key: string]: any;
}>(ComponentOptionsType.OBJECT, loadOption, optionArgs);
}
/**
* Builds a field condition option.
*
* A field condition option defines a field-based condition that must be dynamically evaluated against,
* and satisfied by a query result item in order to initialize a result template component.
*
* **Markup Example:**
*
* ```html
* data-condition-field-author="Alice Smith, Bob Jones"
* data-condition-field-not-filetype="pdf"`
* ```
*
* @returns {string} The resulting option value.
*/
static buildFieldConditionOption(): IFieldConditionOption[] {
return ComponentOptions.buildOption<IFieldConditionOption[]>(ComponentOptionsType.FIELD, ComponentOptions.loadFieldConditionOption);
}
static buildOption<T>(type: ComponentOptionsType, load: IComponentOptionsLoadOption<T>, optionArg: IComponentOptions<T> = {}): T {
const option: IComponentOptionsOption<T> = <any>optionArg;
option.type = type;
option.load = load;
return <any>option;
}
static attrNameFromName(name: string, optionArgs?: IComponentOptions<any>) {
if (optionArgs && optionArgs.attrName) {
return optionArgs.attrName;
}
if (name) {
return 'data-' + ComponentOptions.camelCaseToHyphen(name);
}
return name;
}
static camelCaseToHyphen(name: string) {
return name.replace(camelCaseToHyphenRegex, '-$1$2').toLowerCase();
}
static mergeCamelCase(parent: string, name: string) {
return parent + name.substr(0, 1).toUpperCase() + name.substr(1);
}
/**
* Loads and parses the options of the current element.
*
* Each component calls this method in its constructor.
*
* @param element The element whose markup options the method should load and parse.
* @param component The class of the component whose options the method should load and parse (e.g., `Searchbox`,
* `Facet`, etc.)
* @param values The additional options which the method should merge with the specified markup option values.
*/
static initComponentOptions(element: HTMLElement, component: any, values?: any) {
return ComponentOptions.initOptions(element, component.options, values, component.ID);
}
static initOptions(
element: HTMLElement,
options: {
[name: string]: IComponentOptionsOption<any>;
},
values: any = {},
componentID: string
) {
if (Utils.isNullOrUndefined(values)) {
values = {};
}
each(options, (optionDefinition, name) => {
const value = new ComponentOptionLoader(element, values, name, optionDefinition).load();
new ComponentOptionsMerger(optionDefinition, { value, name }, values).merge();
new ComponentOptionsValidator(optionDefinition, { componentID, name, value }, values).validate();
});
new ComponentOptionsPostProcessor(options, values, componentID).postProcess();
return values;
}
static tryLoadFromAttribute(element: HTMLElement, name: string, optionDefinition: IComponentOptionsOption<any>) {
const loadFromAttribute = optionDefinition.load;
if (!loadFromAttribute) {
return null;
}
return loadFromAttribute(element, name, optionDefinition);
}
static loadStringOption<T extends string>(element: HTMLElement, name: string, option: IComponentOptions<any>): T {
return element.getAttribute(ComponentOptions.attrNameFromName(name, option)) || ComponentOptions.getAttributeFromAlias(element, option);
}
static loadIconOption(element: HTMLElement, name: string, option: IComponentOptions<any>): string {
let svgIconName = ComponentOptions.loadStringOption(element, name, option);
if (svgIconName == null) {
return null;
}
// Old card templates icons used these values as the icon option. These names have changed since we moved to SVG.
// This avoids breaking old default templates that people may still have after moving to 2.0.
svgIconName = svgIconName.replace('coveo-sprites-replies', 'replies');
svgIconName = svgIconName.replace('coveo-sprites-main-search-active', 'search');
if (Utils.isNullOrUndefined(SVGIcons.icons[svgIconName])) {
new Logger(element).warn(`Icon with name ${svgIconName} not found.`);
return null;
}
svgIconName = Utils.toCamelCase(svgIconName);
return svgIconName;
}
static loadFieldOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>): string {
const field = ComponentOptions.loadStringOption(element, name, option);
Assert.check(!Utils.isNonEmptyString(field) || Utils.isCoveoField(field), field + ' is not a valid field');
return field;
}
static loadFieldConditionOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>): IFieldConditionOption[] {
var attrs = Dom.nodeListToArray(element.attributes).filter(attribute =>
Utils.stringStartsWith(attribute.nodeName, 'data-condition-field-')
);
return attrs.length != 0
? attrs.map(attribute => ({
field: attribute.nodeName.replace('data-condition-field-not-', '').replace('data-condition-field-', ''),
values: Utils.isNonEmptyString(attribute.nodeValue) ? attribute.nodeValue.split(/\s*,\s*/) : null,
reverseCondition: attribute.nodeName.indexOf('data-condition-field-not-') == 0
}))
: undefined;
}
static loadFieldsOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>): string[] {
const fieldsAttr = ComponentOptions.loadStringOption(element, name, option);
if (fieldsAttr == null) {
return null;
}
const fields = fieldsAttr.split(fieldsSeperator);
each(fields, (field: string) => {
Assert.check(Utils.isCoveoField(field), field + ' is not a valid field');
});
return fields;
}
static loadLocalizedStringOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>): string {
const attributeValue = ComponentOptions.loadStringOption(element, name, option);
const locale: string = String['locale'] || String['defaultLocale'];
if (locale != null && attributeValue != null) {
const localeParts = locale.toLowerCase().split('-');
const locales = map(localeParts, (part, i) => localeParts.slice(0, i + 1).join('-'));
const localizers = attributeValue.match(localizer);
if (localizers != null) {
for (let i = 0; i < localizers.length; i++) {
const groups = localizer.exec(localizers[i]);
if (groups != null) {
const lang = groups[1].toLowerCase();
if (contains(locales, lang)) {
return groups[2].replace(/^\s+|\s+$/g, '');
}
}
}
}
return attributeValue != null ? attributeValue.toLocaleString() : null;
}
return attributeValue;
}
static loadNumberOption(element: HTMLElement, name: string, option: IComponentOptionsNumberOption): number {
const attributeValue = ComponentOptions.loadStringOption(element, name, option);
if (attributeValue == null) {
return null;
}
let numberValue = option.float === true ? Utils.parseFloatIfNotUndefined(attributeValue) : Utils.parseIntIfNotUndefined(attributeValue);
if (option.min != null && option.min > numberValue) {
new Logger(element).info(
`Value for option ${name} is less than the possible minimum (Value is ${numberValue}, minimum is ${
option.min
}). It has been forced to its minimum value.`,
option
);
numberValue = option.min;
}
if (option.max != null && option.max < numberValue) {
new Logger(element).info(
`Value for option ${name} is higher than the possible maximum (Value is ${numberValue}, maximum is ${
option.max
}). It has been forced to its maximum value.`,
option
);
numberValue = option.max;
}
return numberValue;
}
static loadBooleanOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>): boolean {
return Utils.parseBooleanIfNotUndefined(ComponentOptions.loadStringOption(element, name, option));
}
static loadListOption(element: HTMLElement, name: string, option: IComponentOptionsListOption): string[] {
const separator = option.separator || /\s*,\s*/;
const attributeValue = ComponentOptions.loadStringOption(element, name, option);
return Utils.isNonEmptyString(attributeValue) ? attributeValue.split(separator) : null;
}
static loadEnumOption(element: HTMLElement, name: string, option: IComponentOptionsOption<any>, _enum: any): number {
const enumAsString = ComponentOptions.loadStringOption(element, name, option);
return enumAsString != null ? _enum[enumAsString] : null;
}
static loadJsonObjectOption<T>(element: HTMLElement, name: string, option: IComponentOptions<any>): T {
const jsonAsString = ComponentOptions.loadStringOption(element, name, option);
if (jsonAsString == null) {
return null;
}
try {
return JSON.parse(jsonAsString) as T;
} catch (exception) {
new Logger(element).info(
`Value for option ${name} is not a valid JSON string (Value is ${jsonAsString}). It has been disabled.`,
exception
);
return null;
}
}
static loadSelectorOption(
element: HTMLElement,
name: string,
option: IComponentOptionsOption<any>,
doc: Document = document
): HTMLElement {
const attributeValue = ComponentOptions.loadStringOption(element, name, option);
return Utils.isNonEmptyString(attributeValue) ? <HTMLElement>doc.querySelector(attributeValue) : null;
}
static loadChildHtmlElementOption(
element: HTMLElement,
name: string,
option: IComponentOptionsChildHtmlElementOption,
doc: Document = document
): HTMLElement {
let htmlElement: HTMLElement;
// Attribute: selector
const selectorAttr = option.selectorAttr || ComponentOptions.attrNameFromName(name, option) + '-selector';
const selector = element.getAttribute(selectorAttr) || ComponentOptions.getAttributeFromAlias(element, option);
if (selector != null) {
htmlElement = <HTMLElement>doc.body.querySelector(selector);
}
// Child
if (htmlElement == null) {
let childSelector = option.childSelector;
if (childSelector == null) {
childSelector = '.' + name;
}
htmlElement = ComponentOptions.loadChildHtmlElementFromSelector(element, childSelector);
}
return htmlElement;
}
static loadChildHtmlElementFromSelector(element: HTMLElement, selector: string): HTMLElement {
Assert.isNonEmptyString(selector);
if ($$(element).is(selector)) {
return element;
}
return <HTMLElement>$$(element).find(selector);
}
static loadChildrenHtmlElementFromSelector(element: HTMLElement, selector: string): HTMLElement[] {
Assert.isNonEmptyString(selector);
return $$(element).findAll(selector);
}
static findParentScrolling(element: HTMLElement, doc: Document = document): HTMLElement {
element = this.findParentScrollLockable(element, doc);
return element instanceof HTMLBodyElement || !ComponentOptions.isElementScrollable(element) ? <any>window : element;
}
static findParentScrollLockable(element: HTMLElement, doc: Document = document): HTMLElement {
if (!element) {
return doc.body;
}
if (ComponentOptions.isElementScrollable(element) || element instanceof HTMLBodyElement || !element.parentElement) {
return element;
}
return ComponentOptions.findParentScrollLockable(element.parentElement, doc);
}
static isElementScrollable(element: HTMLElement) {
const overflowProperty = $$(element).css('overflow-y');
return overflowProperty == 'scroll' || overflowProperty == 'auto';
}
static getAttributeFromAlias(element: HTMLElement, option: IComponentOptions<any>) {
if (isArray(option.alias)) {
let attributeFound;
each(option.alias, alias => {
const attributeFoundWithThisAlias = element.getAttribute(ComponentOptions.attrNameFromName(alias));
if (attributeFoundWithThisAlias) {
attributeFound = attributeFoundWithThisAlias;
}
});
return attributeFound;
}
if (option.alias) {
return element.getAttribute(ComponentOptions.attrNameFromName(option.alias));
} else {
return undefined;
}
}
} | the_stack |
import { ASSERT } from './debug';
// @endif
import { ITilelayer } from './tiled/layers';
import { ELayerType } from './ELayerType';
import { GLTileset, TilesetFlags, ITileProps } from './GLTileset';
import { GLProgram } from './utils/GLProgram';
import { ITileAnimationFrame } from './tiled/Tileset';
interface IAnimationDataFrame
{
/** How long this frame is displayed for. */
duration: number;
/** The time index at which this frame starts being displayed. */
startTime: number;
/** The time index at which this frame is over. */
endTime: number;
/** The id of the tile in the tileset of the frame to use. */
tileid: number;
/** The tile properties from the tileset about this frame's tile. */
props: ITileProps;
}
interface IAnimationData
{
/** The index into our data array of the tile to animate. */
index: number;
/** An array of frame data for the animation. */
frames: IAnimationDataFrame[];
/** The index of the currently active frame. */
activeFrame: number;
/**
* The elapsed time of this animation. We store these separately per
* animation so they can be offset from eachother if so desired.
*/
elapsedTime: number;
/** The maximum amount of time this animation lasts. Sum of all frame durations. */
maxTime: number;
}
/**
* Due to the storage format used tileset images are limited to
* 256 x 256 tiles, and there can only be up to 256 tilesets. Similarly
* a multi-image tileset can only have up-to 256 images.
*
* Since a tileset sheet with 256x256 tiles at 16x16 tile size is 4096x4096
* pixels I think this restriciton is probably OK. Additonally if you actually
* approach the 256 image/tileset limit it will likely be a GPU bandwidth issue
* long before it is an issue with our storage format here.
*
*/
export class GLTilelayer
{
type: ELayerType.Tilelayer = ELayerType.Tilelayer;
gl: WebGLRenderingContext | null = null;
scrollScaleX = 1;
scrollScaleY = 1;
texture: WebGLTexture | null = null;
textureData: Uint8Array;
alpha: number;
private _animations: IAnimationData[] = [];
private _inverseTileCount = new Float32Array(2);
private _repeatTiles = true;
constructor(public readonly desc: ITilelayer, tilesets: ReadonlyArray<GLTileset>)
{
this._inverseTileCount[0] = 1 / desc.width;
this._inverseTileCount[1] = 1 / desc.height;
this.textureData = new Uint8Array(desc.width * desc.height * 4);
this.alpha = desc.opacity;
// @if DEBUG
ASSERT(typeof this.desc.data !== 'string', 'Base64 encoded layer data is not supported.');
// @endif
// If this isn't true then we probably did something wrong or got bad data...
// This has caught me putting in base64 data instead of array data more than once!
if ((desc.width * desc.height) !== this.desc.data.length)
throw new Error('Sizes are off!');
this._buildMapTexture(tilesets);
}
get repeatTiles(): boolean
{
return this._repeatTiles;
}
set repeatTiles(v)
{
if (v !== this._repeatTiles)
{
this._repeatTiles = v;
this._setupTexture(); // delay until next draw?
}
}
glInitialize(gl: WebGLRenderingContext): void
{
this.glTerminate();
this.gl = gl;
this.texture = gl.createTexture();
this._upload();
}
glTerminate(): void
{
if (!this.gl)
return;
if (this.texture)
{
this.gl.deleteTexture(this.texture);
this.texture = null;
}
this.gl = null;
}
/**
* Updates the layer's animations by the given delta time.
*
* @param dt Delta time in milliseconds to perform an update for.
*/
update(dt: number): void
{
let needsUpload = false;
for (let i = 0; i < this._animations.length; ++i)
{
const anim = this._animations[i];
anim.elapsedTime = (anim.elapsedTime + dt) % anim.maxTime;
for (let f = 0; f < anim.frames.length; ++f)
{
const frame = anim.frames[f];
if (anim.elapsedTime >= frame.startTime && anim.elapsedTime < frame.endTime)
{
if (anim.activeFrame !== f)
{
needsUpload = true;
anim.activeFrame = f;
this.textureData[anim.index] = frame.props.coords.x;
this.textureData[anim.index + 1] = frame.props.coords.y;
}
break;
}
}
}
if (needsUpload)
this._uploadData(true);
}
uploadUniforms(shader: GLProgram): void
{
// @if DEBUG
ASSERT(!!this.gl, 'Cannot call `uploadUniforms` before `glInitialize`.');
// @endif
if (!this.gl)
return;
const gl = this.gl;
// @if DEBUG
ASSERT(!!(shader.uniforms.uAlpha
&& shader.uniforms.uRepeatTiles
&& shader.uniforms.uInverseLayerTileCount),
'Invalid uniforms for tile layer.');
// @endif
gl.uniform1f(shader.uniforms.uAlpha!, this.alpha);
gl.uniform1i(shader.uniforms.uRepeatTiles!, this._repeatTiles ? 1 : 0);
gl.uniform2fv(shader.uniforms.uInverseLayerTileCount!, this._inverseTileCount);
}
private _upload(): void
{
this._setupTexture();
this._uploadData(false);
}
private _uploadData(doBind: boolean): void
{
if (!this.gl)
return;
const gl = this.gl;
if (doBind)
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texImage2D(gl.TEXTURE_2D,
0, // level
gl.RGBA, // internal format
this.desc.width,
this.desc.height,
0, // border
gl.RGBA, // format
gl.UNSIGNED_BYTE, // type
this.textureData
);
}
private _setupTexture(doBind: boolean = true): void
{
if (!this.gl)
return;
const gl = this.gl;
if (doBind)
gl.bindTexture(gl.TEXTURE_2D, this.texture);
// MUST be filtered with NEAREST or tile lookup fails
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
if (this._repeatTiles)
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
}
else
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
}
/**
* Builds the texture used as the map for this layer. Each texture has the data
* necessary for the shader to lookup the correct texel to display.
*
* @param tilesets The list of tilesets, who's images will be uploaded to the GPU elsewhere.
*/
private _buildMapTexture(tilesets: ReadonlyArray<GLTileset>): void
{
// TODO:
// - Might be faster to build this texture on the GPU in a framebuffer?
// - Should it then be read back into RAM so it can be modified on CPU?
// - Should it just be calculated at runtime in the main shader (upload tileset metadata)?
// * Isn't this last one the same as what I do here? I'd still
// have to format the tileset data for upload...
// - Can I upload animation data and just lookup the right frame in the shader? That would
// mean I don't have to upload a new layer texture each frame like I do now.
let index = 0;
const data = this.desc.data as number[];
dataloop:
for (let i = 0; i < data.length; ++i)
{
const gid = data[i];
let imgIndex = 0;
if (gid)
{
for (let t = 0; t < tilesets.length; ++t)
{
const tileset = tilesets[t];
const tileprops = tileset.getTileProperties(gid);
if (tileprops)
{
if (tileprops.tile && tileprops.tile.animation)
{
this._addAnimation(index, tileset, tileprops.tile.animation);
}
this.textureData[index++] = tileprops.coords.x;
this.textureData[index++] = tileprops.coords.y;
this.textureData[index++] = tileprops.imgIndex + imgIndex;
this.textureData[index++] =
(tileprops.flippedX ? TilesetFlags.FlippedHorizontalFlag : 0)
| (tileprops.flippedY ? TilesetFlags.FlippedVerticalFlag : 0)
| (tileprops.flippedAD ? TilesetFlags.FlippedAntiDiagonalFlag : 0);
continue dataloop;
}
imgIndex += tilesets[t].images.length;
}
}
// if we reach here, it was because either this tile is 0, meaning
// there is no tile here. Or, we failed to find the tileset for it.
// @if DEBUG
// if we got here from a non-0 gid, then assert.
ASSERT(gid === 0, `Unable to find tileset for gid: ${gid}`);
// @endif
// if we failed to find a tileset, or the gid was 0, just write an empty entry.
this.textureData[index++] = 255;
this.textureData[index++] = 255;
this.textureData[index++] = 255;
this.textureData[index++] = 255;
}
}
private _addAnimation(index: number, tileset: GLTileset, animationFrames: ITileAnimationFrame[]): void
{
let maxTime = 0;
this._animations.push({
index,
activeFrame: -1,
elapsedTime: 0,
frames: animationFrames.map((v) =>
{
const animTileGid = v.tileid + tileset.desc.firstgid;
const animTileProps = tileset.getTileProperties(animTileGid);
// @if DEBUG
ASSERT(!!animTileProps, 'Animated tiles must reference a valid GID from within the same tileset.');
// @endif
return {
duration: v.duration,
tileid: v.tileid,
props: animTileProps!,
startTime: maxTime,
endTime: (maxTime += v.duration),
};
}),
maxTime: 0,
});
this._animations[this._animations.length - 1].maxTime = maxTime;
}
} | the_stack |
import _ from 'lodash';
import { FoxCtx } from 'src/types/index-types';
import {
Component,
ComponentDSL,
Content,
ContentVersion,
Dependencies,
EditorEntry,
File,
IdVersion,
IdVersionNumbers,
} from '@foxpage/foxpage-server-types';
import { LOG, TAG, TYPE } from '../../config/constant';
import { ComponentContentInfo } from '../types/component-types';
import { UpdateContentVersion } from '../types/content-types';
import * as Service from './index';
export class ComponentService {
private static _instance: ComponentService;
constructor() { }
/**
* Single instance
* @returns ComponentService
*/
public static getInstance (): ComponentService {
this._instance || (this._instance = new ComponentService());
return this._instance;
}
/**
* Update component version details, including version number
* @param {UpdateContentVersion} params
* @returns Promise
*/
async updateVersionDetail (
params: UpdateContentVersion,
options: { ctx: FoxCtx },
): Promise<Record<string, number | string | string[]>> {
const versionDetail = await Service.version.info.getDetailById(params.id);
const contentDetail = await Service.content.info.getDetailById(versionDetail.contentId || '');
const missingFields = await Service.version.check.contentFields(contentDetail.fileId, params.content);
if (missingFields.length > 0) {
return { code: 1, data: missingFields }; // Check required fields
}
// Update
params.content.id = versionDetail.contentId || '';
options.ctx.transactions.push(
Service.version.info.updateDetailQuery(params.id, {
version: params.version,
versionNumber: Service.version.number.createNumberFromVersion(params.version),
content: params.content,
}),
);
// Save logs
options.ctx.operations.push(
...Service.log.addLogItem(LOG.VERSION_UPDATE, versionDetail, { fileId: contentDetail?.fileId }),
);
return { code: 0 };
}
/**
* Get component details through id and version
* If the component specifies the version, such as: 1.1.2, then get the version of 1.1.2
* If the component does not specify the version or other circumstances, the live version is taken
*
* Recursively obtain component information that the component depends on
*
* Taking into account the problem of obtaining different versions of the same component,
* and the ids are all using contentId, it is impossible to distinguish the attribution of
* different versions of the same component in the returned results
* So, for the time being, if there are multiple versions of the same component,
* the details will be obtained separately
* @param {any[]} componentInfos The information of all acquired components is used to exclude
* the acquired version information of the components
* @returns Promise Returns the component details information object with contentId_version as the key
*/
async getComponentDetailByIdVersion (
idVersions: IdVersion[],
componentInfos: Record<string, ContentVersion> = {},
): Promise<Record<string, ContentVersion>> {
const idNumbers = await this.getComponentVersionNumberFromVersion(idVersions);
if (idNumbers.length === 0) {
return {};
}
const idVersionNumbers = idNumbers.map((item) => {
return { id: item.id, liveVersionNumber: item.versionNumber };
});
// Get component details
const versionList = await Service.version.list.getContentInfoByIdAndNumber(idVersionNumbers);
componentInfos = Object.assign(
componentInfos,
_.keyBy(versionList, (version) => [version.contentId, version.version].join('_')),
);
// Get the dependency information in the component, and exclude the component information that has been obtained
let dependencies = this.getComponentEditorAndDependends(_.map(versionList, 'content'));
dependencies = _.dropWhile(
dependencies,
(item) => componentInfos[[item.id, item?.version || ''].join('_')],
);
// Recursively get component details
if (dependencies.length > 0) {
const dependenciesComponents = await this.getComponentDetailByIdVersion(dependencies, componentInfos);
componentInfos = Object.assign(componentInfos, dependenciesComponents);
}
return componentInfos;
}
/**
* Get the versionNumber corresponding to version by id, version
* If version is empty or undefined, take the live version corresponding to id
* Return:
* [
* {id:xxx, versionNumbers: [1]},
* {id:xxx, version:0.0.2, versionNumbers: [2]},
* ]
* @param {IdVersion[]} idVersions
* @returns Promise
*/
async getComponentVersionNumberFromVersion (idVersions: IdVersion[]): Promise<IdVersionNumbers[]> {
let idVersionNumbers: IdVersionNumbers[] = [];
let liveIdVersions: IdVersion[] = [];
idVersions.forEach((item) => {
if (item.version) {
const versionNumber = Service.version.number.createNumberFromVersion(item.version);
idVersionNumbers.push(Object.assign({}, item, { versionNumber }));
} else {
liveIdVersions.push(item); // Get the live version
}
});
if (liveIdVersions.length > 0) {
const contentList = await Service.content.list.getDetailByIds(_.map(liveIdVersions, 'id'));
contentList.forEach((content) => {
idVersionNumbers.push({ id: content.id, version: '', versionNumber: content.liveVersionNumber });
});
}
return idVersionNumbers;
}
/**
* Obtain the id and version information of editor and dependencies from the component version
* @param {ContentVersion[]} versionList
* @returns IdVersion
*/
getComponentEditorAndDependends (versionList: Component[]): IdVersion[] {
let componentIdVersion: IdVersion[] = [];
versionList.forEach((version) => {
componentIdVersion = componentIdVersion.concat(version?.resource?.['editor-entry'] || []);
componentIdVersion = componentIdVersion.concat(version?.resource?.dependencies || []);
});
return _.uniqWith(componentIdVersion, _.isEqual);
}
/**
* Obtain the id and version information of editor and dependencies from the component version
* @param {ContentVersion[]} versionList
* @returns IdVersion
*/
getEditorAndDependenceFromComponent (componentList: Component[]): IdVersion[] {
let componentIdVersion: IdVersion[] = [];
componentList.forEach((component) => {
componentIdVersion = componentIdVersion.concat(component?.resource?.['editor-entry'] || []);
componentIdVersion = componentIdVersion.concat(component?.resource?.dependencies || []);
});
return componentIdVersion;
}
/**
* Add the name field to the editor-entry and dependencies data in the component
* Support reference modification
* @param {Component[]} componentList
* @param {Record<string} componentFileObject
* @param {} File>
* @returns Component
*/
addNameToEditorAndDepends (
componentList: ComponentContentInfo[],
componentFileObject: Record<string, File>,
): ComponentContentInfo[] {
componentList.forEach((component) => {
if (!component.name && componentFileObject[component.id]) {
component.name = componentFileObject[component.id]?.name || '';
}
((component?.resource?.dependencies || []) as Dependencies[]).forEach((depend) => {
depend.name = componentFileObject[depend.id]?.name || '';
});
((component?.resource?.['editor-entry'] || []) as EditorEntry[]).forEach((editor) => {
editor.name = componentFileObject[editor.id]?.name || '';
});
});
return componentList;
}
/**
* Get component resource host and path by content ids
*
* entry: { node:'cont_gyEx3GoTu5cCMGY' }
* =>
* entry: {
* node: {
"host": "http://app.ares.fx.xxx.com/",
"downloadHost": "http://app.ares.fx.xxx.com/",
"path": "ares-test/flight-searchbox-container/0.3.1/umd/production.min.js",
"contentId": "cont_gyEx3GoTu5cCMGY",
"origin": "ARES"
}
* }
* @param {ComponentDSL} versionContent
* @returns Promise
*/
async getComponentResourcePath (versionContent: ComponentDSL): Promise<ComponentDSL> {
// Get the corresponding resource information in the component
const contentIds = Service.content.component.getComponentResourceIds(<Component[]>[versionContent]);
const idVersion = this.getComponentEditorAndDependends(<Component[]>[versionContent]);
const editorContentIds = _.map(idVersion, 'id');
const fileContentObject = await Service.file.list.getContentFileByIds(editorContentIds);
contentIds.push(...editorContentIds);
// Append the name of the dependency to dependencies
Service.component.addNameToEditorAndDepends(<ComponentContentInfo[]>[versionContent], fileContentObject);
const contentList = await Service.content.list.getDetailByIds(contentIds);
const fileList = await Service.file.info.getDetailByIds(_.map(contentList, 'fileId'));
const [allFoldersObject, contentAllParents] = await Promise.all([
Service.folder.list.getAllParentsRecursive(_.uniq(_.map(fileList, 'folderId'))),
Service.content.list.getContentAllParents(contentIds),
]);
const appResource = await Service.application.getAppResourceFromContent(contentAllParents);
const contentResource = Service.content.info.getContentResourceTypeInfo(appResource, contentAllParents);
const folderPath: Record<string, string> = {};
// Splicing folder path
Object.keys(allFoldersObject).forEach((folderId) => {
folderPath[folderId] = '/' + _.map(_.drop(allFoldersObject[folderId]), 'folderPath').join('/');
});
const filePath: Record<string, string> = {};
fileList.forEach((file) => {
filePath[file.id] = (folderPath[file.folderId] || '') + '/' + file.name;
});
const resourceObject: Record<string, object> = {};
contentList.forEach((content) => {
resourceObject[content.id] = { realPath: filePath[content.fileId] || '' };
});
versionContent.resource = Service.version.component.assignResourceToComponent(
versionContent?.resource || {},
resourceObject,
{ contentResource },
);
return versionContent;
}
/**
* Get component file info by app id and component name
* @param applicationId
* @param componentName
* @returns
*/
async getComponentInfoByNames (applicationId: string, componentNames: string[]) {
return Service.file.info.find({ applicationId, type: TYPE.COMPONENT, name: { $in: componentNames }, deleted: false })
}
/**
* Set the reference component new live status log
* @param fileId
* @param options
*/
async updateReferLiveVersion (fileId: string, options: { ctx: FoxCtx }): Promise<void> {
// Get referenced applications file id
const referenceFileList = await Service.file.list.find({
type: TYPE.COMPONENT,
deleted: false,
tags: { $elemMatch: { type: TAG.DELIVERY_REFERENCE, 'reference.id': fileId } },
});
(referenceFileList || []).forEach(file => {
options.ctx.operations.push(
...Service.log.addLogItem(LOG.LIVE, ({} as Content), {
fileId: file.id,
}),
);
});
}
} | the_stack |
* @module RPC
*/
import { Guid, Id64String, IDisposable } from "@itwin/core-bentley";
import { IModelRpcProps, RpcManager } from "@itwin/core-common";
import { DescriptorJSON, DescriptorOverrides } from "./content/Descriptor";
import { ItemJSON } from "./content/Item";
import { DisplayValueGroupJSON } from "./content/Value";
import { DiagnosticsScopeLogs } from "./Diagnostics";
import { InstanceKeyJSON } from "./EC";
import { ElementProperties } from "./ElementProperties";
import { PresentationError, PresentationStatus } from "./Error";
import { NodeKeyJSON } from "./hierarchy/Key";
import { NodeJSON } from "./hierarchy/Node";
import { NodePathElementJSON } from "./hierarchy/NodePathElement";
import { KeySetJSON } from "./KeySet";
import { LabelDefinitionJSON } from "./LabelDefinition";
import {
ContentDescriptorRequestOptions, ContentRequestOptions, ContentSourcesRequestOptions, DisplayLabelRequestOptions, DisplayLabelsRequestOptions,
DistinctValuesRequestOptions, ElementPropertiesRequestOptions, FilterByInstancePathsHierarchyRequestOptions, FilterByTextHierarchyRequestOptions,
HierarchyRequestOptions, MultiElementPropertiesRequestOptions, Paged, RequestOptions, SelectionScopeRequestOptions,
SingleElementPropertiesRequestOptions,
} from "./PresentationManagerOptions";
import {
ContentSourcesRpcResult, ElementPropertiesRpcResult, PresentationRpcInterface, PresentationRpcRequestOptions, PresentationRpcResponse,
} from "./PresentationRpcInterface";
import { RulesetVariableJSON } from "./RulesetVariables";
import { SelectionScope } from "./selection/SelectionScope";
import { PagedResponse } from "./Utils";
/**
* Configuration parameters for [[RpcRequestsHandler]].
*
* @internal
*/
export interface RpcRequestsHandlerProps {
/**
* Optional ID used to identify client that requests data. If not specified,
* the handler creates a unique GUID as a client id.
* @internal
*/
clientId?: string;
}
/**
* RPC requests handler that wraps [[PresentationRpcInterface]] and
* adds handling for cases when backend needs to be synced with client
* state.
*
* @internal
*/
export class RpcRequestsHandler implements IDisposable {
private _maxRequestRepeatCount: number = 5;
/** ID that identifies this handler as a client */
public readonly clientId: string;
public constructor(props?: RpcRequestsHandlerProps) {
this.clientId = (props && props.clientId) ? props.clientId : Guid.createValue();
}
public dispose() {
}
// eslint-disable-next-line @typescript-eslint/naming-convention
private get rpcClient(): PresentationRpcInterface { return RpcManager.getClientForInterface(PresentationRpcInterface); }
private async requestRepeatedly<TResult>(func: () => PresentationRpcResponse<TResult>, diagnosticsHandler?: (logs: DiagnosticsScopeLogs[]) => void, repeatCount: number = 1): Promise<TResult> {
let diagnostics: DiagnosticsScopeLogs[] | undefined;
let error: unknown | undefined;
let shouldRepeat = false;
try {
const response = await func();
diagnostics = response.diagnostics;
if (response.statusCode === PresentationStatus.Success)
return response.result!;
if (response.statusCode === PresentationStatus.BackendTimeout && repeatCount < this._maxRequestRepeatCount)
shouldRepeat = true;
else
error = new PresentationError(response.statusCode, response.errorMessage);
} catch (e) {
error = e;
if (repeatCount < this._maxRequestRepeatCount)
shouldRepeat = true;
} finally {
if (diagnosticsHandler && diagnostics)
diagnosticsHandler(diagnostics);
}
if (shouldRepeat) {
++repeatCount;
return this.requestRepeatedly(func, diagnosticsHandler, repeatCount);
}
throw error;
}
/**
* Send the request to backend.
*
* If the backend responds with [[PresentationStatus.BackendTimeout]] or there's an RPC-related error,
* the request is repeated up to `this._maxRequestRepeatCount` times. If we fail to get a valid success or error
* response from the backend, throw the last encountered error.
*
* @internal
*/
public async request<TResult, TOptions extends RequestOptions<IModelRpcProps>, TArg = any>(
func: (token: IModelRpcProps, options: PresentationRpcRequestOptions<TOptions>, ...args: TArg[]) => PresentationRpcResponse<TResult>,
options: TOptions,
...additionalOptions: TArg[]): Promise<TResult> {
const { imodel, diagnostics, ...optionsNoIModel } = options;
const { handler: diagnosticsHandler, ...diagnosticsOptions } = diagnostics ?? {};
const rpcOptions: PresentationRpcRequestOptions<TOptions> = {
...optionsNoIModel,
clientId: this.clientId,
};
if (diagnostics)
rpcOptions.diagnostics = diagnosticsOptions;
const doRequest = async () => func(imodel, rpcOptions, ...additionalOptions);
return this.requestRepeatedly(doRequest, diagnosticsHandler);
}
public async getNodesCount(options: HierarchyRequestOptions<IModelRpcProps, NodeKeyJSON, RulesetVariableJSON>): Promise<number> {
return this.request<number, HierarchyRequestOptions<IModelRpcProps, NodeKeyJSON, RulesetVariableJSON>>(
this.rpcClient.getNodesCount.bind(this.rpcClient), options);
}
public async getPagedNodes(options: Paged<HierarchyRequestOptions<IModelRpcProps, NodeKeyJSON, RulesetVariableJSON>>): Promise<PagedResponse<NodeJSON>> {
return this.request<PagedResponse<NodeJSON>, Paged<HierarchyRequestOptions<IModelRpcProps, NodeKeyJSON, RulesetVariableJSON>>>(
this.rpcClient.getPagedNodes.bind(this.rpcClient), options);
}
public async getNodePaths(options: FilterByInstancePathsHierarchyRequestOptions<IModelRpcProps, RulesetVariableJSON>): Promise<NodePathElementJSON[]> {
return this.request<NodePathElementJSON[], FilterByInstancePathsHierarchyRequestOptions<IModelRpcProps, RulesetVariableJSON>>(
this.rpcClient.getNodePaths.bind(this.rpcClient), options);
}
public async getFilteredNodePaths(options: FilterByTextHierarchyRequestOptions<IModelRpcProps, RulesetVariableJSON>): Promise<NodePathElementJSON[]> {
return this.request<NodePathElementJSON[], FilterByTextHierarchyRequestOptions<IModelRpcProps, RulesetVariableJSON>>(
this.rpcClient.getFilteredNodePaths.bind(this.rpcClient), options);
}
public async getContentSources(options: ContentSourcesRequestOptions<IModelRpcProps>): Promise<ContentSourcesRpcResult> {
return this.request<ContentSourcesRpcResult, ContentSourcesRequestOptions<IModelRpcProps>>(
this.rpcClient.getContentSources.bind(this.rpcClient), options);
}
public async getContentDescriptor(options: ContentDescriptorRequestOptions<IModelRpcProps, KeySetJSON, RulesetVariableJSON>): Promise<DescriptorJSON | undefined> {
return this.request<DescriptorJSON | undefined, ContentDescriptorRequestOptions<IModelRpcProps, KeySetJSON, RulesetVariableJSON>>(
this.rpcClient.getContentDescriptor.bind(this.rpcClient), options);
}
public async getContentSetSize(options: ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>): Promise<number> {
return this.request<number, ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>(
this.rpcClient.getContentSetSize.bind(this.rpcClient), options);
}
public async getPagedContent(options: Paged<ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>) {
return this.request<{ descriptor: DescriptorJSON, contentSet: PagedResponse<ItemJSON> } | undefined, Paged<ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>>(
this.rpcClient.getPagedContent.bind(this.rpcClient), options);
}
public async getPagedContentSet(options: Paged<ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>) {
return this.request<PagedResponse<ItemJSON>, Paged<ContentRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>>(
this.rpcClient.getPagedContentSet.bind(this.rpcClient), options);
}
public async getPagedDistinctValues(options: DistinctValuesRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>): Promise<PagedResponse<DisplayValueGroupJSON>> {
return this.request<PagedResponse<DisplayValueGroupJSON>, DistinctValuesRequestOptions<IModelRpcProps, DescriptorOverrides, KeySetJSON, RulesetVariableJSON>>(
this.rpcClient.getPagedDistinctValues.bind(this.rpcClient), options);
}
public async getElementProperties(options: SingleElementPropertiesRequestOptions<IModelRpcProps>): Promise<ElementProperties | undefined>;
public async getElementProperties(options: MultiElementPropertiesRequestOptions<IModelRpcProps>): Promise<PagedResponse<ElementProperties>>;
public async getElementProperties(options: ElementPropertiesRequestOptions<IModelRpcProps>): Promise<ElementPropertiesRpcResult> {
return this.request<ElementPropertiesRpcResult, ElementPropertiesRequestOptions<IModelRpcProps>>(
this.rpcClient.getElementProperties.bind(this.rpcClient), options);
}
public async getDisplayLabelDefinition(options: DisplayLabelRequestOptions<IModelRpcProps, InstanceKeyJSON>): Promise<LabelDefinitionJSON> {
return this.request<LabelDefinitionJSON, DisplayLabelRequestOptions<IModelRpcProps, InstanceKeyJSON>, any>(
this.rpcClient.getDisplayLabelDefinition.bind(this.rpcClient), options);
}
public async getPagedDisplayLabelDefinitions(options: DisplayLabelsRequestOptions<IModelRpcProps, InstanceKeyJSON>): Promise<PagedResponse<LabelDefinitionJSON>> {
return this.request<PagedResponse<LabelDefinitionJSON>, DisplayLabelsRequestOptions<IModelRpcProps, InstanceKeyJSON>, any>(
this.rpcClient.getPagedDisplayLabelDefinitions.bind(this.rpcClient), options);
}
public async getSelectionScopes(options: SelectionScopeRequestOptions<IModelRpcProps>): Promise<SelectionScope[]> {
return this.request<SelectionScope[], SelectionScopeRequestOptions<IModelRpcProps>>(
this.rpcClient.getSelectionScopes.bind(this.rpcClient), options);
}
public async computeSelection(options: SelectionScopeRequestOptions<IModelRpcProps>, ids: Id64String[], scopeId: string): Promise<KeySetJSON> {
return this.request<KeySetJSON, SelectionScopeRequestOptions<IModelRpcProps>>(
this.rpcClient.computeSelection.bind(this.rpcClient), options, ids, scopeId);
}
} | the_stack |
import { Model } from '../model';
import { Repository as BaseRepository, Resource } from '../repository';
import { InputBox, Git, API, Repository, Remote, RepositoryState, Branch, ForcePushMode, Ref, Submodule, Commit, Change, RepositoryUIState, Status, LogOptions, APIState, CommitOptions, RefType, RemoteSourceProvider, CredentialsProvider, BranchQuery, PushErrorHandler, PublishEvent, FetchOptions } from './git';
import { Event, SourceControlInputBox, Uri, SourceControl, Disposable, commands } from 'vscode';
import { mapEvent } from '../util';
import { toGitUri } from '../uri';
import { pickRemoteSource, PickRemoteSourceOptions } from '../remoteSource';
import { GitExtensionImpl } from './extension';
class ApiInputBox implements InputBox {
set value(value: string) { this._inputBox.value = value; }
get value(): string { return this._inputBox.value; }
constructor(private _inputBox: SourceControlInputBox) { }
}
export class ApiChange implements Change {
get uri(): Uri { return this.resource.resourceUri; }
get originalUri(): Uri { return this.resource.original; }
get renameUri(): Uri | undefined { return this.resource.renameResourceUri; }
get status(): Status { return this.resource.type; }
constructor(private readonly resource: Resource) { }
}
export class ApiRepositoryState implements RepositoryState {
get HEAD(): Branch | undefined { return this._repository.HEAD; }
get refs(): Ref[] { return [...this._repository.refs]; }
get remotes(): Remote[] { return [...this._repository.remotes]; }
get submodules(): Submodule[] { return [...this._repository.submodules]; }
get rebaseCommit(): Commit | undefined { return this._repository.rebaseCommit; }
get mergeChanges(): Change[] { return this._repository.mergeGroup.resourceStates.map(r => new ApiChange(r)); }
get indexChanges(): Change[] { return this._repository.indexGroup.resourceStates.map(r => new ApiChange(r)); }
get workingTreeChanges(): Change[] { return this._repository.workingTreeGroup.resourceStates.map(r => new ApiChange(r)); }
readonly onDidChange: Event<void> = this._repository.onDidRunGitStatus;
constructor(private _repository: BaseRepository) { }
}
export class ApiRepositoryUIState implements RepositoryUIState {
get selected(): boolean { return this._sourceControl.selected; }
readonly onDidChange: Event<void> = mapEvent<boolean, void>(this._sourceControl.onDidChangeSelection, () => null);
constructor(private _sourceControl: SourceControl) { }
}
export class ApiRepository implements Repository {
readonly rootUri: Uri = Uri.file(this._repository.root);
readonly inputBox: InputBox = new ApiInputBox(this._repository.inputBox);
readonly state: RepositoryState = new ApiRepositoryState(this._repository);
readonly ui: RepositoryUIState = new ApiRepositoryUIState(this._repository.sourceControl);
constructor(private _repository: BaseRepository) { }
apply(patch: string, reverse?: boolean): Promise<void> {
return this._repository.apply(patch, reverse);
}
getConfigs(): Promise<{ key: string; value: string; }[]> {
return this._repository.getConfigs();
}
getConfig(key: string): Promise<string> {
return this._repository.getConfig(key);
}
setConfig(key: string, value: string): Promise<string> {
return this._repository.setConfig(key, value);
}
getGlobalConfig(key: string): Promise<string> {
return this._repository.getGlobalConfig(key);
}
getObjectDetails(treeish: string, path: string): Promise<{ mode: string; object: string; size: number; }> {
return this._repository.getObjectDetails(treeish, path);
}
detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
return this._repository.detectObjectType(object);
}
buffer(ref: string, filePath: string): Promise<Buffer> {
return this._repository.buffer(ref, filePath);
}
show(ref: string, path: string): Promise<string> {
return this._repository.show(ref, path);
}
getCommit(ref: string): Promise<Commit> {
return this._repository.getCommit(ref);
}
clean(paths: string[]) {
return this._repository.clean(paths.map(p => Uri.file(p)));
}
diff(cached?: boolean) {
return this._repository.diff(cached);
}
diffWithHEAD(): Promise<Change[]>;
diffWithHEAD(path: string): Promise<string>;
diffWithHEAD(path?: string): Promise<string | Change[]> {
return this._repository.diffWithHEAD(path);
}
diffWith(ref: string): Promise<Change[]>;
diffWith(ref: string, path: string): Promise<string>;
diffWith(ref: string, path?: string): Promise<string | Change[]> {
return this._repository.diffWith(ref, path);
}
diffIndexWithHEAD(): Promise<Change[]>;
diffIndexWithHEAD(path: string): Promise<string>;
diffIndexWithHEAD(path?: string): Promise<string | Change[]> {
return this._repository.diffIndexWithHEAD(path);
}
diffIndexWith(ref: string): Promise<Change[]>;
diffIndexWith(ref: string, path: string): Promise<string>;
diffIndexWith(ref: string, path?: string): Promise<string | Change[]> {
return this._repository.diffIndexWith(ref, path);
}
diffBlobs(object1: string, object2: string): Promise<string> {
return this._repository.diffBlobs(object1, object2);
}
diffBetween(ref1: string, ref2: string): Promise<Change[]>;
diffBetween(ref1: string, ref2: string, path: string): Promise<string>;
diffBetween(ref1: string, ref2: string, path?: string): Promise<string | Change[]> {
return this._repository.diffBetween(ref1, ref2, path);
}
hashObject(data: string): Promise<string> {
return this._repository.hashObject(data);
}
createBranch(name: string, checkout: boolean, ref?: string | undefined): Promise<void> {
return this._repository.branch(name, checkout, ref);
}
deleteBranch(name: string, force?: boolean): Promise<void> {
return this._repository.deleteBranch(name, force);
}
getBranch(name: string): Promise<Branch> {
return this._repository.getBranch(name);
}
getBranches(query: BranchQuery): Promise<Ref[]> {
return this._repository.getBranches(query);
}
setBranchUpstream(name: string, upstream: string): Promise<void> {
return this._repository.setBranchUpstream(name, upstream);
}
getMergeBase(ref1: string, ref2: string): Promise<string> {
return this._repository.getMergeBase(ref1, ref2);
}
status(): Promise<void> {
return this._repository.status();
}
checkout(treeish: string): Promise<void> {
return this._repository.checkout(treeish);
}
addRemote(name: string, url: string): Promise<void> {
return this._repository.addRemote(name, url);
}
removeRemote(name: string): Promise<void> {
return this._repository.removeRemote(name);
}
renameRemote(name: string, newName: string): Promise<void> {
return this._repository.renameRemote(name, newName);
}
fetch(arg0?: FetchOptions | string | undefined,
ref?: string | undefined,
depth?: number | undefined,
prune?: boolean | undefined
): Promise<void> {
if (arg0 !== undefined && typeof arg0 !== 'string') {
return this._repository.fetch(arg0);
}
return this._repository.fetch({ remote: arg0, ref, depth, prune });
}
pull(unshallow?: boolean): Promise<void> {
return this._repository.pull(undefined, unshallow);
}
push(remoteName?: string, branchName?: string, setUpstream: boolean = false, force?: ForcePushMode): Promise<void> {
return this._repository.pushTo(remoteName, branchName, setUpstream, force);
}
blame(path: string): Promise<string> {
return this._repository.blame(path);
}
log(options?: LogOptions): Promise<Commit[]> {
return this._repository.log(options);
}
commit(message: string, opts?: CommitOptions): Promise<void> {
return this._repository.commit(message, opts);
}
}
export class ApiGit implements Git {
get path(): string { return this._model.git.path; }
constructor(private _model: Model) { }
}
export class ApiImpl implements API {
readonly git = new ApiGit(this._model);
get state(): APIState {
return this._model.state;
}
get onDidChangeState(): Event<APIState> {
return this._model.onDidChangeState;
}
get onDidPublish(): Event<PublishEvent> {
return this._model.onDidPublish;
}
get onDidOpenRepository(): Event<Repository> {
return mapEvent(this._model.onDidOpenRepository, r => new ApiRepository(r));
}
get onDidCloseRepository(): Event<Repository> {
return mapEvent(this._model.onDidCloseRepository, r => new ApiRepository(r));
}
get repositories(): Repository[] {
return this._model.repositories.map(r => new ApiRepository(r));
}
toGitUri(uri: Uri, ref: string): Uri {
return toGitUri(uri, ref);
}
getRepository(uri: Uri): Repository | null {
const result = this._model.getRepository(uri);
return result ? new ApiRepository(result) : null;
}
async init(root: Uri): Promise<Repository | null> {
const path = root.fsPath;
await this._model.git.init(path);
await this._model.openRepository(path);
return this.getRepository(root) || null;
}
async openRepository(root: Uri): Promise<Repository | null> {
await this._model.openRepository(root.fsPath);
return this.getRepository(root) || null;
}
registerRemoteSourceProvider(provider: RemoteSourceProvider): Disposable {
return this._model.registerRemoteSourceProvider(provider);
}
registerCredentialsProvider(provider: CredentialsProvider): Disposable {
return this._model.registerCredentialsProvider(provider);
}
registerPushErrorHandler(handler: PushErrorHandler): Disposable {
return this._model.registerPushErrorHandler(handler);
}
constructor(private _model: Model) { }
}
function getRefType(type: RefType): string {
switch (type) {
case RefType.Head: return 'Head';
case RefType.RemoteHead: return 'RemoteHead';
case RefType.Tag: return 'Tag';
}
return 'unknown';
}
function getStatus(status: Status): string {
switch (status) {
case Status.INDEX_MODIFIED: return 'INDEX_MODIFIED';
case Status.INDEX_ADDED: return 'INDEX_ADDED';
case Status.INDEX_DELETED: return 'INDEX_DELETED';
case Status.INDEX_RENAMED: return 'INDEX_RENAMED';
case Status.INDEX_COPIED: return 'INDEX_COPIED';
case Status.MODIFIED: return 'MODIFIED';
case Status.DELETED: return 'DELETED';
case Status.UNTRACKED: return 'UNTRACKED';
case Status.IGNORED: return 'IGNORED';
case Status.INTENT_TO_ADD: return 'INTENT_TO_ADD';
case Status.ADDED_BY_US: return 'ADDED_BY_US';
case Status.ADDED_BY_THEM: return 'ADDED_BY_THEM';
case Status.DELETED_BY_US: return 'DELETED_BY_US';
case Status.DELETED_BY_THEM: return 'DELETED_BY_THEM';
case Status.BOTH_ADDED: return 'BOTH_ADDED';
case Status.BOTH_DELETED: return 'BOTH_DELETED';
case Status.BOTH_MODIFIED: return 'BOTH_MODIFIED';
}
return 'UNKNOWN';
}
export function registerAPICommands(extension: GitExtensionImpl): Disposable {
const disposables: Disposable[] = [];
disposables.push(commands.registerCommand('git.api.getRepositories', () => {
const api = extension.getAPI(1);
return api.repositories.map(r => r.rootUri.toString());
}));
disposables.push(commands.registerCommand('git.api.getRepositoryState', (uri: string) => {
const api = extension.getAPI(1);
const repository = api.getRepository(Uri.parse(uri));
if (!repository) {
return null;
}
const state = repository.state;
const ref = (ref: Ref | undefined) => (ref && { ...ref, type: getRefType(ref.type) });
const change = (change: Change) => ({
uri: change.uri.toString(),
originalUri: change.originalUri.toString(),
renameUri: change.renameUri?.toString(),
status: getStatus(change.status)
});
return {
HEAD: ref(state.HEAD),
refs: state.refs.map(ref),
remotes: state.remotes,
submodules: state.submodules,
rebaseCommit: state.rebaseCommit,
mergeChanges: state.mergeChanges.map(change),
indexChanges: state.indexChanges.map(change),
workingTreeChanges: state.workingTreeChanges.map(change)
};
}));
disposables.push(commands.registerCommand('git.api.getRemoteSources', (opts?: PickRemoteSourceOptions) => {
if (!extension.model) {
return;
}
return pickRemoteSource(extension.model, opts as any);
}));
return Disposable.from(...disposables);
} | the_stack |
import {
AssertionError,
AssertionErrorConstructorOptions,
} from "./assertion_error.ts";
import * as asserts from "../testing/asserts.ts";
import { inspect } from "./util.ts";
import {
ERR_AMBIGUOUS_ARGUMENT,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS,
} from "./_errors.ts";
interface ExtendedAssertionErrorConstructorOptions
extends AssertionErrorConstructorOptions {
generatedMessage?: boolean;
}
// TODO(uki00a): This function is a workaround for setting the `generatedMessage` property flexibly.
function createAssertionError(
options: ExtendedAssertionErrorConstructorOptions,
): AssertionError {
const error = new AssertionError(options);
if (options.generatedMessage) {
error.generatedMessage = true;
}
return error;
}
/** Converts the std assertion error to node.js assertion error */
function toNode(
fn: () => void,
opts?: {
actual: unknown;
expected: unknown;
message?: string | Error;
operator?: string;
},
) {
const { operator, message, actual, expected } = opts || {};
try {
fn();
} catch (e) {
if (e instanceof asserts.AssertionError) {
if (typeof message === "string") {
throw new AssertionError({
operator,
message,
actual,
expected,
});
} else if (message instanceof Error) {
throw message;
} else {
throw new AssertionError({
operator,
message: e.message,
actual,
expected,
});
}
}
throw e;
}
}
function assert(actual: unknown, message?: string | Error): asserts actual {
if (arguments.length === 0) {
throw new AssertionError({
message: "No value argument passed to `assert.ok()`",
});
}
toNode(
() => asserts.assert(actual),
{ message, actual, expected: true },
);
}
const ok = assert;
function throws(
fn: () => void,
error?: RegExp | Function | Error,
message?: string,
): void {
// Check arg types
if (typeof fn !== "function") {
throw new ERR_INVALID_ARG_TYPE("fn", "function", fn);
}
if (
typeof error === "object" && error !== null &&
Object.getPrototypeOf(error) === Object.prototype &&
Object.keys(error).length === 0
) {
// error is an empty object
throw new ERR_INVALID_ARG_VALUE(
"error",
error,
"may not be an empty object",
);
}
if (typeof message === "string") {
if (
!(error instanceof RegExp) && typeof error !== "function" &&
!(error instanceof Error) && typeof error !== "object"
) {
throw new ERR_INVALID_ARG_TYPE("error", [
"Function",
"Error",
"RegExp",
"Object",
], error);
}
} else {
if (
typeof error !== "undefined" && typeof error !== "string" &&
!(error instanceof RegExp) && typeof error !== "function" &&
!(error instanceof Error) && typeof error !== "object"
) {
throw new ERR_INVALID_ARG_TYPE("error", [
"Function",
"Error",
"RegExp",
"Object",
], error);
}
}
// Checks test function
try {
fn();
} catch (e) {
if (
validateThrownError(e, error, message, {
operator: throws,
})
) {
return;
}
}
if (message) {
let msg = `Missing expected exception: ${message}`;
if (typeof error === "function" && error?.name) {
msg = `Missing expected exception (${error.name}): ${message}`;
}
throw new AssertionError({
message: msg,
operator: "throws",
actual: undefined,
expected: error,
});
} else if (typeof error === "string") {
// Use case of throws(fn, message)
throw new AssertionError({
message: `Missing expected exception: ${error}`,
operator: "throws",
actual: undefined,
expected: undefined,
});
} else if (typeof error === "function" && error?.prototype !== undefined) {
throw new AssertionError({
message: `Missing expected exception (${error.name}).`,
operator: "throws",
actual: undefined,
expected: error,
});
} else {
throw new AssertionError({
message: "Missing expected exception.",
operator: "throws",
actual: undefined,
expected: error,
});
}
}
function doesNotThrow(
fn: () => void,
message?: string,
): void;
function doesNotThrow(
fn: () => void,
error?: Function,
message?: string | Error,
): void;
function doesNotThrow(
fn: () => void,
error?: RegExp,
message?: string,
): void;
function doesNotThrow(
fn: () => void,
expected?: Function | RegExp | string,
message?: string | Error,
): void {
// Check arg type
if (typeof fn !== "function") {
throw new ERR_INVALID_ARG_TYPE("fn", "function", fn);
} else if (
!(expected instanceof RegExp) && typeof expected !== "function" &&
typeof expected !== "string" && typeof expected !== "undefined"
) {
throw new ERR_INVALID_ARG_TYPE("expected", ["Function", "RegExp"], fn);
}
// Checks test function
try {
fn();
} catch (e) {
gotUnwantedException(e, expected, message, doesNotThrow);
}
return;
}
function equal(
actual: unknown,
expected: unknown,
message?: string | Error,
): void {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
if (actual == expected) {
return;
}
if (Number.isNaN(actual) && Number.isNaN(expected)) {
return;
}
if (typeof message === "string") {
throw new AssertionError({
message,
});
} else if (message instanceof Error) {
throw message;
}
toNode(
() => asserts.assertStrictEquals(actual, expected),
{
message: message || `${actual} == ${expected}`,
operator: "==",
actual,
expected,
},
);
}
function notEqual(
actual: unknown,
expected: unknown,
message?: string | Error,
): void {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
if (Number.isNaN(actual) && Number.isNaN(expected)) {
throw new AssertionError({
message: `${actual} != ${expected}`,
operator: "!=",
actual,
expected,
});
}
if (actual != expected) {
return;
}
if (typeof message === "string") {
throw new AssertionError({
message,
});
} else if (message instanceof Error) {
throw message;
}
toNode(
() => asserts.assertNotStrictEquals(actual, expected),
{
message: message || `${actual} != ${expected}`,
operator: "!=",
actual,
expected,
},
);
}
function strictEqual(
actual: unknown,
expected: unknown,
message?: string | Error,
): void {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
toNode(
() => asserts.assertStrictEquals(actual, expected),
{ message, operator: "strictEqual", actual, expected },
);
}
function notStrictEqual(
actual: unknown,
expected: unknown,
message?: string | Error,
) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
toNode(
() => asserts.assertNotStrictEquals(actual, expected),
{ message, actual, expected, operator: "notStrictEqual" },
);
}
function deepEqual() {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
// TODO(kt3k): Implement deepEqual
throw new Error("Not implemented");
}
function notDeepEqual() {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
// TODO(kt3k): Implement notDeepEqual
throw new Error("Not implemented");
}
function deepStrictEqual(
actual: unknown,
expected: unknown,
message?: string | Error,
) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
toNode(
() => asserts.assertEquals(actual, expected),
{ message, actual, expected, operator: "deepStrictEqual" },
);
}
function notDeepStrictEqual(
actual: unknown,
expected: unknown,
message?: string | Error,
) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "expected");
}
toNode(
() => asserts.assertNotEquals(actual, expected),
{ message, actual, expected, operator: "deepNotStrictEqual" },
);
}
function fail(message?: string | Error): never {
if (typeof message === "string" || message == null) {
throw createAssertionError({
message: message ?? "Failed",
operator: "fail",
generatedMessage: message == null,
});
} else {
throw message;
}
}
function match(actual: string, regexp: RegExp, message?: string | Error) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("actual", "regexp");
}
if (!(regexp instanceof RegExp)) {
throw new ERR_INVALID_ARG_TYPE("regexp", "RegExp", regexp);
}
toNode(
() => asserts.assertMatch(actual, regexp),
{ message, actual, expected: regexp, operator: "match" },
);
}
function doesNotMatch(
string: string,
regexp: RegExp,
message?: string | Error,
) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS("string", "regexp");
}
if (!(regexp instanceof RegExp)) {
throw new ERR_INVALID_ARG_TYPE("regexp", "RegExp", regexp);
}
if (typeof string !== "string") {
if (message instanceof Error) {
throw message;
}
throw new AssertionError({
message: message ||
`The "string" argument must be of type string. Received type ${typeof string} (${
inspect(string)
})`,
actual: string,
expected: regexp,
operator: "doesNotMatch",
});
}
toNode(
() => asserts.assertNotMatch(string, regexp),
{ message, actual: string, expected: regexp, operator: "doesNotMatch" },
);
}
function strict(actual: unknown, message?: string | Error): asserts actual {
if (arguments.length === 0) {
throw new AssertionError({
message: "No value argument passed to `assert.ok()`",
});
}
assert(actual, message);
}
function rejects(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
error?: RegExp | Function | Error,
): Promise<void>;
function rejects(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
message?: string,
): Promise<void>;
// Intentionally avoid using async/await because test-assert-async.js requires it
function rejects(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
error?: RegExp | Function | Error | string,
message?: string,
): Promise<void> {
let promise: Promise<void>;
if (typeof asyncFn === "function") {
try {
promise = asyncFn();
} catch (err) {
// If `asyncFn` throws an error synchronously, this function returns a rejected promise.
return Promise.reject(err);
}
if (!isValidThenable(promise)) {
return Promise.reject(
new ERR_INVALID_RETURN_VALUE(
"instance of Promise",
"promiseFn",
promise,
),
);
}
} else if (!isValidThenable(asyncFn)) {
return Promise.reject(
new ERR_INVALID_ARG_TYPE("promiseFn", ["function", "Promise"], asyncFn),
);
} else {
promise = asyncFn;
}
function onFulfilled(): Promise<void> {
let message = "Missing expected rejection";
if (typeof error === "string") {
message += `: ${error}`;
} else if (typeof error === "function" && error.prototype !== undefined) {
message += ` (${error.name}).`;
} else {
message += ".";
}
return Promise.reject(createAssertionError({
message,
operator: "rejects",
generatedMessage: true,
}));
}
// deno-lint-ignore camelcase
function rejects_onRejected(e: Error): void { // TODO(uki00a): In order to `test-assert-async.js` pass, intentionally adds `rejects_` as a prefix.
if (
validateThrownError(e, error, message, {
operator: rejects,
validationFunctionName: "validate",
})
) {
return;
}
}
return promise.then(onFulfilled, rejects_onRejected);
}
function doesNotReject(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
error?: RegExp | Function,
): Promise<void>;
function doesNotReject(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
message?: string,
): Promise<void>;
// Intentionally avoid using async/await because test-assert-async.js requires it
function doesNotReject(
// deno-lint-ignore no-explicit-any
asyncFn: Promise<any> | (() => Promise<any>),
error?: RegExp | Function | string,
message?: string,
): Promise<void> {
// deno-lint-ignore no-explicit-any
let promise: Promise<any>;
if (typeof asyncFn === "function") {
try {
const value = asyncFn();
if (!isValidThenable(value)) {
return Promise.reject(
new ERR_INVALID_RETURN_VALUE(
"instance of Promise",
"promiseFn",
value,
),
);
}
promise = value;
} catch (e) {
// If `asyncFn` throws an error synchronously, this function returns a rejected promise.
return Promise.reject(e);
}
} else if (!isValidThenable(asyncFn)) {
return Promise.reject(
new ERR_INVALID_ARG_TYPE("promiseFn", ["function", "Promise"], asyncFn),
);
} else {
promise = asyncFn;
}
return promise.then(
() => {},
(e) => gotUnwantedException(e, error, message, doesNotReject),
);
}
function gotUnwantedException(
// deno-lint-ignore no-explicit-any
e: any,
expected: RegExp | Function | string | null | undefined,
message: string | Error | null | undefined,
operator: Function,
): never {
if (typeof expected === "string") {
// The use case of doesNotThrow(fn, message);
throw new AssertionError({
message:
`Got unwanted exception: ${expected}\nActual message: "${e.message}"`,
operator: operator.name,
});
} else if (
typeof expected === "function" && expected.prototype !== undefined
) {
// The use case of doesNotThrow(fn, Error, message);
if (e instanceof expected) {
let msg = `Got unwanted exception: ${e.constructor?.name}`;
if (message) {
msg += ` ${String(message)}`;
}
throw new AssertionError({
message: msg,
operator: operator.name,
});
} else if (expected.prototype instanceof Error) {
throw e;
} else {
const result = expected(e);
if (result === true) {
let msg = `Got unwanted rejection.\nActual message: "${e.message}"`;
if (message) {
msg += ` ${String(message)}`;
}
throw new AssertionError({
message: msg,
operator: operator.name,
});
}
}
throw e;
} else {
if (message) {
throw new AssertionError({
message: `Got unwanted exception: ${message}\nActual message: "${
e ? e.message : String(e)
}"`,
operator: operator.name,
});
}
throw new AssertionError({
message: `Got unwanted exception.\nActual message: "${
e ? e.message : String(e)
}"`,
operator: operator.name,
});
}
}
/**
* Throws `value` if the value is not `null` or `undefined`.
*
* @param err
*/
// deno-lint-ignore no-explicit-any
function ifError(err: any) {
if (err !== null && err !== undefined) {
let message = "ifError got unwanted exception: ";
if (typeof err === "object" && typeof err.message === "string") {
if (err.message.length === 0 && err.constructor) {
message += err.constructor.name;
} else {
message += err.message;
}
} else {
message += inspect(err);
}
const newErr = new AssertionError({
actual: err,
expected: null,
operator: "ifError",
message,
stackStartFn: ifError,
});
// Make sure we actually have a stack trace!
const origStack = err.stack;
if (typeof origStack === "string") {
// This will remove any duplicated frames from the error frames taken
// from within `ifError` and add the original error frames to the newly
// created ones.
const tmp2 = origStack.split("\n");
tmp2.shift();
// Filter all frames existing in err.stack.
let tmp1 = newErr!.stack?.split("\n");
for (const errFrame of tmp2) {
// Find the first occurrence of the frame.
const pos = tmp1?.indexOf(errFrame);
if (pos !== -1) {
// Only keep new frames.
tmp1 = tmp1?.slice(0, pos);
break;
}
}
newErr.stack = `${tmp1?.join("\n")}\n${tmp2.join("\n")}`;
}
throw newErr;
}
}
interface ValidateThrownErrorOptions {
operator: Function;
validationFunctionName?: string;
}
function validateThrownError(
// deno-lint-ignore no-explicit-any
e: any,
error: RegExp | Function | Error | string | null | undefined,
message: string | undefined | null,
options: ValidateThrownErrorOptions,
): boolean {
if (typeof error === "string") {
if (message != null) {
throw new ERR_INVALID_ARG_TYPE(
"error",
["Object", "Error", "Function", "RegExp"],
error,
);
} else if (typeof e === "object" && e !== null) {
if (e.message === error) {
throw new ERR_AMBIGUOUS_ARGUMENT(
"error/message",
`The error message "${e.message}" is identical to the message.`,
);
}
} else if (e === error) {
throw new ERR_AMBIGUOUS_ARGUMENT(
"error/message",
`The error "${e}" is identical to the message.`,
);
}
message = error;
error = undefined;
}
if (
error instanceof Function && error.prototype !== undefined &&
error.prototype instanceof Error
) {
// error is a constructor
if (e instanceof error) {
return true;
}
throw createAssertionError({
message:
`The error is expected to be an instance of "${error.name}". Received "${e
?.constructor?.name}"\n\nError message:\n\n${e?.message}`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: true,
});
}
if (error instanceof Function) {
const received = error(e);
if (received === true) {
return true;
}
throw createAssertionError({
message: `The ${
options.validationFunctionName
? `"${options.validationFunctionName}" validation`
: "validation"
} function is expected to return "true". Received ${
inspect(received)
}\n\nCaught error:\n\n${e}`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: true,
});
}
if (error instanceof RegExp) {
if (error.test(String(e))) {
return true;
}
throw createAssertionError({
message:
`The input did not match the regular expression ${error.toString()}. Input:\n\n'${
String(e)
}'\n`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: true,
});
}
if (typeof error === "object" && error !== null) {
const keys = Object.keys(error);
if (error instanceof Error) {
keys.push("name", "message");
}
for (const k of keys) {
if (e == null) {
throw createAssertionError({
message: message || "object is expected to thrown, but got null",
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: message == null,
});
}
if (typeof e === "string") {
throw createAssertionError({
message: message ||
`object is expected to thrown, but got string: ${e}`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: message == null,
});
}
if (typeof e === "number") {
throw createAssertionError({
message: message ||
`object is expected to thrown, but got number: ${e}`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: message == null,
});
}
if (!(k in e)) {
throw createAssertionError({
message: message || `A key in the expected object is missing: ${k}`,
actual: e,
expected: error,
operator: options.operator.name,
generatedMessage: message == null,
});
}
const actual = e[k];
// deno-lint-ignore no-explicit-any
const expected = (error as any)[k];
if (typeof actual === "string" && expected instanceof RegExp) {
match(actual, expected);
} else {
deepStrictEqual(actual, expected);
}
}
return true;
}
if (typeof error === "undefined") {
return true;
}
throw createAssertionError({
message: `Invalid expectation: ${error}`,
operator: options.operator.name,
generatedMessage: true,
});
}
// deno-lint-ignore no-explicit-any
function isValidThenable(maybeThennable: any): boolean {
if (!maybeThennable) {
return false;
}
if (maybeThennable instanceof Promise) {
return true;
}
const isThenable = typeof maybeThennable.then === "function" &&
typeof maybeThennable.catch === "function";
return isThenable && typeof maybeThennable !== "function";
}
Object.assign(strict, {
AssertionError,
deepEqual: deepStrictEqual,
deepStrictEqual,
doesNotMatch,
doesNotReject,
doesNotThrow,
equal: strictEqual,
fail,
ifError,
match,
notDeepEqual: notDeepStrictEqual,
notDeepStrictEqual,
notEqual: notStrictEqual,
notStrictEqual,
ok,
rejects,
strict,
strictEqual,
throws,
});
export default Object.assign(assert, {
AssertionError,
deepEqual,
deepStrictEqual,
doesNotMatch,
doesNotReject,
doesNotThrow,
equal,
fail,
ifError,
match,
notDeepEqual,
notDeepStrictEqual,
notEqual,
notStrictEqual,
ok,
rejects,
strict,
strictEqual,
throws,
});
export {
AssertionError,
deepEqual,
deepStrictEqual,
doesNotMatch,
doesNotReject,
doesNotThrow,
equal,
fail,
ifError,
match,
notDeepEqual,
notDeepStrictEqual,
notEqual,
notStrictEqual,
ok,
rejects,
strict,
strictEqual,
throws,
}; | the_stack |
import React from "react"
import globalScope, { MockAbortController } from "./globalScope"
import { IfInitial, IfPending, IfFulfilled, IfRejected, IfSettled } from "./helpers"
import propTypes from "./propTypes"
import {
neverSettle,
ActionTypes,
init,
dispatchMiddleware,
reducer as asyncReducer,
} from "./reducer"
import {
AsyncProps,
AsyncState,
InitialChildren,
PendingChildren,
FulfilledChildren,
SettledChildren,
RejectedChildren,
AsyncAction,
ReducerAsyncState,
} from "./types"
export interface InitialProps<T> {
children?: InitialChildren<T>
persist?: boolean
}
export interface PendingProps<T> {
children?: PendingChildren<T>
initial?: boolean
}
export interface FulfilledProps<T> {
children?: FulfilledChildren<T>
persist?: boolean
}
export interface RejectedProps<T> {
children?: RejectedChildren<T>
persist?: boolean
}
export interface SettledProps<T> {
children?: SettledChildren<T>
persist?: boolean
}
class Async<T> extends React.Component<AsyncProps<T>, AsyncState<T>> {}
type GenericAsync = typeof Async & {
Initial<T>(props: InitialProps<T>): JSX.Element
Pending<T>(props: PendingProps<T>): JSX.Element
Loading<T>(props: PendingProps<T>): JSX.Element
Fulfilled<T>(props: FulfilledProps<T>): JSX.Element
Resolved<T>(props: FulfilledProps<T>): JSX.Element
Rejected<T>(props: RejectedProps<T>): JSX.Element
Settled<T>(props: SettledProps<T>): JSX.Element
}
export type AsyncConstructor<T> = React.ComponentClass<AsyncProps<T>> & {
Initial: React.FC<InitialProps<T>>
Pending: React.FC<PendingProps<T>>
Loading: React.FC<PendingProps<T>>
Fulfilled: React.FC<FulfilledProps<T>>
Resolved: React.FC<FulfilledProps<T>>
Rejected: React.FC<RejectedProps<T>>
Settled: React.FC<SettledProps<T>>
}
/**
* createInstance allows you to create instances of Async that are bound to a specific promise.
* A unique instance also uses its own React context for better nesting capability.
*/
export function createInstance<T>(
defaultOptions: AsyncProps<T> = {},
displayName = "Async"
): AsyncConstructor<T> {
const { Consumer: UnguardedConsumer, Provider } = React.createContext<AsyncState<T> | undefined>(
undefined
)
function Consumer({ children }: { children: (value: AsyncState<T>) => React.ReactNode }) {
return (
<UnguardedConsumer>
{value => {
if (!value) {
throw new Error(
"this component should only be used within an associated <Async> component!"
)
}
return children(value)
}}
</UnguardedConsumer>
)
}
type Props = AsyncProps<T>
type State = AsyncState<T>
type Constructor = AsyncConstructor<T>
class Async extends React.Component<Props, State> {
private mounted = false
private counter = 0
private args: any[] = []
private promise?: Promise<T> = neverSettle
private abortController: AbortController = new MockAbortController()
private debugLabel?: string
private dispatch: (action: AsyncAction<T>, ...args: any[]) => void
constructor(props: Props) {
super(props)
this.start = this.start.bind(this)
this.load = this.load.bind(this)
this.run = this.run.bind(this)
this.cancel = this.cancel.bind(this)
this.onResolve = this.onResolve.bind(this)
this.onReject = this.onReject.bind(this)
this.setData = this.setData.bind(this)
this.setError = this.setError.bind(this)
const promise = props.promise
const promiseFn = props.promiseFn || defaultOptions.promiseFn
const initialValue = props.initialValue || defaultOptions.initialValue
this.state = {
...init<T>({ initialValue, promise, promiseFn }),
cancel: this.cancel,
run: this.run,
reload: () => {
this.load()
this.run(...this.args)
},
setData: this.setData,
setError: this.setError,
}
this.debugLabel = props.debugLabel || defaultOptions.debugLabel
const { devToolsDispatcher } = globalScope.__REACT_ASYNC__
const _reducer = props.reducer || defaultOptions.reducer
const _dispatcher = props.dispatcher || defaultOptions.dispatcher || devToolsDispatcher
const reducer: (
state: ReducerAsyncState<T>,
action: AsyncAction<T>
) => ReducerAsyncState<T> = _reducer
? (state, action) => _reducer(state, action, asyncReducer)
: asyncReducer
const dispatch = dispatchMiddleware<T>((action, callback) => {
this.setState(state => reducer(state, action), callback)
})
this.dispatch = _dispatcher ? action => _dispatcher(action, dispatch, props) : dispatch
}
componentDidMount() {
this.mounted = true
if (this.props.promise || !this.state.initialValue) {
this.load()
}
}
componentDidUpdate(prevProps: Props) {
const { watch, watchFn = defaultOptions.watchFn, promise, promiseFn } = this.props
if (watch !== prevProps.watch) {
if (this.counter) this.cancel()
return this.load()
}
if (
watchFn &&
watchFn({ ...defaultOptions, ...this.props }, { ...defaultOptions, ...prevProps })
) {
if (this.counter) this.cancel()
return this.load()
}
if (promise !== prevProps.promise) {
if (this.counter) this.cancel()
if (promise) return this.load()
}
if (promiseFn !== prevProps.promiseFn) {
if (this.counter) this.cancel()
if (promiseFn) return this.load()
}
}
componentWillUnmount() {
this.cancel()
this.mounted = false
}
getMeta<M>(meta?: M) {
return {
counter: this.counter,
promise: this.promise,
debugLabel: this.debugLabel,
...meta,
}
}
start(promiseFn: () => Promise<T>) {
if ("AbortController" in globalScope) {
this.abortController.abort()
this.abortController = new globalScope.AbortController!()
}
this.counter++
return (this.promise = new Promise((resolve, reject) => {
if (!this.mounted) return
const executor = () => promiseFn().then(resolve, reject)
this.dispatch({ type: ActionTypes.start, payload: executor, meta: this.getMeta() })
}))
}
load() {
const promise = this.props.promise
const promiseFn = this.props.promiseFn || defaultOptions.promiseFn
if (promise) {
this.start(() => promise)
.then(this.onResolve(this.counter))
.catch(this.onReject(this.counter))
} else if (promiseFn) {
const props = { ...defaultOptions, ...this.props }
this.start(() => promiseFn(props, this.abortController))
.then(this.onResolve(this.counter))
.catch(this.onReject(this.counter))
}
}
run(...args: any[]) {
const deferFn = this.props.deferFn || defaultOptions.deferFn
if (deferFn) {
this.args = args
const props = { ...defaultOptions, ...this.props }
return this.start(() => deferFn(args, props, this.abortController)).then(
this.onResolve(this.counter),
this.onReject(this.counter)
)
}
}
cancel() {
const onCancel = this.props.onCancel || defaultOptions.onCancel
onCancel && onCancel()
this.counter++
this.abortController.abort()
this.mounted && this.dispatch({ type: ActionTypes.cancel, meta: this.getMeta() })
}
onResolve(counter: Number) {
return (data: T) => {
if (this.counter === counter) {
const onResolve = this.props.onResolve || defaultOptions.onResolve
this.setData(data, () => onResolve && onResolve(data))
}
return data
}
}
onReject(counter: Number) {
return (error: Error) => {
if (this.counter === counter) {
const onReject = this.props.onReject || defaultOptions.onReject
this.setError(error, () => onReject && onReject(error))
}
return error
}
}
setData(data: T, callback?: () => void) {
this.mounted &&
this.dispatch({ type: ActionTypes.fulfill, payload: data, meta: this.getMeta() }, callback)
return data
}
setError(error: Error, callback?: () => void) {
this.mounted &&
this.dispatch(
{ type: ActionTypes.reject, payload: error, error: true, meta: this.getMeta() },
callback
)
return error
}
render() {
const { children, suspense } = this.props
if (suspense && this.state.isPending && this.promise !== neverSettle) {
// Rely on Suspense to handle the loading state
throw this.promise
}
if (typeof children === "function") {
const render = children as (state: State) => React.ReactNode
return <Provider value={this.state}>{render(this.state)}</Provider>
}
if (children !== undefined && children !== null) {
return <Provider value={this.state}>{children}</Provider>
}
return null
}
}
if (propTypes) (Async as React.ComponentClass).propTypes = propTypes.Async
const AsyncInitial: Constructor["Initial"] = props => (
<Consumer>{st => <IfInitial {...props} state={st} />}</Consumer>
)
const AsyncPending: Constructor["Pending"] = props => (
<Consumer>{st => <IfPending {...props} state={st} />}</Consumer>
)
const AsyncFulfilled: Constructor["Fulfilled"] = props => (
<Consumer>{st => <IfFulfilled {...props} state={st} />}</Consumer>
)
const AsyncRejected: Constructor["Rejected"] = props => (
<Consumer>{st => <IfRejected {...props} state={st} />}</Consumer>
)
const AsyncSettled: Constructor["Settled"] = props => (
<Consumer>{st => <IfSettled {...props} state={st} />}</Consumer>
)
AsyncInitial.displayName = `${displayName}.Initial`
AsyncPending.displayName = `${displayName}.Pending`
AsyncFulfilled.displayName = `${displayName}.Fulfilled`
AsyncRejected.displayName = `${displayName}.Rejected`
AsyncSettled.displayName = `${displayName}.Settled`
return Object.assign(Async, {
displayName: displayName,
Initial: AsyncInitial,
Pending: AsyncPending,
Loading: AsyncPending, // alias
Fulfilled: AsyncFulfilled,
Resolved: AsyncFulfilled, // alias
Rejected: AsyncRejected,
Settled: AsyncSettled,
})
}
export default createInstance() as GenericAsync | the_stack |
import * as DiscoveryEntryWithMetaInfo from "../../generated/joynr/types/DiscoveryEntryWithMetaInfo";
import * as UtilInternal from "../util/UtilInternal";
import * as Request from "../dispatching/types/Request";
import MessagingQos from "../messaging/MessagingQos";
import * as Typing from "../util/Typing";
import RequestReplyManager = require("../dispatching/RequestReplyManager");
import SubscriptionManager = require("../dispatching/subscription/SubscriptionManager");
import DiscoveryQos = require("./DiscoveryQos");
import SubscriptionQos = require("./SubscriptionQos");
type ProxyAttributeConstructor<T = ProxyAttribute> = new (...args: any[]) => T;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function asRead<TBase extends ProxyAttributeConstructor, T = unknown>(superclass: TBase) {
return class Readable extends superclass {
/**
* Getter for attribute
*
* @param [settings] the settings object for this function call
* @returns returns an A+ promise object
*/
public get(settings?: { messagingQos?: MessagingQos }): Promise<T> {
// ensure settings variable holds a valid object and initialize
// deferred object
settings = settings || {};
const request = Request.create({
methodName: `get${UtilInternal.firstUpper(this.attributeName)}`
});
return this.executeRequest(request, settings);
}
};
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function asWrite<TBase extends ProxyAttributeConstructor, T = unknown>(superclass: TBase) {
return class WriteAble extends superclass {
/**
* Setter for attribute
*
* @param settings - the settings object for this function call
* @param settings.value - the attribute value to set
* @returns returns an A+ promise
*/
public set(settings: { value: T; messagingQos?: MessagingQos }): Promise<void> {
// ensure settings variable holds a valid object and initialize deferred
// object
settings = settings || {};
try {
settings.value = Typing.augmentTypes(settings.value);
} catch (e) {
return Promise.reject(new Error(`error setting attribute: ${this.attributeName}: ${e.toString()}`));
}
const request = Request.create({
methodName: `set${UtilInternal.firstUpper(this.attributeName)}`,
paramDatatypes: [this.attributeType],
params: [settings.value]
});
return this.executeRequest(request, settings);
}
};
}
export interface SubscribeSettings<T> {
subscriptionQos: SubscriptionQos;
onReceive: (value: T) => void;
onError?: (e: Error) => void;
onSubscribed?: (participantId: string) => void;
subscriptionId?: string;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function asNotify<TBase extends ProxyAttributeConstructor, T = unknown>(superclass: TBase) {
return class Notifiable extends superclass {
/**
* Subscription to isOn attribute
*
* @param settings the settings object for this function call
* @param settings.subscriptionQos - the subscription quality of service object
* @param settings.onReceive this function is called if the attribute has
* been published successfully, method signature:
* "void onReceive({?}value)"
* @param settings.onError - this function is called if a publication of the attribute value was
* missed, method signature: "void onError({Error} error)"
* @param settings.onSubscribed - the callback to inform once the subscription request has been
* delivered successfully
* @param [settings.subscriptionId] - optional subscriptionId to be used for the new subscription
* @returns returns an A+ promise object
*/
public subscribe(settings: SubscribeSettings<T>): Promise<string> {
// return promise to caller
return this.settings.dependencies.subscriptionManager.registerSubscription({
proxyId: this.parent.proxyParticipantId,
providerDiscoveryEntry: this.parent.providerDiscoveryEntry,
attributeName: this.attributeName,
attributeType: this.attributeType,
qos: settings.subscriptionQos,
subscriptionId: settings.subscriptionId,
onReceive: settings.onReceive,
onError: settings.onError,
onSubscribed: settings.onSubscribed
});
}
/**
* Unsubscribe from the attribute
*
* @param settings - the settings object for this function call
* @param settings.subscriptionId - the subscription id retrieved from the subscribe function
* @returns returns an A+ promise object
*
* @see ProxyAttribute#subscribe
*/
public unsubscribe(settings: { subscriptionId: string; messagingQos?: MessagingQos }): Promise<void> {
// passed in (right-most) messagingQos have precedence; undefined values are
// ignored
const messagingQos = new MessagingQos(
UtilInternal.extend({}, this.parent.messagingQos, this.settings.messagingQos, settings.messagingQos)
);
// return promise to caller
return this.settings.dependencies.subscriptionManager.unregisterSubscription({
messagingQos,
subscriptionId: settings.subscriptionId
});
}
};
}
function sendRequestOnSuccess<T>(settings: { response: [T]; settings: string }): T {
const response = settings.response;
const attributeType = settings.settings;
return Typing.augmentTypes(response[0], attributeType);
}
class ProxyAttribute {
/** protected property, needs to be public for tsc -d */
public attributeType: string;
/** protected property, needs to be public for tsc -d */
public attributeName: string;
public settings: {
dependencies: {
requestReplyManager: RequestReplyManager;
subscriptionManager: SubscriptionManager;
};
discoveryQos: DiscoveryQos;
messagingQos: MessagingQos;
};
/** protected property, needs to be public for tsc -d */
public parent: {
proxyParticipantId: string;
providerDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos?: MessagingQos;
};
/**
* Constructor of ProxyAttribute object that is used in the generation of proxy objects
*
* @param parent - the proxy object that contains this attribute
* @param parent.proxyParticipantId - participantId of the proxy itself
* @param parent.providerDiscoveryEntry.participantId - participantId of the provider being addressed
* @param settings - the settings object for this function call
* @param settings.dependencies - the dependencies object for this function call
* @param settings.dependencies.requestReplyManager
* @param settings.dependencies.subscriptionManager
* @param settings.discoveryQos - the Quality of Service parameters for arbitration
* @param settings.messagingQos - the Quality of Service parameters for messaging
* @param attributeName - the name of the attribute
* @param attributeType - the type of the attribute
*/
public constructor(
parent: {
proxyParticipantId: string;
providerDiscoveryEntry: DiscoveryEntryWithMetaInfo;
settings: {
dependencies: {
requestReplyManager: RequestReplyManager;
subscriptionManager: SubscriptionManager;
};
discoveryQos: DiscoveryQos;
messagingQos: MessagingQos;
};
},
attributeName: string,
attributeType: string
) {
this.parent = parent;
this.settings = parent.settings;
this.attributeName = attributeName;
this.attributeType = attributeType;
}
/**
* protected property, but public due to tsc -d
*
* @param request
* @param requestSettings
* @param requestSettings.messagingQos
* @returns an A+ promise
*/
public executeRequest(request: Request.Request, requestSettings: { messagingQos?: MessagingQos }): Promise<any> {
// passed in (right-most) messagingQos have precedence; undefined values are ignored
const messagingQos = UtilInternal.extend(
new MessagingQos(),
this.parent.messagingQos,
this.settings.messagingQos,
requestSettings.messagingQos
);
// return promise to caller
return (this.settings.dependencies.requestReplyManager.sendRequest as any)(
{
toDiscoveryEntry: this.parent.providerDiscoveryEntry,
from: this.parent.proxyParticipantId,
messagingQos,
request
},
this.attributeType
).then(sendRequestOnSuccess);
}
}
/*
The empty container classes below are declared for typing purposes.
Unfortunately declarations need to be repeated since it's impossible to give template parameters
to mixin classes. See https://github.com/Microsoft/TypeScript/issues/26154
*/
const ProxyReadAttributeImpl = asRead<ProxyAttributeConstructor>(ProxyAttribute);
export class ProxyReadAttribute<T> extends ProxyReadAttributeImpl {
public get!: (settings?: { messagingQos?: MessagingQos }) => Promise<T>;
}
const ProxyReadWriteAttributeImpl = asWrite<ProxyAttributeConstructor>(ProxyReadAttribute);
export class ProxyReadWriteAttribute<T> extends ProxyReadWriteAttributeImpl {
public get!: (settings?: { messagingQos?: MessagingQos }) => Promise<T>;
public set!: (settings: { value: T; messagingQos?: MessagingQos }) => Promise<void>;
}
const ProxyReadWriteNotifyAttributeImpl = asNotify<ProxyAttributeConstructor>(ProxyReadWriteAttribute);
export class ProxyReadWriteNotifyAttribute<T> extends ProxyReadWriteNotifyAttributeImpl {
public get!: (settings?: { messagingQos?: MessagingQos }) => Promise<T>;
public set!: (settings: { value: T; messagingQos?: MessagingQos }) => Promise<void>;
public subscribe!: (settings: SubscribeSettings<T>) => Promise<any>;
public unsubscribe!: (settings: { subscriptionId: string; messagingQos?: MessagingQos }) => Promise<void>;
}
const ProxyReadNotifyAttributeImpl = asNotify<ProxyAttributeConstructor>(ProxyReadAttribute);
export class ProxyReadNotifyAttribute<T> extends ProxyReadNotifyAttributeImpl {
public get!: (settings?: { messagingQos?: MessagingQos }) => Promise<T>;
public subscribe!: (settings: SubscribeSettings<T>) => Promise<any>;
public unsubscribe!: (settings: { subscriptionId: string; messagingQos?: MessagingQos }) => Promise<void>;
} | the_stack |
import cloneDeep from "https://cdn.skypack.dev/lodash.clonedeep";
import { parse } from "https://cdn.skypack.dev/html5parser";
import {
IAttribute,
IContextData,
ICustomComponent,
IHTMLAttr,
INode,
IStaticFile,
} from "./types.ts";
import {
checkStaticFileExists,
checkStaticFileIsInsideStaticDir,
contextEval,
getStaticFileBundlePath,
getStaticFileFromRel,
getUnprefixedAttributeName,
interpolate,
isComment,
isDevelopmentEnv,
isExternalURL,
log,
pushBefore,
removeExt,
removeFromParent,
} from "./utils.ts";
import { CHILDREN_COMPONENT_PROP, POTENTIAL_STATIC_ATTR } from "./constants.ts";
import { serialize } from "./index.ts";
/**
* Handle the for/of attributes pair
*/
function computeForOf(
node: INode,
data: IContextData,
availableComponents: ICustomComponent[],
onCustomComponentFound: (event: ICustomComponent) => void,
onStaticFileFound: (staticFile: IStaticFile, destRel: string) => void,
onBuildError?: (e: Error) => void,
) {
// ----- errors handling ----- //
if ("attributes" in node) {
const forAttr = node.attributes.find(
(attr: IHTMLAttr) => attr.name.value === IAttribute.FOR,
);
const ofAttr = node.attributes.find(
(attr: IHTMLAttr) => attr.name.value === IAttribute.OF,
);
if (!forAttr && !ofAttr) return;
if (forAttr && !forAttr.value?.value) {
log.error(
`When parsing "${node.open.value}" : The ${IAttribute.FOR} attribute must be given a value.`,
true,
);
} else if (ofAttr && !ofAttr.value?.value) {
log.error(
`When parsing "${node.open.value}" : The ${IAttribute.OF} attribute must be given a value.`,
true,
);
}
if (forAttr && !ofAttr) {
log.error(
`The use of ${forAttr.name.value}="${forAttr.value
?.value}" must be paired with the use of ${IAttribute.OF}="<iterable>".`,
true,
);
} else if (ofAttr && !forAttr) {
log.error(
`The use of ${ofAttr.name.value}="${ofAttr.value
?.value}" must be paired with the use of ${IAttribute.FOR}="<iterator>".`,
true,
);
}
// ----- logic ----- //
const evaluatedOf: Array<any> = contextEval(
ofAttr?.value?.value ?? "",
data,
node.open.value,
);
if (typeof evaluatedOf[Symbol.iterator] !== "function") {
log.error(
`When parsing "${node.open.value}": "${ofAttr?.value
?.value} is not an iterable.`,
true,
);
}
// remove the for/of attributes from node attributes
node.attributes = node.attributes.filter(
(attr: IHTMLAttr) =>
![IAttribute.FOR.toString(), IAttribute.OF.toString()].includes(
attr.name.value,
),
);
// @ts-ignore
const parent = "body" in node.parent ? node.parent.body : node.parent;
let index = evaluatedOf.length - 1;
for (const item of [...evaluatedOf].reverse()) {
const clone: INode = cloneDeep(node);
clone.parent = node.parent;
pushBefore(parent as INode[], node, clone);
buildHtml(
clone,
{ ...data, index: index--, [forAttr?.value?.value ?? "item"]: item },
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
);
}
// removing the node itself from its parent
removeFromParent(node);
return true;
}
return false;
}
/**
* Handle the if attribute pair
*/
function computeIf(node: INode, data: IContextData): boolean {
// ----- errors handling ----- //
if ("attributes" in node) {
const ifAttr = node.attributes.find(
(attr: IHTMLAttr) => attr.name.value === IAttribute.IF,
);
if (!ifAttr) return true;
if (ifAttr && typeof ifAttr.value === "undefined") {
log.error(
`When parsing "${node.open.value}" : The ${IAttribute.IF} attribute must be given a value.`,
true,
);
}
// ----- logic ----- //
const evaluatedIf: boolean = contextEval(
ifAttr?.value?.value ?? "",
data,
node.open.value,
);
if (!evaluatedIf && !!node.parent) {
const parent = "body" in node.parent ? node.parent.body : node.parent;
const index = (parent as Array<INode>).findIndex((n) => n === node);
if (index !== -1) {
// remove the node from parent's body
(parent as Array<INode>).splice(index, 1);
}
return false;
}
// remove the if attribute from node attributes
node.attributes = node.attributes.filter(
(attr: IHTMLAttr) => attr.name.value !== IAttribute.IF.toString(),
);
}
return true;
}
/**
* Handle if node is a custom component
*/
function computeCustomComponents(
node: INode,
data: IContextData,
availableComponents: ICustomComponent[],
onCustomComponentFound: (component: ICustomComponent) => void,
onStaticFileFound: (staticFile: IStaticFile, destRel: string) => void,
onBuildError?: (e: Error) => void,
) {
if ("name" in node) {
// checking if tag matched a component
const component: ICustomComponent | undefined = availableComponents.find(
(file) => removeExt(file.name) === node.name,
);
if (!component) return;
// binding the component to the template using it
onCustomComponentFound(component);
const props: IContextData = {};
// evaluating every attribute's value to pass as components props
if ("attributes" in node) {
for (const attr of node.attributes) {
if (!Object.values(IAttribute).includes(attr.name.value)) {
props[attr.name.value] = contextEval(
attr.value?.value ?? "",
data,
node.open.value,
);
}
}
}
// building nodes nested inside of component
if ("body" in node && !!node.body) {
for (const childNode of node.body.reverse() as INode[]) {
childNode.parent = node;
buildHtml(
childNode,
data,
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
);
}
node.body.reverse();
// adding the serialized content as 'children' prop
const serializedChildren: string = node.body.map(serialize).join("");
props[CHILDREN_COMPONENT_PROP] = serializedChildren;
}
// reading and parsing the component file
const read = Deno.readTextFileSync(component.path);
const parsed = parse(read);
// building the parsed component
parsed.forEach((componentNode: INode) => {
componentNode.parent = parsed;
buildHtml(
componentNode,
props,
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
);
componentNode.parent = node.parent;
});
if (!!node.parent) {
const parent = "body" in node.parent ? node.parent.body : node.parent;
const index = (parent as INode[]).findIndex((n) => n === node);
if (index !== -1) {
// add new built nodes next to node in parent's body
(parent as Array<INode>).splice(index, 1, ...parsed);
}
}
return true;
}
return false;
}
/**
* Handle eval: prefixed attributes
*/
function computeEval(node: INode, data: IContextData) {
if ("attributes" in node) {
for (const attr of node.attributes) {
if (attr.name.value.startsWith(IAttribute.EVAL)) {
if (typeof attr.value?.value === "undefined") {
return log.warning(
`When parsing ${node.open.value}: ${attr.name.value} has been given no value to evaluate.`,
);
}
attr.name.value = getUnprefixedAttributeName(attr);
let evaluatedValue = contextEval(attr.value?.value || "", data);
// special treatment for eval:class="{ foo: true, bar: false }"
if (attr.name.value === "class" && typeof evaluatedValue === "object") {
let value = "";
for (const key of Object.keys(evaluatedValue)) {
if (evaluatedValue[key]) value += `${key} `;
}
evaluatedValue = value.trim();
}
attr.value.value = evaluatedValue;
}
}
}
}
/**
* Handle resolving and bundling static files
*/
function computeStaticFiles(
node: INode,
onStaticFileFound: (staticFile: IStaticFile, destRel: string) => void,
) {
if ("attributes" in node) {
for (const attr of node.attributes) {
if (POTENTIAL_STATIC_ATTR.includes(attr.name.value)) {
if (node.name === "a" && attr.name.value === "href") continue;
if (typeof attr.value?.value === "undefined") continue;
if (isExternalURL(attr.value.value)) continue;
const staticFile = getStaticFileFromRel(attr.value.value);
if (!checkStaticFileExists(staticFile.path, attr.value.value)) continue;
if (
!checkStaticFileIsInsideStaticDir(staticFile.path, attr.value.value)
) {
continue;
}
attr.value.value = getStaticFileBundlePath(attr.value.value);
onStaticFileFound(staticFile, attr.value.value);
}
}
}
}
/**
* Handle interpolation of given text node
*/
function computeText(node: INode, data: IContextData): boolean {
if (node.type === "Text") {
node.value = interpolate(node.value, data);
return true;
}
return false;
}
/**
* Drive the node build, and recursively call on node's children
*/
export async function buildHtml(
node: INode,
data: IContextData,
availableComponents: ICustomComponent[],
onCustomComponentFound: (component: ICustomComponent) => void,
onStaticFileFound: (staticFile: IStaticFile, destRel: string) => void,
onBuildError?: (e: Error) => void,
) {
// preventing double builds of nodes or build of comments
if (node.built) return;
if (isComment(node)) return;
try {
if (computeText(node, data)) {
node.built = true;
return;
}
if (
computeForOf(
node,
data,
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
)
) {
node.built = true;
return;
}
if (!computeIf(node, data)) {
node.built = true;
return;
}
if (
computeCustomComponents(
node,
data,
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
)
) {
node.built = true;
return;
}
computeEval(node, data);
computeStaticFiles(node, onStaticFileFound);
} catch (e) {
node.built = true;
log.error(e);
if (!isDevelopmentEnv()) {
log.error("Project build failed.");
Deno.exit();
} else if (onBuildError) {
onBuildError(e);
}
}
if ("body" in node && !!node.body) {
for (const childNode of node.body.reverse() as INode[]) {
(childNode as INode).parent = node;
buildHtml(
childNode,
data,
availableComponents,
onCustomComponentFound,
onStaticFileFound,
onBuildError,
);
}
node.body.reverse();
}
node.built = true;
} | the_stack |
import {
MessageMeta,
InitToken,
CPrimitive,
Optional,
CollabEventsRecord,
CollabEvent,
} from "@collabs/collabs";
import { ContainerHostSave } from "../generated/proto_compiled";
import { ContainerMessage, HostMessage, ReceiveMessage } from "./message_types";
// TODO: ability to send our own metadata to the container
// (e.g. user's name)?
// More generally, arbitrary message-passing ability?
export interface CRDTContainerHostEventsRecord extends CollabEventsRecord {
/**
* Emitted when [[CRDTContainerHost.isContainerReady]]
* becomes true, hence user interaction with the container
* is allowed.
*
* This event may be emitted as soon as the next event loop
* iteration after you initialize the container's IFrame.
* So, you must either add an event handler within the same
* event loop iteration that you initialize the IFrame,
* or check [[CRDTContainerHost.isContainerReady]] before
* adding the handler.
*
* Note that this is a local, not replicated, event: it refers
* to conditions on the local replica related to the
* app start cycle, not something that all replicas see
* in sync.
*/
ContainerReady: CollabEvent;
}
/**
* A host for a Collabs container running in a child IFrame.
*
* See [container docs](https://github.com/composablesys/collabs/blob/master/collabs/docs/containers.md).
*
* A `CRDTContainerHost` connects to the `CRDTContainer`
* instance running in the `containerIFrame` provided to
* the constructor. All messages sent by the `CRDTContainer`
* become messages sent by this class, and likewise for
* received messages. This class's save data is also
* derived from the container's own save data, and likewise,
* the container is loaded based on the save data passed to [[load]].
*
* You are responsible for blocking user input to `containerIFrame`
* until [[isContainerReady]] is true (signalled by the
* "ContainerReady" event). Otherwise, the user might interact
* with the container before it is loaded, causing errors.
* Typically, you'll also want to hide the `containerIFrame`
* until then, so that the user doesn't see partially-initialized
* state. You can accomplish both by setting
* `containerIFrame.hidden = true`, then when it is ready,
* setting `containerIFrame.hidden = false`.
*
* You can use `CRDTContainerHost` to embed Collabs containers
* inside your own app. In particular, if you want to
* support a specific network/storage/UX/etc. for containers,
* you can do so by making a Collabs app
* that uses your chosen network/storage/UX/etc.,
* with a `CRDTContainerHost` as its single Collab, and with
* some way for users to specify the container.
*/
export class CRDTContainerHost extends CPrimitive<CRDTContainerHostEventsRecord> {
private messagePort: MessagePort | null = null;
private _isContainerReady = false;
/**
* Queue for messages to be sent over messagePort,
* before it exists.
*/
private messagePortQueue: ContainerMessage[] | null = [];
/**
* Queue for ReceiveMessages that are received
* (via receivePrimitive) before the container is ready.
*/
private receiveMessageQueue: ReceiveMessage[] | null = [];
/**
* The latest save data received from the container
* (possibly extracted in [[load]], i.e., from a prior
* replica), or null if no save
* data was ever received.
*/
private latestSaveData: Uint8Array | null = null;
/**
* The ID for the next received message.
* This increases each time.
* Note that if further messages are found in [[load]],
* then those messages get ids 0, 1, ...; newly
* received messages then start where they leave off.
*/
private nextReceivedMessageID = 0;
/**
* Received messages that are not accounted for in
* latestSaveData, tagged with their IDs,
* in order of receipt.
*
* This includes messages found in [[load]] (until they
* become accounted for in latestSaveData).
*/
private furtherReceivedMessages: [id: number, message: Uint8Array][] = [];
/**
* Sent messages (i.e., sent by the container)
* that are not accounted for in latestSaveData.
* predID is the ID of the last message the replica
* received before sending a message (-1 if no messages
* received), counting received messages found in [[loadd]].
*/
private furtherSentMessages: [predID: number, message: Uint8Array][] = [];
/**
* Constructs a `CRDTContainerHost` that connects to the `CRDTContainer`
* instance running in `containerIFrame`.
*
* Restrictions for now:
* - `containerIFrame`'s `window.parent` must be your `window`.
* - You should call this constructor synchronously after
* constructing the IFrame, so that it is not yet loaded.
*
* @param containerIFrame
*/
constructor(
initToken: InitToken,
readonly containerIFrame: HTMLIFrameElement
) {
super(initToken);
// Listen for this.messagePort.
const onmessage = (e: MessageEvent<unknown>) => {
// TODO: what if contentWindow is not accessible, due to
// same-origin policy, or because it's still null
// for some reason?
if (e.source !== containerIFrame.contentWindow) return;
// TODO: other checks?
this.messagePort = e.ports[0];
// Send queued messages.
this.messagePortQueue!.forEach((message) =>
this.messagePort!.postMessage(message)
);
this.messagePortQueue = null;
// Begin receiving.
// Do this last just in case it starts receiving
// synchronously (although I'm guessing the spec doesn't
// actually allow that).
this.messagePort.onmessage = this.messagePortReceive.bind(this);
window.removeEventListener("message", onmessage);
};
window.addEventListener("message", onmessage);
}
private messagePortSend(message: ContainerMessage) {
if (this.messagePort === null) {
this.messagePortQueue!.push(message);
} else {
this.messagePort.postMessage(message);
}
}
private messagePortReceive(e: MessageEvent<HostMessage>) {
switch (e.data.type) {
case "Ready":
this._isContainerReady = true;
this.emit("ContainerReady", {
meta: { isLocalEcho: true, sender: this.runtime.replicaID },
});
// Deliver queued ReceiveMessages.
this.receiveMessageQueue!.forEach((message) =>
this.messagePortSend(message)
);
this.receiveMessageQueue = null;
break;
case "Send":
const message = e.data.message;
this.furtherSentMessages.push([e.data.predID, message]);
this.sendPrimitive(message);
break;
case "Saved":
this.latestSaveData = e.data.saveData;
// Trim further messages that are accounted for by the
// save: all sent messages, and all received messages
// with id <= e.data.lastReceivedID.
this.furtherSentMessages.splice(0);
if (this.furtherReceivedMessages.length > 0) {
const startID = this.furtherReceivedMessages[0][0];
const deleteCount = e.data.lastReceivedID - startID + 1;
this.furtherReceivedMessages.splice(0, deleteCount);
}
// Resolve the Promise returned by the
// original compactSaveData call.
if (e.data.requestID !== undefined) {
const resolveReject = this.compactSaveDataResolves.get(
e.data.requestID
);
if (resolveReject !== undefined) {
this.compactSaveDataResolves.delete(e.data.requestID);
resolveReject[0]();
}
}
break;
case "SaveRequestFailed":
const resolveReject = this.compactSaveDataResolves.get(
e.data.requestID
);
if (resolveReject !== undefined) {
this.compactSaveDataResolves.delete(e.data.requestID);
resolveReject[1](
"Container had error processing compactSaveData() request: " +
e.data.errorToString
);
}
break;
default:
throw new Error("bad e.data: " + e.data);
}
}
protected receivePrimitive(message: Uint8Array, meta: MessageMeta): void {
if (!meta.isLocalEcho) {
const id = this.nextReceivedMessageID++;
this.furtherReceivedMessages.push([id, message]);
const receiveMessage: ReceiveMessage = { type: "Receive", message, id };
if (this._isContainerReady) {
this.messagePortSend(receiveMessage);
} else {
this.receiveMessageQueue!.push(receiveMessage);
}
}
// Else the container already processed it.
}
/**
* Whether the container is ready to be used by the
* user.
*
* Specifically, this becomes true once the internal
* container's [[CRDTContainer.ready]] method has been called.
*
* Until this is true, you MUST block user input to
* `containerIFrame`. Otherwise, the user might interact
* with the container before it is loaded, causing errors.
* Typically, you'll also want to hide the `containerIFrame`
* until then, so that the user doesn't see partially-initialized
* state. You can accomplish both by setting
* `containerIFrame.hidden = true`, then when it is ready,
* setting `containerIFrame.hidden = false`.
*
* A [[CRDTContainerHostEventsRecord.ContainerReady]] event
* is emitted immediately after this becomes true.
*/
get isContainerReady(): boolean {
return this._isContainerReady;
}
private nextCompactSaveDataID = 0;
private compactSaveDataResolves = new Map<
number,
[resolve: () => void, reject: (reason: unknown) => void]
>();
/**
* Asks the internal [[CRDTContainer]] to call its analog
* of [[CRDTApp.save]], generating compact save data
* describing its current state. This save data will then
* be used in future calls to our own [[save]] method,
* in place of a message log.
*
* To prevent our own save data from becoming too large
* (acting as an ever-growing message log), you should
* call this method occasionally. However, do not call it
* too often, since saving large documents can take some
* time and freezes the container.
*
* The returned Promise resolves when done, i.e., when the
* next call to save() will include
* the compacted saveData due to this method call.
* Note it's not guaranteed that
* the log will be empty even if you then call save() right away,
* because the container may have sent/received more messages
* during the async wait.
*
* The Promise rejects if the container's call to save failed, with
* the container's error as reason.
*
* @throws if [[isContainerReady]] is false
*/
compactSaveData(): Promise<void> {
if (!this._isContainerReady) {
throw new Error("Container is not ready yet");
}
const requestID = this.nextCompactSaveDataID++;
this.messagePortSend({ type: "SaveRequest", requestID });
return new Promise((resolve, reject) => {
// resolve will be called by the "saved" message handler.
this.compactSaveDataResolves.set(requestID, [resolve, reject]);
});
}
save(): Uint8Array {
// Sort further messages in the order they were processed
// (sent or received) by the container.
// This means that each sent message comes right after
// the received message with its predID
// (except that earlier sent messages with the same predID
// come first, of course).
const furtherMessages = new Array<Uint8Array>(
this.furtherSentMessages.length + this.furtherReceivedMessages.length
);
let i = 0,
j = 0;
while (i + j < furtherMessages.length) {
const sent = this.furtherSentMessages[i];
const received = this.furtherReceivedMessages[j];
// Deciding whether to push the next sent message
// or the next received mesage:
// if the received message is a predecessor of the sent
// message, we push the received message, else we
// push the sent message.
if (received[0] <= sent[0]) {
furtherMessages[i + j] = received[1];
j++;
} else {
furtherMessages[i + j] = sent[1];
i++;
}
}
// Note that it makes sense to treat all further message
// (sent + received) as received messages in the saveData:
// from a newly-loaded replica's perspective, they're all
// received messages (sent by different replicas).
const message = ContainerHostSave.create({
latestSaveData: this.latestSaveData,
furtherMessages,
});
return ContainerHostSave.encode(message).finish();
}
load(saveData: Optional<Uint8Array>): void {
// Set our latestSaveData and furtherMessages.
if (!saveData.isPresent) {
// Leave this.latestSaveData, this.furtherReceivedMessages
// as their initial values (null, []).
this.messagePortSend({
type: "Load",
hostSkipped: true,
latestSaveData: null,
furtherMessages: [],
});
} else {
const decoded = ContainerHostSave.decode(saveData.get());
this.latestSaveData = Object.prototype.hasOwnProperty.call(
decoded,
"latestSaveData"
)
? decoded.latestSaveData
: null;
this.furtherReceivedMessages = decoded.furtherMessages.map(
(message, index) => [index, message]
);
this.nextReceivedMessageID = this.furtherReceivedMessages.length;
this.messagePortSend({
type: "Load",
hostSkipped: false,
latestSaveData: this.latestSaveData,
furtherMessages: decoded.furtherMessages,
});
}
}
canGC(): boolean {
return false;
}
} | the_stack |
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { NotifierAction } from '../models/notifier-action.model';
import { NotifierConfig } from '../models/notifier-config.model';
import { NotifierNotification } from '../models/notifier-notification.model';
import { NotifierService } from '../services/notifier.service';
import { NotifierQueueService } from '../services/notifier-queue.service';
import { NotifierNotificationComponent } from './notifier-notification.component';
/**
* Notifier container component
* ----------------------------
* This component acts as a wrapper for all notification components; consequently, it is responsible for creating a new notification
* component and removing an existing notification component. Being more precicely, it also handles side effects of those actions, such as
* shifting or even completely removing other notifications as well. Overall, this components handles actions coming from the queue service
* by subscribing to its action stream.
*
* Technical sidenote:
* This component has to be used somewhere in an application to work; it will not inject and create itself automatically, primarily in order
* to not break the Angular AoT compilation. Moreover, this component (and also the notification components) set their change detection
* strategy onPush, which means that we handle change detection manually in order to get the best performance. (#perfmatters)
*/
@Component({
changeDetection: ChangeDetectionStrategy.OnPush, // (#perfmatters)
host: {
class: 'notifier__container',
},
selector: 'notifier-container',
templateUrl: './notifier-container.component.html',
})
export class NotifierContainerComponent implements OnDestroy {
/**
* List of currently somewhat active notifications
*/
public notifications: Array<NotifierNotification>;
/**
* Change detector
*/
private readonly changeDetector: ChangeDetectorRef;
/**
* Notifier queue service
*/
private readonly queueService: NotifierQueueService;
/**
* Notifier configuration
*/
private readonly config: NotifierConfig;
/**
* Queue service observable subscription (saved for cleanup)
*/
private queueServiceSubscription: Subscription;
/**
* Promise resolve function reference, temporarily used while the notification child component gets created
*/
private tempPromiseResolver: () => void;
/**
* Constructor
*
* @param changeDetector Change detector, used for manually triggering change detection runs
* @param notifierQueueService Notifier queue service
* @param notifierService Notifier service
*/
public constructor(changeDetector: ChangeDetectorRef, notifierQueueService: NotifierQueueService, notifierService: NotifierService) {
this.changeDetector = changeDetector;
this.queueService = notifierQueueService;
this.config = notifierService.getConfig();
this.notifications = [];
// Connects this component up to the action queue, then handle incoming actions
this.queueServiceSubscription = this.queueService.actionStream.subscribe((action: NotifierAction) => {
this.handleAction(action).then(() => {
this.queueService.continue();
});
});
}
/**
* Component destroyment lifecycle hook, cleans up the observable subsciption
*/
public ngOnDestroy(): void {
if (this.queueServiceSubscription) {
this.queueServiceSubscription.unsubscribe();
}
}
/**
* Notification identifier, used as the ngFor trackby function
*
* @param index Index
* @param notification Notifier notification
* @returns Notification ID as the unique identnfier
*/
public identifyNotification(index: number, notification: NotifierNotification): string {
return notification.id;
}
/**
* Event handler, handles clicks on notification dismiss buttons
*
* @param notificationId ID of the notification to dismiss
*/
public onNotificationDismiss(notificationId: string): void {
this.queueService.push({
payload: notificationId,
type: 'HIDE',
});
}
/**
* Event handler, handles notification ready events
*
* @param notificationComponent Notification component reference
*/
public onNotificationReady(notificationComponent: NotifierNotificationComponent): void {
const currentNotification: NotifierNotification = this.notifications[this.notifications.length - 1]; // Get the latest notification
currentNotification.component = notificationComponent; // Save the new omponent reference
this.continueHandleShowAction(currentNotification); // Continue with handling the show action
}
/**
* Handle incoming actions by mapping action types to methods, and then running them
*
* @param action Action object
* @returns Promise, resolved when done
*/
private handleAction(action: NotifierAction): Promise<void> {
switch (
action.type // TODO: Maybe a map (actionType -> class method) is a cleaner solution here?
) {
case 'SHOW':
return this.handleShowAction(action);
case 'HIDE':
return this.handleHideAction(action);
case 'HIDE_OLDEST':
return this.handleHideOldestAction(action);
case 'HIDE_NEWEST':
return this.handleHideNewestAction(action);
case 'HIDE_ALL':
return this.handleHideAllAction();
default:
return new Promise<void>((resolve: () => void) => {
resolve(); // Ignore unknown action types
});
}
}
/**
* Show a new notification
*
* We simply add the notification to the list, and then wait until its properly initialized / created / rendered.
*
* @param action Action object
* @returns Promise, resolved when done
*/
private handleShowAction(action: NotifierAction): Promise<void> {
return new Promise<void>((resolve: () => void) => {
this.tempPromiseResolver = resolve; // Save the promise resolve function so that it can be called later on by another method
this.addNotificationToList(new NotifierNotification(action.payload));
});
}
/**
* Continue to show a new notification (after the notification components is initialized / created / rendered).
*
* If this is the first (and thus only) notification, we can simply show it. Otherwhise, if stacking is disabled (or a low value), we
* switch out notifications, in particular we hide the existing one, and then show our new one. Yet, if stacking is enabled, we first
* shift all older notifications, and then show our new notification. In addition, if there are too many notification on the screen,
* we hide the oldest one first. Furthermore, if configured, animation overlapping is applied.
*
* @param notification New notification to show
*/
private continueHandleShowAction(notification: NotifierNotification): void {
// First (which means only one) notification in the list?
const numberOfNotifications: number = this.notifications.length;
if (numberOfNotifications === 1) {
notification.component.show().then(this.tempPromiseResolver); // Done
} else {
const implicitStackingLimit = 2;
// Stacking enabled? (stacking value below 2 means stacking is disabled)
if (this.config.behaviour.stacking === false || this.config.behaviour.stacking < implicitStackingLimit) {
this.notifications[0].component.hide().then(() => {
this.removeNotificationFromList(this.notifications[0]);
notification.component.show().then(this.tempPromiseResolver); // Done
});
} else {
const stepPromises: Array<Promise<void>> = [];
// Are there now too many notifications?
if (numberOfNotifications > this.config.behaviour.stacking) {
const oldNotifications: Array<NotifierNotification> = this.notifications.slice(1, numberOfNotifications - 1);
// Are animations enabled?
if (this.config.animations.enabled) {
// Is animation overlap enabled?
if (this.config.animations.overlap !== false && this.config.animations.overlap > 0) {
stepPromises.push(this.notifications[0].component.hide());
setTimeout(() => {
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), true));
}, this.config.animations.hide.speed - this.config.animations.overlap);
setTimeout(() => {
stepPromises.push(notification.component.show());
}, this.config.animations.hide.speed + this.config.animations.shift.speed - this.config.animations.overlap);
} else {
stepPromises.push(
new Promise<void>((resolve: () => void) => {
this.notifications[0].component.hide().then(() => {
this.shiftNotifications(oldNotifications, notification.component.getHeight(), true).then(() => {
notification.component.show().then(resolve);
});
});
}),
);
}
} else {
stepPromises.push(this.notifications[0].component.hide());
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), true));
stepPromises.push(notification.component.show());
}
} else {
const oldNotifications: Array<NotifierNotification> = this.notifications.slice(0, numberOfNotifications - 1);
// Are animations enabled?
if (this.config.animations.enabled) {
// Is animation overlap enabled?
if (this.config.animations.overlap !== false && this.config.animations.overlap > 0) {
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), true));
setTimeout(() => {
stepPromises.push(notification.component.show());
}, this.config.animations.shift.speed - this.config.animations.overlap);
} else {
stepPromises.push(
new Promise<void>((resolve: () => void) => {
this.shiftNotifications(oldNotifications, notification.component.getHeight(), true).then(() => {
notification.component.show().then(resolve);
});
}),
);
}
} else {
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), true));
stepPromises.push(notification.component.show());
}
}
Promise.all(stepPromises).then(() => {
if (numberOfNotifications > this.config.behaviour.stacking) {
this.removeNotificationFromList(this.notifications[0]);
}
this.tempPromiseResolver();
}); // Done
}
}
}
/**
* Hide an existing notification
*
* Fist, we skip everything if there are no notifications at all, or the given notification does not exist. Then, we hide the given
* notification. If there exist older notifications, we then shift them around to fill the gap. Once both hiding the given notification
* and shifting the older notificaitons is done, the given notification gets finally removed (from the DOM).
*
* @param action Action object, payload contains the notification ID
* @returns Promise, resolved when done
*/
private handleHideAction(action: NotifierAction): Promise<void> {
return new Promise<void>((resolve: () => void) => {
const stepPromises: Array<Promise<void>> = [];
// Does the notification exist / are there even any notifications? (let's prevent accidential errors)
const notification: NotifierNotification | undefined = this.findNotificationById(action.payload);
if (notification === undefined) {
resolve();
return;
}
// Get older notifications
const notificationIndex: number | undefined = this.findNotificationIndexById(action.payload);
if (notificationIndex === undefined) {
resolve();
return;
}
const oldNotifications: Array<NotifierNotification> = this.notifications.slice(0, notificationIndex);
// Do older notifications exist, and thus do we need to shift other notifications as a consequence?
if (oldNotifications.length > 0) {
// Are animations enabled?
if (this.config.animations.enabled && this.config.animations.hide.speed > 0) {
// Is animation overlap enabled?
if (this.config.animations.overlap !== false && this.config.animations.overlap > 0) {
stepPromises.push(notification.component.hide());
setTimeout(() => {
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), false));
}, this.config.animations.hide.speed - this.config.animations.overlap);
} else {
notification.component.hide().then(() => {
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), false));
});
}
} else {
stepPromises.push(notification.component.hide());
stepPromises.push(this.shiftNotifications(oldNotifications, notification.component.getHeight(), false));
}
} else {
stepPromises.push(notification.component.hide());
}
// Wait until both hiding and shifting is done, then remove the notification from the list
Promise.all(stepPromises).then(() => {
this.removeNotificationFromList(notification);
resolve(); // Done
});
});
}
/**
* Hide the oldest notification (bridge to handleHideAction)
*
* @param action Action object
* @returns Promise, resolved when done
*/
private handleHideOldestAction(action: NotifierAction): Promise<void> {
// Are there any notifications? (prevent accidential errors)
if (this.notifications.length === 0) {
return new Promise<void>((resolve: () => void) => {
resolve();
}); // Done
} else {
action.payload = this.notifications[0].id;
return this.handleHideAction(action);
}
}
/**
* Hide the newest notification (bridge to handleHideAction)
*
* @param action Action object
* @returns Promise, resolved when done
*/
private handleHideNewestAction(action: NotifierAction): Promise<void> {
// Are there any notifications? (prevent accidential errors)
if (this.notifications.length === 0) {
return new Promise<void>((resolve: () => void) => {
resolve();
}); // Done
} else {
action.payload = this.notifications[this.notifications.length - 1].id;
return this.handleHideAction(action);
}
}
/**
* Hide all notifications at once
*
* @returns Promise, resolved when done
*/
private handleHideAllAction(): Promise<void> {
return new Promise<void>((resolve: () => void) => {
// Are there any notifications? (prevent accidential errors)
const numberOfNotifications: number = this.notifications.length;
if (numberOfNotifications === 0) {
resolve(); // Done
return;
}
// Are animations enabled?
if (
this.config.animations.enabled &&
this.config.animations.hide.speed > 0 &&
this.config.animations.hide.offset !== false &&
this.config.animations.hide.offset > 0
) {
for (let i: number = numberOfNotifications - 1; i >= 0; i--) {
const animationOffset: number = this.config.position.vertical.position === 'top' ? numberOfNotifications - 1 : i;
setTimeout(() => {
this.notifications[i].component.hide().then(() => {
// Are we done here, was this the last notification to be hidden?
if (
(this.config.position.vertical.position === 'top' && i === 0) ||
(this.config.position.vertical.position === 'bottom' && i === numberOfNotifications - 1)
) {
this.removeAllNotificationsFromList();
resolve(); // Done
}
});
}, this.config.animations.hide.offset * animationOffset);
}
} else {
const stepPromises: Array<Promise<void>> = [];
for (let i: number = numberOfNotifications - 1; i >= 0; i--) {
stepPromises.push(this.notifications[i].component.hide());
}
Promise.all(stepPromises).then(() => {
this.removeAllNotificationsFromList();
resolve(); // Done
});
}
});
}
/**
* Shift multiple notifications at once
*
* @param notifications List containing the notifications to be shifted
* @param distance Distance to shift (in px)
* @param toMakePlace Flag, defining in which direciton to shift
* @returns Promise, resolved when done
*/
private shiftNotifications(notifications: Array<NotifierNotification>, distance: number, toMakePlace: boolean): Promise<void> {
return new Promise<void>((resolve: () => void) => {
// Are there any notifications to shift?
if (notifications.length === 0) {
resolve();
return;
}
const notificationPromises: Array<Promise<void>> = [];
for (let i: number = notifications.length - 1; i >= 0; i--) {
notificationPromises.push(notifications[i].component.shift(distance, toMakePlace));
}
Promise.all(notificationPromises).then(resolve); // Done
});
}
/**
* Add a new notification to the list of notifications (triggers change detection)
*
* @param notification Notification to add to the list of notifications
*/
private addNotificationToList(notification: NotifierNotification): void {
this.notifications.push(notification);
this.changeDetector.markForCheck(); // Run change detection because the notification list changed
}
/**
* Remove an existing notification from the list of notifications (triggers change detection)
*
* @param notification Notification to be removed from the list of notifications
*/
private removeNotificationFromList(notification: NotifierNotification): void {
this.notifications = this.notifications.filter((item: NotifierNotification) => item.component !== notification.component);
this.changeDetector.markForCheck(); // Run change detection because the notification list changed
}
/**
* Remove all notifications from the list (triggers change detection)
*/
private removeAllNotificationsFromList(): void {
this.notifications = [];
this.changeDetector.markForCheck(); // Run change detection because the notification list changed
}
/**
* Helper: Find a notification in the notification list by a given notification ID
*
* @param notificationId Notification ID, used for finding notification
* @returns Notification, undefined if not found
*/
private findNotificationById(notificationId: string): NotifierNotification | undefined {
return this.notifications.find((currentNotification: NotifierNotification) => currentNotification.id === notificationId);
}
/**
* Helper: Find a notification's index by a given notification ID
*
* @param notificationId Notification ID, used for finding a notification's index
* @returns Notification index, undefined if not found
*/
private findNotificationIndexById(notificationId: string): number | undefined {
const notificationIndex: number = this.notifications.findIndex(
(currentNotification: NotifierNotification) => currentNotification.id === notificationId,
);
return notificationIndex !== -1 ? notificationIndex : undefined;
}
} | the_stack |
import { useEffect, useState } from 'react';
import { Radio, Space } from 'antd';
import { Form, Modal, Button, Input, Select, Upload } from 'antd';
import FolderPicker from '../../components/folderPicker';
import { CATELOGUE_TYPE, formItemLayout, RESOURCE_TYPE } from '@/constant';
import { IComputeType } from '@/interface';
import type { RcFile } from 'antd/lib/upload';
import { resourceNameMapping } from '@/utils/enums';
import { catalogueService } from '@/services';
import resourceManagerTree from '@/services/resourceManagerService';
import { FileTypes } from '@dtinsight/molecule/esm/model';
import api from '@/api';
const FormItem = Form.Item;
const { Option } = Select;
export interface IFormFieldProps {
/**
* Only when editing
*/
id?: number;
originFileName?: string;
/**
* Only when adding
*/
resourceName?: string;
resourceType?: RESOURCE_TYPE;
file?: RcFile;
nodePid?: number;
resourceDesc?: string;
/**
* 计算类型
*/
computeType?: IComputeType;
}
interface IResModalProps {
visible?: boolean;
/**
* 是否替换资源
*/
isCoverUpload?: boolean;
/**
* 初始值设置
*/
defaultValue?: IFormFieldProps;
onClose?: () => void;
onReplaceResource?: (values: IFormFieldProps) => Promise<boolean>;
onAddResource?: (values: IFormFieldProps) => Promise<boolean>;
}
export default function ResModal({
visible,
isCoverUpload,
defaultValue,
onClose,
onReplaceResource,
onAddResource,
}: IResModalProps) {
const [form] = Form.useForm<IFormFieldProps>();
const [confirmLoading, setLoading] = useState(false);
const handleSubmit = () => {
form.validateFields().then((values) => {
const params = { ...values };
params.resourceDesc = values.resourceDesc || '';
setLoading(true);
if (isCoverUpload) {
onReplaceResource?.(values)
.then((res) => {
if (res) {
onClose?.();
form.resetFields();
}
})
.finally(() => {
setLoading(false);
});
} else {
onAddResource?.(values)
.then((res) => {
if (res) {
onClose?.();
form.resetFields();
}
})
.finally(() => {
setLoading(false);
});
}
});
};
const handleFormValueChange = (changed: Partial<IFormFieldProps>) => {
if ('id' in changed) {
const node = resourceManagerTree.get(changed.id!)
if (node?.fileType === FileTypes.File) {
api.getOfflineRes({
resourceId: node.data.id,
}).then(res => {
if (res.code === 1) {
form.setFieldsValue({
originFileName: res.data.originFileName,
resourceType: res.data.resourceType,
computeType: res.data.computeType,
})
}
})
} else {
form.resetFields(['originFileName', 'resourceType', 'computeType']);
}
}
}
/**
* @description 检查所选是否为文件夹
*/
const checkNotDir = (_: any, value: number) => {
const node = resourceManagerTree.get(value);
if (node) {
return Promise.resolve();
}
return Promise.reject(new Error('请选择具体文件, 而非文件夹'));
};
const validateFileType = (_: any, value: RcFile) => {
if (!value) {
return Promise.resolve();
}
const { resourceType: fileType } = form.getFieldsValue();
const fileSuffix = resourceNameMapping(fileType);
if (fileType === RESOURCE_TYPE.OTHER) {
return Promise.resolve();
}
const suffix = value.name.split('.').slice(1).pop();
if (fileSuffix.toLocaleLowerCase() !== suffix) {
return Promise.reject(new Error(`资源文件只能是${fileSuffix}文件!`));
}
return Promise.resolve();
};
const renderFormItem = () => {
if (!isCoverUpload) {
return (
<>
<FormItem
label="资源名称"
name="resourceName"
rules={[
{
required: true,
message: '资源名称不可为空!',
},
{
pattern: /^[A-Za-z0-9_-]+$/,
message: '资源名称只能由字母、数字、下划线组成!',
},
{
max: 20,
message: '资源名称不得超过20个字符!',
},
]}
>
<Input placeholder="请输入资源名称" />
</FormItem>
<FormItem
label="资源类型"
name="resourceType"
rules={[
{
required: true,
message: '资源类型不可为空!',
},
]}
initialValue={RESOURCE_TYPE.JAR}
>
<Select onChange={() => form.resetFields(['file'])}>
<Option value={RESOURCE_TYPE.JAR} key={RESOURCE_TYPE.JAR}>
{resourceNameMapping(RESOURCE_TYPE.JAR)}
</Option>
<Option value={RESOURCE_TYPE.PY} key={RESOURCE_TYPE.PY}>
{resourceNameMapping(RESOURCE_TYPE.PY)}
</Option>
<Option value={RESOURCE_TYPE.EGG} key={RESOURCE_TYPE.EGG}>
{resourceNameMapping(RESOURCE_TYPE.EGG)}
</Option>
<Option value={RESOURCE_TYPE.ZIP} key={RESOURCE_TYPE.ZIP}>
{resourceNameMapping(RESOURCE_TYPE.ZIP)}
</Option>
<Option value={RESOURCE_TYPE.OTHER} key={RESOURCE_TYPE.OTHER}>
{resourceNameMapping(RESOURCE_TYPE.OTHER)}
</Option>
</Select>
</FormItem>
<FormItem
label="上传"
required
shouldUpdate={(pre, cur) =>
pre.resourceType !== cur.resourceType || pre.file !== cur.file
}
>
{({ getFieldValue }) => (
<>
<FormItem
noStyle
name="file"
rules={[
{
required: true,
message: '请选择上传文件',
},
{
validator: validateFileType,
},
]}
valuePropName="file"
getValueFromEvent={(e) => e.file}
>
<Upload
accept={
getFieldValue('resourceType') !== RESOURCE_TYPE.OTHER
? `.${resourceNameMapping(
getFieldValue('resourceType'),
)}`
: undefined
}
beforeUpload={() => false}
showUploadList={false}
>
<Button>选择文件</Button>
</Upload>
</FormItem>
<span className="ml-5px">{getFieldValue('file')?.name}</span>
</>
)}
</FormItem>
<FormItem
name="computeType"
label="计算类型"
required
initialValue={IComputeType.STFP}
tooltip="设置资源上传的计算组件类型"
>
<Radio.Group>
<Space>
<Radio value={IComputeType.STFP}>STFP</Radio>
<Radio value={IComputeType.HDFS}>HDFS</Radio>
</Space>
</Radio.Group>
</FormItem>
<FormItem
name="nodePid"
label="选择存储位置"
rules={[
{
required: true,
message: '存储位置必选!',
},
]}
initialValue={
catalogueService.getRootFolder(CATELOGUE_TYPE.RESOURCE)?.data?.id
}
>
<FolderPicker dataType={CATELOGUE_TYPE.RESOURCE} showFile={false} />
</FormItem>
<FormItem
label="描述"
name="resourceDesc"
rules={[
{
max: 200,
message: '描述请控制在200个字符以内!',
},
]}
>
<Input.TextArea rows={4} />
</FormItem>
</>
);
}
return (
<>
<FormItem
label="选择目标替换资源"
name="id"
rules={[
{
required: true,
message: '替换资源为必选!',
},
{
validator: checkNotDir,
},
]}
initialValue={catalogueService.getRootFolder(CATELOGUE_TYPE.RESOURCE)?.data?.id}
>
<FolderPicker dataType={CATELOGUE_TYPE.RESOURCE} showFile />
</FormItem>
<FormItem label="文件名" name="originFileName">
<Input disabled readOnly />
</FormItem>
<FormItem
label="资源类型"
name="resourceType"
rules={[
{
required: true,
message: '资源类型不可为空!',
},
]}
initialValue={RESOURCE_TYPE.JAR}
>
<Select onChange={() => form.resetFields(['file'])}>
<Option value={RESOURCE_TYPE.JAR} key={RESOURCE_TYPE.JAR}>
{resourceNameMapping(RESOURCE_TYPE.JAR)}
</Option>
<Option value={RESOURCE_TYPE.PY} key={RESOURCE_TYPE.PY}>
{resourceNameMapping(RESOURCE_TYPE.PY)}
</Option>
<Option value={RESOURCE_TYPE.EGG} key={RESOURCE_TYPE.EGG}>
{resourceNameMapping(RESOURCE_TYPE.EGG)}
</Option>
<Option value={RESOURCE_TYPE.ZIP} key={RESOURCE_TYPE.ZIP}>
{resourceNameMapping(RESOURCE_TYPE.ZIP)}
</Option>
<Option value={RESOURCE_TYPE.OTHER} key={RESOURCE_TYPE.OTHER}>
{resourceNameMapping(RESOURCE_TYPE.OTHER)}
</Option>
</Select>
</FormItem>
<FormItem
name="computeType"
label="计算类型"
required
tooltip="设置资源上传的计算组件类型"
>
<Radio.Group disabled>
<Space>
<Radio value={IComputeType.STFP}>STFP</Radio>
<Radio value={IComputeType.HDFS}>HDFS</Radio>
</Space>
</Radio.Group>
</FormItem>
<FormItem
label="上传"
required
shouldUpdate={(pre, cur) =>
pre.resourceType !== cur.resourceType || pre.file !== cur.file
}
>
{({ getFieldValue }) => (
<>
<FormItem
noStyle
name="file"
rules={[
{
required: true,
message: '请选择上传文件',
},
{
validator: validateFileType,
},
]}
valuePropName="file"
getValueFromEvent={(e) => e.file}
>
<Upload
accept={
getFieldValue('resourceType') !== RESOURCE_TYPE.OTHER
? `.${resourceNameMapping(
getFieldValue('resourceType'),
)}`
: undefined
}
beforeUpload={() => false}
showUploadList={false}
>
<Button>选择文件</Button>
</Upload>
</FormItem>
<span className="ml-5px">{getFieldValue('file')?.name}</span>
</>
)}
</FormItem>
<FormItem
label="描述"
name="resourceDesc"
rules={[
{
max: 200,
message: '描述请控制在200个字符以内!',
},
]}
>
<Input.TextArea rows={4} />
</FormItem>
</>
);
};
useEffect(() => {
if (visible) {
form.setFieldsValue({
...defaultValue,
});
}
}, [visible, defaultValue]);
return (
<Modal
title={isCoverUpload ? '替换资源' : '上传资源'}
confirmLoading={confirmLoading}
visible={visible}
onCancel={onClose}
onOk={handleSubmit}
destroyOnClose
>
<Form preserve={false} form={form} onValuesChange={handleFormValueChange} autoComplete="off" {...formItemLayout}>
{renderFormItem()}
</Form>
</Modal>
);
} | the_stack |
import path from 'path';
import { stringifyLogText } from '../puppeteer_wrapper/puppeteer_utils';
import DomElement from '../models/dom_element';
import { FatalError, InjectScriptError } from '../models/errors';
import { FinalBrowserSettings, OpenSettings, MediaOptions } from '../types';
import PuppeteerPage from '../puppeteer_wrapper/puppeteer_page';
import { ViewportOptions, ConsoleMessage, Page, Frame, BrowserContext, Target, GeolocationOptions, Permission, HTTPResponse, Browser } from '../puppeteer_wrapper/puppeteer_types';
import FailIfNotLoaded from '../decorators/fail_if_not_loaded';
import PuppeteerContext from '../puppeteer_wrapper/puppeteer_context';
import OverrideError from '../decorators/override_error';
import WendigoUtilsLoader from '../../injection_scripts/selector_query';
import SelectorQueryLoader from '../../injection_scripts/wendigo_utils';
import SelectorFinderLoader from '../../injection_scripts/selector_finder';
import { arrayfy } from '../utils/utils';
import HeaderHelper from './helpers/header_helper';
async function pageLog(log?: ConsoleMessage): Promise<void> {
if (log) {
const text = await stringifyLogText(log);
let logType = log.type() as string;
if (logType === 'warning') logType = 'warn';
const con = console as any;
if (!(con[logType])) logType = 'log';
con[logType](text);
}
}
const defaultOpenOptions: OpenSettings = {
viewport: {
width: 1440,
height: 900,
isMobile: false
}
};
export default abstract class BrowserCore {
public initialResponse: HTTPResponse | null;
public _headerHelper: HeaderHelper;
protected _page: PuppeteerPage;
protected _context: PuppeteerContext;
protected _originalHtml?: string;
protected _settings: FinalBrowserSettings;
private _loaded: boolean;
private _disabled: boolean;
private _components: Array<string>;
private _cache: boolean;
private _openSettings: OpenSettings = defaultOpenOptions;
constructor(context: PuppeteerContext, page: PuppeteerPage, settings: FinalBrowserSettings, components: Array<string> = []) {
this._page = page;
this._context = context;
this._settings = settings;
this._loaded = false;
this.initialResponse = null;
this._disabled = false;
this._cache = settings.cache !== undefined ? settings.cache : true;
this._components = components;
this._headerHelper = new HeaderHelper(this._page);
this._setEventListeners();
}
public get page(): Page {
return this._page.page;
}
public get context(): BrowserContext {
return this._context.context;
}
public get coreBrowser(): Browser {
return this._page.browser()
}
public get loaded(): boolean {
return this._loaded && !this._disabled;
}
public get incognito(): boolean {
return Boolean(this._settings.incognito);
}
public get cacheEnabled(): boolean {
return this._cache;
}
@OverrideError()
public async open(url: string, options?: OpenSettings): Promise<void> {
this._loaded = false;
this._openSettings = Object.assign({}, defaultOpenOptions, options);
url = this._processUrl(url);
await this.setCache(this._cache);
if (this._openSettings.queryString) {
const qs = this._generateQueryString(this._openSettings.queryString);
url = `${url}${qs}`;
}
try {
await this._beforeOpen(this._openSettings);
const response = await this._page.goto(url);
this.initialResponse = response;
return this._afterPageLoad();
} catch (err: any) {
if (err instanceof FatalError) return Promise.reject(err);
return Promise.reject(new FatalError("open", `Failed to open "${url}". ${err.message}`));
}
}
@OverrideError()
public async openFile(filepath: string, options: OpenSettings): Promise<void> {
try {
const absolutePath = path.resolve(filepath);
await this.open(`file://${absolutePath}`, options);
} catch (err) {
throw new FatalError("openFile", `Failed to open "${filepath}". File not found.`);
}
}
@OverrideError()
public async setContent(html: string): Promise<void> {
this._loaded = false;
await this.setCache(this._cache);
try {
await this._beforeOpen({});
await this.page.setContent(html);
return this._afterPageLoad();
} catch (err: any) {
if (err instanceof FatalError) return Promise.reject(err);
return Promise.reject(new FatalError("setContent", `Failed to set content. ${err.message}`));
}
}
public async setMedia(mediaOptions: MediaOptions | string): Promise<void> {
if (mediaOptions === undefined) return undefined;
if (typeof mediaOptions === 'string' || mediaOptions === null) {
mediaOptions = {
type: mediaOptions
};
}
if (mediaOptions.type !== undefined) {
this._page.emulateMediaType(mediaOptions.type);
}
if (mediaOptions.features) {
this._page.emulateMediaFeatures(mediaOptions.features);
}
}
public async close(): Promise<void> {
if (this._disabled) return Promise.resolve();
const p = this._beforeClose(); // Minor race condition with this._loaded if moved
this._disabled = true;
this._loaded = false;
this.initialResponse = null;
this._originalHtml = undefined;
try {
await p;
await this.coreBrowser.close();
} catch (err: any) {
return Promise.reject(new FatalError("close", `Failed to close browser. ${err.message}`));
}
}
@FailIfNotLoaded
public async evaluate(cb: string | ((...args: Array<any>) => any), ...args: Array<any>): Promise<any> {
args = this._setupEvaluateArguments(args);
const rawResult = await this._page.evaluateHandle(cb, ...args);
const resultAsElement = rawResult.asElement();
if (resultAsElement) {
return new DomElement(resultAsElement);
} else return rawResult.jsonValue();
}
public async pages(): Promise<Array<Page>> {
return this._context.pages();
}
@OverrideError()
public async selectPage(index: number): Promise<void> {
const page = await this._context.getPage(index);
if (!page) throw new FatalError("selectPage", `Invalid page index "${index}".`);
this._page = page;
// TODO: Avoid reload
// await this.page.reload(); // Required to enable bypassCSP
await this._beforeOpen(this._openSettings);
await this._afterPageLoad();
}
public async closePage(index: number): Promise<void> {
const page = await this._context.getPage(index);
if (!page) throw new FatalError("closePage", `Invalid page index "${index}".`);
await page.close();
try {
await this.selectPage(0);
} catch (err) {
this.close();
}
}
public setViewport(config: ViewportOptions = {}): Promise<void> {
return this._page.setViewport(config);
}
public setTimezone(tz?: string): Promise<void> {
return this._page.emulateTimezone(tz);
}
public setGeolocation(geolocation: GeolocationOptions): Promise<void> {
return this._page.setGeolocation(geolocation);
}
@OverrideError()
public async overridePermissions(url: string, permissions: Array<Permission> | Permission): Promise<void> {
return this._context.overridePermissions(url, arrayfy(permissions));
}
@FailIfNotLoaded
public async url(): Promise<string | null> {
let url = await this.evaluate(() => window.location.href);
if (url === "about:blank") url = null;
return url;
}
public frames(): Array<Frame> {
return this._page.frames();
}
@FailIfNotLoaded
public async mockDate(date: Date, options = { freeze: true }): Promise<void> {
await this.evaluate((d: number, f: boolean) => {
WendigoUtils.mockDate(d, f);
}, date.getTime(), options.freeze);
}
@FailIfNotLoaded
public clearDateMock(): Promise<void> {
return this.evaluate(() => {
WendigoUtils.clearDateMock();
});
}
@FailIfNotLoaded
public async addScript(scriptPath: string): Promise<void> {
try {
await this._page.addScriptTag({
path: scriptPath
});
} catch (err: any) {
if (err.message === "Evaluation failed: Event") {
const cspWarning = "This may be caused by the page Content Security Policy. Make sure the option bypassCSP is set to true in Wendigo.";
throw new InjectScriptError("addScript", `Error injecting scripts. ${cspWarning}`); // CSP error
} else throw new InjectScriptError("addScript", err);
}
}
public async setCache(value: boolean): Promise<void> {
await this._page.setCache(value);
this._cache = value;
}
protected async _beforeClose(): Promise<void> {
this._settings.__onClose(this);
if (!this._loaded) return Promise.resolve();
await this._callComponentsMethod("_beforeClose");
}
protected async _beforeOpen(options: OpenSettings): Promise<void> {
if (this._settings.userAgent) {
await this._page.setUserAgent(this._settings.userAgent);
}
if (this._settings.bypassCSP) {
await this._page.setBypassCSP(true);
}
if (options.geolocation) {
await this.setGeolocation(options.geolocation);
}
await this.setViewport(options.viewport);
await this._callComponentsMethod("_beforeOpen", options);
}
protected async _afterPageLoad(): Promise<void> {
const content = await this._page.content();
this._originalHtml = content;
await this._addJsScripts();
this._loaded = true;
await this._callComponentsMethod("_afterOpen");
}
private async _addJsScripts(): Promise<void> {
await Promise.all([
this._page.evaluateHandle(WendigoUtilsLoader),
this._page.evaluateHandle(SelectorQueryLoader),
this._page.evaluateHandle(SelectorFinderLoader)
]);
}
private _setupEvaluateArguments(args: Array<any>): Array<any> {
return args.map((e) => {
if (e instanceof DomElement) return e.element;
else return e;
});
}
private async _callComponentsMethod(method: string, options?: any): Promise<void> {
await Promise.all(this._components.map((c) => {
const anyThis = this as any;
if (typeof anyThis[c][method] === 'function')
return anyThis[c][method](options);
}));
}
private _generateQueryString(qs: string | { [s: string]: string; }): string {
if (typeof qs === 'string') {
if (qs[0] !== "?") qs = `?${qs}`;
return qs;
} else {
const searchParams = new URLSearchParams(qs);
return `?${searchParams.toString()}`;
}
}
private _processUrl(url: string): string {
if (url.split("://").length === 1) {
return `http://${url}`;
} else return url;
}
private _setEventListeners(): void {
if (this._settings.log) {
this._page.on("console", pageLog);
}
// TODO: move to private method
this._context.on('targetcreated', async (target: Target): Promise<void> => {
const createdPage = await target.page();
if (createdPage) {
const puppeteerPage = new PuppeteerPage(createdPage);
try {
await puppeteerPage.setBypassCSP(true);
if (this._settings.userAgent)
await puppeteerPage.setUserAgent(this._settings.userAgent);
} catch (err) {
// Will fail if browser is closed before finishing
}
}
});
this._page.on('load', async (): Promise<void> => {
if (this._loaded) {
try {
await this._afterPageLoad();
} catch (err) {
// Will fail if browser is closed
}
}
});
}
} | the_stack |
import {
AfterViewInit,
Component,
ElementRef,
forwardRef,
Injector,
OnDestroy,
OnInit,
Renderer2,
ViewChild
} from '@angular/core';
import { NG_VALIDATORS, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subscription } from 'rxjs';
import { PoLookupBaseComponent } from './po-lookup-base.component';
import { PoLookupFilterService } from './services/po-lookup-filter.service';
import { PoLookupModalService } from './services/po-lookup-modal.service';
/* istanbul ignore next */
const providers = [
PoLookupFilterService,
PoLookupModalService,
{
provide: NG_VALUE_ACCESSOR,
// eslint-disable-next-line
useExisting: forwardRef(() => PoLookupComponent),
multi: true
},
{
provide: NG_VALIDATORS,
// eslint-disable-next-line
useExisting: forwardRef(() => PoLookupComponent),
multi: true
}
];
/**
* @docsExtends PoLookupBaseComponent
*
* @description
*
* Quando existe muitos dados o po-lookup por padrão traz apenas 10 itens na tabela e os demais são carregados por demanda através do
* botão 'Carregar mais resultados'. Para que funcione corretamente, é importante que o serviço siga o
* [Guia de implementação das APIs TOTVS](https://po-ui.io/guides/api).
*
* Importante:
*
* - Caso o po-lookup contenha o [(ngModel)] sem o atributo name, ocorrerá um erro de angular.
* Então será necessário informar o atributo name ou o atributo [ngModelOptions]="{standalone: true}".
* ```
* <po-lookup
* [(ngModel)]="pessoa.nome"
* [ngModelOptions]="{standalone: true}">
* </po-lookup>
* ```
*
* @example
*
* <example name="po-lookup-basic" title="PO Lookup Basic">
* <file name="sample-po-lookup-basic/sample-po-lookup-basic.component.html"> </file>
* <file name="sample-po-lookup-basic/sample-po-lookup-basic.component.ts"> </file>
* </example>
*
* <example name="po-lookup-labs" title="PO Lookup Labs">
* <file name="sample-po-lookup-labs/sample-po-lookup-labs.component.html"> </file>
* <file name="sample-po-lookup-labs/sample-po-lookup-labs.component.ts"> </file>
* <file name="sample-po-lookup.service.ts"> </file>
* </example>
*
* <example name="po-lookup-hero" title="PO Lookup - Hero">
* <file name="sample-po-lookup-hero/sample-po-lookup-hero.component.html"> </file>
* <file name="sample-po-lookup-hero/sample-po-lookup-hero.component.ts"> </file>
* <file name="sample-po-lookup.service.ts"> </file>
* </example>
*
* <example name="po-lookup-hero-reactive-form" title="PO Lookup - Hero Reactive Form">
* <file name="sample-po-lookup-hero-reactive-form/sample-po-lookup-hero-reactive-form.component.html"> </file>
* <file name="sample-po-lookup-hero-reactive-form/sample-po-lookup-hero-reactive-form.component.ts"> </file>
* <file name="sample-po-lookup.service.ts"> </file>
* </example>
*
* <example name="po-lookup-sw-films" title="PO Lookup - Star Wars films">
* <file name="sample-po-lookup-sw-films/sample-po-lookup-sw-films.component.html"> </file>
* <file name="sample-po-lookup-sw-films/sample-po-lookup-sw-films.component.ts"> </file>
* <file name="sample-po-lookup-sw-films/sample-po-lookup-sw-films.service.ts"> </file>
* </example>
*
* <example name="po-lookup-multiple" title="PO Lookup - Multiple">
* <file name="sample-po-lookup-multiple/sample-po-lookup-multiple.component.html"> </file>
* <file name="sample-po-lookup-multiple/sample-po-lookup-multiple.component.ts"> </file>
* <file name="sample-po-lookup-multiple/sample-po-lookup-multiple.service.ts"> </file>
* </example>
*/
@Component({
selector: 'po-lookup',
templateUrl: './po-lookup.component.html',
providers
})
export class PoLookupComponent extends PoLookupBaseComponent implements AfterViewInit, OnDestroy, OnInit {
@ViewChild('inp', { read: ElementRef, static: false }) inputEl: ElementRef;
initialized = false;
timeoutResize;
visibleElement = false;
disclaimers = [];
visibleDisclaimers = [];
private modalSubscription: Subscription;
private isCalculateVisibleItems: boolean = true;
get autocomplete() {
return this.noAutocomplete ? 'off' : 'on';
}
constructor(
private renderer: Renderer2,
poLookupFilterService: PoLookupFilterService,
private poLookupModalService: PoLookupModalService,
injector: Injector
) {
super(poLookupFilterService, injector);
}
ngAfterViewInit() {
super.ngAfterViewInit();
if (this.autoFocus) {
this.focus();
}
this.initialized = true;
}
ngDoCheck() {
const inputWidth = this.inputEl?.nativeElement.offsetWidth;
// Permite que os disclaimers sejam calculados na primeira vez que o componente torna-se visível,
// evitando com isso, problemas com Tabs ou Divs que iniciem escondidas.
if ((inputWidth && !this.visibleElement && this.initialized) || (inputWidth && this.isCalculateVisibleItems)) {
this.debounceResize();
this.visibleElement = true;
}
}
ngOnDestroy() {
if (this.modalSubscription) {
this.modalSubscription.unsubscribe();
}
}
ngOnInit() {
super.ngOnInit();
this.initializeListeners();
}
/**
* Função que atribui foco ao componente.
*
* Para utilizá-la é necessário ter a instância do componente no DOM, podendo ser utilizado o ViewChild da seguinte forma:
*
* ```
* import { PoLookupComponent } from '@po-ui/ng-components';
*
* ...
*
* @ViewChild(PoLookupComponent, { static: true }) lookup: PoLookupComponent;
*
* focusLookup() {
* this.lookup.focus();
* }
* ```
*/
focus(): void {
if (!this.disabled) {
this.inputEl.nativeElement.focus();
}
}
openLookup(): void {
if (this.isAllowedOpenModal()) {
const {
advancedFilters,
service,
columns,
filterParams,
literals,
infiniteScroll,
multiple,
fieldLabel,
fieldValue
} = this;
const selectedItems = this.checkSelectedItems();
this.poLookupModalService.openModal({
advancedFilters,
service,
columns,
filterParams,
title: this.label,
literals,
infiniteScroll,
multiple,
selectedItems,
fieldLabel,
fieldValue
});
if (!this.modalSubscription) {
this.modalSubscription = this.poLookupModalService.selectValueEvent.subscribe(selectedOptions => {
if (selectedOptions.length > 1 || this.disclaimers.length) {
this.setDisclaimers(selectedOptions);
this.updateVisibleItems();
}
this.selectModel(selectedOptions);
});
}
}
}
checkSelectedItems() {
if (this.multiple) {
if (!this.disclaimers.length && this.valueToModel?.length) {
return [{ value: this.valueToModel[0], label: this.oldValue, ...this.selectedOptions[0] }];
}
return this.disclaimers;
} else {
return this.valueToModel;
}
}
setDisclaimers(selectedOptions: Array<any>) {
this.disclaimers = selectedOptions.map(selectedOption => ({
value: selectedOption[this.fieldValue],
label: selectedOption[this.fieldLabel],
...selectedOption
}));
this.visibleDisclaimers = [...this.disclaimers];
}
setViewValue(value: any, object: any): void {
if (this.inputEl && this.fieldFormat) {
this.setInputValueWipoieldFormat(object);
} else if (this.inputEl) {
this.inputEl.nativeElement.value = this.valueToModel || this.valueToModel === 0 ? value : '';
}
}
getViewValue(): string {
return this.inputEl.nativeElement.value;
}
searchEvent() {
this.onTouched?.();
const value = this.getViewValue();
if (this.oldValue?.toString() !== value) {
this.searchById(value);
}
}
closeDisclaimer(value) {
this.disclaimers = this.disclaimers.filter(disclaimer => disclaimer.value !== value);
this.valueToModel = this.valueToModel.filter(model => model !== value);
this.updateVisibleItems();
this.callOnChange(this.valueToModel.length ? this.valueToModel : undefined);
}
updateVisibleItems() {
if (this.disclaimers && this.disclaimers.length > 0) {
this.visibleDisclaimers = [].concat(this.disclaimers);
}
this.debounceResize();
if (!this.inputEl.nativeElement.offsetWidth) {
this.isCalculateVisibleItems = true;
}
}
debounceResize() {
if (!this.autoHeight) {
clearTimeout(this.timeoutResize);
this.timeoutResize = setTimeout(() => {
this.calculateVisibleItems();
}, 200);
}
}
getInputWidth() {
return this.inputEl.nativeElement.offsetWidth - 40;
}
getDisclaimersWidth() {
const disclaimers = this.inputEl.nativeElement.querySelectorAll('po-disclaimer');
return Array.from(disclaimers).map(disclaimer => disclaimer['offsetWidth']);
}
calculateVisibleItems() {
const disclaimersWidth = this.getDisclaimersWidth();
const inputWidth = this.getInputWidth();
const extraDisclaimerSize = 38;
const disclaimersVisible = disclaimersWidth[0];
const newDisclaimers = [];
const disclaimers = this.disclaimers;
if (inputWidth > 0) {
let sum = 0;
let i = 0;
for (i = 0; i < disclaimers.length; i++) {
sum += disclaimersWidth[i];
newDisclaimers.push(disclaimers[i]);
if (sum > inputWidth) {
sum -= disclaimersWidth[i];
this.isCalculateVisibleItems = false;
break;
}
}
if (disclaimersVisible || !disclaimers.length) {
if (i === disclaimers.length) {
this.isCalculateVisibleItems = false;
return;
}
if (sum + extraDisclaimerSize > inputWidth) {
newDisclaimers.splice(-2, 2);
const label = '+' + (disclaimers.length + 1 - i).toString();
newDisclaimers.push({ value: '', label: label });
} else {
newDisclaimers.splice(-1, 1);
const label = '+' + (disclaimers.length - i).toString();
newDisclaimers.push({ value: '', label: label });
}
}
}
this.visibleDisclaimers = [...newDisclaimers];
}
private isAllowedOpenModal(): boolean {
if (!this.service) {
console.warn('No service informed');
}
return !!(this.service && !this.disabled);
}
private formatFields(objectSelected, properties) {
let formatedField;
if (Array.isArray(properties)) {
for (const property of properties) {
if (objectSelected && objectSelected[property]) {
if (!formatedField) {
formatedField = objectSelected[property];
} else {
formatedField = formatedField + ' - ' + objectSelected[property];
}
}
}
}
if (!formatedField) {
formatedField = objectSelected[this.fieldValue];
}
return formatedField;
}
private setInputValueWipoieldFormat(objectSelected: any) {
const isEmpty = Object.keys(objectSelected).length === 0;
let fieldFormated;
if (Array.isArray(this.fieldFormat)) {
fieldFormated = this.formatFields(objectSelected, this.fieldFormat);
} else {
fieldFormated = this.fieldFormat(objectSelected);
}
this.oldValue = isEmpty ? '' : fieldFormated;
this.inputEl.nativeElement.value = isEmpty ? '' : fieldFormated;
}
private initializeListeners(): void {
this.resizeListener = this.renderer.listen('window', 'resize', () => {
this.updateVisibleItems();
});
}
} | the_stack |
import { identity, theme } from './theme'
/* eslint-disable */
/* **********************************************
Begin prism-core.js
********************************************** */
const _self: any = {}
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/
// Private helper vars
let uniqueId = 0
export var Prism: any = {
manual: _self.Prism && _self.Prism.manual,
disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
util: {
encode: function (tokens: any) {
if (tokens instanceof Token) {
const anyTokens: any = tokens
return new Token(anyTokens.type, Prism.util.encode(anyTokens.content), anyTokens.alias)
} else if (Array.isArray(tokens)) {
return tokens.map(Prism.util.encode)
} else {
return tokens
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/\u00a0/g, ' ')
}
},
type: function (o) {
return Object.prototype.toString.call(o).slice(8, -1)
},
objId: function (obj) {
if (!obj['__id']) {
Object.defineProperty(obj, '__id', { value: ++uniqueId })
}
return obj['__id']
},
// Deep clone a language definition (e.g. to extend it)
clone: function deepClone(o, visited?: any) {
let clone,
id,
type = Prism.util.type(o)
visited = visited || {}
switch (type) {
case 'Object':
id = Prism.util.objId(o)
if (visited[id]) {
return visited[id]
}
clone = {}
visited[id] = clone
for (const key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = deepClone(o[key], visited)
}
}
return clone
case 'Array':
id = Prism.util.objId(o)
if (visited[id]) {
return visited[id]
}
clone = []
visited[id] = clone
o.forEach(function (v, i) {
clone[i] = deepClone(v, visited)
})
return clone
default:
return o
}
},
},
languages: {
extend: function (id, redef) {
const lang = Prism.util.clone(Prism.languages[id])
for (const key in redef) {
lang[key] = redef[key]
}
return lang
},
/**
* Insert a token before another token in a language literal
* As this needs to recreate the object (we cannot actually insert before keys in object literals),
* we cannot just provide an object, we need an object and a key.
* @param inside The key (or language id) of the parent
* @param before The key to insert before.
* @param insert Object with the key/value pairs to insert
* @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
*/
insertBefore: function (inside, before, insert, root) {
root = root || Prism.languages
const grammar = root[inside]
const ret = {}
for (const token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (const newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken]
}
}
}
// Do not insert token which also occur in insert. See #1525
if (!insert.hasOwnProperty(token)) {
ret[token] = grammar[token]
}
}
}
const old = root[inside]
root[inside] = ret
// Update references in other language definitions
Prism.languages.DFS(Prism.languages, function (this: any, key, value) {
if (value === old && key != inside) {
this[key] = ret
}
})
return ret
},
// Traverse a language definition with Depth First Search
DFS: function DFS(o, callback, type?: any, visited?: any) {
visited = visited || {}
const objId = Prism.util.objId
for (const i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i)
const property = o[i],
propertyType = Prism.util.type(property)
if (propertyType === 'Object' && !visited[objId(property)]) {
visited[objId(property)] = true
DFS(property, callback, null, visited)
} else if (propertyType === 'Array' && !visited[objId(property)]) {
visited[objId(property)] = true
DFS(property, callback, i, visited)
}
}
}
},
},
plugins: {},
highlight: function (text, grammar, language) {
const env: any = {
code: text,
grammar: grammar,
language: language,
}
Prism.hooks.run('before-tokenize', env)
env.tokens = Prism.tokenize(env.code, env.grammar)
Prism.hooks.run('after-tokenize', env)
return Token.stringify(Prism.util.encode(env.tokens), env.language)
},
matchGrammar: function (text, strarr, grammar, index, startPos, oneshot, target?: any) {
for (const token in grammar) {
if (!grammar.hasOwnProperty(token) || !grammar[token]) {
continue
}
if (token == target) {
return
}
let patterns = grammar[token]
patterns = Prism.util.type(patterns) === 'Array' ? patterns : [patterns]
for (let j = 0; j < patterns.length; ++j) {
let pattern = patterns[j],
inside = pattern.inside,
lookbehind = !!pattern.lookbehind,
greedy = !!pattern.greedy,
lookbehindLength = 0,
alias = pattern.alias
if (greedy && !pattern.pattern.global) {
// Without the global flag, lastIndex won't work
const flags = pattern.pattern.toString().match(/[imuy]*$/)[0]
pattern.pattern = RegExp(pattern.pattern.source, flags + 'g')
}
pattern = pattern.pattern || pattern
// Don’t cache length as it changes during the loop
for (let i = index, pos = startPos; i < strarr.length; pos += strarr[i].length, ++i) {
let str = strarr[i]
if (strarr.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
return
}
if (str instanceof Token) {
continue
}
if (greedy && i != strarr.length - 1) {
pattern.lastIndex = pos
var match = pattern.exec(text)
if (!match) {
break
}
var from = match.index + (lookbehind ? match[1].length : 0),
to = match.index + match[0].length,
k = i,
p = pos
for (let len = strarr.length; k < len && (p < to || (!strarr[k].type && !strarr[k - 1].greedy)); ++k) {
p += strarr[k].length
// Move the index i to the element in strarr that is closest to from
if (from >= p) {
++i
pos = p
}
}
// If strarr[i] is a Token, then the match starts inside another Token, which is invalid
if (strarr[i] instanceof Token) {
continue
}
// Number of tokens to delete and replace with the new match
delNum = k - i
str = text.slice(pos, p)
match.index -= pos
} else {
pattern.lastIndex = 0
var match = pattern.exec(str),
delNum = 1
}
if (!match) {
if (oneshot) {
break
}
continue
}
if (lookbehind) {
lookbehindLength = match[1] ? match[1].length : 0
}
var from = match.index + lookbehindLength,
match = match[0].slice(lookbehindLength),
to = from + match.length,
before = str.slice(0, from),
after = str.slice(to)
const args: any = [i, delNum]
if (before) {
++i
pos += before.length
args.push(before)
}
const wrapped = new Token(token, inside ? Prism.tokenize(match, inside) : match, alias, match, greedy)
args.push(wrapped)
if (after) {
args.push(after)
}
Array.prototype.splice.apply(strarr, args)
if (delNum != 1) Prism.matchGrammar(text, strarr, grammar, i, pos, true, token)
if (oneshot) break
}
}
}
},
tokenize: function (text, grammar) {
const strarr = [text]
const rest = grammar.rest
if (rest) {
for (const token in rest) {
grammar[token] = rest[token]
}
delete grammar.rest
}
Prism.matchGrammar(text, strarr, grammar, 0, 0, false)
return strarr
},
hooks: {
all: {},
add: function (name, callback) {
const hooks = Prism.hooks.all
hooks[name] = hooks[name] || []
hooks[name].push(callback)
},
run: function (name, env) {
const callbacks = Prism.hooks.all[name]
if (!callbacks || !callbacks.length) {
return
}
for (var i = 0, callback; (callback = callbacks[i++]); ) {
callback(env)
}
},
},
Token: Token,
}
Prism.languages.clike = {
comment: [
{
pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
lookbehind: true,
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true,
greedy: true,
},
],
string: {
pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
greedy: true,
},
'class-name': {
pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i,
lookbehind: true,
inside: {
punctuation: /[.\\]/,
},
},
keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
boolean: /\b(?:true|false)\b/,
function: /\w+(?=\()/,
number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,
operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
punctuation: /[{}[\];(),.:]/,
}
Prism.languages.javascript = Prism.languages.extend('clike', {
'class-name': [
Prism.languages.clike['class-name'],
{
pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,
lookbehind: true,
},
],
keyword: [
{
pattern: /((?:^|})\s*)(?:catch|finally)\b/,
lookbehind: true,
},
{
pattern:
/(^|[^.])\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
lookbehind: true,
},
],
number:
/\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
function: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
operator: /-[-=]?|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/,
})
Prism.languages.javascript['class-name'][0].pattern =
/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/
Prism.languages.insertBefore('javascript', 'keyword', {
regex: {
pattern:
/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=\s*($|[\r\n,.;})\]]))/,
lookbehind: true,
greedy: true,
},
// This must be declared before keyword because we use "function" inside the look-forward
'function-variable': {
pattern:
/[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/,
alias: 'function',
},
parameter: [
{
pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/,
lookbehind: true,
inside: Prism.languages.javascript,
},
{
pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i,
inside: Prism.languages.javascript,
},
{
pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/,
lookbehind: true,
inside: Prism.languages.javascript,
},
{
pattern:
/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/,
lookbehind: true,
inside: Prism.languages.javascript,
},
],
constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/,
})
if (Prism.languages.markup) {
Prism.languages.markup.tag.addInlined('script', 'javascript')
}
Prism.languages.js = Prism.languages.javascript
Prism.languages.typescript = Prism.languages.extend('javascript', {
// From JavaScript Prism keyword list and TypeScript language spec: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#221-reserved-words
keyword:
/\b(?:abstract|as|async|await|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|null|of|package|private|protected|public|readonly|return|require|set|static|super|switch|this|throw|try|type|typeof|var|void|while|with|yield)\b/,
builtin: /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/,
})
Prism.languages.ts = Prism.languages.typescript
export function Token(this: any, type, content, alias, matchedStr?: any, greedy?: any) {
this.type = type
this.content = content
this.alias = alias
// Copy of the full string this token was created from
this.length = (matchedStr || '').length | 0
this.greedy = !!greedy
}
Token.stringify = function (o, language?: any) {
if (typeof o == 'string') {
return o
}
if (Array.isArray(o)) {
return o
.map(function (element) {
return Token.stringify(element, language)
})
.join('')
}
return getColorForSyntaxKind(o.type)(o.content)
}
function getColorForSyntaxKind(syntaxKind: string) {
return theme[syntaxKind] || identity
} | the_stack |
import { lineString } from "@turf/helpers";
import length from "@turf/length";
import * as fs from "fs";
import * as glob from "glob";
import * as path from "path";
import * as sharedstreetsPbf from "sharedstreets-pbf";
import * as sharedstreets from "./src/index";
import envelope from "@turf/envelope";
import * as turfHelpers from '@turf/helpers';
import { TileIndex } from './src/index';
import { TilePathGroup, TileType, TilePathParams, TilePath } from './src/index';
import { Graph, GraphMode } from "./src/graph";
import { getTileIdsForPolygon, getTileIdsForPoint, getTile } from "./src/tiles"
import { CleanedPoints, CleanedLines } from "./src/geom";
import { execSync } from 'child_process';
const test = require('tape');
const pt1 = [110, 45];
const pt2 = [-74.003388, 40.634538];
const pt3 = [-74.004107, 40.63406];
const BUILD_TEST_OUPUT = false;
test("sharedstreets -- test osrm install", (t:any) => {
const osrmPath = require.resolve('osrm');
t.comment('osrmPath: ' + osrmPath);
const osrmLibPath = path.dirname(osrmPath);
const osrmBinPath = path.join(osrmLibPath, '..');
t.comment('osrmBinPath: ' + osrmBinPath);
if(fs.existsSync(osrmBinPath)) {
t.comment('osrmBinPath found');
}
else
t.comment('osrmBinPath not found');
t.end();
});
// core library tests
test("sharedstreets -- intersection", (t:any) => {
t.equal(sharedstreets.intersectionId(pt1), "afd3db07d9baa6deef7acfcaac240607", "intersectionId => pt1");
t.equal(sharedstreets.intersectionId(pt2), "f22b51a95400e250bff8d889a738c0b0", "intersectionId => pt2");
t.equal(sharedstreets.intersectionId(pt3), "eed5479e5315e5a2e71760cc70a4ac76", "intersectionId => pt3");
t.equal(sharedstreets.intersectionMessage(pt1), "Intersection 110.00000 45.00000", "intersectionMessage => pt1");
t.equal(sharedstreets.intersectionMessage(pt2), "Intersection -74.00339 40.63454", "intersectionMessage => pt2");
t.equal(sharedstreets.intersectionMessage(pt3), "Intersection -74.00411 40.63406", "intersectionMessage => pt3");
// Extras
t.equal(sharedstreets.intersectionId([-74.00962750000001, 40.740100500000004]), "68ea64a9f5be2b3a219898387b3da3e8", "intersectionId => extra1");
t.equal(sharedstreets.intersectionMessage([-74.00962750000001, 40.740100500000004]), "Intersection -74.00963 40.74010", "intersectionMessage => extra1");
t.end();
});
test("sharedstreets -- referenceId", (t:any) => {
const locationReferenceOutbound = sharedstreets.locationReference([-74.0048213, 40.7416415], {outboundBearing: 208, distanceToNextRef: 9279});
const locationReferenceInbound = sharedstreets.locationReference([-74.0051265, 40.7408505], {inboundBearing: 188});
const formOfWay = 2; // => "MultipleCarriageway"
t.equal(locationReferenceOutbound.intersectionId, "6d9fe428bc29b591ca1830d44e73099d", "locationReferenceOutbound => intersectionId");
t.equal(locationReferenceInbound.intersectionId, "5a44762edbad541f0fb808c44c018105", "locationReferenceInbound => intersectionId");
var refHash = sharedstreets.generateHash("Reference 2 -74.00482 40.74164 208 93 -74.00513 40.74085");
t.equal(sharedstreets.referenceMessage([locationReferenceOutbound, locationReferenceInbound], formOfWay), "Reference 2 -74.00482 40.74164 208 93 -74.00513 40.74085", "referenceId => pt1");
t.equal(sharedstreets.referenceId([locationReferenceOutbound, locationReferenceInbound], formOfWay), refHash, "referenceId => pt1");
t.end();
});
test("sharedstreets -- locationReference", (t:any) => {
const options = {
distanceToNextRef: 9279,
outboundBearing: 208,
};
const locRef = sharedstreets.locationReference([-74.0048213, 40.7416415], options);
var intersectionHash = sharedstreets.generateHash("Intersection -74.00482 40.74164");
t.equal(locRef.intersectionId, intersectionHash, "locRef => intersectionId");
t.end();
});
test("sharedstreets-pbf -- intersection", (t:any) => {
var count = 1;
for(var filepath of glob.sync(path.join('./', "test", "pbf", `*.intersection.6.pbf`))) {
const buffer = fs.readFileSync(filepath);
const intersections = sharedstreetsPbf.intersection(buffer);
for(var intersection of intersections) {
count++;
if(count > 10)
break;
const {lon, lat, id, nodeId} = intersection;
const expectedId = sharedstreets.intersectionId([lon, lat], nodeId);
const message = sharedstreets.intersectionMessage([lon, lat], nodeId);
t.equal(expectedId, id, `[${message}] => ${id}`);
}
}
t.end();
});
test("sharedstreets-pbf -- geometry", (t:any) => {
var count = 1;
for(var filepath of glob.sync(path.join('./', "test", "pbf", `*.geometry.6.pbf`))) {
const buffer = fs.readFileSync(filepath);
const geometries = sharedstreetsPbf.geometry(buffer);
for(var geometry of geometries) {
count++;
if(count > 10)
break;
const {lonlats, id} = geometry;
const coords = sharedstreets.lonlatsToCoords(lonlats);
const expectedId = sharedstreets.geometryId(coords);
const message = sharedstreets.geometryMessage(coords);
t.equal(expectedId, id, `[${message}] => ${id}`);
}
}
t.end();
});
test("sharedstreets-pbf -- reference", (t:any) => {
var count = 1;
for(var filepath of glob.sync(path.join('./', "test", "pbf", `*.reference.6.pbf`))) {
const buffer = fs.readFileSync(filepath);
const references = sharedstreetsPbf.reference(buffer);
for(var reference of references) {
count++;
if(count > 10)
break;
const {locationReferences, id, formOfWay} = reference;
const expectedId = sharedstreets.referenceId(locationReferences, formOfWay);
const message = sharedstreets.referenceMessage(locationReferences, formOfWay);
t.equal(expectedId, id, `["${message}": ${expectedId}] => ${id}`);
}
}
t.end();
});
test("sharedstreets -- coordsToLonlats", (t:any) => {
const lonlats = sharedstreets.coordsToLonlats([[110, 45], [120, 55]]);
t.deepEqual(lonlats, [110, 45, 120, 55]);
t.end();
});
test("sharedstreets -- geometry", (t:any) => {
const line = lineString([[110, 45], [115, 50], [120, 55]]);
const geom = sharedstreets.geometry(line);
var geomHash = sharedstreets.generateHash("Geometry 110.00000 45.00000 115.00000 50.00000 120.00000 55.00000")
t.equal(geom.id, geomHash);
t.end();
});
test("sharedstreets -- intersection", (t:any) => {
const intersect = sharedstreets.intersection([110, 45]);
t.deepEqual(intersect, {
id: "afd3db07d9baa6deef7acfcaac240607",
lat: 45,
lon: 110,
inboundReferenceIds: [],
outboundReferenceIds: [],
});
t.end();
});
test("sharedstreets -- reference", (t:any) => {
const line = lineString([[110, 45], [115, 50], [120, 55]]);
const geom = sharedstreets.geometry(line);
const locationReferences = [
sharedstreets.locationReference([-74.0048213, 40.7416415], {outboundBearing: 208, distanceToNextRef: 9279}),
sharedstreets.locationReference([-74.0051265, 40.7408505], {inboundBearing: 188}),
];
const formOfWay = 0; // => "Other"
const ref = sharedstreets.reference(geom, locationReferences, formOfWay);
const refHash = sharedstreets.generateHash("Reference 0 -74.00482 40.74164 208 93 -74.00513 40.74085");
t.equal(ref.id, refHash);
t.end();
});
test("sharedstreets -- metadata", (t:any) => {
const line = lineString([[110, 45], [115, 50], [120, 55]]);
const gisMetadata = [{source: "sharedstreets", sections: [{sectionId: "foo", sectionProperties: "bar"}]}];
const geom = sharedstreets.geometry(line);
const metadata = sharedstreets.metadata(geom, {}, gisMetadata);
t.deepEqual(metadata, {
geometryId: "723cda09fa38e07e0957ae939eb2684f",
osmMetadata: {},
gisMetadata: [
{ source: "sharedstreets", sections: [{sectionId: "foo", sectionProperties: "bar"}]},
],
});
t.end();
});
test("sharedstreets -- getFormOfWay", (t:any) => {
const lineA = lineString([[110, 45], [115, 50], [120, 55]], {formOfWay: 3});
const lineB = lineString([[110, 45], [115, 50], [120, 55]]);
const lineC = lineString([[110, 45], [115, 50], [120, 55]], {formOfWay: "Motorway"});
t.equal(sharedstreets.getFormOfWay(lineA), 3);
t.equal(sharedstreets.getFormOfWay(lineB), 0);
t.equal(sharedstreets.getFormOfWay(lineC), 1);
t.end();
});
test("sharedstreets -- forwardReference", (t:any) => {
const line = lineString([[110, 45], [115, 50], [120, 55]]);
const forwardReference = sharedstreets.forwardReference(line).id;
const backReference = sharedstreets.backReference(line).id;
t.equal(forwardReference, "035dc67e1230f1f6c6ec63997f86ba27");
t.equal(backReference, "21993e8f0cdb8fa629418b78552a4503");
t.end();
});
test("sharedstreets -- bearing & distance", (t:any) => {
const line = lineString([[-74.006449, 40.739405000000005], [-74.00790070000001, 40.7393884], [-74.00805100000001, 40.7393804]]);
const lineLength = length(line);
const inboundBearing = sharedstreets.inboundBearing(line, lineLength, lineLength);
const outboundBearing = sharedstreets.outboundBearing(line, lineLength, 0);
const distanceToNextRef = sharedstreets.distanceToNextRef(line);
t.equal(outboundBearing, 269); // => 269 Java Implementation
t.equal(inboundBearing, 269); // => 267 Java Implementation
t.equal(distanceToNextRef, 13502); // => 13502 Java Implementation
t.end();
});
test("sharedstreets -- round", (t:any) => {
t.equal(Number(sharedstreets.round(10.123456789)), 10.12346);
t.end();
});
test("sharedstreets -- closed loops - Issue #8", (t:any) => {
// https://github.com/sharedstreets/sharedstreets-conflator/issues/8
const line = lineString([
[-79.549159053, 43.615639543],
[-79.548687537, 43.615687142],
[-79.547733353, 43.615744613],
[-79.548036429, 43.614913292],
[-79.549024608, 43.615542992],
[-79.549159053, 43.615639543],
]);
t.assert(sharedstreets.forwardReference(line));
t.assert(sharedstreets.backReference(line));
t.end();
});
// cache module tests
test("tiles -- generate tile ids ", (t:any) => {
// test polygon (dc area)
var poloygon:turfHelpers.Feature<turfHelpers.Polygon> = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[[-77.0511531829834,38.88588861057251],
[-77.00746536254883, 38.88588861057251],
[-77.00746536254883, 38.91407701203291],
[-77.0511531829834, 38.91407701203291],
[-77.0511531829834,38.88588861057251]]
]
}
};
// test tiles for polygon
var tiles1 = getTileIdsForPolygon(poloygon);
t.deepEqual(tiles1, ["12-1171-1566","12-1171-1567"]);
// test buffering
var tiles2 = getTileIdsForPolygon(poloygon, 10000);
t.deepEqual(tiles2, ["12-1170-1566","12-1170-1567","12-1171-1566","12-1171-1567","12-1172-1566","12-1172-1567"]);
// test polygon (dc area)
var point = turfHelpers.point([ -77.0511531829834, 38.88588861057251]);
// test tiles for point
var tiles3 = getTileIdsForPoint(point, 10);
t.deepEqual(tiles3, ["12-1171-1567"]);
// test buffering
var tiles4 = getTileIdsForPoint(point, 10000);
t.deepEqual(tiles4, ["12-1170-1566","12-1170-1567","12-1170-1568","12-1171-1566","12-1171-1567","12-1171-1568","12-1172-1566","12-1172-1567","12-1172-1568"]);
t.end();
});
test("tiles -- build tile paths ", (t:any) => {
var pathString = 'osm/planet-180430/12-1171-1566.geometry.6.pbf';
// test path parsing
var tilePath = new TilePath(pathString);
t.deepEqual(tilePath, {"tileId":"12-1171-1566","tileType":"geometry","source":"osm/planet-180430","tileHierarchy":6});
// test path string builder
var pathString2 = tilePath.toPathString();
t.equal(pathString, pathString2);
// test path group
var pathGroup = new TilePathGroup([tilePath]);
t.deepEqual(pathGroup, { source: 'osm/planet-180430', tileHierarchy: 6, tileTypes: ['geometry'], tileIds: ['12-1171-1566']});
// test path gruop eumeration
t.deepEqual([...pathGroup], [{ source: 'osm/planet-180430', tileHierarchy: 6, tileType: 'geometry', tileId: '12-1171-1566' }]);
t.end();
});
test("tiles -- fetch/parse protobuf filese", async (t:any) => {
// get data
var tilePath = new TilePath('osm/planet-180430/12-1171-1566.geometry.6.pbf');
var data = await getTile(tilePath);
t.equal(data.length, 7352);
t.end();
});
test("cache -- load data", async (t:any) => {
// test polygon (dc area)
var polygon:turfHelpers.Feature<turfHelpers.Polygon> = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[[-77.0511531829834,38.88588861057251],
[-77.00746536254883, 38.88588861057251],
[-77.00746536254883, 38.91407701203291],
[-77.0511531829834, 38.91407701203291],
[-77.0511531829834,38.88588861057251]]
]
}
};
var tilesIds = getTileIdsForPolygon(polygon);
var params = new TilePathParams();
params.source = 'osm/planet-180430';
params.tileHierarchy = 6;
var tilePathGroup:TilePathGroup = TilePathGroup.fromPolygon(polygon, 0, params);
tilePathGroup.addType(TileType.GEOMETRY);
var tileIndex = new TileIndex();
await tileIndex.indexTilesByPathGroup(tilePathGroup);
t.equal(tileIndex.tiles.size, 2);
tilePathGroup.addType(TileType.INTERSECTION);
await tileIndex.indexTilesByPathGroup(tilePathGroup);
t.equal(tileIndex.tiles.size, 4);
var data = await tileIndex.intersects(polygon, TileType.GEOMETRY, 0, params);
t.equal(data.features.length, 2102);
var data = await tileIndex.intersects(polygon, TileType.INTERSECTION, 0, params);
t.equal(data.features.length,1162);
t.end();
});
test("tileIndex -- point data", async (t:any) => {
// test polygon (dc area)
const content = fs.readFileSync('test/geojson/points_1.in.geojson');
var points:turfHelpers.FeatureCollection<turfHelpers.Point> = JSON.parse(content.toLocaleString());
var params = new TilePathParams();
params.source = 'osm/planet-180430';
params.tileHierarchy = 6;
// test nearby
var tileIndex = new TileIndex();
var featureCount = 0;
for(var point of points.features) {
var foundFeatures = await tileIndex.nearby(point, TileType.GEOMETRY, 10, params);
featureCount += foundFeatures.features.length;
}
t.equal(featureCount,3);
t.end();
});
test("match points", async (t:any) => {
// test polygon (dc area)
const content = fs.readFileSync('test/geojson/points_1.in.geojson');
var pointsIn:turfHelpers.FeatureCollection<turfHelpers.Point> = JSON.parse(content.toLocaleString());
var cleanedPoints = new CleanedPoints(pointsIn);
var points:turfHelpers.FeatureCollection<turfHelpers.Point> = turfHelpers.featureCollection(cleanedPoints.clean);
var params = new TilePathParams();
params.source = 'osm/planet-180430';
params.tileHierarchy = 6;
// test matcher point candidates
var matcher = new Graph(null, params);
var matchedPoints:turfHelpers.Feature<turfHelpers.Point>[] = [];
for(let searchPoint of points.features) {
let matches = await matcher.matchPoint(searchPoint, null, 3);
for(let match of matches) {
matchedPoints.push(match.toFeature());
}
}
const matchedPointFeatureCollection_1a:turfHelpers.FeatureCollection<turfHelpers.Point> = turfHelpers.featureCollection(matchedPoints);
const expected_1a_file = 'test/geojson/points_1a.out.geojson';
if(BUILD_TEST_OUPUT) {
var expected_1a_out:string = JSON.stringify(matchedPointFeatureCollection_1a);
fs.writeFileSync(expected_1a_file, expected_1a_out);
}
const expected_1a_in = fs.readFileSync(expected_1a_file);
const expected_1a:turfHelpers.FeatureCollection<turfHelpers.Point> = JSON.parse(expected_1a_in.toLocaleString());
t.deepEqual(expected_1a, matchedPointFeatureCollection_1a);
matcher.searchRadius = 1000;
var matchedPoints:turfHelpers.Feature<turfHelpers.Point>[] = [];
let matches = await matcher.matchPoint(points.features[0], null, 10);
for(let match of matches) {
matchedPoints.push(match.toFeature());
}
const matchedPointFeatureCollection_1b:turfHelpers.FeatureCollection<turfHelpers.Point> = turfHelpers.featureCollection(matchedPoints);
const expected_1b_file = 'test/geojson/points_1b.out.geojson';
if(BUILD_TEST_OUPUT) {
var expected_1b_out:{} = JSON.stringify(matchedPointFeatureCollection_1b);
fs.writeFileSync(expected_1b_file, expected_1b_out);
}
const expected_1b_in = fs.readFileSync(expected_1b_file);
const expected_1b:{} = JSON.parse(expected_1b_in.toLocaleString());
t.deepEqual(expected_1b, matchedPointFeatureCollection_1b);
t.end();
});
test("match lines 1", async (t:any) => {
// test polygon (dc area)
const content = fs.readFileSync('test/geojson/sf_centerlines.sample.geojson');
var linesIn:turfHelpers.FeatureCollection<turfHelpers.LineString> = JSON.parse(content.toLocaleString());
var cleanedLines = new CleanedLines(linesIn);
var lines:turfHelpers.FeatureCollection<turfHelpers.LineString> = turfHelpers.featureCollection(cleanedLines.clean);
var params = new TilePathParams();
params.source = 'osm/planet-180430';
params.tileHierarchy = 6;
//test matcher point candidates
var matcher = new Graph(envelope(lines), params);
await matcher.buildGraph();
var matchedLines = turfHelpers.featureCollection([]);
for(var line of lines.features) {
var pathCandidate = await matcher.matchGeom(line);
matchedLines.features.push(pathCandidate.matchedPath);
}
const expected_1a_file = 'test/geojson/sf_centerlines.sample.out.geojson';
if(BUILD_TEST_OUPUT) {
var expected_1a_out:string = JSON.stringify(matchedLines);
fs.writeFileSync(expected_1a_file, expected_1a_out);
}
const expected_1a_in = fs.readFileSync(expected_1a_file);
const expected_1a:{} = JSON.parse(expected_1a_in.toLocaleString());
t.deepEqual(matchedLines, expected_1a);
t.end();
});
test("match lines 2 -- snapping and directed edges", async (t:any) => {
// test polygon (dc area)
const content = fs.readFileSync('test/geojson/line-directed-test.in.geojson');
var linesIn:turfHelpers.FeatureCollection<turfHelpers.LineString> = JSON.parse(content.toLocaleString());
var cleanedLines = new CleanedLines(linesIn);
var lines:turfHelpers.FeatureCollection<turfHelpers.LineString> = turfHelpers.featureCollection(cleanedLines.clean);
var params = new TilePathParams();
params.source = 'osm/planet-180430';
params.tileHierarchy = 6;
//test matcher point candidates
var matcher = new Graph(envelope(lines), params);
await matcher.buildGraph();
matcher.searchRadius = 20;
matcher.snapIntersections = true;
var matchedLines = turfHelpers.featureCollection([]);
for(var line of lines.features) {
var pathCandidate = await matcher.matchGeom(line);
if(pathCandidate)
matchedLines.features.push(pathCandidate.matchedPath);
}
const expected_1a_file = 'test/geojson/line-directed-test-snapped.out.geojson';
if(BUILD_TEST_OUPUT) {
var expected_1a_out:string = JSON.stringify(matchedLines);
fs.writeFileSync(expected_1a_file, expected_1a_out);
}
const expected_1a_in = fs.readFileSync(expected_1a_file);
const expected_1a:{} = JSON.parse(expected_1a_in.toLocaleString());
t.deepEqual(matchedLines, expected_1a);
matcher.snapIntersections = false;
var matchedLines = turfHelpers.featureCollection([]);
for(var line of lines.features) {
var pathCandidate = await matcher.matchGeom(line);
if(pathCandidate)
matchedLines.features.push(pathCandidate.matchedPath);
}
const expected_1b_file = 'test/geojson/line-directed-test-unsnapped.out.geojson';
if(BUILD_TEST_OUPUT) {
var expected_1b_out:string = JSON.stringify(matchedLines);
fs.writeFileSync(expected_1b_file, expected_1b_out);
}
const expected_1b_in = fs.readFileSync(expected_1b_file);
const expected_1b:{} = JSON.parse(expected_1b_in.toLocaleString());
t.deepEqual(matchedLines, expected_1b);
t.end();
}); | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/policy/cr_policy_indicator.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import '../controls/settings_toggle_button.js';
import './sync_account_control.js';
import '../icons.js';
import '../settings_page/settings_animated_pages.js';
import '../settings_page/settings_subpage.js';
import '../settings_shared_css.js';
// <if expr="chromeos">
import {convertImageSequenceToPng} from 'chrome://resources/cr_elements/chromeos/cr_picture/png.js';
// </if>
import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {isChromeOS} from 'chrome://resources/js/cr.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {getImage} from 'chrome://resources/js/icon.js';
import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BaseMixin} from '../base_mixin.js';
import {loadTimeData} from '../i18n_setup.js';
import {OpenWindowProxyImpl} from '../open_window_proxy.js';
import {PageVisibility} from '../page_visibility.js';
import {routes} from '../route.js';
import {RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
// <if expr="chromeos">
import {AccountManagerBrowserProxyImpl} from './account_manager_browser_proxy.js';
// </if>
import {ProfileInfo, ProfileInfoBrowserProxyImpl} from './profile_info_browser_proxy.js';
import {StoredAccount, SyncBrowserProxy, SyncBrowserProxyImpl, SyncStatus} from './sync_browser_proxy.js';
type FocusConfig = Map<string, (string|(() => void))>;
export interface SettingsPeoplePageElement {
$: {
importDataDialogTrigger: HTMLElement,
toast: CrToastElement,
};
}
const SettingsPeoplePageElementBase =
RouteObserverMixin(WebUIListenerMixin(BaseMixin(PolymerElement))) as {
new (): PolymerElement & WebUIListenerMixinInterface &
RouteObserverMixinInterface
};
export class SettingsPeoplePageElement extends SettingsPeoplePageElementBase {
static get is() {
return 'settings-people-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* This flag is used to conditionally show a set of new sign-in UIs to the
* profiles that have been migrated to be consistent with the web
* sign-ins.
* TODO(tangltom): In the future when all profiles are completely
* migrated, this should be removed, and UIs hidden behind it should
* become default.
*/
signinAllowed_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('signinAllowed');
},
},
// <if expr="not chromeos">
/**
* Stored accounts to the system, supplied by SyncBrowserProxy.
*/
storedAccounts: Object,
// </if>
/**
* The current sync status, supplied by SyncBrowserProxy.
*/
syncStatus: Object,
/**
* Dictionary defining page visibility.
*/
pageVisibility: Object,
/**
* Authentication token provided by settings-lock-screen.
*/
authToken_: {
type: String,
value: '',
},
/**
* The currently selected profile icon URL. May be a data URL.
*/
profileIconUrl_: String,
/**
* Whether the profile row is clickable. The behavior depends on the
* platform.
*/
isProfileActionable_: {
type: Boolean,
value() {
if (!isChromeOS) {
// Opens profile manager.
return true;
}
// Post-SplitSettings links out to account manager if it is available.
return loadTimeData.getBoolean('isAccountManagerEnabled');
},
readOnly: true,
},
/**
* The current profile name.
*/
profileName_: String,
// <if expr="not chromeos">
shouldShowGoogleAccount_: {
type: Boolean,
value: false,
computed:
'computeShouldShowGoogleAccount_(storedAccounts, syncStatus,' +
'storedAccounts.length, syncStatus.signedIn, syncStatus.hasError)',
},
showImportDataDialog_: {
type: Boolean,
value: false,
},
// </if>
showSignoutDialog_: Boolean,
focusConfig_: {
type: Object,
value() {
const map = new Map();
if (routes.SYNC) {
map.set(routes.SYNC.path, '#sync-setup');
}
// <if expr="not chromeos">
if (routes.MANAGE_PROFILE) {
map.set(
routes.MANAGE_PROFILE.path,
loadTimeData.getBoolean('signinAllowed') ?
'#edit-profile' :
'#profile-row .subpage-arrow');
}
// </if>
return map;
},
},
};
}
prefs: any;
private signinAllowed_: boolean;
syncStatus: SyncStatus|null;
pageVisibility: PageVisibility;
private authToken_: string;
private profileIconUrl_: string;
private isProfileActionable_: boolean;
private profileName_: String;
// <if expr="not chromeos">
storedAccounts: Array<StoredAccount>|null;
private shouldShowGoogleAccount_: boolean;
private showImportDataDialog_: boolean;
// </if>
private showSignoutDialog_: boolean;
private focusConfig_: FocusConfig;
private syncBrowserProxy_: SyncBrowserProxy =
SyncBrowserProxyImpl.getInstance();
connectedCallback() {
super.connectedCallback();
let useProfileNameAndIcon = true;
// <if expr="chromeos">
if (loadTimeData.getBoolean('isAccountManagerEnabled')) {
// If this is SplitSettings and we have the Google Account manager,
// prefer the GAIA name and icon.
useProfileNameAndIcon = false;
this.addWebUIListener(
'accounts-changed', this.updateAccounts_.bind(this));
this.updateAccounts_();
}
// </if>
if (useProfileNameAndIcon) {
ProfileInfoBrowserProxyImpl.getInstance().getProfileInfo().then(
this.handleProfileInfo_.bind(this));
this.addWebUIListener(
'profile-info-changed', this.handleProfileInfo_.bind(this));
}
this.syncBrowserProxy_.getSyncStatus().then(
this.handleSyncStatus_.bind(this));
this.addWebUIListener(
'sync-status-changed', this.handleSyncStatus_.bind(this));
// <if expr="not chromeos">
const handleStoredAccounts = (accounts: Array<StoredAccount>) => {
this.storedAccounts = accounts;
};
this.syncBrowserProxy_.getStoredAccounts().then(handleStoredAccounts);
this.addWebUIListener('stored-accounts-updated', handleStoredAccounts);
this.addWebUIListener('sync-settings-saved', () => {
this.$.toast.show();
});
// </if>
}
currentRouteChanged() {
// <if expr="not chromeos">
this.showImportDataDialog_ =
Router.getInstance().getCurrentRoute() === routes.IMPORT_DATA;
// </if>
if (Router.getInstance().getCurrentRoute() === routes.SIGN_OUT) {
// If the sync status has not been fetched yet, optimistically display
// the sign-out dialog. There is another check when the sync status is
// fetched. The dialog will be closed when the user is not signed in.
if (this.syncStatus && !this.syncStatus.signedIn) {
Router.getInstance().navigateToPreviousRoute();
} else {
this.showSignoutDialog_ = true;
}
}
}
private getEditPersonAssocControl_(): Element {
return this.signinAllowed_ ?
assert(this.shadowRoot!.querySelector('#edit-profile')!) :
assert(this.shadowRoot!.querySelector('#profile-row')!);
}
private getSyncAndGoogleServicesSubtext_(): string {
if (this.syncStatus && this.syncStatus.hasError &&
this.syncStatus.statusText) {
return this.syncStatus.statusText;
}
return '';
}
/**
* Handler for when the profile's icon and name is updated.
*/
private handleProfileInfo_(info: ProfileInfo) {
this.profileName_ = info.name;
/**
* Extract first frame from image by creating a single frame PNG using
* url as input if base64 encoded and potentially animated.
*/
// <if expr="chromeos">
if (info.iconUrl.startsWith('data:image/png;base64')) {
this.profileIconUrl_ = convertImageSequenceToPng([info.iconUrl]);
return;
}
// </if>
this.profileIconUrl_ = info.iconUrl;
}
// <if expr="chromeos">
private async updateAccounts_() {
const accounts =
await AccountManagerBrowserProxyImpl.getInstance().getAccounts();
// The user might not have any GAIA accounts (e.g. guest mode or Active
// Directory). In these cases the profile row is hidden, so there's nothing
// to do.
if (accounts.length === 0) {
return;
}
this.profileName_ = accounts[0].fullName;
this.profileIconUrl_ = accounts[0].pic;
}
// </if>
/**
* Handler for when the sync state is pushed from the browser.
*/
private handleSyncStatus_(syncStatus: SyncStatus|null) {
// Sign-in impressions should be recorded only if the sign-in promo is
// shown. They should be recorder only once, the first time
// |this.syncStatus| is set.
const shouldRecordSigninImpression = !this.syncStatus && syncStatus &&
this.signinAllowed_ && !syncStatus.signedIn;
this.syncStatus = syncStatus;
if (shouldRecordSigninImpression && !this.shouldShowSyncAccountControl_()) {
// SyncAccountControl records the impressions user actions.
chrome.metricsPrivate.recordUserAction('Signin_Impression_FromSettings');
}
}
// <if expr="not chromeos">
private computeShouldShowGoogleAccount_(): boolean {
if (this.storedAccounts === undefined || this.syncStatus === undefined) {
return false;
}
return (this.storedAccounts!.length > 0 || !!this.syncStatus!.signedIn) &&
!this.syncStatus!.hasError;
}
// </if>
private onProfileTap_() {
// <if expr="chromeos">
if (loadTimeData.getBoolean('isAccountManagerEnabled')) {
// Post-SplitSettings. The browser C++ code loads OS settings in a window.
// Don't use window.open() because that creates an extra empty tab.
window.location.href = 'chrome://os-settings/accountManager';
}
// </if>
// <if expr="not chromeos">
Router.getInstance().navigateTo(routes.MANAGE_PROFILE);
// </if>
}
private onDisconnectDialogClosed_() {
this.showSignoutDialog_ = false;
if (Router.getInstance().getCurrentRoute() === routes.SIGN_OUT) {
Router.getInstance().navigateToPreviousRoute();
}
}
private onSyncTap_() {
// Users can go to sync subpage regardless of sync status.
Router.getInstance().navigateTo(routes.SYNC);
}
// <if expr="not chromeos and not lacros">
private onImportDataTap_() {
Router.getInstance().navigateTo(routes.IMPORT_DATA);
}
private onImportDataDialogClosed_() {
Router.getInstance().navigateToPreviousRoute();
focusWithoutInk(assert(this.$.importDataDialogTrigger));
}
// </if>
/**
* Open URL for managing your Google Account.
*/
private openGoogleAccount_() {
OpenWindowProxyImpl.getInstance().openURL(
loadTimeData.getString('googleAccountUrl'));
chrome.metricsPrivate.recordUserAction('ManageGoogleAccount_Clicked');
}
private shouldShowSyncAccountControl_(): boolean {
// <if expr="chromeos">
return false;
// </if>
// <if expr="not chromeos">
if (this.syncStatus === undefined) {
return false;
}
return !!this.syncStatus!.syncSystemEnabled && this.signinAllowed_;
// </if>
}
/**
* @return A CSS image-set for multiple scale factors.
*/
private getIconImageSet_(iconUrl: string): string {
return getImage(iconUrl);
}
}
declare global {
interface HTMLElementTagNameMap {
'settings-people-page': SettingsPeoplePageElement;
}
}
customElements.define(SettingsPeoplePageElement.is, SettingsPeoplePageElement); | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
import {
getFieldsObject,
quickbaseApiRequest,
quickbaseApiRequestAllItems,
} from './GenericFunctions';
import {
fieldFields,
fieldOperations,
} from './FieldDescription';
import {
fileFields,
fileOperations,
} from './FileDescription';
import {
recordFields,
recordOperations,
} from './RecordDescription';
import {
reportFields,
reportOperations,
} from './ReportDescription';
export class QuickBase implements INodeType {
description: INodeTypeDescription = {
displayName: 'Quick Base',
name: 'quickbase',
icon: 'file:quickbase.png',
group: ['input'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Integrate with the Quick Base RESTful API',
defaults: {
name: 'Quick Base',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'quickbaseApi',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Field',
value: 'field',
},
{
name: 'File',
value: 'file',
},
{
name: 'Record',
value: 'record',
},
{
name: 'Report',
value: 'report',
},
],
default: 'record',
description: 'The resource to operate on.',
},
...fieldOperations,
...fieldFields,
...fileOperations,
...fileFields,
...recordOperations,
...recordFields,
...reportOperations,
...reportFields,
],
};
methods = {
loadOptions: {
async getTableFields(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const tableId = this.getCurrentNodeParameter('tableId') as string;
const fields = await quickbaseApiRequest.call(this, 'GET', '/fields', {}, { tableId });
for (const field of fields) {
returnData.push({
name: field.label,
value: field.id,
});
}
return returnData;
},
async getUniqueTableFields(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const tableId = this.getCurrentNodeParameter('tableId') as string;
const fields = await quickbaseApiRequest.call(this, 'GET', '/fields', {}, { tableId });
for (const field of fields) {
//upsert can be achived just with fields that are set as unique and are no the primary key
if (field.unique === true && field.properties.primaryKey === false) {
returnData.push({
name: field.label,
value: field.id,
});
}
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = (items.length as unknown) as number;
const qs: IDataObject = {};
const headers: IDataObject = {};
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
if (resource === 'field') {
if (operation === 'getAll') {
for (let i = 0; i < length; i++) {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const tableId = this.getNodeParameter('tableId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
const qs: IDataObject = {
tableId,
};
Object.assign(qs, options);
responseData = await quickbaseApiRequest.call(this, 'GET', '/fields', {}, qs);
if (returnAll === false) {
const limit = this.getNodeParameter('limit', i) as number;
responseData = responseData.splice(0, limit);
}
returnData.push.apply(returnData, responseData);
}
}
}
if (resource === 'file') {
if (operation === 'delete') {
for (let i = 0; i < length; i++) {
const tableId = this.getNodeParameter('tableId', i) as string;
const recordId = this.getNodeParameter('recordId', i) as string;
const fieldId = this.getNodeParameter('fieldId', i) as string;
const versionNumber = this.getNodeParameter('versionNumber', i) as string;
responseData = await quickbaseApiRequest.call(this, 'DELETE', `/files/${tableId}/${recordId}/${fieldId}/${versionNumber}`);
returnData.push(responseData);
}
}
if (operation === 'download') {
for (let i = 0; i < length; i++) {
const tableId = this.getNodeParameter('tableId', i) as string;
const recordId = this.getNodeParameter('recordId', i) as string;
const fieldId = this.getNodeParameter('fieldId', i) as string;
const versionNumber = this.getNodeParameter('versionNumber', i) as string;
const newItem: INodeExecutionData = {
json: items[i].json,
binary: {},
};
if (items[i].binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
Object.assign(newItem.binary, items[i].binary);
}
items[i] = newItem;
const dataPropertyNameDownload = this.getNodeParameter('binaryPropertyName', i) as string;
responseData = await quickbaseApiRequest.call(this, 'GET', `/files/${tableId}/${recordId}/${fieldId}/${versionNumber}`, {}, {}, { json: false, resolveWithFullResponse: true });
//content-disposition': 'attachment; filename="dog-puppy-on-garden-royalty-free-image-1586966191.jpg"',
const contentDisposition = responseData.headers['content-disposition'];
const data = Buffer.from(responseData.body as string, 'base64');
items[i].binary![dataPropertyNameDownload] = await this.helpers.prepareBinaryData(data as unknown as Buffer, contentDisposition.split('=')[1]);
}
return this.prepareOutputData(items);
}
}
if (resource === 'record') {
if (operation === 'create') {
const tableId = this.getNodeParameter('tableId', 0) as string;
const simple = this.getNodeParameter('simple', 0) as boolean;
const data: IDataObject[] = [];
const options = this.getNodeParameter('options', 0) as IDataObject;
for (let i = 0; i < length; i++) {
const record: IDataObject = {};
const columns = this.getNodeParameter('columns', i) as string;
const columnList = columns.split(',').map(column => column.trim());
if (options.useFieldIDs === true) {
for (const key of Object.keys(items[i].json)) {
record[key] = { value: items[i].json[key] };
}
} else {
const { fieldsLabelKey } = await getFieldsObject.call(this, tableId);
for (const key of Object.keys(items[i].json)) {
if (fieldsLabelKey.hasOwnProperty(key) && columnList.includes(key)) {
record[fieldsLabelKey[key].toString()] = { value: items[i].json[key] };
}
}
}
data.push(record);
}
const body: IDataObject = {
data,
to: tableId,
};
// If no fields are set return at least the record id
// 3 == Default Quickbase RecordID #
body.fieldsToReturn = [3];
if (options.fields) {
body.fieldsToReturn = options.fields as string[];
}
responseData = await quickbaseApiRequest.call(this, 'POST', '/records', body);
if (simple === true) {
const { data: records } = responseData;
responseData = [];
for (const record of records) {
const data: IDataObject = {};
for (const [key, value] of Object.entries(record)) {
data[key] = (value as IDataObject).value;
}
responseData.push(data);
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData);
} else {
returnData.push(responseData);
}
}
if (operation === 'delete') {
for (let i = 0; i < length; i++) {
const tableId = this.getNodeParameter('tableId', i) as string;
const where = this.getNodeParameter('where', i) as string;
const body: IDataObject = {
from: tableId,
where,
};
responseData = await quickbaseApiRequest.call(this, 'DELETE', '/records', body);
returnData.push(responseData);
}
}
if (operation === 'getAll') {
for (let i = 0; i < length; i++) {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const tableId = this.getNodeParameter('tableId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
const body: IDataObject = {
from: tableId,
};
Object.assign(body, options);
if (options.sortByUi) {
const sort = (options.sortByUi as IDataObject).sortByValues as IDataObject[];
body.sortBy = sort;
delete body.sortByUi;
}
// if (options.groupByUi) {
// const group = (options.groupByUi as IDataObject).groupByValues as IDataObject[];
// body.groupBy = group;
// delete body.groupByUi;
// }
if (returnAll) {
responseData = await quickbaseApiRequestAllItems.call(this, 'POST', '/records/query', body, qs);
} else {
body.options = { top: this.getNodeParameter('limit', i) as number };
responseData = await quickbaseApiRequest.call(this, 'POST', '/records/query', body, qs);
const { data: records, fields } = responseData;
responseData = [];
const fieldsIdKey: { [key: string]: string } = {};
for (const field of fields) {
fieldsIdKey[field.id] = field.label;
}
for (const record of records) {
const data: IDataObject = {};
for (const [key, value] of Object.entries(record)) {
data[fieldsIdKey[key]] = (value as IDataObject).value;
}
responseData.push(data);
}
}
returnData.push.apply(returnData, responseData);
}
}
if (operation === 'update') {
const tableId = this.getNodeParameter('tableId', 0) as string;
const { fieldsLabelKey, fieldsIdKey } = await getFieldsObject.call(this, tableId);
const simple = this.getNodeParameter('simple', 0) as boolean;
const updateKey = this.getNodeParameter('updateKey', 0) as string;
const data: IDataObject[] = [];
const options = this.getNodeParameter('options', 0) as IDataObject;
for (let i = 0; i < length; i++) {
const record: IDataObject = {};
const columns = this.getNodeParameter('columns', i) as string;
const columnList = columns.split(',').map(column => column.trim());
if (options.useFieldIDs === true) {
for (const key of Object.keys(items[i].json)) {
record[key] = { value: items[i].json[key] };
}
} else {
const { fieldsLabelKey } = await getFieldsObject.call(this, tableId);
for (const key of Object.keys(items[i].json)) {
if (fieldsLabelKey.hasOwnProperty(key) && columnList.includes(key)) {
record[fieldsLabelKey[key].toString()] = { value: items[i].json[key] };
}
}
}
if (items[i].json[updateKey] === undefined) {
throw new NodeOperationError(this.getNode(), `The update key ${updateKey} could not be found in the input`);
}
data.push(record);
}
const body: IDataObject = {
data,
to: tableId,
};
// If no fields are set return at least the record id
// 3 == Default Quickbase RecordID #
//body.fieldsToReturn = [fieldsLabelKey['Record ID#']];
if (options.fields) {
body.fieldsToReturn = options.fields as string[];
}
responseData = await quickbaseApiRequest.call(this, 'POST', '/records', body);
if (simple === true) {
const { data: records } = responseData;
responseData = [];
for (const record of records) {
const data: IDataObject = {};
for (const [key, value] of Object.entries(record)) {
data[fieldsIdKey[key]] = (value as IDataObject).value;
}
responseData.push(data);
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData);
} else {
returnData.push(responseData);
}
}
if (operation === 'upsert') {
const tableId = this.getNodeParameter('tableId', 0) as string;
const simple = this.getNodeParameter('simple', 0) as boolean;
const updateKey = this.getNodeParameter('updateKey', 0) as string;
const mergeFieldId = this.getNodeParameter('mergeFieldId', 0) as string;
const data: IDataObject[] = [];
const options = this.getNodeParameter('options', 0) as IDataObject;
for (let i = 0; i < length; i++) {
const record: IDataObject = {};
const columns = this.getNodeParameter('columns', i) as string;
const columnList = columns.split(',').map(column => column.trim());
if (options.useFieldIDs === true) {
for (const key of Object.keys(items[i].json)) {
record[key] = { value: items[i].json[key] };
}
} else {
const { fieldsLabelKey } = await getFieldsObject.call(this, tableId);
for (const key of Object.keys(items[i].json)) {
if (fieldsLabelKey.hasOwnProperty(key) && columnList.includes(key)) {
record[fieldsLabelKey[key].toString()] = { value: items[i].json[key] };
}
}
}
if (items[i].json[updateKey] === undefined) {
throw new NodeOperationError(this.getNode(), `The update key ${updateKey} could not be found in the input`);
}
record[mergeFieldId] = { value: items[i].json[updateKey] };
data.push(record);
}
const body: IDataObject = {
data,
to: tableId,
mergeFieldId,
};
// If no fields are set return at least the record id
// 3 == Default Quickbase RecordID #
body.fieldsToReturn = [3];
if (options.fields) {
body.fieldsToReturn = options.fields as string[];
}
responseData = await quickbaseApiRequest.call(this, 'POST', '/records', body);
if (simple === true) {
const { data: records } = responseData;
responseData = [];
for (const record of records) {
const data: IDataObject = {};
for (const [key, value] of Object.entries(record)) {
data[key] = (value as IDataObject).value;
}
responseData.push(data);
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData);
} else {
returnData.push(responseData);
}
}
}
if (resource === 'report') {
if (operation === 'run') {
for (let i = 0; i < length; i++) {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const tableId = this.getNodeParameter('tableId', i) as string;
const reportId = this.getNodeParameter('reportId', i) as string;
qs.tableId = tableId;
if (returnAll) {
responseData = await quickbaseApiRequestAllItems.call(this, 'POST', `/reports/${reportId}/run`, {}, qs);
} else {
qs.top = this.getNodeParameter('limit', i) as number;
responseData = await quickbaseApiRequest.call(this, 'POST', `/reports/${reportId}/run`, {}, qs);
const { data: records, fields } = responseData;
responseData = [];
const fieldsIdKey: { [key: string]: string } = {};
for (const field of fields) {
fieldsIdKey[field.id] = field.label;
}
for (const record of records) {
const data: IDataObject = {};
for (const [key, value] of Object.entries(record)) {
data[fieldsIdKey[key]] = (value as IDataObject).value;
}
responseData.push(data);
}
}
returnData.push.apply(returnData, responseData);
}
}
if (operation === 'get') {
for (let i = 0; i < length; i++) {
const reportId = this.getNodeParameter('reportId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
qs.tableId = tableId;
responseData = await quickbaseApiRequest.call(this, 'GET', `/reports/${reportId}`, {}, qs);
returnData.push(responseData);
}
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import R2Error from '../../../model/errors/R2Error';
import FileNotFoundError from '../../../model/errors/FileNotFoundError';
import VdfParseError from '../../../model/errors/Vdf/VdfParseError';
import * as vdf from '@node-steam/vdf';
import * as path from 'path';
import { homedir } from 'os';
import ManagerSettings from '../ManagerSettings';
import FsProvider from '../../../providers/generic/file/FsProvider';
import GameDirectoryResolverProvider from '../../../providers/ror2/game/GameDirectoryResolverProvider';
import Game from '../../../model/game/Game';
import GameManager from '../../../model/game/GameManager';
export default class GameDirectoryResolverImpl extends GameDirectoryResolverProvider {
public async getSteamDirectory(): Promise<string | R2Error> {
const settings = await ManagerSettings.getSingleton(GameManager.activeGame);
if (settings.getContext().global.steamDirectory != null) {
return settings.getContext().global.steamDirectory!;
}
try {
const dirs = [
path.resolve(homedir(), '.local', 'share', 'Steam'),
path.resolve(homedir(), '.steam', 'steam'),
path.resolve(homedir(), '.steam', 'root'),
path.resolve(homedir(), '.steam'),
path.resolve(homedir(), '.var', 'app', 'com.valvesoftware.Steam', '.local', 'share', 'Steam'),
path.resolve(homedir(), '.var', 'app', 'com.valvesoftware.Steam', '.steam', 'steam'),
path.resolve(homedir(), '.var', 'app', 'com.valvesoftware.Steam', '.steam', 'root'),
path.resolve(homedir(), '.var', 'app', 'com.valvesoftware.Steam', '.steam')
];
for (let dir of dirs) {
if (await FsProvider.instance.exists(dir) && (await FsProvider.instance.readdir(dir))
.find(value => value.toLowerCase() === 'steam.sh') !== undefined)
return await FsProvider.instance.realpath(dir);
}
throw new Error('Steam is not installed');
} catch(e) {
const err: Error = e;
return new R2Error(
'Unable to resolve Steam install directory',
err.message,
'Try manually setting the Steam directory through the settings'
)
}
}
public async getDirectory(game: Game): Promise<R2Error | string> {
const fs = FsProvider.instance;
const settings = await ManagerSettings.getSingleton(game);
if (settings.getContext().gameSpecific.gameDirectory != null) {
return settings.getContext().gameSpecific.gameDirectory!;
}
try {
const steamPath = await this.getSteamDirectory();
if (steamPath instanceof R2Error)
return steamPath;
const manifestLocation = await this.findAppManifestLocation(steamPath, game);
if (manifestLocation instanceof R2Error)
return manifestLocation;
const parsedVdf = await this.parseAppManifest(manifestLocation, game);
const folderName = parsedVdf.AppState.installdir;
const gamePath = path.join(manifestLocation, 'common', folderName);
if (await fs.exists(gamePath)) {
return gamePath;
} else {
return new FileNotFoundError(
`${game.displayName} does not exist in Steam\'s specified location`,
`Failed to find directory: ${gamePath}`,
null
)
}
} catch(e) {
const err: Error = e;
return new R2Error(
`Unable to resolve the ${game.displayName} install directory`,
err.message,
`Try manually locating the ${game.displayName} install directory through the settings`
)
}
}
public async isProtonGame(game: Game) {
try {
const steamPath = await this.getSteamDirectory();
if (steamPath instanceof R2Error)
return steamPath;
const manifestLocation = await this.findAppManifestLocation(steamPath, game);
if (manifestLocation instanceof R2Error)
return manifestLocation;
const appManifest = await this.parseAppManifest(manifestLocation, game);
if (appManifest instanceof R2Error)
return appManifest;
let isProton: boolean;
const override_source = (appManifest.AppState.UserConfig.platform_override_source || "").toLowerCase();
console.log("Config:", appManifest.AppState.UserConfig);
switch (override_source) {
case "": isProton = false; console.log("Proton.Empty"); break;
case "linux": isProton = false; console.log("Proton.Linux"); break;
default: isProton = true; console.log("Proton.DefaultCase", override_source);
}
console.log("isProton:", isProton)
return isProton;
} catch (e) {
const err: Error = e;
return new R2Error(
`Unable to check if ${game.displayName} is a Proton game`,
err.message,
`If this happened, it is very likely that your game folder is not inside steamapps/common.`
)
}
}
public async getCompatDataDirectory(game: Game){
const fs = FsProvider.instance;
try {
const steamPath = await this.getSteamDirectory();
if (steamPath instanceof R2Error)
return steamPath;
const manifestLocation = await this.findAppManifestLocation(steamPath, game);
if (manifestLocation instanceof R2Error)
return manifestLocation;
const compatDataPath = path.join(manifestLocation, 'compatdata', `${game.activePlatform.storeIdentifier}`);
if (await fs.exists(compatDataPath)) {
return compatDataPath;
} else {
return new FileNotFoundError(
`${game.displayName} compatibility data does not exist in Steam's specified location`,
`Failed to find directory: ${compatDataPath}`,
`If this happened, it is very likely that you did not start the game at least once. Please do it.`
)
}
} catch (e) {
const err: Error = e;
return new R2Error(
`Unable to resolve the ${game.displayName} compatibility data directory`,
err.message,
`If this happened, it is very likely that you did not start the game at least once. Please do it.`
)
}
}
// TODO: Move this to Steam Utils when the multiple store refactor is made
public async getLaunchArgs(game: Game): Promise<R2Error | string> {
const steamDir = await this.getSteamDirectory();
if (steamDir instanceof R2Error) return steamDir;
let steamBaseDir;
const probableSteamBaseDirs = [
steamDir, // standard way
path.join(steamDir, 'steam'), // ubuntu
path.join(steamDir, 'root') // i am really mad at this
];
for(const dir of probableSteamBaseDirs)
if(
await FsProvider.instance.exists(dir) &&
(await FsProvider.instance.readdir(dir)).filter((x: string) => ['config', 'userdata'].includes(x)).length === 2
){
steamBaseDir = await FsProvider.instance.realpath(dir);
break;
}
if (typeof steamBaseDir === "undefined")
return new R2Error(
'An error occured whilst searching Steam user data locations',
'Cannot define the steam config location',
null
);
const loginUsers = vdf.parse((await FsProvider.instance.readFile(path.join(steamBaseDir, 'config', 'loginusers.vdf'))).toString());
let userSteamID64 = '';
for(let _id in loginUsers.users) {
if(loginUsers.users[_id].MostRecent == 1) {
userSteamID64 = _id;
break;
}
}
if(userSteamID64.length === 0) return new R2Error(
'Unable to get the current Steam User ID',
'Please try again',
null
);
const userAccountID = (BigInt(userSteamID64) & BigInt(0xFFFFFFFF)).toString();
const localConfig = vdf.parse((await FsProvider.instance.readFile(path.join(steamBaseDir, 'userdata', userAccountID, 'config', 'localconfig.vdf'))).toString());
const apps = localConfig.UserLocalConfigStore.Software.Valve.Steam.Apps || localConfig.UserLocalConfigStore.Software.Valve.Steam.apps;
return apps[game.activePlatform.storeIdentifier!].LaunchOptions || '';
}
private async findAppManifestLocation(steamPath: string, game: Game): Promise<R2Error | string> {
const probableSteamAppsLocations = [
path.join(steamPath, 'steamapps'), // every proper linux distro ever
path.join(steamPath, 'steam', 'steamapps'), // Ubuntu LTS
path.join(steamPath, 'root', 'steamapps') // wtf? expect the unexpectable
];
let steamapps;
for(const dir of probableSteamAppsLocations)
if(await FsProvider.instance.exists(dir)){
steamapps = await FsProvider.instance.realpath(dir);
break;
}
if (typeof steamapps === "undefined")
return new R2Error(
'An error occured whilst searching Steam library locations',
'Cannot define the root steamapps location',
null
);
const locations: string[] = [steamapps];
const fs = FsProvider.instance;
// Find all locations where games can be installed.
try {
const files = await fs.readdir(steamapps);
for (const file of files) {
if (file.toLowerCase() === 'libraryfolders.vdf') {
try {
const parsedVdf: any = vdf.parse((await fs.readFile(path.join(steamapps, file))).toString());
for (const key in parsedVdf.LibraryFolders) {
if (!isNaN(Number(key))) {
locations.push(
await FsProvider.instance.realpath(path.join(parsedVdf.LibraryFolders[key], 'steamapps'))
);
}
}
} catch(e) {
const err: Error = e;
// Need to throw when inside forEach.
throw new VdfParseError(
'Unable to parse libraryfolders.vdf',
err.message,
null
)
}
}
}
} catch(e) {
if (e instanceof R2Error) {
return e;
}
const err: Error = e;
return new FileNotFoundError(
'Unable to read directory',
err.message,
null
)
}
// Look through given directories for ${appManifest}
let manifestLocation: string | null = null;
try {
for (const location of locations) {
(await fs.readdir(location))
.forEach((file: string) => {
if (file.toLowerCase() === `appmanifest_${game.activePlatform.storeIdentifier}.acf`) {
manifestLocation = location;
}
});
}
} catch(e) {
if (e instanceof R2Error) {
return e;
}
const err: Error = e;
return new R2Error(
'An error occured whilst searching Steam library locations',
err.message,
null
)
}
if (manifestLocation === null) {
return new FileNotFoundError(
`Unable to locate ${game.displayName} Installation Directory`,
`Searched locations: ${locations}`,
null
)
}
// Game manifest found at ${manifestLocation}
return manifestLocation;
}
private async parseAppManifest(manifestLocation: string, game: Game): Promise<any>{
const fs = FsProvider.instance;
try {
const manifestVdf: string = (await fs.readFile(path.join(manifestLocation, `appmanifest_${game.activePlatform.storeIdentifier}.acf`))).toString();
return vdf.parse(manifestVdf);
} catch (e) {
const err: Error = e;
return new R2Error(
`An error occured whilst locating the ${game.displayName} install directory from manifest in ${manifestLocation}`,
err.message,
null
)
}
}
} | the_stack |
import {bind, each, isFunction, isString, indexOf} from 'zrender/src/core/util';
import * as eventTool from 'zrender/src/core/event';
import * as graphic from '../../util/graphic';
import * as throttle from '../../util/throttle';
import DataZoomView from './DataZoomView';
import {linearMap, asc, parsePercent} from '../../util/number';
import * as layout from '../../util/layout';
import sliderMove from '../helper/sliderMove';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import {
LayoutOrient, Payload, ZRTextVerticalAlign, ZRTextAlign, ZRElementEvent, ParsedValue
} from '../../util/types';
import SliderZoomModel from './SliderZoomModel';
import { RectLike } from 'zrender/src/core/BoundingRect';
import Axis from '../../coord/Axis';
import SeriesModel from '../../model/Series';
import { AxisBaseModel } from '../../coord/AxisBaseModel';
import { getAxisMainType, collectReferCoordSysModelInfo } from './helper';
import { enableHoverEmphasis } from '../../util/states';
import { createSymbol, symbolBuildProxies } from '../../util/symbol';
import { deprecateLog } from '../../util/log';
import { PointLike } from 'zrender/src/core/Point';
import Displayable from 'zrender/src/graphic/Displayable';
import {createTextStyle} from '../../label/labelStyle';
const Rect = graphic.Rect;
// Constants
const DEFAULT_LOCATION_EDGE_GAP = 7;
const DEFAULT_FRAME_BORDER_WIDTH = 1;
const DEFAULT_FILLER_SIZE = 30;
const DEFAULT_MOVE_HANDLE_SIZE = 7;
const HORIZONTAL = 'horizontal';
const VERTICAL = 'vertical';
const LABEL_GAP = 5;
const SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
const REALTIME_ANIMATION_CONFIG = {
easing: 'cubicOut',
duration: 100,
delay: 0
} as const;
// const NORMAL_ANIMATION_CONFIG = {
// easing: 'cubicInOut',
// duration: 200
// } as const;
interface Displayables {
sliderGroup: graphic.Group;
handles: [graphic.Path, graphic.Path];
handleLabels: [graphic.Text, graphic.Text];
dataShadowSegs: graphic.Group[];
filler: graphic.Rect;
brushRect: graphic.Rect;
moveHandle: graphic.Rect;
moveHandleIcon: graphic.Path;
// invisible move zone.
moveZone: graphic.Rect;
}
class SliderZoomView extends DataZoomView {
static type = 'dataZoom.slider';
type = SliderZoomView.type;
dataZoomModel: SliderZoomModel;
private _displayables = {} as Displayables;
private _orient: LayoutOrient;
private _range: number[];
/**
* [coord of the first handle, coord of the second handle]
*/
private _handleEnds: number[];
/**
* [length, thick]
*/
private _size: number[];
private _handleWidth: number;
private _handleHeight: number;
private _location: PointLike;
private _brushStart: PointLike;
private _brushStartTime: number;
private _dragging: boolean;
private _brushing: boolean;
private _dataShadowInfo: {
thisAxis: Axis
series: SeriesModel
thisDim: string
otherDim: string
otherAxisInverse: boolean
};
init(ecModel: GlobalModel, api: ExtensionAPI) {
this.api = api;
// A unique handler for each dataZoom component
this._onBrush = bind(this._onBrush, this);
this._onBrushEnd = bind(this._onBrushEnd, this);
}
render(
dataZoomModel: SliderZoomModel,
ecModel: GlobalModel,
api: ExtensionAPI,
payload: Payload & {
from: string
type: string
}
) {
super.render.apply(this, arguments as any);
throttle.createOrUpdate(
this,
'_dispatchZoomAction',
dataZoomModel.get('throttle'),
'fixRate'
);
this._orient = dataZoomModel.getOrient();
if (dataZoomModel.get('show') === false) {
this.group.removeAll();
return;
}
if (dataZoomModel.noTarget()) {
this._clear();
this.group.removeAll();
return;
}
// Notice: this._resetInterval() should not be executed when payload.type
// is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
// or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
this._buildView();
}
this._updateView();
}
dispose() {
this._clear();
super.dispose.apply(this, arguments as any);
}
private _clear() {
throttle.clear(this, '_dispatchZoomAction');
const zr = this.api.getZr();
zr.off('mousemove', this._onBrush);
zr.off('mouseup', this._onBrushEnd);
}
private _buildView() {
const thisGroup = this.group;
thisGroup.removeAll();
this._brushing = false;
this._displayables.brushRect = null;
this._resetLocation();
this._resetInterval();
const barGroup = this._displayables.sliderGroup = new graphic.Group();
this._renderBackground();
this._renderHandle();
this._renderDataShadow();
thisGroup.add(barGroup);
this._positionGroup();
}
private _resetLocation() {
const dataZoomModel = this.dataZoomModel;
const api = this.api;
const showMoveHandle = dataZoomModel.get('brushSelect');
const moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0;
// If some of x/y/width/height are not specified,
// auto-adapt according to target grid.
const coordRect = this._findCoordRect();
const ecSize = {width: api.getWidth(), height: api.getHeight()};
// Default align by coordinate system rect.
const positionInfo = this._orient === HORIZONTAL
? {
// Why using 'right', because right should be used in vertical,
// and it is better to be consistent for dealing with position param merge.
right: ecSize.width - coordRect.x - coordRect.width,
top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize),
width: coordRect.width,
height: DEFAULT_FILLER_SIZE
}
: { // vertical
right: DEFAULT_LOCATION_EDGE_GAP,
top: coordRect.y,
width: DEFAULT_FILLER_SIZE,
height: coordRect.height
};
// Do not write back to option and replace value 'ph', because
// the 'ph' value should be recalculated when resize.
const layoutParams = layout.getLayoutParams(dataZoomModel.option);
// Replace the placeholder value.
each(['right', 'top', 'width', 'height'] as const, function (name) {
if (layoutParams[name] === 'ph') {
layoutParams[name] = positionInfo[name];
}
});
const layoutRect = layout.getLayoutRect(
layoutParams,
ecSize
);
this._location = {x: layoutRect.x, y: layoutRect.y};
this._size = [layoutRect.width, layoutRect.height];
this._orient === VERTICAL && this._size.reverse();
}
private _positionGroup() {
const thisGroup = this.group;
const location = this._location;
const orient = this._orient;
// Just use the first axis to determine mapping.
const targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
const inverse = targetAxisModel && targetAxisModel.get('inverse');
const sliderGroup = this._displayables.sliderGroup;
const otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
// Transform barGroup.
sliderGroup.attr(
(orient === HORIZONTAL && !inverse)
? {scaleY: otherAxisInverse ? 1 : -1, scaleX: 1 }
: (orient === HORIZONTAL && inverse)
? {scaleY: otherAxisInverse ? 1 : -1, scaleX: -1 }
: (orient === VERTICAL && !inverse)
? {scaleY: otherAxisInverse ? -1 : 1, scaleX: 1, rotation: Math.PI / 2}
// Dont use Math.PI, considering shadow direction.
: {scaleY: otherAxisInverse ? -1 : 1, scaleX: -1, rotation: Math.PI / 2}
);
// Position barGroup
const rect = thisGroup.getBoundingRect([sliderGroup]);
thisGroup.x = location.x - rect.x;
thisGroup.y = location.y - rect.y;
thisGroup.markRedraw();
}
private _getViewExtent() {
return [0, this._size[0]];
}
private _renderBackground() {
const dataZoomModel = this.dataZoomModel;
const size = this._size;
const barGroup = this._displayables.sliderGroup;
const brushSelect = dataZoomModel.get('brushSelect');
barGroup.add(new Rect({
silent: true,
shape: {
x: 0, y: 0, width: size[0], height: size[1]
},
style: {
fill: dataZoomModel.get('backgroundColor')
},
z2: -40
}));
// Click panel, over shadow, below handles.
const clickPanel = new Rect({
shape: {
x: 0, y: 0, width: size[0], height: size[1]
},
style: {
fill: 'transparent'
},
z2: 0,
onclick: bind(this._onClickPanel, this)
});
const zr = this.api.getZr();
if (brushSelect) {
clickPanel.on('mousedown', this._onBrushStart, this);
clickPanel.cursor = 'crosshair';
zr.on('mousemove', this._onBrush);
zr.on('mouseup', this._onBrushEnd);
}
else {
zr.off('mousemove', this._onBrush);
zr.off('mouseup', this._onBrushEnd);
}
barGroup.add(clickPanel);
}
private _renderDataShadow() {
const info = this._dataShadowInfo = this._prepareDataShadowInfo();
this._displayables.dataShadowSegs = [];
if (!info) {
return;
}
const size = this._size;
const seriesModel = info.series;
const data = seriesModel.getRawData();
const otherDim: string = seriesModel.getShadowDim
? seriesModel.getShadowDim() // @see candlestick
: info.otherDim;
if (otherDim == null) {
return;
}
let otherDataExtent = data.getDataExtent(otherDim);
// Nice extent.
const otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
otherDataExtent = [
otherDataExtent[0] - otherOffset,
otherDataExtent[1] + otherOffset
];
const otherShadowExtent = [0, size[1]];
const thisShadowExtent = [0, size[0]];
const areaPoints = [[size[0], 0], [0, 0]];
const linePoints: number[][] = [];
const step = thisShadowExtent[1] / (data.count() - 1);
let thisCoord = 0;
// Optimize for large data shadow
const stride = Math.round(data.count() / size[0]);
let lastIsEmpty: boolean;
data.each([otherDim], function (value: ParsedValue, index) {
if (stride > 0 && (index % stride)) {
thisCoord += step;
return;
}
// FIXME
// Should consider axis.min/axis.max when drawing dataShadow.
// FIXME
// 应该使用统一的空判断?还是在list里进行空判断?
const isEmpty = value == null || isNaN(value as number) || value === '';
// See #4235.
const otherCoord = isEmpty
? 0 : linearMap(value as number, otherDataExtent, otherShadowExtent, true);
// Attempt to draw data shadow precisely when there are empty value.
if (isEmpty && !lastIsEmpty && index) {
areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
linePoints.push([linePoints[linePoints.length - 1][0], 0]);
}
else if (!isEmpty && lastIsEmpty) {
areaPoints.push([thisCoord, 0]);
linePoints.push([thisCoord, 0]);
}
areaPoints.push([thisCoord, otherCoord]);
linePoints.push([thisCoord, otherCoord]);
thisCoord += step;
lastIsEmpty = isEmpty;
});
const dataZoomModel = this.dataZoomModel;
function createDataShadowGroup(isSelectedArea?: boolean) {
const model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
const group = new graphic.Group();
const polygon = new graphic.Polygon({
shape: {points: areaPoints},
segmentIgnoreThreshold: 1,
style: model.getModel('areaStyle').getAreaStyle(),
silent: true,
z2: -20
});
const polyline = new graphic.Polyline({
shape: {points: linePoints},
segmentIgnoreThreshold: 1,
style: model.getModel('lineStyle').getLineStyle(),
silent: true,
z2: -19
});
group.add(polygon);
group.add(polyline);
return group;
}
// let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
for (let i = 0; i < 3; i++) {
const group = createDataShadowGroup(i === 1);
this._displayables.sliderGroup.add(group);
this._displayables.dataShadowSegs.push(group);
}
}
private _prepareDataShadowInfo() {
const dataZoomModel = this.dataZoomModel;
const showDataShadow = dataZoomModel.get('showDataShadow');
if (showDataShadow === false) {
return;
}
// Find a representative series.
let result: SliderZoomView['_dataShadowInfo'];
const ecModel = this.ecModel;
dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
const seriesModels = dataZoomModel
.getAxisProxy(axisDim, axisIndex)
.getTargetSeriesModels();
each(seriesModels, function (seriesModel) {
if (result) {
return;
}
if (showDataShadow !== true && indexOf(
SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
) < 0
) {
return;
}
const thisAxis = (
ecModel.getComponent(getAxisMainType(axisDim), axisIndex) as AxisBaseModel
).axis;
let otherDim = getOtherDim(axisDim);
let otherAxisInverse;
const coordSys = seriesModel.coordinateSystem;
if (otherDim != null && coordSys.getOtherAxis) {
otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
}
otherDim = seriesModel.getData().mapDimension(otherDim);
result = {
thisAxis: thisAxis,
series: seriesModel,
thisDim: axisDim,
otherDim: otherDim,
otherAxisInverse: otherAxisInverse
};
}, this);
}, this);
return result;
}
private _renderHandle() {
const thisGroup = this.group;
const displayables = this._displayables;
const handles: [graphic.Path, graphic.Path] = displayables.handles = [null, null];
const handleLabels: [graphic.Text, graphic.Text] = displayables.handleLabels = [null, null];
const sliderGroup = this._displayables.sliderGroup;
const size = this._size;
const dataZoomModel = this.dataZoomModel;
const api = this.api;
const borderRadius = dataZoomModel.get('borderRadius') || 0;
const brushSelect = dataZoomModel.get('brushSelect');
const filler = displayables.filler = new Rect({
silent: brushSelect,
style: {
fill: dataZoomModel.get('fillerColor')
},
textConfig: {
position: 'inside'
}
});
sliderGroup.add(filler);
// Frame border.
sliderGroup.add(new Rect({
silent: true,
subPixelOptimize: true,
shape: {
x: 0,
y: 0,
width: size[0],
height: size[1],
r: borderRadius
},
style: {
stroke: dataZoomModel.get('dataBackgroundColor' as any) // deprecated option
|| dataZoomModel.get('borderColor'),
lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
fill: 'rgba(0,0,0,0)'
}
}));
// Left and right handle to resize
each([0, 1] as const, function (handleIndex) {
let iconStr = dataZoomModel.get('handleIcon');
if (
!symbolBuildProxies[iconStr]
&& iconStr.indexOf('path://') < 0
&& iconStr.indexOf('image://') < 0
) {
// Compatitable with the old icon parsers. Which can use a path string without path://
iconStr = 'path://' + iconStr;
if (__DEV__) {
deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
}
}
const path = createSymbol(
iconStr,
-1, 0, 2, 2, null, true
) as graphic.Path;
path.attr({
cursor: getCursor(this._orient),
draggable: true,
drift: bind(this._onDragMove, this, handleIndex),
ondragend: bind(this._onDragEnd, this),
onmouseover: bind(this._showDataInfo, this, true),
onmouseout: bind(this._showDataInfo, this, false),
z2: 5
});
const bRect = path.getBoundingRect();
const handleSize = dataZoomModel.get('handleSize');
this._handleHeight = parsePercent(handleSize, this._size[1]);
this._handleWidth = bRect.width / bRect.height * this._handleHeight;
path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
path.style.strokeNoScale = true;
path.rectHover = true;
path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
enableHoverEmphasis(path);
const handleColor = dataZoomModel.get('handleColor' as any); // deprecated option
// Compatitable with previous version
if (handleColor != null) {
path.style.fill = handleColor;
}
sliderGroup.add(handles[handleIndex] = path);
const textStyleModel = dataZoomModel.getModel('textStyle');
thisGroup.add(
handleLabels[handleIndex] = new graphic.Text({
silent: true,
invisible: true,
style: createTextStyle(textStyleModel, {
x: 0, y: 0, text: '',
verticalAlign: 'middle',
align: 'center',
fill: textStyleModel.getTextColor(),
font: textStyleModel.getFont()
}),
z2: 10
}));
}, this);
// Handle to move. Only visible when brushSelect is set true.
let actualMoveZone: Displayable = filler;
if (brushSelect) {
const moveHandleHeight = parsePercent(dataZoomModel.get('moveHandleSize'), size[1]);
const moveHandle = displayables.moveHandle = new graphic.Rect({
style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
silent: true,
shape: {
r: [0, 0, 2, 2],
y: size[1] - 0.5,
height: moveHandleHeight
}
});
const iconSize = moveHandleHeight * 0.8;
const moveHandleIcon = displayables.moveHandleIcon = createSymbol(
dataZoomModel.get('moveHandleIcon'),
-iconSize / 2, -iconSize / 2, iconSize, iconSize,
'#fff',
true
);
moveHandleIcon.silent = true;
moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
moveHandle.ensureState('emphasis').style = dataZoomModel.getModel(
['emphasis', 'moveHandleStyle']
).getItemStyle();
const moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
actualMoveZone = displayables.moveZone = new graphic.Rect({
invisible: true,
shape: {
y: size[1] - moveZoneExpandSize,
height: moveHandleHeight + moveZoneExpandSize
}
});
actualMoveZone.on('mouseover', () => {
api.enterEmphasis(moveHandle);
})
.on('mouseout', () => {
api.leaveEmphasis(moveHandle);
});
sliderGroup.add(moveHandle);
sliderGroup.add(moveHandleIcon);
sliderGroup.add(actualMoveZone);
}
actualMoveZone.attr({
draggable: true,
cursor: getCursor(this._orient),
drift: bind(this._onDragMove, this, 'all'),
ondragstart: bind(this._showDataInfo, this, true),
ondragend: bind(this._onDragEnd, this),
onmouseover: bind(this._showDataInfo, this, true),
onmouseout: bind(this._showDataInfo, this, false)
});
}
private _resetInterval() {
const range = this._range = this.dataZoomModel.getPercentRange();
const viewExtent = this._getViewExtent();
this._handleEnds = [
linearMap(range[0], [0, 100], viewExtent, true),
linearMap(range[1], [0, 100], viewExtent, true)
];
}
private _updateInterval(handleIndex: 0 | 1 | 'all', delta: number): boolean {
const dataZoomModel = this.dataZoomModel;
const handleEnds = this._handleEnds;
const viewExtend = this._getViewExtent();
const minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
const percentExtent = [0, 100];
sliderMove(
delta,
handleEnds,
viewExtend,
dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
minMaxSpan.minSpan != null
? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
minMaxSpan.maxSpan != null
? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
);
const lastRange = this._range;
const range = this._range = asc([
linearMap(handleEnds[0], viewExtend, percentExtent, true),
linearMap(handleEnds[1], viewExtend, percentExtent, true)
]);
return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
}
private _updateView(nonRealtime?: boolean) {
const displaybles = this._displayables;
const handleEnds = this._handleEnds;
const handleInterval = asc(handleEnds.slice());
const size = this._size;
each([0, 1] as const, function (handleIndex) {
// Handles
const handle = displaybles.handles[handleIndex];
const handleHeight = this._handleHeight;
(handle as graphic.Path).attr({
scaleX: handleHeight / 2,
scaleY: handleHeight / 2,
// This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
// NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
y: size[1] / 2 - handleHeight / 2
});
}, this);
// Filler
displaybles.filler.setShape({
x: handleInterval[0],
y: 0,
width: handleInterval[1] - handleInterval[0],
height: size[1]
});
const viewExtent = {
x: handleInterval[0],
width: handleInterval[1] - handleInterval[0]
};
// Move handle
if (displaybles.moveHandle) {
displaybles.moveHandle.setShape(viewExtent);
displaybles.moveZone.setShape(viewExtent);
// Force update path on the invisible object
displaybles.moveZone.getBoundingRect();
displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
}
// update clip path of shadow.
const dataShadowSegs = displaybles.dataShadowSegs;
const segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
for (let i = 0; i < dataShadowSegs.length; i++) {
const segGroup = dataShadowSegs[i];
let clipPath = segGroup.getClipPath();
if (!clipPath) {
clipPath = new graphic.Rect();
segGroup.setClipPath(clipPath);
}
clipPath.setShape({
x: segIntervals[i],
y: 0,
width: segIntervals[i + 1] - segIntervals[i],
height: size[1]
});
}
this._updateDataInfo(nonRealtime);
}
private _updateDataInfo(nonRealtime?: boolean) {
const dataZoomModel = this.dataZoomModel;
const displaybles = this._displayables;
const handleLabels = displaybles.handleLabels;
const orient = this._orient;
let labelTexts = ['', ''];
// FIXME
// date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
if (dataZoomModel.get('showDetail')) {
const axisProxy = dataZoomModel.findRepresentativeAxisProxy();
if (axisProxy) {
const axis = axisProxy.getAxisModel().axis;
const range = this._range;
const dataInterval = nonRealtime
// See #4434, data and axis are not processed and reset yet in non-realtime mode.
? axisProxy.calculateDataWindow({
start: range[0], end: range[1]
}).valueWindow
: axisProxy.getDataValueWindow();
labelTexts = [
this._formatLabel(dataInterval[0], axis),
this._formatLabel(dataInterval[1], axis)
];
}
}
const orderedHandleEnds = asc(this._handleEnds.slice());
setLabel.call(this, 0);
setLabel.call(this, 1);
function setLabel(this: SliderZoomView, handleIndex: 0 | 1) {
// Label
// Text should not transform by barGroup.
// Ignore handlers transform
const barTransform = graphic.getTransform(
displaybles.handles[handleIndex].parent, this.group
);
const direction = graphic.transformDirection(
handleIndex === 0 ? 'right' : 'left', barTransform
);
const offset = this._handleWidth / 2 + LABEL_GAP;
const textPoint = graphic.applyTransform(
[
orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
this._size[1] / 2
],
barTransform
);
handleLabels[handleIndex].setStyle({
x: textPoint[0],
y: textPoint[1],
verticalAlign: orient === HORIZONTAL ? 'middle' : direction as ZRTextVerticalAlign,
align: orient === HORIZONTAL ? direction as ZRTextAlign : 'center',
text: labelTexts[handleIndex]
});
}
}
private _formatLabel(value: ParsedValue, axis: Axis) {
const dataZoomModel = this.dataZoomModel;
const labelFormatter = dataZoomModel.get('labelFormatter');
let labelPrecision = dataZoomModel.get('labelPrecision');
if (labelPrecision == null || labelPrecision === 'auto') {
labelPrecision = axis.getPixelPrecision();
}
const valueStr = (value == null || isNaN(value as number))
? ''
// FIXME Glue code
: (axis.type === 'category' || axis.type === 'time')
? axis.scale.getLabel({
value: Math.round(value as number)
})
// param of toFixed should less then 20.
: (value as number).toFixed(Math.min(labelPrecision as number, 20));
return isFunction(labelFormatter)
? labelFormatter(value as number, valueStr)
: isString(labelFormatter)
? labelFormatter.replace('{value}', valueStr)
: valueStr;
}
/**
* @param showOrHide true: show, false: hide
*/
private _showDataInfo(showOrHide?: boolean) {
// Always show when drgging.
showOrHide = this._dragging || showOrHide;
const displayables = this._displayables;
const handleLabels = displayables.handleLabels;
handleLabels[0].attr('invisible', !showOrHide);
handleLabels[1].attr('invisible', !showOrHide);
// Highlight move handle
displayables.moveHandle
&& this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
}
private _onDragMove(handleIndex: 0 | 1 | 'all', dx: number, dy: number, event: ZRElementEvent) {
this._dragging = true;
// For mobile device, prevent screen slider on the button.
eventTool.stop(event.event);
// Transform dx, dy to bar coordination.
const barTransform = this._displayables.sliderGroup.getLocalTransform();
const vertex = graphic.applyTransform([dx, dy], barTransform, true);
const changed = this._updateInterval(handleIndex, vertex[0]);
const realtime = this.dataZoomModel.get('realtime');
this._updateView(!realtime);
// Avoid dispatch dataZoom repeatly but range not changed,
// which cause bad visual effect when progressive enabled.
changed && realtime && this._dispatchZoomAction(true);
}
private _onDragEnd() {
this._dragging = false;
this._showDataInfo(false);
// While in realtime mode and stream mode, dispatch action when
// drag end will cause the whole view rerender, which is unnecessary.
const realtime = this.dataZoomModel.get('realtime');
!realtime && this._dispatchZoomAction(false);
}
private _onClickPanel(e: ZRElementEvent) {
const size = this._size;
const localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
if (localPoint[0] < 0 || localPoint[0] > size[0]
|| localPoint[1] < 0 || localPoint[1] > size[1]
) {
return;
}
const handleEnds = this._handleEnds;
const center = (handleEnds[0] + handleEnds[1]) / 2;
const changed = this._updateInterval('all', localPoint[0] - center);
this._updateView();
changed && this._dispatchZoomAction(false);
}
private _onBrushStart(e: ZRElementEvent) {
const x = e.offsetX;
const y = e.offsetY;
this._brushStart = new graphic.Point(x, y);
this._brushing = true;
this._brushStartTime = +new Date();
// this._updateBrushRect(x, y);
}
private _onBrushEnd(e: ZRElementEvent) {
if (!this._brushing) {
return;
}
const brushRect = this._displayables.brushRect;
this._brushing = false;
if (!brushRect) {
return;
}
brushRect.attr('ignore', true);
const brushShape = brushRect.shape;
const brushEndTime = +new Date();
// console.log(brushEndTime - this._brushStartTime);
if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
// Will treat it as a click
return;
}
const viewExtend = this._getViewExtent();
const percentExtent = [0, 100];
this._range = asc([
linearMap(brushShape.x, viewExtend, percentExtent, true),
linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)
]);
this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
this._updateView();
this._dispatchZoomAction(false);
}
private _onBrush(e: ZRElementEvent) {
if (this._brushing) {
// For mobile device, prevent screen slider on the button.
eventTool.stop(e.event);
this._updateBrushRect(e.offsetX, e.offsetY);
}
}
private _updateBrushRect(mouseX: number, mouseY: number) {
const displayables = this._displayables;
const dataZoomModel = this.dataZoomModel;
let brushRect = displayables.brushRect;
if (!brushRect) {
brushRect = displayables.brushRect = new Rect({
silent: true,
style: dataZoomModel.getModel('brushStyle').getItemStyle()
});
displayables.sliderGroup.add(brushRect);
}
brushRect.attr('ignore', false);
const brushStart = this._brushStart;
const sliderGroup = this._displayables.sliderGroup;
const endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
const startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
const size = this._size;
endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
brushRect.setShape({
x: startPoint[0], y: 0,
width: endPoint[0] - startPoint[0], height: size[1]
});
}
/**
* This action will be throttled.
*/
_dispatchZoomAction(realtime: boolean) {
const range = this._range;
this.api.dispatchAction({
type: 'dataZoom',
from: this.uid,
dataZoomId: this.dataZoomModel.id,
animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
start: range[0],
end: range[1]
});
}
private _findCoordRect() {
// Find the grid coresponding to the first axis referred by dataZoom.
let rect: RectLike;
const coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
if (!rect && coordSysInfoList.length) {
const coordSys = coordSysInfoList[0].model.coordinateSystem;
rect = coordSys.getRect && coordSys.getRect();
}
if (!rect) {
const width = this.api.getWidth();
const height = this.api.getHeight();
rect = {
x: width * 0.2,
y: height * 0.2,
width: width * 0.6,
height: height * 0.6
};
}
return rect;
}
}
function getOtherDim(thisDim: 'x' | 'y' | 'radius' | 'angle' | 'single' | 'z') {
// FIXME
// 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
const map = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
return map[thisDim as 'x' | 'y' | 'radius' | 'angle'];
}
function getCursor(orient: LayoutOrient) {
return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
}
export default SliderZoomView; | the_stack |
'use babel'
/*!
* XAtom Debug
* Copyright(c) 2017 Williams Medina <williams.medinaa@gmail.com>
* MIT Licensed
*/
import {
createGroupButtons,
createButton,
createIcon,
createIconFromPath,
createText,
createSelect,
createOption,
createElement,
createInput,
createTextEditor,
insertElement
} from './element';
import { isEqual } from 'lodash';
import { Plugin } from './plugin';
import { Observable, ReplaySubject, BehaviorSubject } from 'rxjs/Rx';
export interface SchemeState {
activePlugin: Plugin;
plugins: Array<Plugin>;
}
export class SchemeView {
private element: HTMLElement;
private listElement: HTMLElement;
private editorElement: HTMLElement;
private data: Object = {};
private panel: any;
private activePlugin: Plugin;
private plugins: Array<Plugin> = [];
private subject: BehaviorSubject<SchemeState>;
constructor () {
this.element = document.createElement('xatom-debug-scheme');
this.listElement = createElement('xatom-debug-scheme-list');
this.editorElement = createElement('xatom-debug-scheme-editor', {
// className: 'native-key-bindings'
});
this.subject = new BehaviorSubject(<SchemeState> {
activePlugin: this.activePlugin,
plugins: this.plugins
});
insertElement(this.element, [
createElement('xatom-debug-scheme-content', {
elements: [ this.listElement, this.editorElement ]
}),
createElement('xatom-debug-scheme-buttons', {
elements: [
createButton({
click: () => this.close()
}, [createText('Close')])
]
})
]);
let modalOptions = {
className: 'xatom-debug-modal',
item: this.element,
visible: false
};
this.panel = atom.workspace.addModalPanel(modalOptions);
}
open (activePlugin?: Plugin): void {
if (activePlugin) {
this.openPlugin(activePlugin)
}
this.panel.show()
}
changes () {
return this.subject.asObservable();
}
close (): void {
this.panel.hide()
}
activatePlugin (plugin: Plugin): void {
this.activePlugin = plugin;
this.registerChange();
}
registerChange (): void {
const newValue = {
activePlugin: this.activePlugin,
plugins: this.plugins
};
this.subject.next(newValue);
}
openPlugin (plugin: Plugin) {
let id = this.getPluginId(plugin)
// find plugin and activate
let item = this.listElement.querySelector(`[id="${id}"]`)
if (!item.classList.contains('active')) {
// remove active
let items = this.listElement.querySelectorAll('xatom-debug-scheme-item.active');
Array.from(items, (item: HTMLElement) => item.classList.remove('active'));
this.activatePlugin(plugin);
// add active class
item.classList.add('active');
this.editorElement.innerHTML = '';
// build options
let optionVisibles = []
let optionElements = Object.keys(plugin.options).map((name) => {
let elementOptions = plugin.options[name];
let configElement = createElement('xatom-debug-scheme-config', {
elements: [
createElement('scheme-label', {
elements: [createText(elementOptions.title)]
})
]
})
if (!this.data[plugin.name]) {
this.data[plugin.name] = {}
}
if (this.data[plugin.name][name] === undefined) {
this.data[plugin.name][name] = elementOptions.default
}
let controlElement
switch (elementOptions.type) {
case 'string':
case 'number':
let controlType = 'createControlText'
if (Array.isArray(elementOptions.enum)) {
controlType = 'createControlSelect'
}
controlElement = this[controlType](plugin.name, name, elementOptions)
break;
case 'boolean':
controlElement = this.createControlCheckbox(plugin.name, name, elementOptions)
break;
case 'object':
controlElement = this.createControlObject(plugin.name, name, elementOptions)
break;
case 'array':
controlElement = this.createControlArray(plugin.name, name, elementOptions)
break;
}
if (controlElement) {
insertElement(configElement, controlElement)
}
if (elementOptions.description && controlElement) {
insertElement(controlElement, createElement('p', {
className: 'text-muted',
elements: [
createText(elementOptions.description)
]
}))
}
if (elementOptions.visible) {
let visible = elementOptions.visible
let visibleHandler = () => this.analizeVisibleControl(plugin.name, configElement, elementOptions.visible);
optionVisibles.push(visibleHandler);
if (elementOptions.$subscriber) {
elementOptions.$subscriber.unsubscribe();
}
elementOptions.$subscriber = this.subject.subscribe(() => visibleHandler());
}
return configElement
})
optionVisibles.forEach((analize) => analize());
insertElement(this.editorElement, optionElements);
}
}
createControlText (pluginName: string, key: string, config: any) {
let value = this.data[pluginName][key] || ''
if (value === config.default) {
value = null
}
let inputElement = createTextEditor({
value,
placeholder: config.default,
change: (value) => {
if (String(value).trim().length > 0) {
this.data[pluginName][key] = value
} else {
this.data[pluginName][key] = config.default
}
this.registerChange();
}
})
return createElement('scheme-control', {
elements: [inputElement]
})
}
createControlCheckbox (pluginName: string, key: string, config: any) {
return createElement('scheme-control', {
elements: [createInput({
type: 'checkbox',
className: 'input-checkbox',
value: this.data[pluginName][key],
change: (value) => {
this.data[pluginName][key] = value;
this.registerChange();
}
})]
})
}
createControlSelect (pluginName: string, key: string, config: any) {
let selectOptions = config.enum.map((value) => createOption(value, value))
let selectElement = createSelect({
change: (value) => {
this.data[pluginName][key] = value;
this.registerChange();
}
}, selectOptions)
selectElement.value = this.data[pluginName][key]
return createElement('scheme-control', {
elements: [ selectElement ]
})
}
createArrayItem (data: any, index: number) {
let itemInput = createInput({
readOnly: true,
value: data[index]
})
let itemElement = createElement('div', {
className: 'input-item',
elements: [
itemInput,
createButton ({
click: () => {
itemElement.remove();
data.splice(index, 1);
this.registerChange();
}
}, createIcon('remove'))
]
})
return itemElement
}
createControlArray (pluginName: string, key: string, config: any) {
let source = this.data[pluginName][key]
let addInput: any = createTextEditor({})
let itemsElement = createElement('div', {
className: 'input-items'
})
let arrayElement = createElement('section', {
className: 'input-array',
elements: [
itemsElement,
createElement('div', {
className: 'input-form',
elements: [
addInput,
createButton({
click: () => {
let editor = addInput.getModel()
let value = editor.getText()
if (value.trim().length > 0) {
let index = source.push(value);
let itemElement = this.createArrayItem(source, index - 1);
editor.setText('');
insertElement(itemsElement, itemElement);
this.registerChange();
}
}
}, createIcon('add'))
]
})
]
})
// restore data
source.forEach((item, index) => {
insertElement(itemsElement, this.createArrayItem(source, index))
})
return createElement('scheme-control', {
elements: [ arrayElement ]
})
}
createControlObject (pluginName: string, key: string, config: any) {
let source = this.data[pluginName][key]
let nameInput: any = createTextEditor({})
let valueInput: any = createTextEditor({})
let itemsElement = createElement('div', {
className: 'input-items'
})
let arrayElement = createElement('section', {
className: 'input-object',
elements: [
itemsElement,
createElement('div', {
className: 'input-form',
elements: [
nameInput,
valueInput,
createButton({
click: () => {
let nameEditor = nameInput.getModel()
let valueEditor = valueInput.getModel()
let nameValue = nameEditor.getText()
let value = valueEditor.getText()
if (nameValue.trim().length > 0 && value.trim().length > 0) {
source[nameValue] = value
let itemElement = this.createObjectItem(source, nameValue)
nameEditor.setText('')
valueEditor.setText('')
insertElement(itemsElement, itemElement);
this.registerChange();
}
}
}, createIcon('add'))
]
})
]
})
// restore data
Object.keys(source).forEach((name) => {
insertElement(itemsElement, this.createObjectItem(source, name))
})
return createElement('scheme-control', {
elements: [ arrayElement ]
})
}
createObjectItem (data: any, index: string) {
let nameInput = createInput({})
let valueInput = createInput({})
let itemElement = createElement('div', {
className: 'input-item',
elements: [
nameInput,
valueInput,
createButton ({
click: () => {
itemElement.remove();
delete data[index];
this.registerChange();
}
}, createIcon('remove'))
]
})
nameInput.setAttribute('readonly', true)
valueInput.setAttribute('readonly', true)
nameInput.value = index
valueInput.value = data[index]
return itemElement
}
analizeVisibleControl (pluginName: string, element: HTMLElement, visible: any) {
Object.keys(visible).forEach((name) => {
let rules = visible[name];
let show = false
if (rules.contains && Array.isArray(rules.contains)) {
show = rules.contains.includes(this.data[pluginName][name])
}
if (rules.is) {
show = (this.data[pluginName][name] === rules.is)
}
element.style.display = show ? '' : 'none'
})
}
getPluginId (plugin: Plugin): string {
let token = btoa(plugin.name)
return `plugin-${token}`
}
restoreData (data) {
this.data = data || {}
}
getData (): Object {
return this.data;
}
getPluginDefaultOptions (plugin: Plugin) {
let defaults: any = {}
Object
.keys(plugin.options)
.map((optionName) => {
defaults[optionName] = plugin.options[optionName].default
})
return defaults
}
async getActivePluginOptions (): Promise<Object> {
return new Promise((resolve, reject) => {
let data = this.data[this.activePlugin.name]
if (data && Object.keys(data).length > 0) {
resolve(data)
} else {
resolve(this.getPluginDefaultOptions(this.activePlugin))
}
})
}
addPlugin (plugin: Plugin) {
let item = createElement('xatom-debug-scheme-item', {
id: this.getPluginId(plugin),
options: {
click: () => {
this.openPlugin(plugin)
}
},
elements: [
createIconFromPath(plugin.iconPath),
createText(plugin.name)
]
})
this.data[plugin.name] = {};
this.plugins.push(plugin)
insertElement(this.listElement, [item])
if (!this.activePlugin) {
this.activePlugin = plugin
}
}
getElement (): HTMLElement {
return this.element
}
destroy () {
this.element.remove()
this.panel.destroy()
}
} | the_stack |
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {map} from 'rxjs/operators';
import {CollectionParameters, CpuInterval, CpuIntervalCollection, Layer, SchedEvent, ThreadInterval, WaitingCpuInterval} from '../models';
import * as services from '../models/render_data_services';
import {Viewport} from '../util';
/**
* A render service fetches intervals and events as needed for heatmap
* rendering, on viewport change.
*/
export interface RenderDataService {
getCpuIntervals(
parameters: CollectionParameters, viewport: Viewport,
minIntervalDuration: number,
cpus: number[]): Observable<CpuIntervalCollection[]>;
getPidIntervals(
parameters: CollectionParameters, layers: Layer[], viewport: Viewport,
minIntervalDuration: number): Observable<Layer[]>;
getSchedEvents(
parameters: CollectionParameters, layer: Layer, viewport: Viewport,
cpus: number[]): Observable<Layer>;
}
/**
* A render service that fetches data from the SchedViz server.
*/
@Injectable({providedIn: 'root'})
export class HttpRenderDataService implements RenderDataService {
private readonly cpuIntervalsUrl = '/get_cpu_intervals';
private readonly pidIntervalsUrl = '/get_pid_intervals';
private readonly ftraceEventsUrl = '/get_ftrace_events';
constructor(private readonly http: HttpClient) {}
/** Get CPU intervals from the server via POST */
getCpuIntervals(
parameters: CollectionParameters, viewport: Viewport,
minIntervalDuration: number,
cpus: number[]): Observable<CpuIntervalCollection[]> {
const cpuIntervalsReq: services.CpuIntervalsRequest = {
collectionName: parameters.name,
minIntervalDurationNs: minIntervalDuration,
cpus,
};
const leftNs = Math.floor(
viewport.left * (parameters.endTimeNs - parameters.startTimeNs));
const rightNs = Math.ceil(
viewport.right * (parameters.endTimeNs - parameters.startTimeNs));
cpuIntervalsReq.startTimestampNs = parameters.startTimeNs + leftNs;
cpuIntervalsReq.endTimestampNs = parameters.startTimeNs + rightNs;
return this.http
.post<services.CpuIntervalsResponse>(
this.cpuIntervalsUrl, cpuIntervalsReq)
.pipe(
map(res => res.intervals),
map(intervalsByCpu => intervalsByCpu.map(
({cpu, running, waiting}) => new CpuIntervalCollection(
cpu,
running.map(
interval =>
constructCpuInterval(parameters, interval)),
waiting.map(
interval => constructWaitingCpuInterval(
parameters, interval)),
))),
);
}
/** Get PID intervals from the server via POST */
getPidIntervals(
parameters: CollectionParameters, layers: Layer[], viewport: Viewport,
minIntervalDuration: number): Observable<Layer[]> {
const pidList = layers.map(layer => layer.ids)
.reduce((acc, curr) => [...acc, ...curr], []);
const leftNs = Math.floor(
viewport.left * (parameters.endTimeNs - parameters.startTimeNs));
const rightNs = Math.ceil(
viewport.right * (parameters.endTimeNs - parameters.startTimeNs));
const pidIntervalsReq: services.PidIntervalsRequest = {
collectionName: parameters.name,
startTimestampNs: parameters.startTimeNs + leftNs,
endTimestampNs: parameters.startTimeNs + rightNs,
minIntervalDurationNs: minIntervalDuration,
pids: pidList,
};
return this.http
.post<services.PidIntervalsResponse>(
this.pidIntervalsUrl, pidIntervalsReq)
.pipe(
map(res => res.pidIntervals.map(intervalsList => {
const pid = intervalsList.pid;
return intervalsList.intervals
.map(interval => {
// Double check that there is only one command
const commands =
Array.from(new Set(interval.threadResidencies.map(
tr => tr.thread.command)));
if (commands.length !== 1) {
return;
}
return new ThreadInterval(
parameters,
interval.cpu,
interval.startTimestamp,
interval.startTimestamp + interval.duration,
pid,
commands[0],
interval.threadResidencies,
);
})
.filter((i): i is ThreadInterval => i != null);
})),
map(nestedIntervals =>
new Array<ThreadInterval>().concat(...nestedIntervals)),
map(intervals => {
const intervalMap: {[k: number]: ThreadInterval[]} = {};
intervals.forEach(ival => {
intervalMap[ival.pid] =
[...(intervalMap[ival.pid] || []), ival];
});
return intervalMap;
}),
map(intervalMap => {
for (const layer of layers) {
layer.intervals = [];
for (const pid of layer.ids) {
layer.intervals = [...layer.intervals, ...intervalMap[pid]];
}
}
return layers;
}),
);
}
getSchedEvents(
parameters: CollectionParameters, layer: Layer, viewport: Viewport,
cpus: number[]): Observable<Layer> {
const leftNs = Math.floor(
viewport.left * (parameters.endTimeNs - parameters.startTimeNs));
const rightNs = Math.ceil(
viewport.right * (parameters.endTimeNs - parameters.startTimeNs));
const ftraceEventsReq: services.FtraceEventsRequest = {
collectionName: parameters.name,
startTimestamp: parameters.startTimeNs + leftNs,
endTimestamp: parameters.startTimeNs + rightNs,
cpus,
eventTypes: [layer.name],
};
return this.http
.post<services.FtraceEventsResponse>(
this.ftraceEventsUrl, ftraceEventsReq)
.pipe(
map(res => Object.values(res.eventsByCpu)),
map(eventList => eventList.map(events => events.map(event => {
const properties = new Map<string, string>();
const eventTextProps = event.textProperties;
for (const [key, value] of Object.entries(eventTextProps)) {
properties.set(key, value);
}
const eventNumProps = event.numberProperties;
for (const [key, value] of Object.entries(eventNumProps)) {
properties.set(key, `${value}`);
}
return new SchedEvent(
parameters,
event.index,
event.name,
event.cpu,
event.timestamp,
properties,
);
}))),
map(nestedEvents => {
layer.intervals = new Array<SchedEvent>().concat(...nestedEvents);
return layer;
}));
}
}
// END-INTERNAL
/**
* A render service that returns mock data.
*/
@Injectable({providedIn: 'root'})
export class LocalRenderDataService implements RenderDataService {
/** Returns set of mock Intervals for all CPUs */
getCpuIntervals(
parameters: CollectionParameters, viewport: Viewport,
minIntervalDuration: number,
cpus: number[]): Observable<CpuIntervalCollection[]> {
const collection = [];
const duration = parameters.endTimeNs - parameters.startTimeNs;
for (let cpu = 0; cpu < parameters.size; cpu++) {
const runningIntervals: CpuInterval[] = [];
const waitingIntervals: WaitingCpuInterval[] = [];
let timestamp = parameters.startTimeNs;
let prevTimestamp = timestamp;
while (timestamp < parameters.endTimeNs) {
prevTimestamp = timestamp;
const delta = Math.max(minIntervalDuration, duration / 100);
timestamp += delta;
timestamp = Math.min(timestamp, parameters.endTimeNs);
const percentIdle = 0.5 * Math.random();
const runningTime = (1 - percentIdle) * (timestamp - prevTimestamp);
const running = [{
thread: {command: 'foo', pid: 0, priority: 100},
state: services.ThreadState.RUNNING_STATE,
duration: runningTime,
droppedEventIDs: [],
includesSyntheticTransitions: false,
}];
const runningInterval = new CpuInterval(
parameters, cpu, prevTimestamp, timestamp, running, []);
runningIntervals.push(runningInterval);
const waitingInterval = new WaitingCpuInterval(
parameters, cpu, prevTimestamp, timestamp, running, []);
waitingIntervals.push(waitingInterval);
}
collection.push(
new CpuIntervalCollection(cpu, runningIntervals, waitingIntervals));
}
// TODO(sainsley): Store visible CPUs on CPU Layers and return rendered
// layer as in PidIntervals callback.
return of(collection);
}
/** Returns set of mock Intervals for a few CPUs */
getPidIntervals(
parameters: CollectionParameters, layers: Layer[], viewport: Viewport,
minIntervalDuration: number): Observable<Layer[]> {
const intervals = [];
const cpuCount = parameters.size;
for (const layer of layers) {
for (let i = 0; i < cpuCount; i++) {
const cpu = Math.floor(Math.random() * parameters.size);
let timestamp = parameters.startTimeNs;
let prevTimestamp = timestamp;
while (timestamp < parameters.endTimeNs) {
const pid = Math.floor(Math.random() * 5000);
prevTimestamp = timestamp;
const delta = minIntervalDuration;
timestamp += delta;
timestamp = Math.min(timestamp, parameters.endTimeNs);
const interval = new ThreadInterval(
parameters, cpu, prevTimestamp, timestamp, pid, 'bar', [{
thread: {command: 'foo', pid: 0, priority: 100},
state: services.ThreadState.RUNNING_STATE,
duration: timestamp - prevTimestamp,
droppedEventIDs: [],
includesSyntheticTransitions: false,
}]);
intervals.push(interval);
}
}
layer.intervals = intervals;
}
return of(layers);
}
getSchedEvents(
parameters: CollectionParameters, layer: Layer, viewport: Viewport,
cpus: number[]): Observable<Layer> {
const intervals = [];
const cpuCount = parameters.size;
for (let i = 0; i < cpuCount; i++) {
const cpu = Math.floor(Math.random() * parameters.size);
let timestamp = parameters.startTimeNs;
while (timestamp < parameters.endTimeNs) {
const delta = 3 * Math.random() *
(parameters.endTimeNs - parameters.startTimeNs) / parameters.size;
timestamp += delta;
timestamp = Math.min(timestamp, parameters.endTimeNs);
const interval =
new SchedEvent(parameters, 1234, 'event_type', cpu, timestamp);
intervals.push(interval);
}
}
layer.intervals = intervals;
return of(layer);
}
}
function getThreadResidenciesByType(
threadResidencies: services.ThreadResidency[]) {
return threadResidencies.reduce((acc, tr) => {
acc[tr.state] = acc[tr.state] || [];
acc[tr.state]!.push(tr);
return acc;
}, {} as {[k in services.ThreadState]?: services.ThreadResidency[]});
}
function constructCpuInterval(
parameters: CollectionParameters, interval: services.Interval) {
const threadResidenciesByType =
getThreadResidenciesByType(interval.threadResidencies);
return new CpuInterval(
parameters,
interval.cpu,
interval.startTimestamp,
interval.startTimestamp + interval.duration,
threadResidenciesByType[services.ThreadState.RUNNING_STATE] || [],
threadResidenciesByType[services.ThreadState.WAITING_STATE] || [],
);
}
function constructWaitingCpuInterval(
parameters: CollectionParameters, interval: services.Interval) {
const threadResidenciesByType =
getThreadResidenciesByType(interval.threadResidencies);
return new WaitingCpuInterval(
parameters,
interval.cpu,
interval.startTimestamp,
interval.startTimestamp + interval.duration,
threadResidenciesByType[services.ThreadState.RUNNING_STATE] || [],
threadResidenciesByType[services.ThreadState.WAITING_STATE] || [],
);
} | the_stack |
import 'mocha';
import { typeCheck } from './utils';
import {
SchemaInput,
SchemaParameters,
SchemaResolveType,
SchemaValidatorFunction,
} from './io';
/* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types */
describe('schema/io', () => {
describe('SchemaParameters', () => {
it('primitives', () => {
typeCheck<SchemaParameters<number>, [number]>('ok');
typeCheck<SchemaParameters<string>, [string]>('ok');
typeCheck<SchemaParameters<boolean>, [boolean]>('ok');
typeCheck<SchemaParameters<undefined>, [undefined]>('ok');
typeCheck<SchemaParameters<unknown>, [unknown]>('ok');
typeCheck<SchemaParameters<null>, [null]>('ok');
typeCheck<SchemaParameters<void>, [void]>('ok');
typeCheck<SchemaParameters<any>, unknown[]>('ok');
});
it('primitives constructors', () => {
typeCheck<SchemaParameters<StringConstructor>, [any?]>('ok');
typeCheck<SchemaParameters<NumberConstructor>, [any?]>('ok');
typeCheck<SchemaParameters<BooleanConstructor>, [unknown?]>('ok');
typeCheck<SchemaParameters<ObjectConstructor>, [any]>('ok');
typeCheck<
SchemaParameters<SymbolConstructor>,
[(string | number | undefined)?]
>('ok');
});
it('primitives values', () => {
typeCheck<SchemaParameters<'foo'>, ['foo']>('ok');
typeCheck<SchemaParameters<'foo'>, ['bar']>(['foo']);
typeCheck<SchemaParameters<123>, [123]>('ok');
typeCheck<SchemaParameters<123>, [number]>([123]);
typeCheck<SchemaParameters<true>, [true]>('ok');
typeCheck<SchemaParameters<true>, [false]>([true]);
typeCheck<SchemaParameters<true>, [boolean]>([true]);
});
it('plain arrays', () => {
typeCheck<SchemaParameters<[]>, [[]]>('ok');
typeCheck<SchemaParameters<[number]>, [[number]]>('ok');
typeCheck<SchemaParameters<[number, string]>, [[number, string]]>('ok');
typeCheck<SchemaParameters<[unknown]>, [[unknown]]>('ok');
typeCheck<SchemaParameters<[unknown]>, [[unknown?]]>([[1]]);
typeCheck<SchemaParameters<[unknown?]>, [[unknown?]]>('ok');
typeCheck<SchemaParameters<[number?]>, [[number?]]>('ok');
typeCheck<SchemaParameters<[number?]>, [[number]]>([[]]);
typeCheck<SchemaParameters<string[]>, [string[]]>('ok');
typeCheck<SchemaParameters<[1, 'foo']>, [[1, 'foo']]>('ok');
typeCheck<SchemaParameters<['foo', 1]>, [[1, 'foo']]>([['foo', 1]]);
});
it('regexp', () => {
typeCheck<SchemaParameters<RegExp>, [string]>('ok');
typeCheck<SchemaParameters<RegExp>, ['']>(['string']);
});
it('or', () => {
typeCheck<SchemaParameters<string | number>, [string | number]>('ok');
typeCheck<SchemaParameters<string | number>, [string]>(['string']);
typeCheck<SchemaParameters<string | number>, [number]>(['string']);
typeCheck<SchemaParameters<string | number>, [1]>(['string']);
typeCheck<SchemaParameters<string | number>, ['str']>(['string']);
});
it('functions', () => {
typeCheck<SchemaParameters<() => void>, []>('ok');
typeCheck<SchemaParameters<(x: unknown) => void>, [unknown]>('ok');
typeCheck<SchemaParameters<(x: string) => void>, [string]>('ok');
typeCheck<SchemaParameters<(x?: string) => void>, [string?]>('ok');
typeCheck<SchemaParameters<(x: 'foo') => void>, ['foo']>('ok');
});
it('functions or', () => {
typeCheck<SchemaParameters<(() => void) | (() => string)>, []>('ok');
typeCheck<
SchemaParameters<(() => void) | ((x: number) => string)>,
[number] | []
>('ok');
typeCheck<
SchemaParameters<((o: string) => void) | ((o: number) => void)>,
[string] | [number]
>('ok');
typeCheck<
SchemaParameters<
((o: { x: number }) => void) | ((o: { y: number }) => void)
>,
[{ x: number }] | [{ y: number }]
>('ok');
});
it('functions and', () => {
typeCheck<
// SchemaParameters<
Parameters<((o: { x: number }) => void) | ((o: { y: number }) => void)>,
// >,
[{ x: number }] | [{ y: number }]
>('ok');
});
it('objects', () => {
typeCheck<SchemaParameters<{}>, [{}]>('ok');
typeCheck<SchemaParameters<{ foo: string }>, [{ foo: string }]>('ok');
typeCheck<SchemaParameters<{ foo?: string }>, [{ foo?: string }]>('ok');
});
it('validators properties', () => {
typeCheck<
SchemaParameters<{ foo: (x: string) => void }>,
[{ foo: string }]
>('ok');
typeCheck<
SchemaParameters<{ foo: (x: unknown) => void }>,
[{ foo: unknown }]
>('ok');
typeCheck<SchemaParameters<{ foo: (x: any) => void }>, [{ foo: any }]>(
'ok',
);
});
it('optional properties', () => {
typeCheck<
SchemaParameters<{ foo: (x: string | undefined) => void }>,
[{ foo: string | undefined }]
>('ok');
typeCheck<
SchemaParameters<{ foo: (x?: string) => void }>,
[{ foo?: string }]
>('ok');
typeCheck<SchemaParameters<{ foo: () => void }>, [{}]>('ok');
typeCheck<
SchemaParameters<{
foo: { bar: (x: string | undefined) => void };
x: boolean;
}>,
[{ foo: { bar: string | undefined }; x: boolean }]
>('ok');
typeCheck<
SchemaParameters<{ foo: { bar: (x?: string) => void }; x: boolean }>,
[{ foo: { bar?: string }; x: boolean }]
>('ok');
});
it('optional array items', () => {
typeCheck<
SchemaParameters<[(x: string | undefined) => void]>,
[[string | undefined]]
>('ok');
// Not supported Yet
// typeCheck<SchemaParameters<[(x?: string) => void]>, [[string?]]>('ok');
// typeCheck<SchemaParameters<[[number]?]>, [[[number]?]]>('ok');
});
});
describe('SchemaInput', () => {
it('basic use case', () => {
typeCheck<
SchemaInput<{
foo: (x: string) => string;
bar: 'hello';
optional: (i?: number) => number | undefined;
}>,
{ foo: string; bar: 'hello'; optional?: number }
>('ok');
});
it('optional validator', () => {
typeCheck<
SchemaInput<(i?: number) => number | undefined>,
number | undefined
>('ok');
});
});
describe('SchemaReturnType', () => {
it('primitives', () => {
typeCheck<SchemaResolveType<null>, null>('ok');
typeCheck<SchemaResolveType<void>, void>('ok');
typeCheck<SchemaResolveType<number>, number>('ok');
typeCheck<SchemaResolveType<string>, string, true>(true);
typeCheck<SchemaResolveType<boolean>, boolean>('ok');
typeCheck<[SchemaResolveType<unknown>], [unknown]>('ok');
typeCheck<SchemaResolveType<undefined>, undefined>('ok');
typeCheck<[SchemaResolveType<any>], [any]>('ok');
});
it('primitives constructors', () => {
typeCheck<SchemaResolveType<StringConstructor>, string, true>(true);
typeCheck<SchemaResolveType<NumberConstructor>, number>('ok');
typeCheck<SchemaResolveType<BooleanConstructor>, boolean>('ok');
typeCheck<SchemaResolveType<ObjectConstructor>, object>('ok');
typeCheck<SchemaResolveType<SymbolConstructor>, symbol>('ok');
});
it('primitives values', () => {
typeCheck<SchemaResolveType<'foo'>, 'foo'>('ok');
typeCheck<SchemaResolveType<'foo'>, 'bar'>('foo');
typeCheck<SchemaResolveType<123>, 123>('ok');
typeCheck<SchemaResolveType<123>, number>(123);
typeCheck<SchemaResolveType<true>, true>('ok');
typeCheck<SchemaResolveType<true>, false>(true);
typeCheck<SchemaResolveType<true>, boolean>(true);
});
it('plain arrays', () => {
typeCheck<SchemaResolveType<[]>, []>('ok');
typeCheck<SchemaResolveType<[number]>, [number]>('ok');
typeCheck<SchemaResolveType<[number, string]>, [number, string]>('ok');
typeCheck<SchemaResolveType<[unknown]>, [unknown]>('ok');
typeCheck<SchemaResolveType<[unknown]>, [unknown?]>([[1]]);
typeCheck<SchemaResolveType<[unknown?]>, [unknown?]>('ok');
typeCheck<SchemaResolveType<[number?]>, [number?]>('ok');
typeCheck<SchemaResolveType<[number?]>, [number]>([]);
typeCheck<SchemaResolveType<string[]>, string[]>('ok');
typeCheck<SchemaResolveType<[1, 'foo']>, [1, 'foo']>('ok');
typeCheck<SchemaResolveType<['foo', 1]>, [1, 'foo']>(['foo', 1]);
});
it('regexp', () => {
typeCheck<SchemaResolveType<RegExp>, string, true>(true);
typeCheck<SchemaResolveType<RegExp>, ''>('string');
});
it('or', () => {
typeCheck<SchemaResolveType<string | number>, string | number, true>(
true,
);
typeCheck<SchemaResolveType<string | number>, string>('string');
typeCheck<SchemaResolveType<string | number>, number>('string');
typeCheck<SchemaResolveType<string | number>, 1>('string');
typeCheck<SchemaResolveType<string | number>, 'str'>('string');
});
it('validators', () => {
typeCheck<SchemaResolveType<() => void>, void>('ok');
typeCheck<[SchemaResolveType<() => unknown>], [unknown]>('ok');
typeCheck<[SchemaResolveType<() => string>], [string]>('ok');
typeCheck<[SchemaResolveType<() => 'foo'>], ['foo']>('ok');
typeCheck<SchemaResolveType<() => number>, number>('ok');
typeCheck<SchemaResolveType<() => boolean>, boolean>('ok');
typeCheck<SchemaResolveType<() => false>, false>('ok');
typeCheck<SchemaResolveType<() => 1>, 1>('ok');
});
it('promises', () => {
typeCheck<SchemaResolveType<() => Promise<string>>, string, true>(true);
typeCheck<
SchemaResolveType<() => string | Promise<string>>,
string,
true
>(true);
typeCheck<
SchemaResolveType<() => number | Promise<string>>,
number | string,
true
>(true);
});
it('objects', () => {
typeCheck<SchemaResolveType<{}>, {}, true>(true);
typeCheck<SchemaResolveType<{ foo: string }>, { foo: string }>('ok');
typeCheck<SchemaResolveType<{ foo?: string }>, { foo?: string }>('ok');
});
it('validators properties', () => {
typeCheck<SchemaResolveType<{ foo: () => string }>, { foo: string }>(
'ok',
);
typeCheck<SchemaResolveType<{ foo: () => 1 }>, { foo: 1 }>('ok');
typeCheck<
SchemaResolveType<{ foo: () => 1 | 'foo' }>,
{ foo: 1 | 'foo' }
>('ok');
typeCheck<SchemaResolveType<{ foo: () => void }>, { foo: void }>('ok');
typeCheck<
SchemaResolveType<{ foo: () => Promise<number> }>,
{ foo: number }
>('ok');
});
it('optional properties', () => {
typeCheck<SchemaResolveType<{ foo: (x: string) => void }>, { foo: void }>(
'ok',
);
typeCheck<
SchemaResolveType<{ foo: (x?: string) => void }>,
{ foo: void }
>('ok');
});
it('optional array items', () => {
typeCheck<SchemaResolveType<[(x: string | undefined) => void]>, [void]>(
'ok',
);
typeCheck<SchemaResolveType<[(x?: string | undefined) => void]>, [void]>(
'ok',
);
});
});
describe('SchemaValidatorFunction', () => {
it('sync', () => {
typeCheck<SchemaValidatorFunction<() => string>, () => string>('ok');
typeCheck<
SchemaValidatorFunction<() => string | number>,
() => string | number
>('ok');
typeCheck<
SchemaValidatorFunction<{ foo: () => string | number }>,
(x: { foo?: undefined }) => { foo: string | number }
>('ok');
});
it('async', () => {
typeCheck<
SchemaValidatorFunction<() => PromiseLike<string>>,
() => PromiseLike<string>
>('ok');
typeCheck<
SchemaValidatorFunction<() => PromiseLike<string | number>>,
() => PromiseLike<string | number>
>('ok');
typeCheck<
SchemaValidatorFunction<() => Promise<string | number>>,
() => PromiseLike<string | number>
>('ok');
typeCheck<
SchemaValidatorFunction<() => PromiseLike<true>>,
() => PromiseLike<true>
>('ok');
typeCheck<
SchemaValidatorFunction<() => Promise<string>>,
() => PromiseLike<string>
>('ok');
typeCheck<
SchemaValidatorFunction<{ foo(): Promise<string | number> }>,
(x: { foo?: undefined }) => PromiseLike<{ foo: string | number }>
>('ok');
typeCheck<
SchemaValidatorFunction<{
foo: () => Promise<string | number>;
bar: string;
}>,
(x: {
foo?: undefined;
bar: string;
}) => PromiseLike<{ foo: string | number; bar: string }>
>('ok');
});
it('maybe async', () => {
typeCheck<
SchemaValidatorFunction<() => string | PromiseLike<number>>,
() => string | number | PromiseLike<number | string>
>('ok');
typeCheck<
SchemaValidatorFunction<() => unknown>,
() => unknown | PromiseLike<unknown>
>('ok');
typeCheck<
SchemaValidatorFunction<{
foo: () => Promise<string> | number;
bar: string;
}>,
(x: {
foo?: undefined;
bar: string;
}) =>
| PromiseLike<{ foo: string | number; bar: string }>
| { foo: string | number; bar: string }
>('ok');
typeCheck<
SchemaValidatorFunction<{ foo: () => unknown }>,
(x: {
foo?: undefined;
}) => { foo: unknown } | PromiseLike<{ foo: unknown }>
>('ok');
});
});
}); | the_stack |
import chitu = require('chitu');
import shopping = require('services/Shopping');
import auth = require('services/Auth');
import site = require('Site');
import member = require('services/Member');
import shoppingCart = require('services/ShoppingCart');
import ko = require('knockout');
const DEFAULT_HEADER_PATH = 'ui/Headers/Default';
const DEFAULT_WITH_BACK = 'ui/Headers/DefaultWithBack';
function generateProductHeader(headerNode: HTMLElement, routeData: chitu.RouteData) {
var model = {
isFavored: ko.observable<boolean>(false),
favor: () => {
if (model.isFavored()) {
shopping.unFavorProduct(ko.unwrap(productId));
return;
}
shopping.favorProduct(ko.unwrap(productId), 'NULL PRODUCT NAME').done(() => {
model.isFavored(true);
});
}
};
var productId = routeData.values.id;
auth.whenLogin(() => shopping.isFavored(productId).done((value) => model.isFavored(value)));
ko.applyBindings(model, headerNode);
}
function createHeaderNode(container: chitu.PageContainer, header_path: string): JQueryPromise<HTMLElement> {
var result = $.Deferred<HTMLElement>();
var header_node: HTMLElement = document.createElement('header');
container.element.appendChild(header_node);
chitu.Utility.loadjs('text!' + header_path + '.html', 'css!sc/Headers.css').done(function (html) {
header_node.innerHTML = html;
result.resolve(header_node);
});
return result;
}
function setHeaderTitle(node: HTMLElement, title: string) {
$(node).find('h4').html(title);
}
class PageContainerFactory {
static createContainerHeader(routeData: chitu.RouteData, container: chitu.PageContainer) {
var controller = routeData.values.controller;
var action = routeData.values.action;
var header_path = DEFAULT_HEADER_PATH;
var header_title: JQueryPromise<string>;
switch (controller) {
case 'AccountSecurity':
switch (action) {
case 'Index':
createHeaderNode(container, DEFAULT_WITH_BACK).done(function (node: HTMLElement) {
setHeaderTitle(node, '账户安全');
});
break;
case 'Setting':
var title: string;// = routeData.values().type == 'MobileBinding' ? '手机绑定' : '';
if (routeData.values.type == 'MobileBinding')
title = '手机绑定';
else if (routeData.values.type == 'LoginPassword')
title = '登录密码';
else if (routeData.values.type == 'PaymentPassword')
title = '支付密码';
createHeaderNode(container, DEFAULT_WITH_BACK).done(function (node: HTMLElement) {
setHeaderTitle(node, title);
});
break;
}
break;
case 'Home':
switch (action) {
case 'Index':
header_path = 'ui/Headers/Home_Index';
createHeaderNode(container, header_path);
break;
case 'Class':
header_path = 'ui/Headers/Home_Class';
createHeaderNode(container, header_path);
break;
case 'NewsList':
createHeaderNode(container, DEFAULT_HEADER_PATH).done(function (node: HTMLElement) {
setHeaderTitle(node, '微资讯');
});
break;
case 'News':
createHeaderNode(container, DEFAULT_WITH_BACK).done(function (node: HTMLElement) {
setHeaderTitle(node, '资讯详情');
});
break;
case 'Product':
header_path = 'ui/Headers/Home_Product';
createHeaderNode(container, header_path).done(function (node) {
generateProductHeader(node, routeData);
});
break;
case 'ProductComments':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '产品评价'));
break;
case 'ProductDetail':
createHeaderNode(container, DEFAULT_WITH_BACK).done(function (node: HTMLElement) {
setHeaderTitle(node, '产品详情');
});
break;
case 'ProductList':
$.when(createHeaderNode(container, DEFAULT_WITH_BACK), shopping.getCategory(routeData.values.id))
.done(function (node: HTMLElement, category) {
setHeaderTitle(node, category.Name);
})
break;
case 'Search':
header_path = 'ui/Headers/Home_Search';
createHeaderNode(container, header_path).done(function (node) {
//generateProductHeader(node, routeData);
});
break;
}
break;
case 'Shopping'://Shopping_OrderProducts
switch (action) {
case 'OrderDetail':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '订单详情'));
break;
case 'OrderList':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '我的订单'));
break;
case 'OrderProducts':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '确认订单'));
break;
case 'Invoice':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '发票信息'));
break;
case 'ShoppingCart':
createHeaderNode(container, DEFAULT_HEADER_PATH)
.done((node) => setHeaderTitle(node, '购物车'))
break;
}
break;
case 'User':
switch (action) {
case 'Coupon':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '我的优惠券'));
break;
case 'Favors':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '我的收藏'));
break;
case 'Index':
createHeaderNode(container, DEFAULT_HEADER_PATH)
.done((node) => setHeaderTitle(node, '用户中心'));
break;
case 'Login':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '登录'))
break;
case 'Messages':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '我的消息'));
break;
case 'ScoreList':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '我的积分'));
break;
case 'ReceiptEdit':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '编辑地址'));
break;
case 'ReceiptList':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '收货地址'));
break;
case 'Recharge':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '充值'));
break;
case 'RechargeList':
createHeaderNode(container, 'ui/Headers/RechargeList')
.done((node) => setHeaderTitle(node, '充值记录'));
break;
case 'UserInfoItemEdit':
//debugger;
var title = " "
switch (routeData.values.field) {
case 'Region':
title = '地区';
break;
}
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, title));
break;
case 'UserInfo':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done((node) => setHeaderTitle(node, '用户信息'));
break;
}
break;
case 'Error':
createHeaderNode(container, DEFAULT_WITH_BACK)
.done(function (node) {
setHeaderTitle(node, '网络错误');
});
break;
}
}
static createContainerFooter(routeData: chitu.RouteData, container: chitu.PageContainer) {
var controller = routeData.values.controller;
var action = routeData.values.action;
if ((controller == 'Home' && action == 'Index') || (controller == 'Home' && action == 'Class') ||
(controller == 'Home' && action == 'NewsList') || (controller == 'User' && action == 'Index') ||
(controller == 'Shopping' && action == 'ShoppingCart')) {
new Menu(container.element, routeData);
}
}
static createInstance(app: chitu.Application, routeData: chitu.RouteData, previous: chitu.PageContainer, enableSwipeClose: boolean): chitu.PageContainer {
//debugger;
var c: chitu.PageContainer = chitu.PageContainerFactory.createInstance({
app: app, previous: previous, enableSwipeClose: enableSwipeClose, routeData
});
$(c.element).addClass(routeData.values.controller + '-' + routeData.values.action);
PageContainerFactory.createContainerHeader(routeData, c);
PageContainerFactory.createContainerFooter(routeData, c);
//if (site.env.isApp && site.env.isIOS)
$(c.element).addClass('immersion');
// var a = {
// page: {
// name: '',
// left: {}
// }
// }
return c;
}
}
export = PageContainerFactory;
var menu_html: string;
class Menu {
private node: HTMLElement;
constructor(parentNode: HTMLElement, routeData: chitu.RouteData) {
this.node = document.createElement('div');
parentNode.appendChild(this.node);
var updateProductsCount = () => {
var $products_count = $(this.node).find('[name="products-count"]');
if (shoppingCart.info.itemsCount() == 0) {
$products_count.hide();
}
else {
$products_count.show();
}
$products_count.text(shoppingCart.info.itemsCount());
}
shoppingCart.info.itemsCount.subscribe(updateProductsCount);
this.loadHTML().done((html) => {
this.node.innerHTML = html;
var args = routeData.values;
var $tab = $(this.node).find('[name="' + args.controller + '_' + args.action + '"]');
if ($tab.length > 0) {
$tab.addClass('active');
}
updateProductsCount();
});
}
private loadHTML(): JQueryPromise<string> {
if (menu_html)
return $.Deferred<string>().resolve(menu_html);
var deferred = $.Deferred<string>();
requirejs(['text!ui/Menu.html'], function (html) {
menu_html = html;
deferred.resolve(html);
});
return deferred;
}
} | the_stack |
import * as turf from '@turf/turf';
import { BoundingBox, proj4Defs } from '@ngageoint/geopackage';
import proj4 from 'proj4';
import _ from 'lodash';
export const TILE_SIZE_IN_PIXELS = 256;
export const WEB_MERCATOR_MIN_LAT_RANGE = -85.05112877980659;
export const WEB_MERCATOR_MAX_LAT_RANGE = 85.0511287798066;
export class GeoSpatialUtilities {
/**
* Finds the Longitude of a tile
*
* Taken from Map Cache Electron
*
* @static
* @param {number} x x tile coordinate
* @param {number} zoom zoom level
* @returns {number}
* @memberof GeoSpatialUtilities
*/
static tile2lon(x: number, zoom: number): number {
return (x / Math.pow(2, zoom)) * 360 - 180;
}
/**
* Finds the Latitude of a tile
*
* Taken from Map Cache Electron
*
* @static
* @param {number} y y tile coordinate
* @param {number} zoom Zoom level
* @returns {number}
* @memberof GeoSpatialUtilities
*/
static tile2lat(y: number, zoom: number): number {
const n = Math.PI - (2 * Math.PI * y) / Math.pow(2, zoom);
return (180 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
}
/**
* Finds the x position of a tile
*
* Taken from Map Cache Electron
*
* @static
* @param {number} lon longitude in degrees
* @param {number} zoom Zoom level
* @returns {number}
* @memberof GeoSpatialUtilities
*/
static long2tile(lon: number, zoom: number): number {
return Math.min(Math.pow(2, zoom) - 1, Math.floor(((lon + 180) / 360) * Math.pow(2, zoom)));
}
/**
* Finds the y position of a tile
*
* Taken from Map Cache Electron
* @static
* @param {number} lat Latitude in degrees
* @param {number} zoom Zoom level
* @returns {number}
* @memberof GeoSpatialUtilities
*/
static lat2tile(lat: number, zoom: number): number {
if (lat < WEB_MERCATOR_MIN_LAT_RANGE) {
lat = WEB_MERCATOR_MIN_LAT_RANGE;
} else if (lat > WEB_MERCATOR_MAX_LAT_RANGE) {
lat = WEB_MERCATOR_MAX_LAT_RANGE;
}
return Math.floor(
((1 - Math.log(Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)) / Math.PI) / 2) *
Math.pow(2, zoom),
);
}
/**
* Calculates the ranges of tile need for a given longitude range.
*
* Taken from Map Cache Electron
*
* @static
* @param {BoundingBox} bbox Geopackage Bounding box
* @param {*} zoom zoom level
* @returns {{ min: number; max: number }} Max and Min X Tiles
* @memberof GeoSpatialUtilities
*/
static calculateXTileRange(bbox: BoundingBox, zoom: any): { min: number; max: number } {
const west = this.long2tile(bbox.maxLongitude, zoom);
const east = this.long2tile(bbox.minLongitude, zoom);
return {
min: Math.max(0, Math.min(west, east)),
max: Math.max(0, Math.max(west, east)),
};
}
/**
* Calculates the ranges of tile need for a given latitude range.
*
* Taken from Map Cache Electron
*
* @static
* @param {BoundingBox} Geopackage Bounding box
* @param {*} zoom zoom level
* @returns {{ min: number; max: number; current: number }}
* @memberof GeoSpatialUtilities
*/
static calculateYTileRange(bbox: BoundingBox, zoom: any): { min: number; max: number; current: number } {
const south = this.lat2tile(bbox.minLatitude, zoom);
const north = this.lat2tile(bbox.maxLatitude, zoom);
return {
min: Math.max(0, Math.min(south, north)),
max: Math.max(0, Math.max(south, north)),
current: Math.max(0, Math.min(south, north)),
};
}
/**
* Calls function for each tile needed.
*
* Taken from Map Cache Electron
*
* @static
* @param {BoundingBox} extent Bounding Box
* @param {number[]} zoomLevels Array of Zoom Levels
* @param {(arg0: { z: number; x: number; y: number }) => Promise<boolean>} tileCallback Function that will be called for every tile
* @returns {Promise<void>}
* @memberof GeoSpatialUtilities
*/
static async iterateAllTilesInExtentForZoomLevels(
extent: BoundingBox,
zoomLevels: number[],
tileCallback: (arg0: { z: number; x: number; y: number }) => Promise<boolean>,
): Promise<void> {
let stop = false;
for (let i = 0; i < zoomLevels.length && !stop; i++) {
const z = zoomLevels[i];
const yRange = this.calculateYTileRange(extent, z);
const xRange = this.calculateXTileRange(extent, z);
for (let x = xRange.min; x <= xRange.max && !stop; x++) {
for (let y = yRange.min; y <= yRange.max && !stop; y++) {
stop = await tileCallback({ z, x, y });
}
}
}
}
/**
* Converts tiles to a geopackage Bounding box.
*
* @static
* @param {number} x x tile position
* @param {number} y y tile position
* @param {number} zoom zoom level
* @returns {BoundingBox} Geopackage Bounding box.
* @memberof GeoSpatialUtilities
*/
static tileBboxCalculator(x: number, y: number, zoom: number): BoundingBox {
return new BoundingBox(
this.tile2lon(x, zoom), // West -> MinLongitude
this.tile2lon(x + 1, zoom), // East -> MaxLongitude
this.tile2lat(y + 1, zoom), // South -> MinLatitude
this.tile2lat(y, zoom), // North -> MaxLatitude
);
}
/**
* Uses turf to rotate a bounding box.
*
* @static
* @param {BoundingBox} bbox GeoPackage Bounding Box EPSG:4326
* @param {number} rotation Rotation in degrees; clockwise rotations are negative
* @returns {BoundingBox} GeoPackage Bounding Box Rotated by given number of degrees
* @memberof GeoSpatialUtilities
*/
public static getKmlBBoxRotation(bbox: BoundingBox, rotation: number): BoundingBox {
// Convert to geoJson polygon format which turf can read.
// turf rotates and returns a geoJson polygon
const rotatedPoly = turf.transformRotate(bbox.toGeoJSON().geometry, rotation);
// Coverts the geoJson polygon to a geoJson bbox
const rotatedBBox = turf.bbox(rotatedPoly);
// Converts geoJson bbox into a Geopackage js bounding box.
const rotMinLongitude = rotatedBBox[0];
const rotMinLatitude = rotatedBBox[1];
const rotMaxLongitude = rotatedBBox[2];
const rotMaxLatitude = rotatedBBox[3];
return new BoundingBox(rotMinLongitude, rotMaxLongitude, rotMinLatitude, rotMaxLatitude);
}
/**
* Returns the floor of the zoom level where 1 image pixel equals 1 tile pixel.
* floor(log_2((360 * imageWidth) / (bbox_width * tile_size)))
* @static
* @param {BoundingBox} bbox Must be in EPSG:4326
* @param {number} imageWidth Must be in Pixels
* @returns {number} zoom level
* @memberof GeoSpatialUtilities
*/
public static getNaturalScale(bbox: BoundingBox, imageWidth: number): number {
const widthHeight = this.getWidthAndHeightFromBBox(bbox);
return Math.floor(Math.log2((360 * imageWidth) / (widthHeight.width * TILE_SIZE_IN_PIXELS)));
}
/**
* Get height and width of a bounding box
*
* @static
* @param {BoundingBox} bbox geopackage bounding box.
* @returns {{ width: number; height: number }} Object with width and height
* @memberof GeoSpatialUtilities
*/
public static getWidthAndHeightFromBBox(bbox: BoundingBox): { width: number; height: number } {
return {
height: Math.abs(bbox.maxLatitude - bbox.minLatitude),
width: Math.abs(bbox.maxLongitude - bbox.minLongitude),
};
}
/**
* Converts the Min/Max Latitude and Longitude into EPSG:3857 (Web Mercator)
*
* @static
* @param {string} currentProjection EPSG:#### string of the current projection
* @param {BoundingBox} bbox Geopackage Bounding Box
* @returns {BoundingBox} New Geopackage Bounding Box with the transformed coordinates.
* @memberof GeoSpatialUtilities
*/
public static getWebMercatorBoundingBox(currentProjection: string, bbox: BoundingBox): BoundingBox {
proj4.defs(currentProjection, proj4Defs[currentProjection]);
proj4.defs(
'EPSG:3857',
'+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs',
);
const converter = proj4('EPSG:4326', 'EPSG:3857');
const temp = new BoundingBox(bbox);
if (temp.minLatitude < WEB_MERCATOR_MIN_LAT_RANGE) {
temp.minLatitude = WEB_MERCATOR_MIN_LAT_RANGE;
}
if (temp.maxLatitude > WEB_MERCATOR_MAX_LAT_RANGE) {
temp.maxLatitude = WEB_MERCATOR_MAX_LAT_RANGE;
}
[temp.minLongitude, temp.minLatitude] = converter.forward([temp.minLongitude, temp.minLatitude]);
[temp.maxLongitude, temp.maxLatitude] = converter.forward([temp.maxLongitude, temp.maxLatitude]);
return temp;
}
/**
* Creates a list of zoom level where the number of filled tiles changes.
*
* @static
* @param {BoundingBox} bbox Bounding box after rotation
* @param {number} naturalScale Zoom level closest to one to one in terms of pixels
* @returns {Set<number>} A set of zoom levels
* @memberof GeoSpatialUtilities
*/
public static getZoomLevels(bbox: BoundingBox, naturalScale: number): Set<number> {
const levels = new Set<number>();
let z = Math.round(naturalScale);
let ySize: number;
let xSize: number;
if (naturalScale < 0) {
z = 0;
} else if (naturalScale > 20) {
z = 20;
}
do {
const yRange = GeoSpatialUtilities.calculateYTileRange(bbox, z);
const xRange = GeoSpatialUtilities.calculateXTileRange(bbox, z);
ySize = yRange.max - yRange.min + 1;
xSize = xRange.max - xRange.min + 1;
levels.add(z);
z -= 2;
} while (xSize * ySize !== 1 && z > 0);
return levels;
}
/**
* Expand the bounds to include provided latitude and longitude value.
*
* @static
* @param {BoundingBox} boundingBox Bounding Box to be expanded
* @param {number} [latitude] Line of latitude to be included the bounding box
* @param {number} [longitude] Line of longitude to be included the bounding box
* @param {boolean} [copyBoundingBox=false] Copy the object and return that or mutate and return the original object.
* @returns {BoundingBox}
* @memberof GeoSpatialUtilities
*/
public static expandBoundingBoxToIncludeLatLonPoint(
boundingBox: BoundingBox,
latitude?: number,
longitude?: number,
copyBoundingBox = false,
): BoundingBox {
if (copyBoundingBox) {
boundingBox = new BoundingBox(boundingBox);
}
if (!_.isNil(latitude)) {
if (_.isNil(boundingBox.minLatitude)) {
if (_.isNil(boundingBox.maxLatitude)) {
boundingBox.minLatitude = latitude;
} else {
boundingBox.minLatitude = boundingBox.maxLatitude;
}
}
if (_.isNil(boundingBox.maxLatitude)) {
if (_.isNil(boundingBox.minLatitude)) {
boundingBox.maxLatitude = latitude;
} else {
boundingBox.maxLatitude = boundingBox.minLatitude;
}
}
if (latitude < boundingBox.minLatitude) boundingBox.minLatitude = latitude;
if (latitude > boundingBox.maxLatitude) boundingBox.maxLatitude = latitude;
}
if (!_.isNil(longitude)) {
if (_.isNil(boundingBox.minLongitude)) {
if (_.isNil(boundingBox.maxLongitude)) {
boundingBox.minLongitude = longitude;
} else {
boundingBox.minLongitude = boundingBox.maxLongitude;
}
}
if (_.isNil(boundingBox.maxLongitude)) {
if (_.isNil(boundingBox.minLongitude)) {
boundingBox.maxLongitude = longitude;
} else {
boundingBox.maxLongitude = boundingBox.minLongitude;
}
}
if (longitude < boundingBox.minLongitude) boundingBox.minLongitude = longitude;
if (longitude > boundingBox.maxLongitude) boundingBox.maxLongitude = longitude;
}
return boundingBox;
}
} | the_stack |
import moment from 'moment';
import * as _ from 'underscore';
import { getKarmaInflationSeries, timeSeriesIndexExpr } from '../../../server/karmaInflation/cache';
import { combineIndexWithDefaultViewIndex, ensureIndex } from '../../collectionUtils';
import type { FilterMode, FilterSettings, FilterTag } from '../../filterSettings';
import { forumTypeSetting } from '../../instanceSettings';
import { defaultVisibilityTags } from '../../publicSettings';
import { defaultScoreModifiers, timeDecayExpr } from '../../scoring';
import { viewFieldAllowAny, viewFieldNullOrMissing } from '../../vulcan-lib';
import { Posts } from './collection';
import { postStatuses, startHerePostIdSetting } from './constants';
export const DEFAULT_LOW_KARMA_THRESHOLD = -10
export const MAX_LOW_KARMA_THRESHOLD = -1000
const isEAForum = forumTypeSetting.get() === 'EAForum'
const eventBuffer = isEAForum ? {startBuffer: '1 hour', endBuffer: null} : {startBuffer: '6 hours', endBuffer: '3 hours'}
type ReviewSortings = "fewestReviews"|"mostReviews"|"lastCommentedAt"
declare global {
interface PostsViewTerms extends ViewTermsBase {
view?: PostsViewName,
includeRelatedQuestions?: "true"|"false",
karmaThreshold?: number|string,
meta?: boolean,
userId?: string,
filter?: any,
filters?: any,
filterSettings?: any,
sortBy?: ReviewSortings,
sortByMost?: boolean,
sortedBy?: string,
af?: boolean,
excludeEvents?: boolean,
onlineEvent?: boolean,
globalEvent?: boolean,
eventType?: Array<string>,
groupId?: string,
lat?: number,
lng?: number,
slug?: string,
sortDrafts?: string,
forum?: boolean,
question?: boolean,
tagId?: string,
legacyId?: string,
postId?: string,
authorIsUnreviewed?: boolean|null,
before?: Date|string|null,
after?: Date|string|null,
timeField?: keyof DbPost,
postIds?: Array<string>,
reviewYear?: number,
excludeContents?: boolean,
distance?: number,
}
}
/**
* @description In allPosts and elsewhere (every component that uses PostsListSettings and some
* that use PostsList) we use the concept of filters which are like Vulcan's
* views, but are more composable. Filters only specify selectors, and are
* written with MongoDB query syntax.
* To avoid duplication of code, views with the same name, will reference the
* corresponding filter
*
* TODO: This should be worked to be more nicely tied in with the filterSettings
* paradigm
*/
export const filters: Record<string,any> = {
"curated": {
curatedDate: {$gt: new Date(0)}
},
"uncurated": {
curatedDate: viewFieldNullOrMissing
},
"nonSticky": {
sticky: false,
},
"frontpage": {
frontpageDate: {$gt: new Date(0)}
},
"all": {
groupId: null
},
"questions": {
question: true,
hiddenRelatedQuestion: viewFieldAllowAny
},
"events": {
isEvent: true,
groupId: null
},
"untagged": {
tagRelevance: {}
},
"unnominated2019": {
nominationCount2019: 0
},
// TODO(Review) is this indexed?
"unnominated": {
positiveReviewVoteCount: 0
},
"unNonCoreTagged": {
tagRelevance: {$exists: true},
baseScore: {$gt: 25},
$expr: {
$lt: [
{$size:
{$filter: {
// this was a hack during the Tagging Sprint, where we wanted people to tag posts with non-core-tags
input: {$objectToArray: "$tagRelevance"},
cond: {$not: {$in: ["$$this.k", ["xexCWMyds6QLWognu", "sYm3HiWcfZvrGu3ui", "izp6eeJJEg9v5zcur", "fkABsGCJZ6y9qConW", "Ng8Gice9KNkncxqcj", "MfpEPj6kJneT9gWT6", "3uE2pXvbcnS9nnZRE"]]}}
}}
},
1]
}
},
"tagged": {
tagRelevance: {$ne: {}}
},
"includeMetaAndPersonal": {},
}
/**
* @summary Similar to filters (see docstring above), but specifying MongoDB-style sorts
*
* NB: Vulcan views overwrite sortings. If you are using a named view with a
* sorting, do not try to supply your own.
*/
export const sortings = {
magic: { score: -1 },
top: { baseScore: -1 },
topAdjusted: { karmaInflationAdjustedScore: -1 },
new: { postedAt: -1 },
old: { postedAt: 1 },
recentComments: { lastCommentedAt: -1 }
}
/**
* @summary Base parameters that will be common to all other view unless specific properties are overwritten
*
* NB: Specifying "before" into posts views is a bit of a misnomer at present,
* as it is *inclusive*. The parameters callback that handles it outputs
* ~ $lt: before.endOf('day').
*/
Posts.addDefaultView((terms: PostsViewTerms) => {
const validFields: any = _.pick(terms, 'userId', 'groupId', 'af','question', 'authorIsUnreviewed');
// Also valid fields: before, after, timeField (select on postedAt), excludeEvents, and
// karmaThreshold (selects on baseScore).
const alignmentForum = forumTypeSetting.get() === 'AlignmentForum' ? {af: true} : {}
let params: any = {
selector: {
status: postStatuses.STATUS_APPROVED,
draft: false,
isFuture: false,
unlisted: false,
shortform: false,
authorIsUnreviewed: false,
hiddenRelatedQuestion: false,
groupId: viewFieldNullOrMissing,
...validFields,
...alignmentForum
},
options: {},
}
// TODO: Use default threshold in default view
// TODO: Looks like a bug in cases where karmaThreshold = 0, because we'd
// still want to filter.
if (terms.karmaThreshold && terms.karmaThreshold !== "0") {
params.selector.baseScore = {$gte: parseInt(terms.karmaThreshold+"", 10)}
params.selector.maxBaseScore = {$gte: parseInt(terms.karmaThreshold+"", 10)}
}
if (terms.excludeEvents) {
params.selector.isEvent = false
}
if (terms.userId) {
params.selector.hideAuthor = false
}
if (terms.includeRelatedQuestions === "true") {
params.selector.hiddenRelatedQuestion = viewFieldAllowAny
}
if (terms.filter) {
if (filters[terms.filter]) {
params.selector = {...params.selector, ...filters[terms.filter]}
} else {
// eslint-disable-next-line no-console
console.warn(
`Filter '${terms.filter}' not recognized while constructing defaultView`,
terms.view ? ` for view ${terms.view}` : ''
)
}
}
if (terms.filterSettings) {
const filterParams = filterSettingsToParams(terms.filterSettings);
params = {
selector: { ...params.selector, ...filterParams.selector },
options: { ...params.options, ...filterParams.options },
syntheticFields: { ...params.syntheticFields, ...filterParams.syntheticFields },
};
}
if (terms.sortedBy) {
if (terms.sortedBy === 'topAdjusted') {
params.syntheticFields = { ...params.syntheticFields, ...buildInflationAdjustedField() }
}
if (sortings[terms.sortedBy]) {
params.options = {sort: {...params.options.sort, ...sortings[terms.sortedBy]}}
} else {
// eslint-disable-next-line no-console
console.warn(
`Sorting '${terms.sortedBy}' not recognized while constructing defaultView`,
terms.view ? ` for view ${terms.view}` : ''
)
}
}
if (terms.after || terms.before) {
let postedAt: any = {};
if (terms.after) {
postedAt.$gt = moment(terms.after).toDate();
}
if (terms.before) {
postedAt.$lt = moment(terms.before).toDate();
}
if (!_.isEmpty(postedAt) && !terms.timeField) {
params.selector.postedAt = postedAt;
} else if (!_.isEmpty(postedAt) && terms.timeField) {
params.selector[terms.timeField] = postedAt;
}
}
return params;
})
const getFrontpageFilter = (filterSettings: FilterSettings): {filter: any, softFilter: Array<any>} => {
if (filterSettings.personalBlog === "Hidden") {
return {
filter: {frontpageDate: {$gt: new Date(0)}},
softFilter: []
}
} else if (filterSettings.personalBlog === "Required") {
return {
filter: {frontpageDate: viewFieldNullOrMissing},
softFilter: []
}
} else {
const personalBonus = filterModeToAdditiveKarmaModifier(filterSettings.personalBlog)
return {
filter: {},
softFilter: personalBonus ? [
{
$cond: {
if: "$frontpageDate",
then: 0,
else: personalBonus
}
},
] : []
}
}
}
function buildInflationAdjustedField(): any {
const karmaInflationSeries = getKarmaInflationSeries();
return {
karmaInflationAdjustedScore: {
$multiply: [
"$baseScore",
{
$ifNull: [
{
$arrayElemAt: [
karmaInflationSeries.values,
{
$max: [
timeSeriesIndexExpr("$postedAt", karmaInflationSeries.start, karmaInflationSeries.interval),
0 // fall back to first value if out of range
]
}]
},
karmaInflationSeries.values[karmaInflationSeries.values.length - 1] // fall back to final value if out of range
]
}
]
}
}
}
function filterSettingsToParams(filterSettings: FilterSettings): any {
// We get the default tag relevance from the database config
const tagFilterSettingsWithDefaults: FilterTag[] = filterSettings.tags.map(t =>
t.filterMode === "TagDefault" ? {
tagId: t.tagId,
tagName: t.tagName,
filterMode: defaultVisibilityTags.get().find(dft => dft.tagId === t.tagId)?.filterMode || 'Default',
} :
t
)
const tagsRequired = _.filter(tagFilterSettingsWithDefaults, t=>t.filterMode==="Required");
const tagsExcluded = _.filter(tagFilterSettingsWithDefaults, t=>t.filterMode==="Hidden");
const frontpageFiltering = getFrontpageFilter(filterSettings)
const {filter: frontpageFilter, softFilter: frontpageSoftFilter} = frontpageFiltering
let tagsFilter = {};
for (let tag of tagsRequired) {
tagsFilter[`tagRelevance.${tag.tagId}`] = {$gte: 1};
}
for (let tag of tagsExcluded) {
tagsFilter[`tagRelevance.${tag.tagId}`] = {$not: {$gte: 1}};
}
const tagsSoftFiltered = tagFilterSettingsWithDefaults.filter(
t => (t.filterMode!=="Hidden" && t.filterMode!=="Required" && t.filterMode!=="Default" && t.filterMode!==0)
);
const syntheticFields = {
score: {$divide:[
{$multiply: [
{$add:[
"$baseScore",
...tagsSoftFiltered.map(t => (
{$cond: {
if: {$gt: ["$tagRelevance."+t.tagId, 0]},
then: filterModeToAdditiveKarmaModifier(t.filterMode),
else: 0
}}
)),
...defaultScoreModifiers(),
...frontpageSoftFilter,
]},
...tagsSoftFiltered.map(t => (
{$cond: {
if: {$gt: ["$tagRelevance."+t.tagId, 0]},
then: filterModeToMultiplicativeKarmaModifier(t.filterMode),
else: 1
}}
)),
]},
timeDecayExpr()
]}
}
return {
selector: {
...frontpageFilter,
...tagsFilter
},
syntheticFields,
};
}
function filterModeToAdditiveKarmaModifier(mode: FilterMode): number {
if (typeof mode === "number" && (mode <= 0 || 1 <= mode)) {
return mode;
} else switch(mode) {
default:
case "Default": return 0;
case "Subscribed": return 25;
}
}
function filterModeToMultiplicativeKarmaModifier(mode: FilterMode): number {
if (typeof mode === "number" && 0 < mode && mode < 1) {
return mode;
} else switch(mode) {
default:
case "Default": return 1;
case "Reduced": return 0.5;
}
}
export function augmentForDefaultView(indexFields)
{
return combineIndexWithDefaultViewIndex({
viewFields: indexFields,
prefix: {status:1, isFuture:1, draft:1, unlisted:1, shortform: 1, hiddenRelatedQuestion:1, authorIsUnreviewed:1, groupId:1 },
suffix: { _id:1, meta:1, isEvent:1, af:1, frontpageDate:1, curatedDate:1, postedAt:1, baseScore:1 },
});
}
/**
* @summary User posts view
*/
Posts.addView("userPosts", (terms: PostsViewTerms) => {
const sortOverride = terms.sortedBy ? {} : {sort: {postedAt: -1}}
return {
selector: {
userId: viewFieldAllowAny,
hiddenRelatedQuestion: viewFieldAllowAny,
shortform: viewFieldAllowAny,
groupId: null, // TODO: fix vulcan so it doesn't do deep merges on viewFieldAllowAny
$or: [{userId: terms.userId}, {"coauthorStatuses.userId": terms.userId}],
},
options: {
limit: 5,
...sortOverride
}
}
});
// This index is currently unused on LW.
// ensureIndex(Posts,
// augmentForDefaultView({ userId: 1, hideAuthor: 1, postedAt: -1, }),
// {
// name: "posts.userId_postedAt",
// }
// );
ensureIndex(Posts,
augmentForDefaultView({ 'coauthorStatuses.userId': 1, userId: 1, postedAt: -1 }),
{
name: "posts.coauthorStatuses_postedAt",
}
);
const setStickies = (sortOptions, terms: PostsViewTerms) => {
if (terms.af && terms.forum) {
return { afSticky: -1, stickyPriority: -1, ...sortOptions}
} else if (terms.meta && terms.forum) {
return { metaSticky: -1, stickyPriority: -1, ...sortOptions}
} else if (terms.forum) {
return { sticky: -1, stickyPriority: -1, ...sortOptions}
}
return sortOptions
}
const stickiesIndexPrefix = {
sticky: -1, afSticky: -1, metaSticky: -1, stickyPriority: -1
};
Posts.addView("magic", (terms: PostsViewTerms) => {
const selector = forumTypeSetting.get() === 'EAForum' ? filters.nonSticky : { isEvent: false };
return {
selector,
options: {sort: setStickies(sortings.magic, terms)},
};
});
ensureIndex(Posts,
augmentForDefaultView({ score:-1, isEvent: 1 }),
{
name: "posts.score",
}
);
// Wildcard index on tagRelevance, enables us to efficiently filter on tagRel scores
ensureIndex(Posts,{ "tagRelevance.$**" : 1 } )
// This index doesn't appear used, but seems like it should be.
// ensureIndex(Posts,
// augmentForDefaultView({ afSticky:-1, score:-1 }),
// {
// name: "posts.afSticky_score",
// }
// );
Posts.addView("top", (terms: PostsViewTerms) => ({
options: {sort: setStickies(sortings.top, terms)}
}))
// unused on LW. If EA forum is also not using we can delete.
// ensureIndex(Posts,
// augmentForDefaultView({ ...stickiesIndexPrefix, baseScore:-1 }),
// {
// name: "posts.stickies_baseScore",
// }
// );
// ensureIndex(Posts,
// augmentForDefaultView({ userId: 1, hideAuthor: 1, ...stickiesIndexPrefix, baseScore:-1 }),
// {
// name: "posts.userId_stickies_baseScore",
// }
// );
Posts.addView("new", (terms: PostsViewTerms) => ({
options: {sort: setStickies(sortings.new, terms)}
}))
Posts.addView("recentComments", (terms: PostsViewTerms) => ({
options: {sort: sortings.recentComments}
}))
Posts.addView("old", (terms: PostsViewTerms) => ({
options: {sort: sortings.old}
}))
// Covered by the same index as `new`
Posts.addView("timeframe", (terms: PostsViewTerms) => ({
options: {limit: terms.limit}
}))
ensureIndex(Posts,
augmentForDefaultView({ postedAt:1, baseScore:1}),
{
name: "posts.postedAt_baseScore",
}
);
Posts.addView("daily", (terms: PostsViewTerms) => ({
options: {
sort: {baseScore: -1}
}
}));
ensureIndex(Posts,
augmentForDefaultView({ postedAt:1, baseScore:1}),
{
name: "posts.postedAt_baseScore",
}
);
Posts.addView("tagRelevance", (terms: PostsViewTerms) => ({
// note: this relies on the selector filtering done in the default view
// sorts by the "sortedBy" parameter if it's been passed in, or otherwise sorts by tag relevance
options: {
sort: terms.sortedBy ? sortings[terms.sortedBy] : { [`tagRelevance.${terms.tagId}`]: -1, baseScore: -1}
}
}));
Posts.addView("frontpage", (terms: PostsViewTerms) => ({
selector: filters.frontpage,
options: {
sort: {sticky: -1, stickyPriority: -1, score: -1}
}
}));
ensureIndex(Posts,
augmentForDefaultView({ sticky: -1, stickyPriority: -1, score: -1, frontpageDate:1 }),
{
name: "posts.frontpage",
partialFilterExpression: filters.frontpage,
}
);
Posts.addView("frontpage-rss", (terms: PostsViewTerms) => ({
selector: filters.frontpage,
options: {
sort: {frontpageDate: -1, postedAt: -1}
}
}));
// Covered by the same index as `frontpage`
Posts.addView("curated", (terms: PostsViewTerms) => ({
selector: filters.curated,
options: {
sort: {sticky: -1, curatedDate: -1, postedAt: -1}
}
}));
ensureIndex(Posts,
augmentForDefaultView({ sticky:-1, curatedDate:-1, postedAt:-1 }),
{
name: "posts.curated",
partialFilterExpression: { curatedDate: {$gt: new Date(0)} },
}
);
Posts.addView("curated-rss", (terms: PostsViewTerms) => ({
selector: {
curatedDate: {$gt: new Date(0)},
},
options: {
sort: {curatedDate: -1, postedAt: -1}
}
}));
// Covered by the same index as `curated`
Posts.addView("community", (terms: PostsViewTerms) => ({
selector: {
frontpageDatgroupId: { $exists: false },
isEvent: false,
},
options: {
sort: {sticky: -1, score: -1}
}
}));
ensureIndex(Posts,
augmentForDefaultView({ sticky: -1, score: -1 }),
{
name: "posts.community",
}
);
Posts.addView("community-rss", (terms: PostsViewTerms) => ({
selector: {
frontpageDate: null,
maxBaseScore: {$gt: 2}
},
options: {
sort: {postedAt: -1}
}
}));
// Covered by the same index as `new`
Posts.addView("meta-rss", (terms: PostsViewTerms) => ({
selector: {
meta: true,
},
options: {
sort: {
postedAt: -1
}
}
}))
// Covered by the same index as `new`
Posts.addView('rss', Posts.views['community-rss']); // default to 'community-rss' for rss
Posts.addView("topQuestions", (terms: PostsViewTerms) => ({
selector: {
question: true,
hiddenRelatedQuestion: viewFieldAllowAny,
baseScore: {$gte: 40}
},
options: {
sort: { lastCommentedAt: -1 }
}
}));
ensureIndex(Posts,
augmentForDefaultView({ question:1, lastCommentedAt: -1 }),
{
name: "posts.topQuestions",
}
);
Posts.addView("recentQuestionActivity", (terms: PostsViewTerms) => ({
selector: {
question: true,
hiddenRelatedQuestion: viewFieldAllowAny,
},
options: {
sort: {lastCommentedAt: -1}
}
}));
// covered by same index as 'topQuestions'
/**
* @summary Scheduled view
*/
Posts.addView("scheduled", (terms: PostsViewTerms) => ({
selector: {
status: postStatuses.STATUS_APPROVED,
isFuture: true
},
options: {
sort: {postedAt: -1}
}
}));
// Covered by the same index as `new`
/**
* @summary Draft view
*/
Posts.addView("drafts", (terms: PostsViewTerms) => {
let query = {
selector: {
userId: viewFieldAllowAny,
$or: [
{userId: terms.userId},
{shareWithUsers: terms.userId},
{"coauthorStatuses.userId": terms.userId},
],
draft: true,
deletedDraft: false,
hideAuthor: false,
unlisted: null,
groupId: null, // TODO: fix vulcan so it doesn't do deep merges on viewFieldAllowAny
authorIsUnreviewed: viewFieldAllowAny,
hiddenRelatedQuestion: viewFieldAllowAny,
},
options: {
sort: {}
}
}
switch (terms.sortDrafts) {
case 'wordCount': {
query.options.sort = {wordCount: -1, modifiedAt: -1, createdAt: -1}
break
}
default: {
query.options.sort = {modifiedAt: -1, createdAt: -1}
}
}
return query
});
// not currently used, but seems like it should be?
// ensureIndex(Posts,
// augmentForDefaultView({ wordCount: 1, userId: 1, hideAuthor: 1, deletedDraft: 1, modifiedAt: -1, createdAt: -1 }),
// { name: "posts.userId_wordCount" }
// );
ensureIndex(Posts,
augmentForDefaultView({ userId: 1, hideAuthor: 1, deletedDraft: 1, modifiedAt: -1, createdAt: -1 }),
{ name: "posts.userId_createdAt" }
);
ensureIndex(Posts,
augmentForDefaultView({ shareWithUsers: 1, deletedDraft: 1, modifiedAt: -1, createdAt: -1 }),
{ name: "posts.userId_shareWithUsers" }
);
/**
* @summary All drafts view
*/
Posts.addView("all_drafts", (terms: PostsViewTerms) => ({
selector: {
draft: true
},
options: {
sort: {createdAt: -1}
}
}));
Posts.addView("unlisted", (terms: PostsViewTerms) => {
return {
selector: {
userId: terms.userId,
unlisted: true,
groupId: null,
},
options: {
sort: {createdAt: -1}
}
}});
Posts.addView("userAFSubmissions", (terms: PostsViewTerms) => {
return {
selector: {
userId: terms.userId,
af: false,
suggestForAlignmentUserIds: terms.userId,
},
options: {
sort: {createdAt: -1}
}
}});
Posts.addView("slugPost", (terms: PostsViewTerms) => ({
selector: {
slug: terms.slug,
},
options: {
limit: 1,
}
}));
ensureIndex(Posts, {"slug": "hashed"});
Posts.addView("legacyIdPost", (terms: PostsViewTerms) => {
if (!terms.legacyId) throw new Error("Missing view argument: legacyId");
const legacyId = parseInt(terms.legacyId, 36)
if (isNaN(legacyId)) throw new Error("Invalid view argument: legacyId must be base36, was "+terms.legacyId);
return {
selector: {
legacyId: ""+legacyId
},
options: {
limit: 1
}
}
});
ensureIndex(Posts, {legacyId: "hashed"});
// Corresponds to the postCommented subquery in recentDiscussionFeed.ts
ensureIndex(Posts,
{
status: 1,
isFuture: 1,
draft: 1,
unlisted: 1,
authorIsUnreviewed: 1,
hideFrontpageComments: 1,
lastCommentedAt: -1,
_id: 1,
baseScore: 1,
af: 1,
isEvent: 1,
globalEvent: 1,
commentCount: 1,
},
);
const recentDiscussionFilter = {
baseScore: {$gt:0},
hideFrontpageComments: false,
hiddenRelatedQuestion: viewFieldAllowAny,
shortform: viewFieldAllowAny,
groupId: null,
}
Posts.addView("recentDiscussionThreadsList", (terms: PostsViewTerms) => {
return {
selector: {
...recentDiscussionFilter
},
options: {
sort: {lastCommentedAt:-1},
limit: terms.limit || 12,
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ lastCommentedAt:-1, baseScore:1, hideFrontpageComments:1 }),
{ name: "posts.recentDiscussionThreadsList", }
);
Posts.addView("afRecentDiscussionThreadsList", (terms: PostsViewTerms) => {
return {
selector: {
...recentDiscussionFilter
},
options: {
sort: {afLastCommentedAt:-1},
limit: terms.limit || 12,
}
}
})
// this index appears unused
// ensureIndex(Posts,
// augmentForDefaultView({ hideFrontpageComments:1, afLastCommentedAt:-1, baseScore:1 }),
// { name: "posts.afRecentDiscussionThreadsList", }
// );
Posts.addView("2018reviewRecentDiscussionThreadsList", (terms: PostsViewTerms) => {
return {
selector: {
...recentDiscussionFilter,
nominationCount2018: { $gt: 0 }
},
options: {
sort: {lastCommentedAt:-1},
limit: terms.limit || 12,
}
}
})
// ensureIndex(Posts,
// augmentForDefaultView({ nominationCount2018: 1, lastCommentedAt:-1, baseScore:1, hideFrontpageComments:1 }),
// { name: "posts.2018reviewRecentDiscussionThreadsList", }
// );
Posts.addView("2019reviewRecentDiscussionThreadsList", (terms: PostsViewTerms) => {
return {
selector: {
...recentDiscussionFilter,
nominationCount2019: { $gt: 0 }
},
options: {
sort: {lastCommentedAt:-1},
limit: terms.limit || 12,
}
}
})
// ensureIndex(Posts,
// augmentForDefaultView({ nominationCount2019: 1, lastCommentedAt:-1, baseScore:1, hideFrontpageComments:1 }),
// { name: "posts.2019reviewRecentDiscussionThreadsList", }
// );
Posts.addView("globalEvents", (terms: PostsViewTerms) => {
const timeSelector = {$or: [
{startTime: {$gt: moment().subtract(eventBuffer.startBuffer).toDate()}},
{endTime: {$gt: moment().subtract(eventBuffer.endBuffer).toDate()}}
]}
let onlineEventSelector: {} = terms.onlineEvent ? {onlineEvent: true} : {}
if (terms.onlineEvent === false) {
onlineEventSelector = {$or: [
{onlineEvent: false}, {onlineEvent: {$exists: false}}
]}
}
let query = {
selector: {
globalEvent: true,
isEvent: true,
groupId: null,
eventType: terms.eventType ? {$in: terms.eventType} : null,
$and: [
timeSelector, onlineEventSelector
],
},
options: {
sort: {
startTime: 1,
_id: 1
}
}
}
return query
})
ensureIndex(Posts,
augmentForDefaultView({ globalEvent:1, eventType:1, startTime:1, endTime:1 }),
{ name: "posts.globalEvents" }
);
Posts.addView("nearbyEvents", (terms: PostsViewTerms) => {
const timeSelector = {$or: [
{startTime: {$gt: moment().subtract(eventBuffer.startBuffer).toDate()}},
{endTime: {$gt: moment().subtract(eventBuffer.endBuffer).toDate()}}
]}
let onlineEventSelector: {} = terms.onlineEvent ? {onlineEvent: true} : {}
if (terms.onlineEvent === false) {
onlineEventSelector = {$or: [
{onlineEvent: false}, {onlineEvent: {$exists: false}}
]}
}
// Note: distance is in miles
let query: any = {
selector: {
groupId: null,
isEvent: true,
eventType: terms.eventType ? {$in: terms.eventType} : null,
$and: [
timeSelector, onlineEventSelector
],
$or: [
{
mongoLocation: {
$geoWithin: {
$centerSphere: [ [ terms.lng, terms.lat ], (terms.distance || 100) / 3963.2 ] // only show in-person events within 100 miles
}
}
},
{globalEvent: true} // also include events that are open to everyone around the world
]
},
options: {
sort: {
startTime: 1, // show events in chronological order
_id: 1
}
}
};
if(Array.isArray(terms.filters) && terms.filters.length) {
query.selector.types = {$in: terms.filters};
} else if (typeof terms.filters === "string") { //If there is only single value we can't distinguish between Array and value
query.selector.types = {$in: [terms.filters]};
}
return query;
});
ensureIndex(Posts,
augmentForDefaultView({ mongoLocation:"2dsphere", eventType:1, startTime:1, endTime: 1 }),
{ name: "posts.2dsphere" }
);
Posts.addView("events", (terms: PostsViewTerms) => {
const timeSelector = {$or: [
{startTime: {$gt: moment().subtract(eventBuffer.startBuffer).toDate()}},
{endTime: {$gt: moment().subtract(eventBuffer.endBuffer).toDate()}}
]}
const twoMonthsAgo = moment().subtract(60, 'days').toDate();
// make sure that, by default, events are not global
let globalEventSelector: {} = terms.globalEvent ? {globalEvent: true} : {};
if (terms.globalEvent === false) {
globalEventSelector = {$or: [
{globalEvent: false}, {globalEvent: {$exists:false}}
]}
}
let onlineEventSelector: {} = terms.onlineEvent ? {onlineEvent: true} : {}
if (terms.onlineEvent === false) {
onlineEventSelector = {$or: [
{onlineEvent: false}, {onlineEvent: {$exists: false}}
]}
}
return {
selector: {
isEvent: true,
$and: [
timeSelector, globalEventSelector, onlineEventSelector
],
createdAt: {$gte: twoMonthsAgo},
groupId: terms.groupId ? terms.groupId : null,
baseScore: {$gte: 1},
},
options: {
sort: {
startTime: 1
}
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ globalEvent: 1, onlineEvent: 1, startTime:1, endTime: 1, createdAt:1, baseScore:1 }),
{ name: "posts.events" }
);
Posts.addView("eventsInTimeRange", (terms: PostsViewTerms) => {
return {
selector: {
isEvent: true,
groupId: terms.groupId ? terms.groupId : null,
},
options: {
sort: {
startTime: -1,
}
}
}
})
// Same index as events
Posts.addView("upcomingEvents", (terms: PostsViewTerms) => {
const timeCutoff = moment().subtract(eventBuffer.startBuffer).toDate();
return {
selector: {
isEvent: true,
groupId: terms.groupId ? terms.groupId : null,
startTime: {$gte: timeCutoff},
},
options: {
sort: {
startTime: 1,
}
}
}
})
Posts.addView("pastEvents", (terms: PostsViewTerms) => {
const timeCutoff = moment().subtract(eventBuffer.startBuffer).toDate();
return {
selector: {
isEvent: true,
groupId: terms.groupId ? terms.groupId : null,
startTime: {$lt: timeCutoff},
},
options: {
sort: {
startTime: -1,
}
},
}
});
Posts.addView("tbdEvents", (terms: PostsViewTerms) => {
return {
selector: {
isEvent: true,
groupId: terms.groupId ? terms.groupId : null,
startTime: viewFieldNullOrMissing,
},
options: {
sort: {
postedAt: 1,
}
},
}
});
Posts.addView("nonEventGroupPosts", (terms: PostsViewTerms) => {
return {
selector: {
isEvent: false,
groupId: terms.groupId ? terms.groupId : null,
},
}
});
Posts.addView("postsWithBannedUsers", function () {
return {
selector: {
bannedUserIds: {$exists: true}
},
}
})
ensureIndex(Posts,
augmentForDefaultView({ bannedUserIds:1 }),
{ name: "posts.postsWithBannedUsers" }
);
Posts.addView("communityResourcePosts", function () {
return {
selector: {
_id: {$in: ['bDnFhJBcLQvCY3vJW', 'qMuAazqwJvkvo8teR', 'PqMT9zGrNsGJNfiFR', 'YdcF6WbBmJhaaDqoD', 'mQDoZ2yCX2ujLxJDk']}
},
}
})
// No index needed
Posts.addView("sunshineNewPosts", function () {
return {
selector: {
reviewedByUserId: {$exists: false},
},
options: {
sort: {
createdAt: -1,
}
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ status:1, reviewedByUserId:1, frontpageDate: 1, authorIsUnreviewed:1, meta: 1 }),
{ name: "posts.sunshineNewPosts" }
);
Posts.addView("sunshineNewUsersPosts", (terms: PostsViewTerms) => {
return {
selector: {
status: null, // allow sunshines to see posts marked as spam
userId: terms.userId,
authorIsUnreviewed: null,
groupId: null,
draft: viewFieldAllowAny
},
options: {
sort: {
createdAt: -1,
}
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ status:1, userId:1, hideAuthor: 1, reviewedByUserId:1, frontpageDate: 1, authorIsUnreviewed:1, createdAt: -1 }),
{ name: "posts.sunshineNewUsersPosts" }
);
Posts.addView("sunshineCuratedSuggestions", function () {
return {
selector: {
suggestForCuratedUserIds: {$exists:true, $ne: []},
reviewForCuratedUserId: {$exists:false}
},
options: {
sort: {
createdAt: -1,
},
hint: "posts.sunshineCuratedSuggestions",
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ createdAt:1, reviewForCuratedUserId:1, suggestForCuratedUserIds:1, }),
{
name: "posts.sunshineCuratedSuggestions",
partialFilterExpression: {suggestForCuratedUserIds: {$exists:true}},
}
);
// Used in Posts.find() in various places
ensureIndex(Posts, {userId:1, createdAt:-1});
// Used in routes
ensureIndex(Posts, {agentFoundationsId: "hashed"});
// Used in checkScheduledPosts cronjob
ensureIndex(Posts, {isFuture:1, postedAt:1});
// Used in scoring aggregate query
ensureIndex(Posts, {inactive:1,postedAt:1});
// Used for recommendations
ensureIndex(Posts,
augmentForDefaultView({ meta:1, disableRecommendation:1, baseScore:1, curatedDate:1, frontpageDate:1 }),
{ name: "posts.recommendable" }
);
Posts.addView("pingbackPosts", (terms: PostsViewTerms) => {
return {
selector: {
"pingbacks.Posts": terms.postId,
baseScore: {$gt: 0}
},
options: {
sort: { baseScore: -1 },
},
}
});
ensureIndex(Posts,
augmentForDefaultView({ "pingbacks.Posts": 1, baseScore: 1 }),
{ name: "posts.pingbackPosts" }
);
// TODO: refactor nominations2018 to use nominationCount + postedAt
Posts.addView("nominations2018", (terms: PostsViewTerms) => {
return {
selector: {
// FIXME: Should only apply during voting
nominationCount2018: { $gt: 2 }
},
options: {
sort: {
nominationCount2018: terms.sortByMost ? -1 : 1
}
}
}
})
// ensureIndex(Posts,
// augmentForDefaultView({ nominationCount2018:1 }),
// { name: "posts.nominations2018", }
// );
// TODO: refactor nominations2019 to filter for nominationsCount + postedAt
Posts.addView("nominations2019", (terms: PostsViewTerms) => {
return {
selector: {
// FIXME: Should only apply during voting
nominationCount2019: { $gt: 0 }
},
options: {
sort: {
nominationCount2019: terms.sortByMost ? -1 : 1
}
}
}
})
// ensureIndex(Posts,
// augmentForDefaultView({ nominationCount2019:1 }),
// { name: "posts.nominations2019", }
// );
Posts.addView("reviews2018", (terms: PostsViewTerms) => {
const sortings = {
"fewestReviews" : {reviewCount2018: 1},
"mostReviews" : {reviewCount2018: -1},
"lastCommentedAt" : {lastCommentedAt: -1}
}
return {
selector: {
nominationCount2018: { $gte: 2 },
// FIXME: Should only apply to voting
reviewCount2018: { $gte: 1 }
},
options: {
sort: { ...(terms.sortBy ? sortings[terms.sortBy] : undefined), nominationCount2018: -1 }
}
}
})
const reviews2019Sortings : Record<ReviewSortings, MongoSort<DbPost>> = {
"fewestReviews" : {reviewCount2019: 1},
"mostReviews" : {reviewCount2019: -1},
"lastCommentedAt" : {lastCommentedAt: -1}
}
Posts.addView("reviews2019", (terms: PostsViewTerms) => {
return {
selector: {
nominationCount2019: { $gte: 2 }
},
options: {
sort: { ...(terms.sortBy && reviews2019Sortings[terms.sortBy]), nominationCount2019: -1 }
}
}
})
Posts.addView("voting2019", (terms: PostsViewTerms) => {
return {
selector: {
nominationCount2019: { $gte: 2 },
// FIXME: Should only apply to voting
reviewCount2019: { $gte: 1 }
},
options: {
sort: { ...(terms.sortBy && reviews2019Sortings[terms.sortBy]), nominationCount2019: -1 }
}
}
})
// We're filtering on nominationCount greater than 2, so do not need additional indexes
// using nominations2018
Posts.addView("stickied", (terms: PostsViewTerms, _, context?: ResolverContext) => ({
selector: {
sticky: true,
...(context?.currentUser?._id ? {_id: {$ne: startHerePostIdSetting.get()}} : {}),
},
options: {
sort: {
stickyPriority: -1,
},
},
}
));
// used to find a user's upvoted posts, so they can nominate them for the Review
Posts.addView("nominatablePostsByVote", (terms: PostsViewTerms, _, context?: ResolverContext) => {
return {
selector: {
_id: {$in: terms.postIds},
userId: {$ne: context?.currentUser?._id,},
isEvent: false
},
options: {
sort: {
baseScore: -1
}
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ _id: 1, userId: 1, isEvent:1, baseScore:1 }),
{ name: "posts.nominatablePostsByVote", }
);
// Nominations for the (≤)2020 review are determined by the number of votes
Posts.addView("reviewVoting", (terms: PostsViewTerms) => {
return {
selector: {
positiveReviewVoteCount: { $gte: 1 },
},
options: {
// This sorts the posts deterministically, which is important for the
// relative stability of the seeded frontend sort
sort: {
lastCommentedAt: -1
},
...(terms.excludeContents ?
{projection: {contents: 0}} :
{})
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ positiveReviewVoteCount: 1, createdAt: 1 }),
{ name: "posts.positiveReviewVoteCount", }
);
// During the Final Voting phase, posts need at least one positive vote and at least one review to qualify
Posts.addView("reviewFinalVoting", (terms: PostsViewTerms) => {
return {
selector: {
reviewCount: { $gte: 1 },
positiveReviewVoteCount: { $gte: 1 }, // TODO: Ray thinks next year this should change to "has at least 4 points"
},
options: {
// This sorts the posts deterministically, which is important for the
// relative stability of the seeded frontend sort
sort: {
lastCommentedAt: -1
},
...(terms.excludeContents ?
{projection: {contents: 0}} :
{})
}
}
})
ensureIndex(Posts,
augmentForDefaultView({ positiveReviewVoteCount: 1, reviewCount: 1, createdAt: 1 }),
{ name: "posts.positiveReviewVoteCount", }
); | the_stack |
import { DateTime } from "@arkecosystem/platform-sdk-intl";
import { Contracts, DTO } from "@arkecosystem/platform-sdk-profiles";
import { BigNumber } from "@arkecosystem/platform-sdk-support";
import { screen } from "@testing-library/react";
import { act as hookAct, renderHook } from "@testing-library/react-hooks";
import { LedgerProvider } from "app/contexts";
import { toasts } from "app/services";
import { translations as transactionTranslations } from "domains/transaction/i18n";
import { createMemoryHistory } from "history";
import nock from "nock";
import React from "react";
import { FormProvider, useForm } from "react-hook-form";
import { Route } from "react-router-dom";
import transactionFixture from "tests/fixtures/coins/ark/devnet/transactions/transfer.json";
import transactionMultipleFixture from "tests/fixtures/coins/ark/devnet/transactions/transfer-multiple.json";
import {
env,
fireEvent,
getDefaultLedgerTransport,
getDefaultProfileId,
getDefaultWalletId,
getDefaultWalletMnemonic,
MNEMONICS,
render,
RenderResult,
renderWithRouter,
syncFees,
waitFor,
within,
} from "utils/testing-library";
import { FormStep } from "./FormStep";
import { NetworkStep } from "./NetworkStep";
import { ReviewStep } from "./ReviewStep";
import { SendTransfer } from "./SendTransfer";
import { SummaryStep } from "./SummaryStep";
const passphrase = getDefaultWalletMnemonic();
const fixtureProfileId = getDefaultProfileId();
const fixtureWalletId = getDefaultWalletId();
const createTransactionMultipleMock = (wallet: Contracts.IReadWriteWallet) =>
// @ts-ignore
jest.spyOn(wallet.transaction(), "transaction").mockReturnValue({
amount: () => +transactionMultipleFixture.data.amount / 1e8,
data: () => ({ data: () => transactionMultipleFixture.data }),
explorerLink: () => `https://dexplorer.ark.io/transaction/${transactionFixture.data.id}`,
fee: () => +transactionMultipleFixture.data.fee / 1e8,
id: () => transactionMultipleFixture.data.id,
recipient: () => transactionMultipleFixture.data.recipient,
recipients: () => [
{
address: transactionMultipleFixture.data.recipient,
amount: +transactionMultipleFixture.data.amount / 1e8,
},
],
sender: () => transactionMultipleFixture.data.sender,
type: () => "multiPayment",
});
const createTransactionMock = (wallet: Contracts.IReadWriteWallet) =>
// @ts-ignore
jest.spyOn(wallet.transaction(), "transaction").mockReturnValue({
amount: () => +transactionFixture.data.amount / 1e8,
data: () => ({ data: () => transactionFixture.data }),
explorerLink: () => `https://dexplorer.ark.io/transaction/${transactionFixture.data.id}`,
fee: () => +transactionFixture.data.fee / 1e8,
id: () => transactionFixture.data.id,
recipient: () => transactionFixture.data.recipient,
recipients: () => [
{
address: transactionFixture.data.recipient,
amount: +transactionFixture.data.amount / 1e8,
},
],
sender: () => transactionFixture.data.sender,
type: () => "transfer",
});
let profile: Contracts.IProfile;
let wallet: Contracts.IReadWriteWallet;
describe("SendTransfer", () => {
beforeAll(async () => {
profile = env.profiles().findById("b999d134-7a24-481e-a95d-bc47c543bfc9");
await env.profiles().restore(profile);
await profile.sync();
wallet = profile.wallets().first();
nock("https://dwallets.ark.io")
.get("/api/transactions?address=D8rr7B1d6TL6pf14LgMz4sKp1VBMs6YUYD")
.reply(200, require("tests/fixtures/coins/ark/devnet/transactions.json"))
.get("/api/transactions?page=1&limit=20&senderId=D8rr7B1d6TL6pf14LgMz4sKp1VBMs6YUYD")
.reply(200, { data: [], meta: {} })
.get("/api/transactions/8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877")
.reply(200, () => require("tests/fixtures/coins/ark/devnet/transactions.json"));
await syncFees(profile);
});
it("should render form step", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
let rendered: RenderResult;
await hookAct(async () => {
rendered = render(
<FormProvider {...form.current}>
<FormStep networks={[]} profile={profile} />
</FormProvider>,
);
});
const { getByTestId, asFragment } = rendered;
expect(getByTestId("SendTransfer__form-step")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
});
it("should render form step without test networks", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
const useNetworksMock = jest.spyOn(profile.settings(), "get").mockReturnValue(false);
let rendered: RenderResult;
await hookAct(async () => {
rendered = render(
<FormProvider {...form.current}>
<FormStep networks={env.availableNetworks()} profile={profile} />
</FormProvider>,
);
});
const { getByTestId, asFragment } = rendered;
expect(getByTestId("SendTransfer__form-step")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
useNetworksMock.mockRestore();
});
it("should render network step without test networks", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
const useNetworksMock = jest.spyOn(profile.settings(), "get").mockReturnValue(false);
let rendered: RenderResult;
await hookAct(async () => {
rendered = render(
<FormProvider {...form.current}>
<NetworkStep networks={env.availableNetworks()} profile={profile} />
</FormProvider>,
);
});
const { getByTestId, asFragment } = rendered;
expect(getByTestId("SendTransfer__network-step")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
useNetworksMock.mockRestore();
});
it("should render form step with deeplink values and use them", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
const deeplinkProperties: any = {
amount: "1.2",
coin: "ark",
memo: "ARK",
method: "transfer",
network: "ark.mainnet",
recipient: "DNjuJEDQkhrJ7cA9FZ2iVXt5anYiM8Jtc9",
};
await hookAct(async () => {
const { getByTestId, asFragment } = render(
<FormProvider {...form.current}>
<FormStep networks={[]} profile={profile} deeplinkProps={deeplinkProperties} />
</FormProvider>,
);
expect(getByTestId("SendTransfer__form-step")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
});
});
it("should render 1st step with custom deeplink values and use them", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
const deeplinkProperties: any = {
amount: "1.2",
coin: "ark",
method: "transfer",
network: "ark.mainnet",
recipient: "DNjuJEDQkhrJ7cA9FZ2iVXt5anYiM8Jtc9",
};
let rendered: RenderResult;
await hookAct(async () => {
rendered = render(
<FormProvider {...form.current}>
<FormStep networks={[]} profile={profile} deeplinkProps={deeplinkProperties} />
</FormProvider>,
);
});
const { getByTestId, asFragment } = rendered;
expect(getByTestId("SendTransfer__form-step")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
});
it("should render review step", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
fee: "1",
memo: "test memo",
network: wallet.network(),
recipients: [
{
address: wallet.address(),
amount: BigNumber.make(1),
},
],
senderAddress: wallet.address(),
},
}),
);
const { asFragment, container, getByTestId } = render(
<FormProvider {...form.current}>
<ReviewStep wallet={wallet} />
</FormProvider>,
);
expect(getByTestId("SendTransfer__review-step")).toBeTruthy();
expect(container).toHaveTextContent(wallet.network().name());
expect(container).toHaveTextContent("D8rr7B1d6TL6pf14LgMz4sKp1VBMs6YUYD");
expect(container).toHaveTextContent("test memo");
expect(asFragment()).toMatchSnapshot();
});
it("should render summary step", async () => {
const { result: form } = renderHook(() =>
useForm({
defaultValues: {
network: wallet.network(),
senderAddress: wallet.address(),
},
}),
);
await wallet.synchroniser().identity();
const transaction = new DTO.ExtendedSignedTransactionData(
await wallet
.coin()
.transaction()
.transfer({
data: {
amount: "1",
to: wallet.address(),
},
fee: "1",
nonce: "1",
signatory: await wallet
.coin()
.signatory()
.multiSignature(2, [wallet.publicKey()!, profile.wallets().last().publicKey()!]),
}),
wallet,
);
const { getByTestId, asFragment } = render(
<FormProvider {...form.current}>
<SummaryStep transaction={transaction} senderWallet={wallet} />
</FormProvider>,
);
expect(getByTestId("TransactionSuccessful")).toBeTruthy();
expect(asFragment()).toMatchSnapshot();
});
it("should render network selection without selected wallet", async () => {
const transferURL = `/profiles/${fixtureProfileId}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { asFragment, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__network-step")).toBeTruthy());
expect(asFragment()).toMatchSnapshot();
});
it("should render form and use location state", async () => {
const history = createMemoryHistory();
const transferURL = `/profiles/${fixtureProfileId}/wallets/${fixtureWalletId}/send-transfer?recipient=DNjuJEDQkhrJ7cA9FZ2iVXt5anYiM8Jtc9&memo=ARK&coin=ark&network=ark.devnet`;
history.push(transferURL);
const { asFragment } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(screen.getByTestId("SendTransfer__form-step")).toBeTruthy());
expect(asFragment()).toMatchSnapshot();
});
it("should render form and use location state without memo", async () => {
const history = createMemoryHistory();
const transferURL = `/profiles/${fixtureProfileId}/wallets/${fixtureWalletId}/send-transfer?coin=ark&network=ark.devnet`;
history.push(transferURL);
const { getByTestId, asFragment } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
expect(asFragment()).toMatchSnapshot();
});
it("should show network connection warning when selecting unsynced wallet", async () => {
const transferURL = `/profiles/${fixtureProfileId}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__network-step")).toBeTruthy());
fireEvent.click(getByTestId("NetworkIcon-ARK-ark.devnet"));
await waitFor(() =>
expect(getByTestId("SelectNetworkInput__network")).toHaveAttribute("aria-label", "ARK Devnet"),
);
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const walletMock = jest.spyOn(profile.wallets().first(), "hasSyncedWithNetwork").mockReturnValue(false);
const toastSpy = jest.spyOn(toasts, "warning").mockImplementation();
fireEvent.click(within(getByTestId("sender-address")).getByTestId("SelectAddress__wrapper"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getByTestId("SearchWalletListItem__select-0"));
await waitFor(() =>
expect(getByTestId("SelectAddress__input")).toHaveValue(profile.wallets().first().address()),
);
expect(toastSpy).toHaveBeenCalled();
walletMock.mockRestore();
toastSpy.mockRestore();
});
it("should select cryptoasset", async () => {
const transferURL = `/profiles/${fixtureProfileId}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getByTestId, asFragment } = renderWithRouter(
<Route path="/profiles/:profileId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__network-step")).toBeTruthy());
const input = getByTestId("SelectNetworkInput__input");
fireEvent.change(input, { target: { value: "no match" } });
await waitFor(() => expect(input).toHaveValue("no match"));
expect(input).toHaveAttribute("aria-invalid", "true");
fireEvent.change(input, { target: { value: "ARK Dev" } });
await waitFor(() => expect(input).toHaveValue("ARK Dev"));
expect(input).not.toHaveAttribute("aria-invalid");
fireEvent.change(input, { target: { value: "" } });
await waitFor(() => expect(input).toHaveValue(""));
expect(input).toHaveAttribute("aria-invalid", "true");
await waitFor(() => expect(getByTestId("NetworkIcon-ARK-ark.devnet")).toBeTruthy());
fireEvent.click(getByTestId("NetworkIcon-ARK-ark.devnet"));
await waitFor(() => expect(input).toHaveValue("ARK Devnet"));
expect(input).not.toHaveAttribute("aria-invalid");
expect(asFragment()).toMatchSnapshot();
});
it("should select a cryptoasset and select sender without wallet id param", async () => {
const transferURL = `/profiles/${fixtureProfileId}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__network-step")).toBeTruthy());
fireEvent.click(getByTestId("NetworkIcon-ARK-ark.devnet"));
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue("ARK Devnet"));
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
expect(getByTestId("SelectNetworkInput__network")).toHaveAttribute("aria-label", "ARK Devnet");
// Select sender
fireEvent.click(within(getByTestId("sender-address")).getByTestId("SelectAddress__wrapper"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
const firstAddress = getByTestId("SearchWalletListItem__select-1");
fireEvent.click(firstAddress);
expect(() => getByTestId("modal__inner")).toThrow(/Unable to find an element by/);
await waitFor(() => expect(container).toMatchSnapshot());
});
it("should recalculate amount when fee changes and send all is selected", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.click(getByTestId("AddRecipient__send-all"));
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"));
expect(screen.getByTestId("AddRecipient__send-all")).toHaveClass("active");
fireEvent.click(getByTestId("AddRecipient__send-all"));
expect(screen.getByTestId("AddRecipient__send-all")).not.toHaveClass("active");
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.AVERAGE));
await waitFor(() => expect(screen.getAllByRole("radio")[1]).toBeChecked());
expect(screen.getAllByRole("radio")[1]).toHaveTextContent("0.07320598");
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.FAST));
await waitFor(() => expect(screen.getAllByRole("radio")[2]).toBeChecked());
expect(screen.getAllByRole("radio")[2]).toHaveTextContent("0.1");
});
it("should handle fee change", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${fixtureWalletId}/send-transfer?coin=ark&network=ark.devnet`;
const history = createMemoryHistory();
history.push(transferURL);
const { getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
// Amount
const sendAll = getByTestId("AddRecipient__send-all");
fireEvent.click(sendAll);
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"));
// Fee
fireEvent.click(within(getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
fireEvent.click(within(getByTestId("InputFee")).getByText(transactionTranslations.FEES.AVERAGE));
await waitFor(() => expect(screen.getAllByRole("radio")[1]).toBeChecked());
expect(screen.getAllByRole("radio")[1]).toHaveTextContent("0.07320598");
fireEvent.click(within(getByTestId("InputFee")).getByText(transactionTranslations.FEES.FAST));
await waitFor(() => expect(screen.getAllByRole("radio")[2]).toBeChecked());
expect(screen.getAllByRole("radio")[2]).toHaveTextContent("0.1");
fireEvent.click(
within(getByTestId("InputFee")).getByText(transactionTranslations.INPUT_FEE_VIEW_TYPE.ADVANCED),
);
fireEvent.change(getByTestId("InputCurrency"), { target: { value: "1000000000" } });
await waitFor(() => expect(getByTestId("InputCurrency")).toHaveValue("1000000000"));
});
it("should send a single transfer", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
const goSpy = jest.spyOn(history, "go").mockImplementation();
const backButton = getByTestId("StepNavigation__back-button");
expect(backButton).not.toHaveAttribute("disabled");
fireEvent.click(backButton);
expect(goSpy).toHaveBeenCalledWith(-1);
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
// Go back to wallet
const pushSpy = jest.spyOn(history, "push");
fireEvent.click(getByTestId("StepNavigation__back-to-wallet-button"));
expect(pushSpy).toHaveBeenCalledWith(`/profiles/${profile.id()}/wallets/${wallet.id()}`);
goSpy.mockRestore();
pushSpy.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
});
it("should fail sending a single transfer", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
const goSpy = jest.spyOn(history, "go").mockImplementation();
const backButton = getByTestId("StepNavigation__back-button");
expect(backButton).not.toHaveAttribute("disabled");
fireEvent.click(backButton);
expect(goSpy).toHaveBeenCalledWith(-1);
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Back to Step 1
fireEvent.click(getByTestId("StepNavigation__back-button"));
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [],
//@ts-ignore
errors: { [transactionFixture.data.id]: "ERROR" },
rejected: [transactionFixture.data.id],
});
const transactionMock = createTransactionMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("ErrorStep")).toBeTruthy());
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
});
it("should send a single transfer and handle undefined expiration", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
const goSpy = jest.spyOn(history, "go").mockImplementation();
const backButton = getByTestId("StepNavigation__back-button");
expect(backButton).not.toHaveAttribute("disabled");
fireEvent.click(backButton);
expect(goSpy).toHaveBeenCalledWith(-1);
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
const expirationMock = jest
.spyOn(wallet.coin().transaction(), "estimateExpiration")
.mockResolvedValue(undefined);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
// Go back to wallet
const pushSpy = jest.spyOn(history, "push");
fireEvent.click(getByTestId("StepNavigation__back-to-wallet-button"));
expect(pushSpy).toHaveBeenCalledWith(`/profiles/${profile.id()}/wallets/${wallet.id()}`);
goSpy.mockRestore();
pushSpy.mockRestore();
expirationMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
});
it("should send a single transfer with a multisignature wallet", async () => {
const isMultiSignatureSpy = jest.spyOn(wallet, "isMultiSignature").mockImplementation(() => true);
const multisignatureSpy = jest
.spyOn(wallet.multiSignature(), "all")
.mockReturnValue({ min: 2, publicKeys: [wallet.publicKey()!, profile.wallets().last().publicKey()!] });
const transferURL = `/profiles/${fixtureProfileId}/transactions/${wallet.id()}/transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/transactions/:walletId/transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
await waitFor(() => expect(getByTestId("AddRecipient__send-all")).toBeInTheDocument());
fireEvent.click(getByTestId("AddRecipient__send-all"));
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"), { timeout: 4000 });
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
);
expect(signMock).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.anything(),
fee: expect.any(Number),
nonce: expect.any(String),
signatory: expect.any(Object),
}),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
isMultiSignatureSpy.mockRestore();
multisignatureSpy.mockRestore();
});
it("should send a single transfer with a ledger wallet", async () => {
jest.useFakeTimers();
const isLedgerSpy = jest.spyOn(wallet, "isLedger").mockImplementation(() => true);
jest.spyOn(wallet.coin(), "__construct").mockImplementation();
const getPublicKeySpy = jest
.spyOn(wallet.coin().ledger(), "getPublicKey")
.mockResolvedValue("0335a27397927bfa1704116814474d39c2b933aabb990e7226389f022886e48deb");
const signTransactionSpy = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const transactionMock = createTransactionMock(wallet);
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transferURL = `/profiles/${fixtureProfileId}/transactions/${wallet.id()}/transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/transactions/:walletId/transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.click(getByTestId("AddRecipient__send-all"));
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"), { timeout: 4000 });
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
expect(getByTestId("Input__memo")).toHaveValue("test memo");
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Auto broadcast
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
getPublicKeySpy.mockRestore();
broadcastMock.mockRestore();
isLedgerSpy.mockRestore();
signTransactionSpy.mockRestore();
transactionMock.mockRestore();
});
it("should return to form step by cancelling fee warning", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(
within(getByTestId("InputFee")).getByText(transactionTranslations.INPUT_FEE_VIEW_TYPE.ADVANCED),
);
fireEvent.change(getByTestId("InputCurrency"), { target: { value: "" } });
await waitFor(() => expect(getByTestId("InputCurrency")).toHaveValue(""));
await waitFor(() => {
expect(getByTestId("Input__error")).toBeVisible();
});
fireEvent.change(getByTestId("InputCurrency"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("InputCurrency")).toHaveValue("1"));
await waitFor(() => expect(() => getByTestId("Input__error")).toThrow());
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Fee warning
await waitFor(() => expect(getByTestId("FeeWarning__cancel-button")).toBeTruthy());
fireEvent.click(getByTestId("FeeWarning__cancel-button"));
await waitFor(() => expect(() => getByTestId("modal__inner")).toThrow(/Unable to find an element by/));
});
it.each(["cancel", "continue"])(
"should update the profile settings when dismissing the fee warning (%s)",
async (action) => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(
within(getByTestId("InputFee")).getByText(transactionTranslations.INPUT_FEE_VIEW_TYPE.ADVANCED),
);
fireEvent.change(getByTestId("InputCurrency"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("InputCurrency")).toHaveValue("1"));
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Review Step
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
const profileSpy = jest.spyOn(profile.settings(), "set").mockImplementation();
// Fee warning
await waitFor(() => expect(getByTestId("FeeWarning__suppressWarning-toggle")).toBeTruthy());
fireEvent.click(getByTestId("FeeWarning__suppressWarning-toggle"));
fireEvent.click(getByTestId(`FeeWarning__${action}-button`));
expect(profileSpy).toHaveBeenCalledWith(Contracts.ProfileSetting.DoNotShowFeeWarning, true);
await waitFor(() =>
expect(
getByTestId(action === "cancel" ? "SendTransfer__form-step" : "AuthenticationStep"),
).toBeTruthy(),
);
profileSpy.mockRestore();
},
);
it.each([
["high", "1"],
["low", "0.000001"],
])("should send a single transfer with a %s fee by confirming the fee warning", async (type, fee) => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(
within(getByTestId("InputFee")).getByText(transactionTranslations.INPUT_FEE_VIEW_TYPE.ADVANCED),
);
fireEvent.change(getByTestId("InputCurrency"), { target: { value: fee } });
await waitFor(() => expect(getByTestId("InputCurrency")).toHaveValue(fee));
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Review Step
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Fee warning
await waitFor(() => expect(getByTestId("FeeWarning__continue-button")).toBeTruthy());
fireEvent.click(getByTestId("FeeWarning__continue-button"));
// Auth Step
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Summary Step (skip ledger confirmation for now)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
// Go back to wallet
const pushSpy = jest.spyOn(history, "push");
fireEvent.click(getByTestId("StepNavigation__back-to-wallet-button"));
expect(pushSpy).toHaveBeenCalledWith(`/profiles/${profile.id()}/wallets/${wallet.id()}`);
pushSpy.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
});
it("should error if wrong mnemonic", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address());
// Amount
fireEvent.click(getByTestId("AddRecipient__send-all"));
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"), { timeout: 4000 });
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
expect(getByTestId("Input__memo")).toHaveValue("test memo");
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Review Step
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
// Auth Step
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled();
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: MNEMONICS[0] } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(MNEMONICS[0]));
expect(getByTestId("StepNavigation__send-button")).toBeDisabled();
await waitFor(() => expect(getByTestId("Input__error")).toBeVisible());
expect(getByTestId("Input__error")).toHaveAttribute(
"data-errortext",
"This mnemonic does not correspond to your wallet",
);
expect(container).toMatchSnapshot();
});
it("should show error step and go back", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address());
// Amount
fireEvent.click(getByTestId("AddRecipient__send-all"));
await waitFor(() => expect(getByTestId("AddRecipient__amount")).not.toHaveValue("0"), { timeout: 4000 });
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
expect(getByTestId("Input__memo")).toHaveValue("test memo");
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockImplementation(() => {
throw new Error("broadcast error");
});
const historyMock = jest.spyOn(history, "push").mockReturnValue();
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("ErrorStep")).toBeInTheDocument());
expect(getByTestId("ErrorStep__errorMessage")).toHaveTextContent("broadcast error");
expect(getByTestId("ErrorStep__wallet-button")).toBeInTheDocument();
expect(getByTestId("clipboard-button__wrapper")).toBeInTheDocument();
expect(container).toMatchSnapshot();
fireEvent.click(getByTestId("ErrorStep__wallet-button"));
const walletDetailPage = `/profiles/${getDefaultProfileId()}/wallets/${getDefaultWalletId()}`;
await waitFor(() => expect(historyMock).toHaveBeenCalledWith(walletDetailPage));
broadcastMock.mockRestore();
});
it("should show fee update warning when switching transaction type", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getByTestId, getByText } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const toastSpy = jest.spyOn(toasts, "warning").mockImplementation();
fireEvent.click(getByText(transactionTranslations.MULTIPLE));
await waitFor(() => expect(toastSpy).toHaveBeenCalled());
fireEvent.click(getByText(transactionTranslations.SINGLE));
await waitFor(() => expect(toastSpy).toHaveBeenCalled());
toastSpy.mockRestore();
});
it("should send a multi payment", async () => {
nock("https://dwallets.ark.io")
.get("/api/wallets/DFJ5Z51F1euNNdRUQJKQVdG4h495LZkc6T")
.reply(200, require("tests/fixtures/coins/ark/devnet/wallets/DFJ5Z51F1euNNdRUQJKQVdG4h495LZkc6T.json"));
nock("https://dwallets.ark.io")
.get("/api/wallets/DDA5nM7KEqLeTtQKv5qGgcnc6dpNBKJNTS")
.reply(200, require("tests/fixtures/coins/ark/devnet/wallets/D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb.json"));
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, getByText } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => {
expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address());
expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel);
});
// Select multiple type
fireEvent.click(getByText(transactionTranslations.MULTIPLE));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
fireEvent.change(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
fireEvent.click(getByTestId("AddRecipient__add-button"));
await waitFor(() => expect(getAllByTestId("recipient-list__recipient-list-item").length).toEqual(1));
// Select recipient #2
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
fireEvent.click(getByTestId("AddRecipient__add-button"));
await waitFor(() => expect(getAllByTestId("recipient-list__recipient-list-item").length).toEqual(2));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.1");
// Step 2
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
const passwordInput = getByTestId("AuthenticationStep__mnemonic");
fireEvent.input(passwordInput, { target: { value: passphrase } });
await waitFor(() => expect(passwordInput).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const coin = profile.coins().set("ARK", "ark.devnet");
const coinMock = jest.spyOn(coin.address(), "validate").mockReturnValue(true);
const signMock = jest
.spyOn(wallet.transaction(), "signMultiPayment")
.mockReturnValue(Promise.resolve(transactionMultipleFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMultipleMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
coinMock.mockRestore();
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
});
it("should require amount if not set", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: " " } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveAttribute("aria-invalid"));
});
it("should send a single transfer and show unconfirmed transactions modal", async () => {
//@ts-ignore
const sentTransactionsMock = jest.spyOn(wallet.transactionIndex(), "sent").mockImplementation(() =>
Promise.resolve({
items: () => [
{
convertedTotal: () => 0,
isConfirmed: () => false,
isMultiPayment: () => false,
isSent: () => true,
isTransfer: () => true,
isUnvote: () => false,
isVote: () => false,
recipient: () => "D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb",
recipients: () => ["D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb", wallet.address()],
timestamp: () => DateTime.make(),
total: () => 1,
type: () => "transfer",
wallet: () => wallet,
},
{
convertedTotal: () => 0,
isConfirmed: () => false,
isMultiPayment: () => true,
isSent: () => true,
isTransfer: () => false,
isUnvote: () => false,
isVote: () => false,
recipient: () => "D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb",
recipients: () => ["D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb", wallet.address()],
timestamp: () => DateTime.make(),
total: () => 1,
type: () => "multiPayment",
wallet: () => wallet,
},
],
}),
);
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
const goSpy = jest.spyOn(history, "go").mockImplementation();
const backButton = getByTestId("StepNavigation__back-button");
expect(backButton).not.toHaveAttribute("disabled");
fireEvent.click(backButton);
expect(goSpy).toHaveBeenCalledWith(-1);
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getByTestId("ConfirmSendTransaction__cancel"));
await waitFor(() => expect(() => getByTestId("modal__inner")).toThrow());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
fireEvent.click(getByTestId("ConfirmSendTransaction__confirm"));
await waitFor(() => expect(() => getByTestId("modal__inner")).toThrow());
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
// Go back to wallet
const pushSpy = jest.spyOn(history, "push");
fireEvent.click(getByTestId("StepNavigation__back-to-wallet-button"));
expect(pushSpy).toHaveBeenCalledWith(`/profiles/${profile.id()}/wallets/${wallet.id()}`);
goSpy.mockRestore();
pushSpy.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
sentTransactionsMock.mockRestore();
});
it("should display unconfirmed transactions modal when submitting with Enter", async () => {
const sentTransactionsMock = jest.spyOn(wallet.transactionIndex(), "sent").mockImplementation(() =>
Promise.resolve<any>({
items: () => [
{
convertedTotal: () => 0,
isConfirmed: () => false,
isMultiPayment: () => false,
isSent: () => true,
isTransfer: () => true,
isUnvote: () => false,
isVote: () => false,
recipient: () => "D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb",
recipients: () => ["D5sRKWckH4rE1hQ9eeMeHAepgyC3cvJtwb", wallet.address()],
timestamp: () => DateTime.make(),
total: () => 1,
type: () => "transfer",
wallet: () => wallet,
},
],
}),
);
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
// select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// enter amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
// proceed to step 2
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// proceed to step 3
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
// enter mnemonic
fireEvent.input(getByTestId("AuthenticationStep__mnemonic"), { target: { value: passphrase } });
await waitFor(() => expect(getByTestId("AuthenticationStep__mnemonic")).toHaveValue(passphrase));
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
// submit form
fireEvent.submit(getByTestId("Form"));
await waitFor(() => expect(getByTestId("modal__inner")).toBeTruthy());
// confirm within the modal
fireEvent.click(getByTestId("ConfirmSendTransaction__confirm"));
await waitFor(() => expect(() => getByTestId("modal__inner")).toThrow());
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
sentTransactionsMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
});
it("should send a single transfer using wallet with encryption password", async () => {
const transferURL = `/profiles/${fixtureProfileId}/wallets/${wallet.id()}/send-transfer`;
const actsWithMnemonicMock = jest.spyOn(wallet, "actsWithMnemonic").mockReturnValue(false);
const actsWithWifWithEncryptionMock = jest.spyOn(wallet, "actsWithWifWithEncryption").mockReturnValue(true);
const wifGetMock = jest
.spyOn(wallet.wif(), "get")
.mockResolvedValue("S9rDfiJ2ar4DpWAQuaXECPTJHfTZ3XjCPv15gjxu4cHJZKzABPyV");
const history = createMemoryHistory();
history.push(transferURL);
const { getAllByTestId, getByTestId, container } = renderWithRouter(
<Route path="/profiles/:profileId/wallets/:walletId/send-transfer">
<LedgerProvider transport={getDefaultLedgerTransport()}>
<SendTransfer />
</LedgerProvider>
</Route>,
{
history,
routes: [transferURL],
},
);
await waitFor(() => expect(getByTestId("SendTransfer__form-step")).toBeTruthy());
const networkLabel = `${wallet.network().coin()} ${wallet.network().name()}`;
await waitFor(() => expect(getByTestId("SelectNetworkInput__input")).toHaveValue(networkLabel));
await waitFor(() => expect(getByTestId("SelectAddress__input")).toHaveValue(wallet.address()));
const goSpy = jest.spyOn(history, "go").mockImplementation();
const backButton = getByTestId("StepNavigation__back-button");
expect(backButton).not.toHaveAttribute("disabled");
fireEvent.click(backButton);
expect(goSpy).toHaveBeenCalledWith(-1);
// Select recipient
fireEvent.click(within(getByTestId("recipient-address")).getByTestId("SelectRecipient__select-recipient"));
expect(getByTestId("modal__inner")).toBeTruthy();
fireEvent.click(getAllByTestId("RecipientListItem__select-button")[0]);
await waitFor(() =>
expect(getByTestId("SelectDropdown__input")).toHaveValue(profile.wallets().first().address()),
);
// Amount
fireEvent.input(getByTestId("AddRecipient__amount"), { target: { value: "1" } });
await waitFor(() => expect(getByTestId("AddRecipient__amount")).toHaveValue("1"));
// Memo
fireEvent.input(getByTestId("Input__memo"), { target: { value: "test memo" } });
await waitFor(() => expect(getByTestId("Input__memo")).toHaveValue("test memo"));
// Fee
fireEvent.click(within(screen.getByTestId("InputFee")).getByText(transactionTranslations.FEES.SLOW));
await waitFor(() => expect(screen.getAllByRole("radio")[0]).toBeChecked());
expect(screen.getAllByRole("radio")[0]).toHaveTextContent("0.00357");
// Step 2
await waitFor(() => expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("SendTransfer__review-step")).toBeTruthy());
// Step 3
expect(getByTestId("StepNavigation__continue-button")).not.toBeDisabled();
fireEvent.click(getByTestId("StepNavigation__continue-button"));
await waitFor(() => expect(getByTestId("AuthenticationStep")).toBeTruthy());
fireEvent.input(getByTestId("AuthenticationStep__encryption-password"), { target: { value: "password" } });
await waitFor(() => expect(getByTestId("AuthenticationStep__encryption-password")).toHaveValue("password"));
// Step 5 (skip step 4 for now - ledger confirmation)
const signMock = jest
.spyOn(wallet.transaction(), "signTransfer")
.mockReturnValue(Promise.resolve(transactionFixture.data.id));
const broadcastMock = jest.spyOn(wallet.transaction(), "broadcast").mockResolvedValue({
accepted: [transactionFixture.data.id],
errors: {},
rejected: [],
});
const transactionMock = createTransactionMock(wallet);
await waitFor(() => expect(getByTestId("StepNavigation__send-button")).not.toBeDisabled());
fireEvent.click(getByTestId("StepNavigation__send-button"));
await waitFor(() => expect(getByTestId("TransactionSuccessful")).toBeTruthy());
await waitFor(() =>
expect(getByTestId("TransactionSuccessful")).toHaveTextContent(
"8f913b6b719e7767d49861c0aec79ced212767645cb793d75d2f1b89abb49877",
),
);
signMock.mockRestore();
broadcastMock.mockRestore();
transactionMock.mockRestore();
actsWithMnemonicMock.mockRestore();
actsWithWifWithEncryptionMock.mockRestore();
wifGetMock.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
// Go back to wallet
const pushSpy = jest.spyOn(history, "push");
fireEvent.click(getByTestId("StepNavigation__back-to-wallet-button"));
expect(pushSpy).toHaveBeenCalledWith(`/profiles/${profile.id()}/wallets/${wallet.id()}`);
goSpy.mockRestore();
pushSpy.mockRestore();
await waitFor(() => expect(container).toMatchSnapshot());
});
}); | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace mybusinessplaceactions_v1 {
export interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* My Business Place Actions API
*
* The My Business Place Actions API provides an interface for managing place action links of a location on Google.
*
* @example
* ```js
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
* ```
*/
export class Mybusinessplaceactions {
context: APIRequestContext;
locations: Resource$Locations;
placeActionTypeMetadata: Resource$Placeactiontypemetadata;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.locations = new Resource$Locations(this.context);
this.placeActionTypeMetadata = new Resource$Placeactiontypemetadata(
this.context
);
}
}
/**
* A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \}
*/
export interface Schema$Empty {}
/**
* Response message for PlaceActions.ListPlaceActionLinks.
*/
export interface Schema$ListPlaceActionLinksResponse {
/**
* If there are more place action links than the requested page size, then this field is populated with a token to fetch the next page of results.
*/
nextPageToken?: string | null;
/**
* The returned list of place action links.
*/
placeActionLinks?: Schema$PlaceActionLink[];
}
/**
* Response message for PlaceActions.ListPlaceActionTypeMetadata.
*/
export interface Schema$ListPlaceActionTypeMetadataResponse {
/**
* If the number of action types exceeded the requested page size, this field will be populated with a token to fetch the next page on a subsequent call to `placeActionTypeMetadata.list`. If there are no more results, this field will not be present in the response.
*/
nextPageToken?: string | null;
/**
* A collection of metadata for the available place action types.
*/
placeActionTypeMetadata?: Schema$PlaceActionTypeMetadata[];
}
/**
* Represents a place action link and its attributes.
*/
export interface Schema$PlaceActionLink {
/**
* Output only. The time when the place action link was created.
*/
createTime?: string | null;
/**
* Output only. Indicates whether this link can be edited by the client.
*/
isEditable?: boolean | null;
/**
* Optional. Whether this link is preferred by the merchant. Only one link can be marked as preferred per place action type at a location. If a future request marks a different link as preferred for the same place action type, then the current preferred link (if any exists) will lose its preference.
*/
isPreferred?: boolean | null;
/**
* Optional. The resource name, in the format `locations/{location_id\}/placeActionLinks/{place_action_link_id\}`. The name field will only be considered in UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting links respectively. However, it will be ignored in CreatePlaceActionLink request, where `place_action_link_id` will be assigned by the server on successful creation of a new link and returned as part of the response.
*/
name?: string | null;
/**
* Required. The type of place action that can be performed using this link.
*/
placeActionType?: string | null;
/**
* Output only. Specifies the provider type.
*/
providerType?: string | null;
/**
* Output only. The time when the place action link was last modified.
*/
updateTime?: string | null;
/**
* Required. The link uri. The same uri can be reused for different action types across different locations. However, only one place action link is allowed for each unique combination of (uri, place action type, location).
*/
uri?: string | null;
}
/**
* Metadata for supported place action types.
*/
export interface Schema$PlaceActionTypeMetadata {
/**
* The localized display name for the attribute, if available; otherwise, the English display name.
*/
displayName?: string | null;
/**
* The place action type.
*/
placeActionType?: string | null;
}
export class Resource$Locations {
context: APIRequestContext;
placeActionLinks: Resource$Locations$Placeactionlinks;
constructor(context: APIRequestContext) {
this.context = context;
this.placeActionLinks = new Resource$Locations$Placeactionlinks(
this.context
);
}
}
export class Resource$Locations$Placeactionlinks {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Creates a place action link associated with the specified location, and returns it. The request is considered duplicate if the `parent`, `place_action_link.uri` and `place_action_link.place_action_type` are the same as a previous request.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.locations.placeActionLinks.create({
* // Required. The resource name of the location where to create this place action link. `locations/{location_id\}`.
* parent: 'locations/my-location',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "createTime": "my_createTime",
* // "isEditable": false,
* // "isPreferred": false,
* // "name": "my_name",
* // "placeActionType": "my_placeActionType",
* // "providerType": "my_providerType",
* // "updateTime": "my_updateTime",
* // "uri": "my_uri"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "createTime": "my_createTime",
* // "isEditable": false,
* // "isPreferred": false,
* // "name": "my_name",
* // "placeActionType": "my_placeActionType",
* // "providerType": "my_providerType",
* // "updateTime": "my_updateTime",
* // "uri": "my_uri"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
create(
params: Params$Resource$Locations$Placeactionlinks$Create,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
create(
params?: Params$Resource$Locations$Placeactionlinks$Create,
options?: MethodOptions
): GaxiosPromise<Schema$PlaceActionLink>;
create(
params: Params$Resource$Locations$Placeactionlinks$Create,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
create(
params: Params$Resource$Locations$Placeactionlinks$Create,
options: MethodOptions | BodyResponseCallback<Schema$PlaceActionLink>,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
create(
params: Params$Resource$Locations$Placeactionlinks$Create,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
create(callback: BodyResponseCallback<Schema$PlaceActionLink>): void;
create(
paramsOrCallback?:
| Params$Resource$Locations$Placeactionlinks$Create
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$PlaceActionLink> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Placeactionlinks$Create;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Placeactionlinks$Create;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/placeActionLinks').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'POST',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$PlaceActionLink>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$PlaceActionLink>(parameters);
}
}
/**
* Deletes a place action link from the specified location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.locations.placeActionLinks.delete({
* // Required. The resource name of the place action link to remove from the location.
* name: 'locations/my-location/placeActionLinks/my-placeActionLink',
* });
* console.log(res.data);
*
* // Example response
* // {}
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
delete(
params: Params$Resource$Locations$Placeactionlinks$Delete,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
delete(
params?: Params$Resource$Locations$Placeactionlinks$Delete,
options?: MethodOptions
): GaxiosPromise<Schema$Empty>;
delete(
params: Params$Resource$Locations$Placeactionlinks$Delete,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
delete(
params: Params$Resource$Locations$Placeactionlinks$Delete,
options: MethodOptions | BodyResponseCallback<Schema$Empty>,
callback: BodyResponseCallback<Schema$Empty>
): void;
delete(
params: Params$Resource$Locations$Placeactionlinks$Delete,
callback: BodyResponseCallback<Schema$Empty>
): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
delete(
paramsOrCallback?:
| Params$Resource$Locations$Placeactionlinks$Delete
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Placeactionlinks$Delete;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Placeactionlinks$Delete;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Empty>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Empty>(parameters);
}
}
/**
* Gets the specified place action link.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.locations.placeActionLinks.get({
* // Required. The name of the place action link to fetch.
* name: 'locations/my-location/placeActionLinks/my-placeActionLink',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "createTime": "my_createTime",
* // "isEditable": false,
* // "isPreferred": false,
* // "name": "my_name",
* // "placeActionType": "my_placeActionType",
* // "providerType": "my_providerType",
* // "updateTime": "my_updateTime",
* // "uri": "my_uri"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Locations$Placeactionlinks$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Locations$Placeactionlinks$Get,
options?: MethodOptions
): GaxiosPromise<Schema$PlaceActionLink>;
get(
params: Params$Resource$Locations$Placeactionlinks$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Locations$Placeactionlinks$Get,
options: MethodOptions | BodyResponseCallback<Schema$PlaceActionLink>,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
get(
params: Params$Resource$Locations$Placeactionlinks$Get,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
get(callback: BodyResponseCallback<Schema$PlaceActionLink>): void;
get(
paramsOrCallback?:
| Params$Resource$Locations$Placeactionlinks$Get
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$PlaceActionLink> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Placeactionlinks$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Placeactionlinks$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$PlaceActionLink>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$PlaceActionLink>(parameters);
}
}
/**
* Lists the place action links for the specified location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.locations.placeActionLinks.list({
* // Optional. A filter constraining the place action links to return. The response includes entries that match the filter. We support only the following filter: 1. place_action_type=XYZ where XYZ is a valid PlaceActionType.
* filter: 'placeholder-value',
* // Optional. How many place action links to return per page. Default of 10. The minimum is 1.
* pageSize: 'placeholder-value',
* // Optional. If specified, returns the next page of place action links.
* pageToken: 'placeholder-value',
* // Required. The name of the location whose place action links will be listed. `locations/{location_id\}`.
* parent: 'locations/my-location',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "placeActionLinks": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Locations$Placeactionlinks$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Locations$Placeactionlinks$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListPlaceActionLinksResponse>;
list(
params: Params$Resource$Locations$Placeactionlinks$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Locations$Placeactionlinks$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListPlaceActionLinksResponse>,
callback: BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
): void;
list(
params: Params$Resource$Locations$Placeactionlinks$List,
callback: BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
): void;
list(
callback: BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Locations$Placeactionlinks$List
| BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListPlaceActionLinksResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListPlaceActionLinksResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Placeactionlinks$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Placeactionlinks$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/placeActionLinks').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListPlaceActionLinksResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListPlaceActionLinksResponse>(
parameters
);
}
}
/**
* Updates the specified place action link and returns it.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.locations.placeActionLinks.patch({
* // Optional. The resource name, in the format `locations/{location_id\}/placeActionLinks/{place_action_link_id\}`. The name field will only be considered in UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting links respectively. However, it will be ignored in CreatePlaceActionLink request, where `place_action_link_id` will be assigned by the server on successful creation of a new link and returned as part of the response.
* name: 'locations/my-location/placeActionLinks/my-placeActionLink',
* // Required. The specific fields to update. The only editable fields are `uri`, `place_action_type` and `is_preferred`. If the updated link already exists at the same location with the same `place_action_type` and `uri`, fails with an `ALREADY_EXISTS` error.
* updateMask: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "createTime": "my_createTime",
* // "isEditable": false,
* // "isPreferred": false,
* // "name": "my_name",
* // "placeActionType": "my_placeActionType",
* // "providerType": "my_providerType",
* // "updateTime": "my_updateTime",
* // "uri": "my_uri"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "createTime": "my_createTime",
* // "isEditable": false,
* // "isPreferred": false,
* // "name": "my_name",
* // "placeActionType": "my_placeActionType",
* // "providerType": "my_providerType",
* // "updateTime": "my_updateTime",
* // "uri": "my_uri"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
patch(
params: Params$Resource$Locations$Placeactionlinks$Patch,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
patch(
params?: Params$Resource$Locations$Placeactionlinks$Patch,
options?: MethodOptions
): GaxiosPromise<Schema$PlaceActionLink>;
patch(
params: Params$Resource$Locations$Placeactionlinks$Patch,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
patch(
params: Params$Resource$Locations$Placeactionlinks$Patch,
options: MethodOptions | BodyResponseCallback<Schema$PlaceActionLink>,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
patch(
params: Params$Resource$Locations$Placeactionlinks$Patch,
callback: BodyResponseCallback<Schema$PlaceActionLink>
): void;
patch(callback: BodyResponseCallback<Schema$PlaceActionLink>): void;
patch(
paramsOrCallback?:
| Params$Resource$Locations$Placeactionlinks$Patch
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$PlaceActionLink>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$PlaceActionLink> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Placeactionlinks$Patch;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Placeactionlinks$Patch;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'PATCH',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$PlaceActionLink>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$PlaceActionLink>(parameters);
}
}
}
export interface Params$Resource$Locations$Placeactionlinks$Create
extends StandardParameters {
/**
* Required. The resource name of the location where to create this place action link. `locations/{location_id\}`.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$PlaceActionLink;
}
export interface Params$Resource$Locations$Placeactionlinks$Delete
extends StandardParameters {
/**
* Required. The resource name of the place action link to remove from the location.
*/
name?: string;
}
export interface Params$Resource$Locations$Placeactionlinks$Get
extends StandardParameters {
/**
* Required. The name of the place action link to fetch.
*/
name?: string;
}
export interface Params$Resource$Locations$Placeactionlinks$List
extends StandardParameters {
/**
* Optional. A filter constraining the place action links to return. The response includes entries that match the filter. We support only the following filter: 1. place_action_type=XYZ where XYZ is a valid PlaceActionType.
*/
filter?: string;
/**
* Optional. How many place action links to return per page. Default of 10. The minimum is 1.
*/
pageSize?: number;
/**
* Optional. If specified, returns the next page of place action links.
*/
pageToken?: string;
/**
* Required. The name of the location whose place action links will be listed. `locations/{location_id\}`.
*/
parent?: string;
}
export interface Params$Resource$Locations$Placeactionlinks$Patch
extends StandardParameters {
/**
* Optional. The resource name, in the format `locations/{location_id\}/placeActionLinks/{place_action_link_id\}`. The name field will only be considered in UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting links respectively. However, it will be ignored in CreatePlaceActionLink request, where `place_action_link_id` will be assigned by the server on successful creation of a new link and returned as part of the response.
*/
name?: string;
/**
* Required. The specific fields to update. The only editable fields are `uri`, `place_action_type` and `is_preferred`. If the updated link already exists at the same location with the same `place_action_type` and `uri`, fails with an `ALREADY_EXISTS` error.
*/
updateMask?: string;
/**
* Request body metadata
*/
requestBody?: Schema$PlaceActionLink;
}
export class Resource$Placeactiontypemetadata {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Returns the list of available place action types for a location or country.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessplaceactions.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinessplaceactions = google.mybusinessplaceactions('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinessplaceactions.placeActionTypeMetadata.list({
* // Optional. A filter constraining the place action types to return metadata for. The response includes entries that match the filter. We support only the following filters: 1. location=XYZ where XYZ is a string indicating the resource name of a location, in the format `locations/{location_id\}`. 2. region_code=XYZ where XYZ is a Unicode CLDR region code to find available action types. If no filter is provided, all place action types are returned.
* filter: 'placeholder-value',
* // Optional. The IETF BCP-47 code of language to get display names in. If this language is not available, they will be provided in English.
* languageCode: 'placeholder-value',
* // Optional. How many action types to include per page. Default is 10, minimum is 1.
* pageSize: 'placeholder-value',
* // Optional. If specified, the next page of place action type metadata is retrieved. The `pageToken` is returned when a call to `placeActionTypeMetadata.list` returns more results than can fit into the requested page size.
* pageToken: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "placeActionTypeMetadata": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Placeactiontypemetadata$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Placeactiontypemetadata$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListPlaceActionTypeMetadataResponse>;
list(
params: Params$Resource$Placeactiontypemetadata$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Placeactiontypemetadata$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>,
callback: BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
): void;
list(
params: Params$Resource$Placeactiontypemetadata$List,
callback: BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
): void;
list(
callback: BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Placeactiontypemetadata$List
| BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListPlaceActionTypeMetadataResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListPlaceActionTypeMetadataResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Placeactiontypemetadata$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Placeactiontypemetadata$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessplaceactions.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/placeActionTypeMetadata').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: [],
pathParams: [],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListPlaceActionTypeMetadataResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListPlaceActionTypeMetadataResponse>(
parameters
);
}
}
}
export interface Params$Resource$Placeactiontypemetadata$List
extends StandardParameters {
/**
* Optional. A filter constraining the place action types to return metadata for. The response includes entries that match the filter. We support only the following filters: 1. location=XYZ where XYZ is a string indicating the resource name of a location, in the format `locations/{location_id\}`. 2. region_code=XYZ where XYZ is a Unicode CLDR region code to find available action types. If no filter is provided, all place action types are returned.
*/
filter?: string;
/**
* Optional. The IETF BCP-47 code of language to get display names in. If this language is not available, they will be provided in English.
*/
languageCode?: string;
/**
* Optional. How many action types to include per page. Default is 10, minimum is 1.
*/
pageSize?: number;
/**
* Optional. If specified, the next page of place action type metadata is retrieved. The `pageToken` is returned when a call to `placeActionTypeMetadata.list` returns more results than can fit into the requested page size.
*/
pageToken?: string;
}
} | the_stack |
import * as assert from 'assert';
import { expect } from 'chai';
import {
CompletionItemKind,
CompletionList,
TextDocument
} from 'vscode-languageserver-types';
import * as htmlLanguageService from '../../src/htmlLanguageService';
import { applyEdits } from './textEditSupport';
export interface ItemDescription {
label: string;
documentation?: string;
kind?: CompletionItemKind;
resultText?: string;
notAvailable?: boolean;
}
describe('HTML Completion', () => {
const assertCompletion = (
completions: CompletionList,
expected: ItemDescription,
document: TextDocument,
offset: number
) => {
const matches = completions.items.filter(completion => {
return completion.label === expected.label;
});
if (expected.notAvailable) {
assert.equal(
matches.length,
0,
expected.label + ' should not existing is results'
);
return;
}
assert.equal(
matches.length,
1,
expected.label +
' should only existing once: Actual: ' +
completions.items.map(c => c.label).join(', ')
);
const match = matches[0];
if (expected.documentation) {
assert.equal(match.documentation, expected.documentation);
}
if (expected.kind) {
assert.equal(match.kind, expected.kind);
}
if (expected.resultText) {
assert.equal(applyEdits(document, [match.textEdit]), expected.resultText);
}
};
const testCompletionFor = (
value: string,
expected: { count?: number; items?: ItemDescription[] },
settings?: htmlLanguageService.CompletionConfiguration
): PromiseLike<void> => {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const ls = htmlLanguageService.getLanguageService();
const document = TextDocument.create(
'test://test/test.page',
'visualforce',
0,
value
);
const position = document.positionAt(offset);
const vfDoc = ls.parseHTMLDocument(document);
const list = ls.doComplete(document, position, vfDoc, settings);
if (expected.count) {
assert.equal(list.items, expected.count);
}
if (expected.items) {
for (const item of expected.items) {
assertCompletion(list, item, document, offset);
}
}
return Promise.resolve();
};
const testTagCompletion = (value: string, expected: string): void => {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const ls = htmlLanguageService.getLanguageService();
const document = TextDocument.create(
'test://test/test.page',
'visualforce',
0,
value
);
const position = document.positionAt(offset);
const vfDoc = ls.parseHTMLDocument(document);
const actual = ls.doTagComplete(document, position, vfDoc);
assert.equal(actual, expected);
};
function run(tests: Array<PromiseLike<void>>, testDone) {
// tslint:disable-next-line:no-floating-promises
Promise.all(tests).then(
() => {
testDone();
},
error => {
testDone(error);
}
);
}
it('Complete', testDone => {
run(
[
testCompletionFor('<|', {
items: [
{ label: 'iframe', resultText: '<iframe' },
{ label: 'h1', resultText: '<h1' },
{ label: 'div', resultText: '<div' }
]
}),
testCompletionFor('< |', {
items: [
{ label: 'iframe', resultText: '<iframe' },
{ label: 'h1', resultText: '<h1' },
{ label: 'div', resultText: '<div' }
]
}),
testCompletionFor('<h|', {
items: [
{ label: 'html', resultText: '<html' },
{ label: 'h1', resultText: '<h1' },
{ label: 'header', resultText: '<header' }
]
}),
testCompletionFor('<input|', {
items: [{ label: 'input', resultText: '<input' }]
}),
testCompletionFor('<inp|ut', {
items: [{ label: 'input', resultText: '<input' }]
}),
testCompletionFor('<|inp', {
items: [{ label: 'input', resultText: '<input' }]
}),
testCompletionFor('<input |', {
items: [
{ label: 'type', resultText: '<input type="$1"' },
{ label: 'style', resultText: '<input style="$1"' },
{ label: 'onmousemove', resultText: '<input onmousemove="$1"' }
]
}),
testCompletionFor('<input t|', {
items: [
{ label: 'type', resultText: '<input type="$1"' },
{ label: 'tabindex', resultText: '<input tabindex="$1"' }
]
}),
testCompletionFor('<input t|ype', {
items: [
{ label: 'type', resultText: '<input type="$1"' },
{ label: 'tabindex', resultText: '<input tabindex="$1"' }
]
}),
testCompletionFor('<input t|ype="text"', {
items: [
{ label: 'type', resultText: '<input type="text"' },
{ label: 'tabindex', resultText: '<input tabindex="text"' }
]
}),
testCompletionFor('<input type="text" |', {
items: [
{ label: 'style', resultText: '<input type="text" style="$1"' },
{ label: 'type', resultText: '<input type="text" type="$1"' },
{ label: 'size', resultText: '<input type="text" size="$1"' }
]
}),
testCompletionFor('<input type="text" s|', {
items: [
{ label: 'style', resultText: '<input type="text" style="$1"' },
{ label: 'src', resultText: '<input type="text" src="$1"' },
{ label: 'size', resultText: '<input type="text" size="$1"' }
]
}),
testCompletionFor('<input di| type="text"', {
items: [
{ label: 'disabled', resultText: '<input disabled type="text"' },
{ label: 'dir', resultText: '<input dir="$1" type="text"' }
]
}),
testCompletionFor('<input disabled | type="text"', {
items: [
{
label: 'dir',
resultText: '<input disabled dir="$1" type="text"'
},
{
label: 'style',
resultText: '<input disabled style="$1" type="text"'
}
]
}),
testCompletionFor('<input type=|', {
items: [
{ label: 'text', resultText: '<input type="text"' },
{ label: 'checkbox', resultText: '<input type="checkbox"' }
]
}),
testCompletionFor('<input type="c|', {
items: [
{ label: 'color', resultText: '<input type="color' },
{ label: 'checkbox', resultText: '<input type="checkbox' }
]
}),
testCompletionFor('<input type="|', {
items: [
{ label: 'color', resultText: '<input type="color' },
{ label: 'checkbox', resultText: '<input type="checkbox' }
]
}),
testCompletionFor('<input type= |', {
items: [
{ label: 'color', resultText: '<input type= "color"' },
{ label: 'checkbox', resultText: '<input type= "checkbox"' }
]
}),
testCompletionFor('<input src="c" type="color|" ', {
items: [
{ label: 'color', resultText: '<input src="c" type="color" ' }
]
}),
testCompletionFor('<iframe sandbox="allow-forms |', {
items: [
{
label: 'allow-modals',
resultText: '<iframe sandbox="allow-forms allow-modals'
}
]
}),
testCompletionFor('<iframe sandbox="allow-forms allow-modals|', {
items: [
{
label: 'allow-modals',
resultText: '<iframe sandbox="allow-forms allow-modals'
}
]
}),
testCompletionFor('<iframe sandbox="allow-forms all|"', {
items: [
{
label: 'allow-modals',
resultText: '<iframe sandbox="allow-forms allow-modals"'
}
]
}),
testCompletionFor('<iframe sandbox="allow-forms a|llow-modals "', {
items: [
{
label: 'allow-modals',
resultText: '<iframe sandbox="allow-forms allow-modals "'
}
]
}),
testCompletionFor('<input src="c" type=color| ', {
items: [
{ label: 'color', resultText: '<input src="c" type="color" ' }
]
}),
testCompletionFor('<div dir=|></div>', {
items: [
{ label: 'ltr', resultText: '<div dir="ltr"></div>' },
{ label: 'rtl', resultText: '<div dir="rtl"></div>' }
]
}),
testCompletionFor('<ul><|>', {
items: [
{ label: '/ul', resultText: '<ul></ul>' },
{ label: 'li', resultText: '<ul><li>' }
]
}),
testCompletionFor('<ul><li><|', {
items: [
{ label: '/li', resultText: '<ul><li></li>' },
{ label: 'a', resultText: '<ul><li><a' }
]
}),
testCompletionFor('<goo></|>', {
items: [{ label: '/goo', resultText: '<goo></goo>' }]
}),
testCompletionFor('<foo></f|', {
items: [{ label: '/foo', resultText: '<foo></foo>' }]
}),
testCompletionFor('<foo></f|o', {
items: [{ label: '/foo', resultText: '<foo></foo>' }]
}),
testCompletionFor('<foo></|fo', {
items: [{ label: '/foo', resultText: '<foo></foo>' }]
}),
testCompletionFor('<foo></ |>', {
items: [{ label: '/foo', resultText: '<foo></foo>' }]
}),
testCompletionFor('<span></ s|', {
items: [{ label: '/span', resultText: '<span></span>' }]
}),
testCompletionFor('<li><br></ |>', {
items: [{ label: '/li', resultText: '<li><br></li>' }]
}),
testCompletionFor('<li/|>', {
count: 0
}),
testCompletionFor(' <div/| ', {
count: 0
}),
testCompletionFor('<foo><br/></ f|>', {
items: [{ label: '/foo', resultText: '<foo><br/></foo>' }]
}),
testCompletionFor('<li><div/></|', {
items: [{ label: '/li', resultText: '<li><div/></li>' }]
}),
testCompletionFor('<li><br/|>', { count: 0 }),
testCompletionFor('<li><br>a/|', { count: 0 }),
testCompletionFor('<foo><bar></bar></| ', {
items: [{ label: '/foo', resultText: '<foo><bar></bar></foo> ' }]
}),
testCompletionFor(
'<div>\n <form>\n <div>\n <label></label>\n <|\n </div>\n </form></div>',
{
items: [
{
label: 'span',
resultText:
'<div>\n <form>\n <div>\n <label></label>\n <span\n </div>\n </form></div>'
},
{
label: '/div',
resultText:
'<div>\n <form>\n <div>\n <label></label>\n </div>\n </div>\n </form></div>'
}
]
}
),
testCompletionFor('<body><div><div></div></div></| >', {
items: [
{
label: '/body',
resultText: '<body><div><div></div></div></body >'
}
]
}),
testCompletionFor(['<body>', ' <div>', ' </|'].join('\n'), {
items: [
{
label: '/div',
resultText: ['<body>', ' <div>', ' </div>'].join('\n')
}
]
}),
testCompletionFor('<div><a hre|</div>', {
items: [{ label: 'href', resultText: '<div><a href="$1"</div>' }]
}),
testCompletionFor('<a><b>foo</b><|f>', {
items: [
{ label: '/a', resultText: '<a><b>foo</b></a>' },
{ notAvailable: true, label: '/f' }
]
}),
testCompletionFor('<a><b>foo</b><| bar.', {
items: [
{ label: '/a', resultText: '<a><b>foo</b></a> bar.' },
{ notAvailable: true, label: '/bar' }
]
}),
testCompletionFor('<div><h1><br><span></span><img></| </h1></div>', {
items: [
{
label: '/h1',
resultText: '<div><h1><br><span></span><img></h1> </h1></div>'
}
]
}),
testCompletionFor('<div>|', {
items: [{ label: '</div>', resultText: '<div>$0</div>' }]
}),
testCompletionFor(
'<div>|',
{
items: [{ notAvailable: true, label: '</div>' }]
},
{ hideAutoCompleteProposals: true }
)
],
testDone
);
});
it('Case sensitivity', testDone => {
run(
[
testCompletionFor('<LI></|', {
items: [
{ label: '/LI', resultText: '<LI></LI>' },
{ label: '/li', notAvailable: true }
]
}),
testCompletionFor('<lI></|', {
items: [{ label: '/lI', resultText: '<lI></lI>' }]
}),
testCompletionFor('<iNpUt |', {
items: [{ label: 'type', resultText: '<iNpUt type="$1"' }]
}),
testCompletionFor('<INPUT TYPE=|', {
items: [{ label: 'color', resultText: '<INPUT TYPE="color"' }]
}),
testCompletionFor('<dIv>|', {
items: [{ label: '</dIv>', resultText: '<dIv>$0</dIv>' }]
})
],
testDone
);
});
it('Handlebar Completion', testDone => {
run(
[
testCompletionFor(
'<script id="entry-template" type="text/x-handlebars-template"> <| </script>',
{
items: [
{
label: 'div',
resultText:
'<script id="entry-template" type="text/x-handlebars-template"> <div </script>'
}
]
}
)
],
testDone
);
});
it('Complete aria', testDone => {
const expectedAriaAttributes = [
{ label: 'aria-activedescendant' },
{ label: 'aria-atomic' },
{ label: 'aria-autocomplete' },
{ label: 'aria-busy' },
{ label: 'aria-checked' },
{ label: 'aria-colcount' },
{ label: 'aria-colindex' },
{ label: 'aria-colspan' },
{ label: 'aria-controls' },
{ label: 'aria-current' },
{ label: 'aria-describedat' },
{ label: 'aria-describedby' },
{ label: 'aria-disabled' },
{ label: 'aria-dropeffect' },
{ label: 'aria-errormessage' },
{ label: 'aria-expanded' },
{ label: 'aria-flowto' },
{ label: 'aria-grabbed' },
{ label: 'aria-haspopup' },
{ label: 'aria-hidden' },
{ label: 'aria-invalid' },
{ label: 'aria-kbdshortcuts' },
{ label: 'aria-label' },
{ label: 'aria-labelledby' },
{ label: 'aria-level' },
{ label: 'aria-live' },
{ label: 'aria-modal' },
{ label: 'aria-multiline' },
{ label: 'aria-multiselectable' },
{ label: 'aria-orientation' },
{ label: 'aria-owns' },
{ label: 'aria-placeholder' },
{ label: 'aria-posinset' },
{ label: 'aria-pressed' },
{ label: 'aria-readonly' },
{ label: 'aria-relevant' },
{ label: 'aria-required' },
{ label: 'aria-roledescription' },
{ label: 'aria-rowcount' },
{ label: 'aria-rowindex' },
{ label: 'aria-rowspan' },
{ label: 'aria-selected' },
{ label: 'aria-setsize' },
{ label: 'aria-sort' },
{ label: 'aria-valuemax' },
{ label: 'aria-valuemin' },
{ label: 'aria-valuenow' },
{ label: 'aria-valuetext' }
];
run(
[
testCompletionFor('<div |> </div >', {
items: expectedAriaAttributes
}),
testCompletionFor('<span |> </span >', {
items: expectedAriaAttributes
}),
testCompletionFor('<input |> </input >', {
items: expectedAriaAttributes
})
],
testDone
);
});
it('Settings', testDone => {
run(
[
testCompletionFor(
'<|',
{
items: [
{ label: 'ion-checkbox', notAvailable: true },
{ label: 'div' }
]
},
{ html5: true, ionic: false, angular1: false }
),
testCompletionFor(
'<input |> </input >',
{
items: [
{ label: 'ng-model', notAvailable: true },
{ label: 'type' }
]
},
{ html5: true, ionic: false, angular1: false }
)
],
testDone
);
});
it('doTagComplete', () => {
testTagCompletion('<div>|', '$0</div>');
testTagCompletion('<div>|</div>', null);
testTagCompletion('<div class="">|', '$0</div>');
testTagCompletion('<img>|', null);
testTagCompletion('<div><br></|', 'div>');
testTagCompletion('<div><br><span></span></|', 'div>');
testTagCompletion('<div><h1><br><span></span><img></| </h1></div>', 'h1>');
});
// Visualforce
//////////////
function getCompletionSuggestions(value: string): CompletionList {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const ls = htmlLanguageService.getLanguageService();
const document = TextDocument.create(
'test://test/test.page',
'visualforce',
0,
value
);
const position = document.positionAt(offset);
const vfDoc = ls.parseHTMLDocument(document);
const list = ls.doComplete(document, position, vfDoc);
return list;
}
describe('Visualforce Completions', () => {
// This list is from https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_map.htm
it('Should display basic tags', () => {
const expectedNamespaces = [
'analytics',
'apex',
'chatter',
'flow',
'ideas',
'knowledge',
'liveAgent',
'messaging',
'site',
'social',
'support',
'topic',
'wave'
];
const seenNamespaces: Map<string, boolean> = new Map<string, boolean>();
expectedNamespaces.forEach(name => seenNamespaces.set(name, false));
const completionList = getCompletionSuggestions('<|');
completionList.items.forEach(completion => {
seenNamespaces.forEach((value, name) => {
if (completion.label.match(name)) {
seenNamespaces.set(name, true);
}
});
});
seenNamespaces.forEach((value, name) => {
expect(value, `namespace ${name} was not seen`).to.be.true;
});
});
it('Should have only Visualforce attributes - no HTML attributes', () => {
// Used apex:page since it's one of the main tags
testCompletionFor('<apex:page |> </apex:page>', {
items: [
{ label: 'action' },
{ label: 'apiVersion' },
{ label: 'applyBodyTag' },
{ label: 'applyHtmlTag' },
{ label: 'cache' },
{ label: 'contentType' },
{ label: 'controller' },
{ label: 'deferLastCommandUntilReady' },
{ label: 'docType' },
{ label: 'expires' },
{ label: 'extensions' },
{ label: 'id' },
{ label: 'label' },
{ label: 'language' },
{ label: 'lightningStylesheets' },
{ label: 'manifest' },
{ label: 'name' },
{ label: 'pageStyle' },
{ label: 'readOnly' },
{ label: 'recordSetName' },
{ label: 'recordSetVar' },
{ label: 'renderAs' },
{ label: 'rendered' },
{ label: 'rendered' },
{ label: 'setup' },
{ label: 'showChat' },
{ label: 'showHeader' },
{ label: 'showQuickActionVfHeader' },
{ label: 'sidebar' },
{ label: 'standardController' },
{ label: 'standardStylesheets' },
{ label: 'tabStyle' },
{ label: 'title' },
{ label: 'wizard' },
{ label: 'ion-checkbox', notAvailable: true },
{ label: 'ng-model', notAvailable: true },
{ label: 'aria-activedescendant', notAvailable: true }
]
});
});
it('Should show true, false as attribute options automatically', () => {
testCompletionFor('<apex:page applyBodyTag="|"> </apex:page>', {
items: [{ label: 'true' }, { label: 'false' }]
});
});
});
}); | the_stack |
import React from 'react'
import Markdown from 'markdown-to-jsx'
import { useLocation, Redirect } from 'react-router-dom'
import pluralize from 'pluralize'
import formatDistanceToNow from 'date-fns/formatDistanceToNow'
import parseISO from 'date-fns/parseISO'
import Validation from '../validation/validation.jsx'
import Files from './files'
import { config } from '../../config'
import {
getUnexpiredProfile,
hasEditPermissions,
} from '../authentication/profile'
import { useCookies } from 'react-cookie'
import Comments from './comments/comments.jsx'
import {
MetaDataBlock,
ModalitiesMetaDataBlock,
BrainLifeButton,
ValidationBlock,
CloneDropdown,
DatasetHeader,
DatasetAlert,
DatasetHeaderMeta,
DatasetPage,
DatasetGitAccess,
VersionList,
DatasetTools,
} from '@openneuro/components/dataset'
import { Modal } from '@openneuro/components/modal'
import { ReadMore } from '@openneuro/components/read-more'
import { FollowDataset } from './mutations/follow'
import { StarDataset } from './mutations/star'
import EditDescriptionField from './fragments/edit-description-field.jsx'
import EditDescriptionList from './fragments/edit-description-list.jsx'
export interface DraftContainerProps {
dataset
tag?: string
}
const formatDate = dateObject =>
new Date(dateObject).toISOString().split('T')[0]
// Helper function for getting version from URL
const snapshotVersion = location => {
const matches = location.pathname.match(/versions\/(.*?)(\/|$)/)
return matches && matches[1]
}
const DraftContainer: React.FC<DraftContainerProps> = ({ dataset }) => {
const location = useLocation()
const activeDataset = snapshotVersion(location) || 'draft'
const [selectedVersion, setSelectedVersion] = React.useState(activeDataset)
const [deprecatedmodalIsOpen, setDeprecatedModalIsOpen] =
React.useState(false)
const summary = dataset.draft.summary
const description = dataset.draft.description
const datasetId = dataset.id
const numSessions =
summary && summary.sessions.length > 0 ? summary.sessions.length : 1
const dateAdded = formatDate(dataset.created)
const dateAddedDifference = formatDistanceToNow(parseISO(dataset.created))
const dateModified = formatDate(dataset.draft.modified)
const dateUpdatedDifference = formatDistanceToNow(
parseISO(dataset.draft.modified),
)
const isSnapshot = activeDataset !== 'draft'
const rootPath = isSnapshot
? `/datasets/${datasetId}/versions/${activeDataset}`
: `/datasets/${datasetId}`
//TODO deprecated needs to be added to the dataset snapshot obj and an admin needs to be able to say a version is deprecated somehow.
const isPublic = dataset.public === true
const [cookies] = useCookies()
const profile = getUnexpiredProfile(cookies)
const isAdmin = profile?.admin
const hasEdit =
hasEditPermissions(dataset.permissions, profile?.sub) || isAdmin
const hasDraftChanges =
dataset.snapshots.length === 0 ||
dataset.draft.head !==
dataset.snapshots[dataset.snapshots.length - 1].hexsha
return (
<>
{dataset.snapshots && !hasEdit && (
<Redirect
to={`/datasets/${dataset.id}/versions/${
dataset.snapshots.length &&
dataset.snapshots[dataset.snapshots.length - 1].tag
}`}
/>
)}
<DatasetPage
modality={summary?.modalities[0] || ''}
renderHeader={() => (
<>
<DatasetHeader
pageHeading={description.Name}
modality={summary?.modalities[0] || null}
renderEditor={() => (
<EditDescriptionField
datasetId={datasetId}
field="Name"
rows={2}
description={description.Name}
editMode={hasEdit}
>
{description.Name}
</EditDescriptionField>
)}
/>
</>
)}
renderAlert={() => (
<>
{hasEdit && (
<DatasetAlert
isPrivate={!dataset.public}
datasetId={dataset.id}
hasDraftChanges={hasDraftChanges}
hasSnapshot={dataset.snapshots.length !== 0}
/>
)}
</>
)}
renderHeaderMeta={() => (
<>
{summary && (
<DatasetHeaderMeta
size={summary.size}
totalFiles={summary.totalFiles}
datasetId={datasetId}
/>
)}
</>
)}
renderFollowBookmark={() => (
<>
<FollowDataset
profile={profile}
datasetId={dataset.id}
following={dataset.following}
followers={dataset.followers.length}
/>
<StarDataset
profile={profile}
datasetId={dataset.id}
starred={dataset.starred}
stars={dataset.stars.length}
/>
</>
)}
renderBrainLifeButton={() => (
<BrainLifeButton
datasetId={datasetId}
onBrainlife={dataset.onBrainlife}
/>
)}
renderValidationBlock={() => (
<ValidationBlock>
<Validation datasetId={dataset.id} issues={dataset.draft.issues} />
</ValidationBlock>
)}
renderCloneDropdown={() => (
<CloneDropdown
gitAccess={
<DatasetGitAccess
configUrl={config.url}
worker={dataset.worker}
datasetId={datasetId}
gitHash={dataset.draft.head}
/>
}
/>
)}
renderToolButtons={() => (
<DatasetTools
hasEdit={hasEdit}
isPublic={dataset.public}
isSnapshot={isSnapshot}
datasetId={datasetId}
isAdmin={isAdmin}
hasSnapshot={dataset.snapshots.length !== 0}
/>
)}
renderFiles={() => (
<ReadMore
fileTree={true}
id="collapse-tree"
expandLabel="Expand File Tree"
collapseabel="Collapse File Tree"
>
<Files
datasetId={datasetId}
snapshotTag={null}
datasetName={dataset.draft.description.Name}
files={dataset.draft.files}
editMode={hasEdit}
datasetPermissions={dataset.permissions}
/>
</ReadMore>
)}
renderReadMe={() => (
<MetaDataBlock
heading="README"
className="dataset-readme markdown-body"
item={dataset.draft.readme}
renderEditor={() => (
<EditDescriptionField
datasetId={datasetId}
field="readme"
rows={12}
description={dataset.draft.readme}
editMode={hasEdit}
>
<ReadMore
id="readme"
expandLabel="Read More"
collapseabel="Collapse"
>
<Markdown>{dataset.draft.readme || 'N/A'}</Markdown>
</ReadMore>
</EditDescriptionField>
)}
/>
)}
renderSidebar={() => (
<>
<EditDescriptionList
className="dmb-inline-list"
datasetId={datasetId}
field="Authors"
heading="Authors"
description={description.Authors}
editMode={hasEdit}
>
{description.Authors?.length ? description.Authors : ['N/A']}
</EditDescriptionList>
{summary && (
<ModalitiesMetaDataBlock
items={summary.modalities}
className="dmb-modalities"
/>
)}
<MetaDataBlock
heading={dataset.snapshots.length ? 'Versions' : 'Version'}
item={
<div className="version-block">
<VersionList
datasetId={datasetId}
hasEdit={hasEdit}
items={dataset.snapshots}
className="version-dropdown"
activeDataset={activeDataset}
dateModified={dateModified}
selected={selectedVersion}
setSelected={setSelectedVersion}
setDeprecatedModalIsOpen={setDeprecatedModalIsOpen}
/>
</div>
}
/>
{summary && (
<MetaDataBlock
heading="Tasks"
item={summary.tasks.length ? summary.tasks.join(', ') : 'N/A'}
className="dmb-inline-list"
/>
)}
{summary?.modalities.includes('pet') ||
summary?.modalities.includes('Pet') ||
(summary?.modalities.includes('PET') && (
<>
<MetaDataBlock
heading={pluralize('Target', summary.pet?.BodyPart)}
item={summary.pet?.BodyPart}
/>
<MetaDataBlock
heading={pluralize(
'Scanner Manufacturer',
summary.pet?.ScannerManufacturer,
)}
item={
summary.pet?.ScannerManufacturer
? summary.pet?.ScannerManufacturer
: 'N/A'
}
/>
<MetaDataBlock
heading={pluralize(
'Scanner Model',
summary.pet?.ScannerManufacturersModelName,
)}
item={
summary.pet?.ScannerManufacturersModelName
? summary.pet?.ScannerManufacturersModelName
: 'N/A'
}
/>
<MetaDataBlock
heading={pluralize(
'Radionuclide',
summary.pet?.TracerRadionuclide,
)}
item={
summary.pet?.TracerRadionuclide
? summary.pet?.TracerRadionuclide
: 'N/A'
}
/>
<MetaDataBlock
heading={pluralize('Radiotracer', summary.pet?.TracerName)}
item={
summary.pet?.TracerName ? summary.pet?.TracerName : 'N/A'
}
/>
</>
))}
<MetaDataBlock
heading="Uploaded by"
item={
<>
{dataset.uploader.name} on {dateAdded} - {dateAddedDifference}{' '}
ago
</>
}
/>
{dataset.snapshots?.length ? (
<MetaDataBlock
heading="Last Updated"
item={
<>
{dateModified} - {dateUpdatedDifference} ago
</>
}
/>
) : null}
<MetaDataBlock heading="Sessions" item={numSessions} />
<>
{summary && (
<MetaDataBlock
heading="Participants"
item={summary.subjects.length}
/>
)}
</>
<MetaDataBlock
heading="Dataset DOI"
item={
description.DatasetDOI ||
'Create a new snapshot to obtain a DOI for the snapshot.'
}
/>
<MetaDataBlock heading="License" item={description.License} />
<MetaDataBlock
heading="Acknowledgements"
item={description.Acknowledgements}
renderEditor={() => (
<EditDescriptionField
datasetId={datasetId}
field="Acknowledgements"
rows={2}
description={description.Acknowledgements}
editMode={hasEdit}
>
<Markdown>{description.Acknowledgements || 'N/A'}</Markdown>
</EditDescriptionField>
)}
/>
<MetaDataBlock
heading="How to Acknowledge"
item={description.HowToAcknowledge}
renderEditor={() => (
<EditDescriptionField
datasetId={datasetId}
field="HowToAcknowledge"
rows={2}
description={description.HowToAcknowledge}
editMode={hasEdit}
>
<Markdown>{description.HowToAcknowledge || 'N/A'}</Markdown>
</EditDescriptionField>
)}
/>
<EditDescriptionList
className="dmb-list"
datasetId={datasetId}
field="Funding"
heading="Funding"
description={description.Funding}
editMode={hasEdit}
>
{description.Funding?.length ? description.Funding : ['N/A']}
</EditDescriptionList>
<EditDescriptionList
className="dmb-list"
datasetId={datasetId}
field="ReferencesAndLinks"
heading="References and Links"
description={description.ReferencesAndLinks}
editMode={hasEdit}
>
{description.ReferencesAndLinks?.length
? description.ReferencesAndLinks
: ['N/A']}
</EditDescriptionList>
<EditDescriptionList
className="dmb-list"
datasetId={datasetId}
field="EthicsApprovals"
heading="Ethics Approvals"
description={description.EthicsApprovals}
editMode={hasEdit}
>
{description.EthicsApprovals?.length
? description.EthicsApprovals
: ['N/A']}
</EditDescriptionList>
</>
)}
renderDeprecatedModal={() => (
<Modal
isOpen={deprecatedmodalIsOpen}
toggle={() => setDeprecatedModalIsOpen(prevIsOpen => !prevIsOpen)}
closeText={'close'}
className="deprecated-modal"
>
<p>
You have selected a deprecated version. The author of the dataset
does not recommend this specific version.
</p>
</Modal>
)}
renderComments={() => (
<Comments
datasetId={dataset.id}
uploader={dataset.uploader}
comments={dataset.comments}
/>
)}
/>
</>
)
}
export default DraftContainer | the_stack |
import FormDesign from '@/@types/form-design';
import { Enum } from '@/config/enum';
export let basicProps: Array<FormDesign.FormControlProperty> = [
{
name: 'visible', title: '是否显示', default: true,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '控件是否在界面上显示。'
}, {
name: 'loading', title: '是否加载中', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '控件当前是否为加载中状态。'
}, {
name: 'margin', title: '外边距',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.box,
attrs: { styleName: 'margin' },
remark: '控件外边距。'
}, {
name: 'padding', title: '内边距',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.box,
attrs: { styleName: 'padding' },
remark: '控件内边距。'
}, {
name: 'tip', title: '悬浮提示',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '控件的悬浮提示。'
}, {
name: 'id', title: '控件编号', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '在页面中调用控件属性或函数使用的控件编号。',
attrs: {
'read-only': true
}
}, {
name: 'remark', title: '备注名', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}
];
/** flex子项相关属性 */
export let flexItemProps: Array<FormDesign.FormControlProperty> = [
{
name: 'order', title: '排序', default: 0,
group: Enum.FormControlPropertyGroup.flex, editor: Enum.FormControlPropertyEditor.int,
remark: '子项的排列顺序,数值越小越靠前,默认为0。'
}, {
name: 'flexGrow', title: '放大比例', default: 0,
group: Enum.FormControlPropertyGroup.flex, editor: Enum.FormControlPropertyEditor.int,
remark: '子项的放大比例,默认为0,即如果存在剩余空间,也不放大。'
}, {
name: 'flexShrink', title: '缩小比例', default: 1,
group: Enum.FormControlPropertyGroup.flex, editor: Enum.FormControlPropertyEditor.int,
remark: '子项的的缩小比例,默认为1,即如果空间不足,该项目将缩小。'
}, {
name: 'flexBasis', title: '基础空间', default: 'auto',
group: Enum.FormControlPropertyGroup.flex, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '定义了在分配多余空间之前,项目占据的主轴空间。'
}, {
name: 'alignSelf', title: '独立对齐方式', default: 'auto',
group: Enum.FormControlPropertyGroup.flex, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '自动 Auto', value: 'auto' },
{ title: '头部对齐 FlexStart', value: 'flex-start' },
{ title: '尾部对齐 FlexEnd', value: 'flex-end' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '占满高度 Stretch', value: 'stretch' },
{ title: '基线对齐 Baseline', value: 'baseline' },
] },
remark: '定义了在分配多余空间之前,项目占据的主轴空间。'
},
];
/** 表格列字段相关属性 */
export let columnItemProps: Array<FormDesign.FormControlProperty> = [
{
name: 'title', title: '列标题', default: '标签',
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '表格列头部显示的文字标题。'
}, {
name: 'width', title: '列宽度',
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.pixel,
}, {
name: 'fixed', title: '是否冻结', default: false,
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'dataIndex', title: '字段名', default: '',
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.singerLine,
}, {
name: 'sorter', title: '允许排序', default: false,
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'onlyText', title: '仅文本', default: false,
group: Enum.FormControlPropertyGroup.childform, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '组件内容是否展示为纯文本。'
}
];
/** 表单项相关属性 */
export let formItemProps: Array<FormDesign.FormControlProperty> = [
{
name: 'colon', title: '是否显示冒号', default: true,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.boolean,
remark: '配合 label 属性使用,表示是否显示 label 后面的冒号。'
}, {
name: 'extra', title: '额外提示信息', default: '',
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.multiLine,
remark: '额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。'
}, {
name: 'help', title: '提示信息', default: '',
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '提示信息,如不设置,则会根据校验规则自动生成。'
}, {
name: 'label', title: '标签文本', default: '标签',
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '控件左侧标签文本。'
}, {
name: 'labelSpan', title: '标签占用列数', default: 5,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.int,
remark: '左侧标签占用的列数,最大值24。', attrs: { min: 0, max: 24 }
}, {
name: 'labelOffset', title: '标签右移列数', default: 1,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.int,
remark: '左侧标签在左侧填充的空白列数,最大值24。', attrs: { min: 0, max: 24 }
}, {
name: 'wrapperSpan', title: '内容占用列数', default: 18,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.int,
remark: '右侧控件占用的列数,最大值24。', attrs: { min: 0, max: 24 }
}, {
name: 'wrapperOffset', title: '内容右移列数', default: 0,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.int,
remark: '右侧控件在左侧填充的空白列数,最大值24。', attrs: { min: 0, max: 24 }
}, {
name: 'required', title: '是否必填', default: false,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '是否必填,如不设置,则会根据校验规则自动生成。'
}, {
name: 'onlyText', title: '仅文本', default: false,
group: Enum.FormControlPropertyGroup.form, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '组件内容是否展示为纯文本。'
}
];
export const formControls: Array<FormDesign.FormControl> = [
/**
* 弹出框
*/
{
id: '',
control: {
control: 'a-modal',
isMain: false,
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'dialog',
title: '弹出框',
type: Enum.FormControlType.hidden,
propertys: [
{
name: 'visible', title: '是否显示', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'width', title: '宽度', default: 'auto', remark: '可用像素宽度或百分比宽度。',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}
],
events: [
]
},
/**
* 抽屉
*/
{
id: '',
control: {
control: 'a-drawer',
isMain: false,
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'drawer',
title: '抽屉',
type: Enum.FormControlType.hidden,
propertys: [
{
name: 'visible', title: '是否显示', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'width', title: '宽度', default: 'auto', remark: '可用像素宽度或百分比宽度。',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'height', title: '高度', default: 'auto', remark: '',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'placement', title: '抽屉方向', default: 'right', remark: '',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: {
options: [
{ title: '上方 Top', value: 'top' },
{ title: '右侧 Right', value: 'right' },
{ title: '下方 Bottom', value: 'bottom' },
{ title: '左侧 Left', value: 'left' }
]
}
}
],
events: [
]
},
/**
* 高级子表单
*/
{
id: '',
control: {
control: 'antd-form-design-complex-childform',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'complex-childform',
icon: '',
title: '高级子表单',
autoPrefix: 'childform',
type: Enum.FormControlType.layout,
children: [ [] ],
childrenSlot: '.complex-child-form',
isOriginal: true,
propertys: [
{
name: 'bordered', title: '边框', default: false, remark: '是否展示表格的外边框和列边框',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'scrollX', title: '固定宽度', remark: '用于设置表格宽度,如果需要表格具有一定的宽度并且具有横向滚动条时可设置',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'scrollY', title: '固定高度', remark: '用于设置表格高度,如果需要表格具有一定的高度并且具有纵向滚动条时可设置',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'rowKey', title: '主键', default: 'id',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'dataSource', title: '数据源', default: '', isSync: true,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable,
attach: [
Enum.FormControlPropertyEditor.expression,
Enum.FormControlPropertyEditor.basicData,
Enum.FormControlPropertyEditor.viewData,
Enum.FormControlPropertyEditor.api
],
attrs: { style: { height: '200px' } }
// change(prop, propMap, control, value, refs) {
// // propMap['view-data'].visible = value == JSON.parse(value);
// }
}
],
events: [
{ name: '', title: '', remark: '' },
],
render(control) {
const _getCol = (child, index) => {
return `<a-table-column title="${child.control.attrs.title}" dataIndex="${child.control.attrs.dataIndex}" key="${child.control.attrs.dataIndex}">
<template slot-scope="text, record, index">
{{children_${index}}}
</template>
</a-table-column>`;
};
return `<task-detail-table {{attrs}}>
${this.children?.flat(2).map((i, index) => _getCol(i, index)).join('\n')}
</task-detail-table>`;
}
},
/**
* Flex布局
*/
{
id: '',
control: {
control: 'antd-form-design-control-flex',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
type: 'flex'
}
},
name: 'flex',
icon: '',
title: 'Flex布局',
autoPrefix: 'flex',
type: Enum.FormControlType.layout,
children: [ [] ],
childrenSlot: '.form-flex',
isOriginal: true,
propertys: [
{
name: 'flexDirection', title: '主轴方向', default: 'row',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '行 Row', value: 'row' },
{ title: '行逆序 RowReverse', value: 'row-reverse' },
{ title: '列 Column', value: 'column' },
{ title: '列逆序 ColumnReverse', value: 'column-reverse' }
] }
}, {
name: 'flexWrap', title: '换行规则', default: 'nowrap',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '不换行 Nowrap', value: 'nowrap' },
{ title: '换行 Wrap', value: 'wrap' },
{ title: '换行逆序 WrapReverse', value: 'wrap-reverse' }
] }
}, {
name: 'justifyContent', title: '主轴对齐方式', default: 'flex-start',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '头部对齐 FlexStart', value: 'flex-start' },
{ title: '尾部对齐 FlexEnd', value: 'flex-end' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '两端对齐 SpaceBetween', value: 'space-between' },
{ title: '分布对齐 SpaceAround', value: 'space-around' }
] }
}, {
name: 'alignItems', title: '交叉轴对齐方式', default: 'stretch',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '头部对齐 FlexStart', value: 'flex-start' },
{ title: '尾部对齐 FlexEnd', value: 'flex-end' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '占满高度 Stretch', value: 'stretch' },
{ title: '基线对齐 Baseline', value: 'baseline' },
] }
}, {
name: 'alignContent', title: '多轴线对齐方式', default: 'stretch',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '头部对齐 FlexStart', value: 'flex-start' },
{ title: '尾部对齐 FlexEnd', value: 'flex-end' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '两端对齐 SpaceBetween', value: 'space-between' },
{ title: '分布对齐 SpaceAround', value: 'space-around' },
{ title: '占满高度 Stretch', value: 'stretch' },
], allowClear: false }
}
],
events: [
]
},
/**
* 栅格
*/
{
id: '',
control: {
control: 'antd-form-design-control-row',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
type: 'flex'
}
},
name: 'row',
icon: '',
title: '栅格',
autoPrefix: 'row',
type: Enum.FormControlType.layout,
children: [ [], [] ],
childrenSlot: '.ant-col',
isOriginal: true,
propertys: [
{
name: 'gutter', title: '列间距', default: 0,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'tag', title: '元素标签', default: 'div',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'justify', title: '水平对齐方式', default: 'start',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '左侧对齐 Start', value: 'start' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '右侧对齐 End', value: 'end' },
{ title: '完全分散 SpaceAround', value: 'space-around' },
{ title: '居中分散 SpaceBetween', value: 'space-between' }
] }
}, {
name: 'align', title: '垂直对齐方式', default: 'top',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '顶部对齐 Top', value: 'top' },
{ title: '居中对齐 Center', value: 'center' },
{ title: '底部对齐 Bottom', value: 'bottom' },
] }
}, {
name: 'options', title: '子栅格', default: [
{ span: 12, offset: 0 },
{ span: 12, offset: 0 },
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attrs: {
columns: [
{ name: 'span', title: '栅格大小', editor: Enum.FormControlPropertyEditor.int, attrs: { max: 24, min: 0 } },
{ name: 'offset', title: '左位移', editor: Enum.FormControlPropertyEditor.int, attrs: { max: 24, min: 0 } },
],
onRemove: (value, index, control) => !control?.children?.[index]?.length,
onChange(control, index, removeCount, insertCount) {
[].splice.apply(control.children, [index, removeCount].concat(new Array(insertCount).fill([])) as [number, number, ...never[]])
}
}
}
],
events: [
],
render() {
let _options = this.control.attrs.options.map((item, index) => `
<a-col :span="${item.span}" :offset="${item.offset}">
{{children_${index}}}
</a-col>`).join('\n');
return `<a-row {{attrs}}>\n${_options}\n</a-row>`;
}
},
/**
* 标签页
*/
{
id: '',
control: {
control: 'antd-form-design-control-tabs',
attrs: {},
propAttrs: {},
events: {},
slot: {},
defaultAttrs: {}
},
name: 'tabs',
title: '标签页',
autoPrefix: 'tabs',
type: Enum.FormControlType.layout,
children: [ [], [], [] ],
childrenSlot: '.ant-tabs-tabpane',
isOriginal: true,
propertys: [
{
name: 'type', title: '样式类型', default: 'line',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '常规标签页样式', value: 'line' },
{ title: '按钮组样式', value: 'card' },
{ title: '可编辑按钮组样式', value: 'editable-card' }
] }
}, {
name: 'tabBarGutter', title: '标签间隙', default: 0,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'size', title: '大小', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '大号', value: 'large' },
{ title: '中号', value: 'default' },
{ title: '小号', value: 'small' }
] }
}, {
name: 'animated', title: '使用动画切换', default: true,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'tabPosition', title: '页签位置', default: 'top',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '上方', value: 'top' },
{ title: '右侧', value: 'right' },
{ title: '下方', value: 'bottom' },
{ title: '左侧', value: 'left' }
] }
}, {
name: 'hideAdd', title: '隐藏加号图标', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'model', title: '绑定变量', default: '', require: true,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'options', title: '子标签', default: [
{ title: '标签1', icon: '' },
{ title: '标签2', icon: '' },
{ title: '标签3', icon: '' },
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attrs: {
rowKey: 'title',
columns: [
{ name: 'icon', width: '30%', title: '图标', editor: Enum.FormControlPropertyEditor.icon, attrs: { } },
{ name: 'title', width: '70%', title: '标题', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
],
onRemove: (value, index, control) => !control?.children?.[index]?.length,
onChange(control, index, removeCount, insertCount) {
[].splice.apply(control.children, [index, removeCount].concat(new Array(insertCount).fill([])) as [number, number, ...never[]])
}
},
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}
],
events: [
{ name: 'change', title: '切换面板', remark: '切换面板后的回调事件。' },
{ name: 'tabClick', title: '点击tab', remark: 'Tab被点击后的回调事件。' },
{ name: 'prevClick', title: '点击prev按钮', remark: 'Prev按钮被点击后的回调事件。' },
{ name: 'nextClick', title: '点击next按钮', remark: 'Next按钮被点击后的回调事件。' }
]
},
/**
* 折叠面板
*/
{
id: '',
control: {
control: 'antd-form-design-control-collapse',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
activeKey: [ 'a0', 'a1', 'a2' ],
value: [ 'a0', 'a1', 'a2' ]
}
},
name: 'collapse',
title: '折叠面板',
autoPrefix: 'collapse',
type: Enum.FormControlType.layout,
children: [ [], [], [] ],
childrenSlot: '.ant-collapse-content-box',
isOriginal: true,
propertys: [
{
name: 'bordered', title: '边框', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'accordion', title: '手风琴模式', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
change(prop, propMap, control, value, refs) {
if (!value) {
control[0].control.attrs.value = [
control[0].control.attrs['value']
];
}
}
}, {
name: 'model', title: '绑定变量', default: '', require: true, type: 'Array<string>',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'options', title: '子面板', default: [
{ title: '标题1', icon: '' },
{ title: '标题2', icon: '' },
{ title: '标题3', icon: '' },
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attrs: {
rowKey: 'title',
columns: [
{ name: 'icon', width: '30%', title: '图标', editor: Enum.FormControlPropertyEditor.icon, attrs: { } },
{ name: 'title', width: '70%', title: '标题', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
],
onRemove: (value, index, control) => !control?.children?.[index]?.length,
onChange(control, index, removeCount, insertCount) {
[].splice.apply(control.children, [index, removeCount].concat(new Array(insertCount).fill([])) as [number, number, ...never[]])
}
},
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}
],
events: [
]
},
/**
* 卡片
*/
{
id: '',
control: {
control: 'antd-form-design-control-card',
attrs: {},
events: {},
propAttrs: {},
slot: {
default: [
{
control: 'form-design-blank-control',
attrs: {},
events: {},
propAttrs: {},
slot: {}
}
]
},
defaultAttrs: {}
},
name: 'card',
title: '卡片',
autoPrefix: 'card',
type: Enum.FormControlType.layout,
children: [ [] ],
childrenSlot: '.ant-card-body',
isOriginal: true,
propertys: [
{
name: 'title', title: '区域标题', default: '卡片',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'border', title: '边框', default: true,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'hoverable', title: '鼠标移过可浮起', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}
],
events: [
]
},
/**
* 单行文本框
*/
{
id: '',
control: {
control: 'a-input',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'textbox',
title: '单行文本框',
autoPrefix: 'textbox',
type: Enum.FormControlType.input,
isFormItem: true,
propertys: [
{
name: 'type', title: '文本框类型', default: 'text',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '文本 Text', value: 'text' },
{ title: '密码 Password', value: 'password' },
{ title: '电话 Tel', value: 'tel' },
{ title: 'URL地址', value: 'url' }
] }
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}, {
name: 'prefix', title: '前缀',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'suffix', title: '后缀',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'placeholder', title: '占位提示文字',
group: Enum.FormControlPropertyGroup.style, default: '请输入', editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'maxlength', title: '最大输入字数',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '是否只读', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'allowClear', title: '启用清除', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'defaultValue', title: '默认值', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
remark: '文本框控件默认值。'
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.text }
}, {
name: 'model', title: '绑定变量', type: 'string',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
{ name: 'change', title: '内容变换', remark: '输入框内容变化时的回调事件。' },
{ name: 'pressEnter', title: '按下回车', remark: '在输入框焦点时按下回车时的回调事件。' },
],
// render() {
// if (this.control.attrs.label) {
// let _attrs = this.control.attrs;
// return `<form-control label="${_attrs.label}" :colon="false" :label-col="{ span: ${_attrs.labelSpan}, offset: ${_attrs.labelOffset} }" :wrapper-col="{ span: ${_attrs.wrapperSpan}, offset: ${_attrs.wrapperOffset} }">
// <span class="control-custom ant-form-text">{{${_attrs?.renderFn?.replace(/\bme\.\b/g, '')}}}</span>
// </form-control>`;
// } else {
// return `<span class="control-custom ant-form-text">{{${this.control.attrs.renderFn.replace(/\bme\.\b/g, '')}}}</span>`;
// }
// }
},
/**
* 多行文本框
*/
{
id: '',
control: {
control: 'a-textarea',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
value: ''
}
},
name: 'textarea',
autoPrefix: 'textarea',
title: '多行文本框',
type: Enum.FormControlType.input,
isFormItem: true,
propertys: [
{
name: 'placeholder', title: '占位提示文字', default: '请输入',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'type', title: '文本框类型', default: 'text',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '文本 Text', value: 'text' },
{ title: '密码 Password', value: 'password' },
{ title: '电话 Tel', value: 'tel' },
{ title: 'URL地址', value: 'url' }
] }
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}, {
name: 'rows', title: '默认显示行数',
group: Enum.FormControlPropertyGroup.style, default: 3, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'autosize', title: '自适应高度',
group: Enum.FormControlPropertyGroup.style, default: false, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'defaultValue', title: '默认值',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.multiLine,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
}, {
name: 'maxlength', title: '最大输入字数',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '是否只读', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'allowClear', title: '启用清除', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.text }
}, {
name: 'model', title: '绑定变量', type: 'string',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 数字输入框
*/
{
id: '',
control: {
control: 'a-input-number',
isMain: false,
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
style: 'width: 100%;'
}
},
name: 'input-number',
title: '数字输入框',
autoPrefix: 'number',
type: Enum.FormControlType.input,
isFormItem: true,
propertys: [
{
name: 'placeholder', title: '占位提示文字', default: '请选择',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}, {
name: 'decimalSeparator', title: '小数点',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'precision', title: '数值精度',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'max', title: '最大值',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'min', title: '最小值', default: 1,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'step', title: '步长', default: 1,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.float
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '是否只读', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.number }
}, {
name: 'model', title: '绑定变量', type: 'number',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 日期框
*/
{
id: '',
control: {
control: 'antd-form-design-control-date-picker',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
style: 'width: 100%;'
}
},
name: 'date-picker',
title: '日期框',
autoPrefix: 'datepicker',
type: Enum.FormControlType.input,
isFormItem: true,
propertys: [
{
name: 'placeholder', title: '占位提示文字',
group: Enum.FormControlPropertyGroup.style, default: '请选择日期', editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '允许编辑日期', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'allowClear', title: '是否启用清除', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.date }
}, {
name: 'model', title: '绑定变量', type: 'string',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 下拉框
*/
{
id: '',
control: {
control: 'antd-form-design-control-select',
attrs: {
style: {
width: '100%'
}
},
events: {},
propAttrs: {},
slot: {
},
defaultAttrs: {
enterButton: true
}
},
name: 'a-select',
title: '下拉框',
autoPrefix: 'data',
type: Enum.FormControlType.select,
isFormItem: true,
propertys: [
{
name: 'placeholder', title: '占位提示文字', default: '请选择',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '是否只读', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'clearable', title: '是否启用清除', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'labelField', title: '文本属性', default: 'label',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'valueField', title: '值属性', type: 'value',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.select }
}, {
name: 'model', title: '绑定变量', type: 'string | Array<string>',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}, {
name: 'options', title: '数据源', require: true, default: [], remark: '展示字段为label,值字段为value',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.json,
attach: [
Enum.FormControlPropertyEditor.variable,
Enum.FormControlPropertyEditor.expression,
Enum.FormControlPropertyEditor.basicData,
Enum.FormControlPropertyEditor.viewData,
Enum.FormControlPropertyEditor.api
]
}
],
events: [
]
},
/**
* 值选择器
*/
{
id: '',
control: {
control: 'antd-form-design-control-data-search',
attrs: {},
events: {},
propAttrs: {},
slot: {
},
defaultAttrs: {
enterButton: true
}
},
name: 'data-search',
title: '值选择器',
autoPrefix: 'data',
type: Enum.FormControlType.select,
isFormItem: true,
propertys: [
{
name: 'dialogTitle', title: '弹出框标题', default: '查询数据',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'placeholder', title: '占位提示文字', default: '请选择',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'prefix', title: '前缀',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'suffix', title: '后缀',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'read-only', title: '是否只读', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'clearable', title: '是否启用清除', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.select }
}, {
name: 'model', title: '绑定变量', type: 'string[]', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}, {
name: 'rowKey', title: '标识列字段', default: 'id', remark: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'rowTextKey', title: '文本列字段', default: 'text', remark: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'dataSource', title: '数据源', require: true, default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.json,
attach: [
Enum.FormControlPropertyEditor.variable,
Enum.FormControlPropertyEditor.expression,
Enum.FormControlPropertyEditor.basicData,
Enum.FormControlPropertyEditor.viewData,
Enum.FormControlPropertyEditor.api
]
}, {
name: 'columns', title: '表格列', default: [
{ dataIndex: 'id', title: '编号' },
{ dataIndex: 'name', title: '姓名' },
{ dataIndex: 'age', title: '年龄' },
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
attrs: {
columns: [
{
name: 'dataIndex',
title: '字段名',
width: '120px',
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'title',
title: '标题',
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'width',
title: '宽度',
width: '60px',
editor: Enum.FormControlPropertyEditor.int
}, {
name: 'align',
title: '对齐',
editor: Enum.FormControlPropertyEditor.list,
width: '60px',
attrs: {
options: [
{ title: '左', value: 'left' },
{ title: '中', value: 'center' },
{ title: '右', value: 'right' }
]
}
}
],
onRemove: (value, index, control) => !control?.children?.[index]?.length,
onChange(control, index, removeCount, insertCount) {
[].splice.apply(control.children, [index, removeCount].concat(new Array(insertCount).fill([])) as [number, number, ...never[]])
}
}
}
],
events: [
]
},
/**
* 单选框组
*/
{
id: '',
control: {
control: 'antd-form-design-control-radio-group', //van-radio-group
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'radio-group',
title: '单选框组',
autoPrefix: 'radio',
type: Enum.FormControlType.select,
isFormItem: true,
propertys: [
{
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'labelField', title: '文本属性', default: 'label',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'valueField', title: '值属性', default: 'value',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'options', title: '列表项', default: [
{ value: '1', label: '单选框 1' }
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attach: [
Enum.FormControlPropertyEditor.variable,
Enum.FormControlPropertyEditor.expression,
Enum.FormControlPropertyEditor.basicData,
Enum.FormControlPropertyEditor.viewData,
Enum.FormControlPropertyEditor.api
],
attrs: { rowKey: 'title', columns: [
{ name: 'value', width: '30%', title: '值', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
{ name: 'label', width: '40%', title: '文本', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
{ name: 'disabled', width: '30%', title: '禁用', editor: Enum.FormControlPropertyEditor.boolean, default: false, attrs: { } },
] }
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.select }
}, {
name: 'model', title: '绑定变量', type: 'string',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 复选框组
*/
{
id: '',
control: {
control: 'antd-form-design-control-checkbox-group',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'checkbox-group',
title: '复选框组',
autoPrefix: 'checkbox',
type: Enum.FormControlType.select,
isFormItem: true,
propertys: [
{
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'labelField', title: '文本属性', default: 'label',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'valueField', title: '值属性', default: 'value',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'options', title: '列表项', default: [
{ value: '1', label: '单选框 1' }
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attach: [
Enum.FormControlPropertyEditor.variable,
Enum.FormControlPropertyEditor.expression,
Enum.FormControlPropertyEditor.basicData,
Enum.FormControlPropertyEditor.viewData,
Enum.FormControlPropertyEditor.api
],
attrs: { rowKey: 'title', columns: [
{ name: 'value', width: '30%', title: '值', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
{ name: 'label', width: '40%', title: '文本', editor: Enum.FormControlPropertyEditor.singerLine, attrs: { } },
{ name: 'disabled', width: '30%', title: '禁用', editor: Enum.FormControlPropertyEditor.boolean, default: false, attrs: { } },
] }
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.select }
}, {
name: 'model', title: '绑定变量', type: 'string',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 开关
*/
{
id: '',
control: {
control: 'a-switch',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'switch',
title: '开关',
autoPrefix: 'switch',
type: Enum.FormControlType.select,
isFormItem: true,
propertys: [
{
name: 'checkedChildren', title: '选中文本',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'unCheckedChildren', title: '未选中文本',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'size', title: '尺寸', default: 'default',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通 Default', value: 'default' },
{ title: '小型 Small', value: 'small' }
] }
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ]
}, {
name: 'model', title: '绑定变量', type: 'boolean',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 上传
*/
{
id: '',
control: {
control: 'antd-form-design-control-upload',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'uploader',
title: '上传',
autoPrefix: 'uploader',
isFormItem: true,
type: Enum.FormControlType.upload,
propertys: [
{
name: 'btn-text', title: '按钮文本', default: '点击上传',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'upload-tip', title: '文字提示',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'listType', title: '文件列表样式', default: 'text',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '普通文件 Text', value: 'text' },
{ title: '图片模式 Picture', value: 'picture' },
{ title: '图片卡片 Picture-Card', value: 'picture-card' },
] }
}, {
name: 'image-fit', title: '图片裁剪模式', default: 'cover',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [
{ title: '保持宽高比,显示长边', value: 'contain' },
{ title: '保持宽高比,显示短边', value: 'cover' },
{ title: '拉伸', value: 'fill' },
{ title: '不处理', value: 'none' },
{ title: '较小处理', value: 'scale-down' }
] }
}, {
name: 'preview-size', title: '预览图尺寸', default: '80px',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'name', title: '文件参数名', default: 'file',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'accept', title: '接受文件类型', default: 'image/*',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'preview-image', title: '完成展示预览图', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'preview-full-image', title: '点击预览', default: true,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'multiple', title: '图片多选上传', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'capture', title: '图片选取模式',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [ { title: '——', value: '' }, { title: '摄像头', value: 'camera' } ] }
}, {
name: 'max-size', title: '文件大小(byte)',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'max-count', title: '文件数量',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'url', title: '上传地址',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.api,
attrs: { hasFormatter: false, hasParams: false }
}, {
name: 'result-type', title: '结果类型', default: 'file',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [ { title: '文件 File', value: 'file' }, { title: '文本 Text', value: 'text' } ] }
}, {
name: 'data', title: '附加参数', default: '(file) => {}',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.expression,
}, {
name: 'headers', title: '请求头部', default: '{}',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.expression
}, {
name: 'rules', title: '校验规则', default: [],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.rules,
attach: [ Enum.FormControlPropertyEditor.expression ],
remark: '控件值校验规则。',
attrs: { type: Enum.FormControlRuleType.upload }
}, {
name: 'model', title: '绑定变量', type: 'Array<string>',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}, {
name: 'after-read', title: '读取完成回调函数',
group: Enum.FormControlPropertyGroup.function, editor: Enum.FormControlPropertyEditor.function
}, {
name: 'before-read', title: '读取前回调函数',
group: Enum.FormControlPropertyGroup.function, editor: Enum.FormControlPropertyEditor.function
}, {
name: 'before-delete', title: '删除前回调函数',
group: Enum.FormControlPropertyGroup.function, editor: Enum.FormControlPropertyEditor.function
}
],
events: [
]
},
/**
* 自定义控件
*/
{
id: '',
control: {
control: 'antd-form-design-control-custom',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'custom',
title: '自定义控件',
autoPrefix: 'custom',
type: Enum.FormControlType.else,
isFormItem: true,
propertys: [
{
name: 'renderFn', title: 'JS表达式', default: '', remark: '使用JS构造字符串或节点,节点构造函数是h(),对应页面vue对象的变量是me。',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.javascript,
}
],
events: [
],
render() {
if (this.control.attrs.label) {
let _attrs = this.control.attrs;
return `<a-form-item label="${_attrs.label}" :colon="false" :label-col="{ span: ${_attrs.labelSpan}, offset: ${_attrs.labelOffset} }" :wrapper-col="{ span: ${_attrs.wrapperSpan}, offset: ${_attrs.wrapperOffset} }">
<span class="control-custom ant-form-text">{{${this.control.attrs.renderFn.replace(/\bme\.\b/g, '')}}}</span>
</a-form-item>`;
} else {
return `<span class="control-custom ant-form-text">{{${this.control.attrs.renderFn.replace(/\bme\.\b/g, '')}}}</span>`;
}
}
},
/**
* 分页
*/
{
id: '',
control: {
control: 'a-pagination',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
current: 0,
total: 999
}
},
name: 'pagination',
title: '分页',
autoPrefix: 'pagination',
type: Enum.FormControlType.else,
propertys: [
{
name: 'hideOnSinglePage', title: '单页时隐藏', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
}, {
name: 'simple', title: '简单模式', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean,
}, {
name: 'items-per-page', title: '每页数据条数', default: 10,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'showQuickJumper', title: '快速跳转', default: false, remark: '是否可以快速跳转至某页 ',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
}, {
name: 'showSizeChanger', title: '可变页大小', default: false, remark: '是否可以改变每页数据条数',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean,
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'model', title: '绑定变量', type: 'number',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 滑动输入条
*/
{
id: '',
control: {
control: 'a-slider',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'slider',
title: '滑动输入条',
autoPrefix: 'slider',
type: Enum.FormControlType.else,
isFormItem: true,
propertys: [
{
name: 'bar-height', title: '进度条高度', default: '2px',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'vertical', title: '是否垂直', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'dots', title: '仅为刻度值', default: false, remark: '是否只能拖拽到刻度上。',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'max', title: '最大值', default: 100,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'min', title: '最小值', default: 0,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'step', title: '步长', default: 1, remark: '步长,取值必须大于 0,并且可被 (max - min) 整除。当 marks 不为空对象时,可以设置 step 为 null,此时 Slider 的可选值仅有 marks 标出来的部分。',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'range', title: '双滑块模式', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'defaultValue', title: '默认值',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.multiLine,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
}, {
name: 'model', title: '绑定变量', type: 'number',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 评分
*/
{
id: '',
control: {
control: 'a-rate',
isMain: false,
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'rate',
title: '评分',
type: Enum.FormControlType.else,
isFormItem: true,
propertys: [
{
name: 'count', title: '图标总数', default: 5,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.int
}, {
name: 'allowHalf', title: '允许半选', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'allowClear', title: '允许清除', default: true, remark: '是否允许再次点击后清除。',
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'disabled', title: '是否禁用', default: false,
group: Enum.FormControlPropertyGroup.action, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'model', title: '绑定变量', type: 'number',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.variable
}
],
events: [
]
},
/**
* 分割线
*/
{
id: '',
control: {
control: 'a-divider',
isMain: false,
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'divider',
title: '分割线',
type: Enum.FormControlType.else,
isOriginal: true,
propertys: [
{
name: 'text', title: '标题', default: '',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'dashed', title: '虚线', default: false,
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'orientation', title: '标题位置', default: 'left',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [ { title: '左侧 Left', value: 'left' }, { title: '居中 Center', value: '' }, { title: '右侧 Right', value: 'right' } ] }
}, {
name: 'type', title: '分割线类型', default: 'horizontal',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.list,
attrs: { options: [ { title: '水平 Horizontal', value: 'horizontal' }, { title: '垂直 Vertical', value: 'vertical' } ] }
},
],
events: [
]
},
/**
* 子表单
*/
{
id: '',
control: {
control: 'antd-form-design-childform',
attrs: {},
events: {},
propAttrs: {},
slot: {},
defaultAttrs: {
}
},
name: 'childform',
icon: '',
title: '子表单',
autoPrefix: 'childform',
type: Enum.FormControlType.else,
isOriginal: true,
propertys: [
{
name: 'bordered', title: '边框', default: false, remark: '是否展示表格的外边框和列边框',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.boolean
}, {
name: 'scrollX', title: '固定宽度', remark: '用于设置表格宽度,如果需要表格具有一定的宽度并且具有横向滚动条时可设置',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'scrollY', title: '固定高度', remark: '用于设置表格高度,如果需要表格具有一定的高度并且具有纵向滚动条时可设置',
group: Enum.FormControlPropertyGroup.style, editor: Enum.FormControlPropertyEditor.pixel
}, {
name: 'rowKey', title: '主键', default: 'id',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'columns', title: '表格列', default: [
{ dataIndex: 'id', title: '编号' },
{ dataIndex: 'name', title: '姓名' },
{ dataIndex: 'age', title: '年龄' },
],
layout: Enum.PropertyLayout.block,
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.modelList,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
attrs: {
columns: [
{
name: 'dataIndex',
title: '字段名',
width: '80px',
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'title',
title: '标题',
width: '80px',
editor: Enum.FormControlPropertyEditor.singerLine
}, {
name: 'width',
title: '宽度',
width: '50px',
editor: Enum.FormControlPropertyEditor.int
}, {
name: 'align',
title: '对齐',
editor: Enum.FormControlPropertyEditor.list,
width: '50px',
attrs: {
options: [
{ title: '左', value: 'left' },
{ title: '中', value: 'center' },
{ title: '右', value: 'right' }
]
}
}, {
name: 'colSpan',
title: '合并列数',
editor: Enum.FormControlPropertyEditor.int,
width: '60px',
attrs: { max: 99, min: 0 }
}
],
onRemove: (value, index, control) => !control?.children?.[index]?.length,
onChange(control, index, removeCount, insertCount) {
[].splice.apply(control.children, [index, removeCount].concat(new Array(insertCount).fill([])) as [number, number, ...never[]])
}
}
}, {
name: 'dataSource', title: '数据数组', default: [
{ id: '1', name: '张三', age: 20 },
{ id: '2', name: '李四', age: 21 },
{ id: '3', name: '王五', age: 22 },
],
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.json,
attach: [ Enum.FormControlPropertyEditor.variable, Enum.FormControlPropertyEditor.expression ],
attrs: { style: { height: '200px' } }
// change(prop, propMap, control, value, refs) {
// // propMap['view-data'].visible = value == JSON.parse(value);
// }
}
],
events: [
]
},
]
export function initAntDesignControls(controlList?: Array<FormDesign.FormControl>) {
if (!controlList) {
controlList = formControls;
}
let _blankPropertys: FormDesign.FormControlProperty[] = [];
let _propertys: FormDesign.FormControlProperty[] = [
{
name: 'id', title: '控件编号', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine,
remark: '在页面中调用控件属性或函数使用的控件编号。',
attrs: { readonly: true }
}, {
name: 'remark', title: '备注名', default: '',
group: Enum.FormControlPropertyGroup.data, editor: Enum.FormControlPropertyEditor.singerLine
}
];
const _getBasicProps = (control) => {
return control.type == 'hidden' ? _propertys : basicProps;
}
return controlList.map(i => ({
...i,
propertyEditors: Object.assign.apply({}, [{}].concat(_blankPropertys
.concat(_getBasicProps(i))
.concat(i.propertys)
.concat(i.isFormItem ? [...flexItemProps, ...columnItemProps, ...formItemProps] : [])
.filter(o => o.attach?.length)
.map(o => {
return {[o.name]: o.editor};
})) as [object, ...FormDesign.FormControlProperty[]]
),
control: {
...i.control,
propertys: _getBasicProps(i).concat(i.propertys).map(prop => ({
...prop,
})).concat([
]),
attrs: Object.assign.apply({}, [{}].concat(Object.entries(i.control.defaultAttrs as Record<string, any>)
.map(([key, value]) => ({[key]:value}))
.concat(
_blankPropertys
.concat(_getBasicProps(i))
.concat(i.propertys)
.concat(i.isFormItem ? [...flexItemProps, ...columnItemProps, ...formItemProps] : [])
.filter(o => o.default !== undefined)
.map(o => ({[o.name]: o.default}))
)
.concat(
Object.entries(i.control.attrs)
.map(([key, value]) => ({[key]:value}))
)) as [object, ...FormDesign.FormControlProperty[]]
)
},
propertys: [
..._getBasicProps(i),
...i.propertys
]
}))
} | the_stack |
import * as firebase from 'firebase-admin';
import * as functions from 'firebase-functions';
import { OAuth2Client } from 'google-auth-library';
import { generateToken } from '../shared';
// Put config.json file into server/ root folder.
// It should hold firebase configuration info such as
// - the project id
// - GIS OAuth client id
import * as CONFIG from '../../../config.json';
const AUTH_CODE_EXPIRY = 600; // seconds until expiry, 10 minutes
const ACCESS_TOKEN_EXPIRY = 3600; // seconds until expiry, 1 hour
const PROJECT_ID = CONFIG.project_id;
const CLIENT_ID = CONFIG.client_id;
// Audience ID for OAuth 2.0 Playground
const PLAYGROUND_ID = '407408718192.apps.googleusercontent.com';
/**
* This endpoint starts the authorization flow.
* @param client_id The ID given to the client sending the request
* @param redirect_uri The URI supplied by the client where the authorization
* code will be sent
* @param state A bookkeeping value that should be returned unchanged to the
* redirect URI
* @param scope Optional, a space-delimited set of strings
* @param response_type The string 'code' - this server only supports the
* authorization code flow
* @return Redirects the user to a sign-in page
*/
export const auth_endpoint = functions.https.onRequest(async (req, res) => {
// OAuth error response details: https://www.oauth.com/oauth2-servers/authorization/the-authorization-response/
console.log(`method: ${req.method}
client_id: ${req.query.client_id}
redirect_uri: ${req.query.redirect_uri}
state: ${req.query.state}
scope: ${req.query.scope}
response_type: ${req.query.response_type}`);
// Verify request method
if (req.method !== 'GET') {
// Only accept GET requests
res.status(405).send({
error: 'invalid_request',
error_description: 'Method not allowed'
});
return;
}
// This is ugly fix with casting client id to string
// TODO: https://github.com/firebase/firebase-functions/issues/587
const client_id = <string>req.query.client_id;
const redirect_uri = req.query.redirect_uri;
const state = req.query.state;
const scope = req.query.scope;
const response_type = req.query.response_type;
// Verify client_id
const db = firebase.app().firestore();
const snapshot = await db.collection('clients').doc(client_id).get();
if (!snapshot.exists) {
// Error if client ID is not found
res.redirect(`${redirect_uri}?error=unauthorized_client&state=${state}`);
return;
}
// Verify redirect_uri
if (snapshot.get('redirect_uri') !== redirect_uri) {
// Error if redirect_uri doesn't match
res.redirect(`${redirect_uri}?error=invalid_request&error_description=
Incorrect+or+malformed+redirect+URI&state=${state}`);
return;
}
// Verify response_type === 'code'
if (response_type !== 'code') {
// Error if response_type is not 'code'
res.redirect(`${redirect_uri}?error=unsupported_response_type
&state=${state}`);
return;
}
res.redirect(`https://${PROJECT_ID}.web.app/oauth?redirect_uri=
${redirect_uri}&client_id=${client_id}&state=${state}&scope=${scope}`);
});
/**
* This endpoint completes the authorization flow, after a user has signed in.
* @param client_id The ID given to the client sending the request, passed
* through from auth_endpoint
* @param redirect_uri The URI supplied by the client where the authorization
* code will be sent, passed through from auth_endpoint
* @param state A bookkeeping value that should be returned unchanged to the
* redirect URI, passed through from auth_endpoint
* @param scope Optional, a space-delimited set of strings, passed through
* from auth_endpoint
* @param uid The unique ID for the signed-in user
* @return Redirects to the redirect_uri with the authorization code
*/
export const auth_callback = functions.https.onRequest(async (req, res) => {
console.log(`method: ${req.method}
client_id: ${req.query.client_id}
redirect_uri: ${req.query.redirect_uri}
state: ${req.query.state}
scope: ${req.query.scope}
uid: ${req.query.uid}`);
const client_id = req.query.client_id;
const redirect_uri = req.query.redirect_uri;
const state = req.query.state;
const scope = req.query.scope;
const uid = req.query.uid;
// Generate new authentication code
const newCode = await generateToken(32, 'code');
// Store newly generated authentication code in database
try {
const db = firebase.app().firestore();
await db.collection('authcodes').add({
client_id: client_id,
user_id: uid,
scope: scope,
auth_code: newCode,
expires_in: AUTH_CODE_EXPIRY,
created_on: Date.now()
});
// Return generated authentication code if database write is successful
res.redirect(`${redirect_uri}?code=${newCode}&state=${state}`);
} catch (err) {
// Return error if database write is unsuccessful
console.error(err);
res.redirect(`${redirect_uri}?error=server_error&state=${state}`);
}
});
/**
* This endpoint returns information about a user given an access token
* @param access_token Located in the Authorization header, preceded by 'Bearer'
* @return UserInfo object with fields 'sub' and 'email'
*/
export const user_info = functions.https.onRequest(async (req, res) => {
console.log(`method: ${req.method}
auth header: ${req.headers.authorization}`);
// Verify request method
if (req.method !== 'GET' && req.method !== 'POST') {
// Only accept GET or POST requests
res.status(405).send('Method not allowed');
return;
}
const access_token = req.headers.authorization.replace('Bearer ', '');
// Verify access token
const tokensDbRef = firebase.app().firestore().collection('tokens');
const snapshot = await tokensDbRef.orderBy('created_on', 'desc')
.where('access_token', '==', access_token).get();
if (snapshot.empty) {
// Error if access token is not found
res.set('WWW-Authenticate', 'error=\'invalid_token\',' +
'error_description=\'Invalid access token\'').status(401).send();
return;
}
// Pick the newest entry in the database, probably redundant (there should
// only be one entry anyway)
const token_info = snapshot.docs[0];
const created_on = token_info.get('created_on');
const expires_in = token_info.get('expires_in');
// Check if access token is expired
if (created_on + expires_in * 1000 > Date.now()) {
const user_id = token_info.get('user_id');
const user = await firebase.auth().getUser(user_id);
// Construct response from user data
const data = {
sub: user.email,
email: user.email
};
res.status(200).send(data);
} else {
// Error if access token is expired
res.set('WWW-Authenticate', 'error=\'invalid_token\',' +
'error_description=\'Expired access token\'').status(401).send();
}
});
/**
* This endpoint handles a few different use-cases:
* 1. Exchanging an Authorization Code for Access + Refresh tokens
* 2. Exchanging a Refresh token for a new Access token
* 3. Streamlined Account Linking Check, Link, and Create requests
* @param client_id The ID given to the client sending the request
* @param client_secret The secret given to the client sending the request
* @param grant_type The type of exchange that is being requested
* @param [code] For use-case 1, the Authorization Code to exchange
* @param [refresh_token] For use-case 2, the Refresh token to exchange
* @param [intent] For use-case 3, the type of request
* @param [assertion] For use-case 3, the Google ID Token
*/
export const token_exchange = functions.https.onRequest(async (req, res) => {
// OAuth error response details: https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/
// NOTE: This log statement is for demonstrative/testing purposes only. It is
// recommended that you do not display/store the client secret in
// plaintext anywhere.
console.log(`method: ${req.method}
client_id: ${req.body.client_id}
client_secret: ${req.body.client_secret}
grant_type: ${req.body.grant_type}
code: ${req.body.code}
intent: ${req.body.intent}
assertion: ${req.body.assertion}`);
// OAuth error response details:
// https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/
if (req.method !== 'POST') {
// Only accept POST requests
res.status(405).send('Method not allowed');
return;
}
const client_id = req.body.client_id;
const client_secret = req.body.client_secret;
// Verify client
if(!await verifyClient(client_id, client_secret)) {
res.status(401).send({
error: 'invalid_client',
error_description: 'Invalid client ID or secret'
});
return;
}
// Split into different process based on grant type
const grant_type = req.body.grant_type;
if (grant_type === 'authorization_code') {
console.log("Authorization code exchange");
await handleAuthCodeExchange(req, res);
} else if (grant_type === 'refresh_token') {
console.log("Refresh token exchange");
await handleRefreshTokenExchange(req, res);
} else if (grant_type === 'urn:ietf:params:oauth:grant-type:jwt-bearer') {
const intent = req.body.intent;
const assertion = req.body.assertion;
let uid = '';
let email = '';
let hd = '';
let verified = false;
try {
// Using the Google ID Token: https://developers.google.com/identity/sign-in/web/backend-auth#verify-the-integrity-of-the-id-token
const client = new OAuth2Client(PROJECT_ID);
console.log(`ID Token: ${assertion}`);
const ticket = await client.verifyIdToken({
idToken: assertion,
audience: [
PROJECT_ID, CLIENT_ID, PLAYGROUND_ID
],
});
const payload = ticket.getPayload();
uid = payload['sub'];
email = payload['email'];
hd = payload['hd'];
verified = payload['email_verified'];
const iss = payload['iss'];
if (iss !== 'https://accounts.google.com') {
console.error('Invalid iss');
res.status(400).send({
error: 'invalid_grant',
error_description: 'Error with Google ID Token'
});
return;
}
const aud = payload['aud'];
if (aud !== CLIENT_ID) {
console.error('Invalid aud');
res.status(400).send({
error: 'invalid_grant',
error_description: 'Error with Google ID Token'
});
return;
}
} catch (err) {
console.error(err);
res.status(400).send({
error: 'invalid_grant',
error_description: 'Error with Google ID Token'
});
return;
}
// Split into different Streamlined Account Linking requests
if (intent === 'check') {
console.log("Streamlined Account Linking - Check request");
await handleStreamlinedCheck(uid, email, hd, verified, res);
} else if (intent === 'get') {
console.log("Streamlined Account Linking - Link request");
try {
const user = await firebase.auth().getUserByEmail(email);
// handleStreamlinedLinkOrCreate catches all errors internally
await handleStreamlinedLinkOrCreate(user.uid, client_id, res);
} catch {
// We should only reach here if the user could not be found
res.status(401).send({
error: 'user_not_found',
error_description: 'User not found'
});
}
} else if (intent === 'create') {
console.log("Streamlined Account Linking - Create request");
try {
const user = await firebase.auth().createUser({email: email});
// handleStreamlinedLinkOrCreate catches all errors internally
await handleStreamlinedLinkOrCreate(user.uid, client_id, res);
} catch {
// We should only reach here if the user could not be created
res.status(401).send({
error: 'linking_error',
error_description: 'Could not create user'
});
}
} else {
res.status(400).send({
error: 'invalid_grant',
error_description: 'Intent not supported'
});
}
} else {
res.status(400).send({
error: 'unsupported_grant_type',
error_description: 'Grant type not supported'
});
}
});
/**
* This helper function handles use-case 1 for the Token Exchange endpoint.
* A successful response will include the new access token (access_token) and
* refresh token (refresh_token) issued to the client for the authenticated
* user, the validity lifetime of the access token in seconds (expires_in), and
* the string 'Bearer' (token_type)
* @param client_id The ID given to the client sending the request, passed
* through from token_exchange
* @param code The Authorization Code to exchange, passed through from
* token_exchange
*/
async function handleAuthCodeExchange(
req: functions.Request, res: functions.Response) {
const client_id = req.body.client_id;
const code = req.body.code;
const db = firebase.app().firestore();
// Verify authorization code
const codeSnapshot = await db.collection('authcodes')
.orderBy('created_on', 'desc')
.where('client_id', '==', client_id)
.where('auth_code', '==', code)
.get();
if (codeSnapshot.empty) {
res.status(400).send({
error: 'invalid_grant',
error_description: 'Invalid authorization code'
});
return;
}
// Pick the newest entry in the database, probably redundant (there should
// only be one entry anyway)
const code_info = codeSnapshot.docs[0];
const user_id = code_info.get('user_id');
const created_on = code_info.get('created_on');
const expires_in = code_info.get('expires_in');
// Check if token is expired
if (created_on + expires_in * 1000 < Date.now()) {
res.status(400).send({
error: 'invalid_grant',
error_description: 'Authorization code expired'
});
return;
}
// Generate tokens
const access_token = await generateToken(32, 'token');
const refresh_token = await generateToken(64, 'token');
try {
// Store in database
await db.collection('tokens').add({
client_id: client_id,
user_id: user_id,
scope: [],
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
// Return generated tokens if database write was successful
res.status(200).send({
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
refresh_token: refresh_token,
token_type: 'Bearer'
});
} catch (err) {
// Return error if database write was unsuccessful
console.error(err);
res.status(500).send(err);
}
}
/**
* This helper function handles use-case 2 for the Token Exchange endpoint.
* A successful response will include the new access token (access_token) and
* old refresh token (refresh_token) issued to the client for the authenticated
* user, the validity lifetime of the access token in seconds (expires_in), and
* the string 'Bearer' (token_type)
* @param client_id The ID given to the client sending the request, passed
* through from token_exchange
* @param refresh_token The Refresh token to exchange, passed through from
* token_exchange
*/
async function handleRefreshTokenExchange(
req: functions.Request, res: functions.Response) {
const client_id = req.body.client_id;
const refresh_token = req.body.refresh_token;
const db = firebase.app().firestore();
// Verify refresh token
const tokenSnapshot = await db.collection('tokens')
.where('client_id', '==', client_id)
.where('refresh_token', '==', refresh_token)
.get();
if (tokenSnapshot.empty) {
res.status(400).send({
error: 'invalid_grant',
error_description: 'Invalid refresh token'
});
return;
}
// Pick the newest entry in the database, probably redundant (should only be
// one entry anyway)
const token_info = tokenSnapshot.docs[0];
const user_id = token_info.get('user_id');
const scope = token_info.get('scope');
// Generate token
const access_token = await generateToken(32, 'token');
try {
// Store in database
await db.collection('tokens').add({
client_id: client_id,
user_id: user_id,
scope: scope,
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
// Return generated token if database write was successful
res.status(200).send({
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
refresh_token: refresh_token,
token_type: 'Bearer'
});
} catch (err) {
// Return error if database write was unsuccessful
console.error(err);
res.status(500).send(err);
}
}
/**
* This helper function handles the 'Check' request for use-case 3 of the Token
* Exchange endpoint.
* @param uid The requested account's UID, extracted from the Google ID Token
* in the Token Exchange endpoint
* @param email The requested account's email address, extracted from the Google
* ID Token in the Token Exchange endpoint
* @param hd The requested account's host domain, extracted from the Google ID
* Token in the Token Exchange endpoint
* @param verified The requested account's email verification status, extracted
* from the Google ID Token in the Token Exchange endpoint
* @return account_found A boolean for whether the requested account exists
*/
async function handleStreamlinedCheck(
uid: string,
email: string,
hd: string,
verified: boolean,
res: functions.Response) {
try {
// Attempt to find user via UID
await firebase.auth().getUser(uid);
// Return true if found
res.status(200).send({account_found: true});
} catch {
try {
// If not found, attempt to find user via email
await firebase.auth().getUserByEmail(email);
// Verify that Google is authoritative
if (email.endsWith('@gmail.com')) {
// If email has @gmail.com suffix, always authoritative
res.status(200).send({account_found: true});
return;
}
if (hd) {
// If host domain is populated, always authoritative
res.status(200).send({account_found: true});
return;
}
if (verified) {
// If email_verified is true, not authoritative but still trust
console.warn(`Google is not authoritative for ${email}`);
res.status(200).send({account_found: true});
return;
}
// Google is not authoritative and email is not verified
console.warn(`${email} is not verified`);
res.status(404).send({account_found: false});
return;
} catch {
// Return false if error (not found)
res.status(404).send({account_found: false});
return;
}
}
}
/**
* This helper function handles the 'Link' and 'Create' requests for use-case 3
* of the Token Exchange endpoint.
* A successful response will include the new access token (access_token) and
* old refresh token (refresh_token) issued to the client for the authenticated
* user, the validity lifetime of the access token in seconds (expires_in), and
* the string 'Bearer' (token_type)
* @param user_id The user's UID to check for, passed through from
* token_exchange. If the UID is found, perform the Link the account.
* Otherwise, create an account.
* @param client_id The ID given to the client sending the request, passed
* through from token_exchange
*/
async function handleStreamlinedLinkOrCreate(
user_id: string, client_id: string, res: functions.Response) {
const db = firebase.app().firestore();
try {
// Generate tokens
const access_token = await generateToken(32, 'token');
const refresh_token = await generateToken(64, 'token');
// Check for existing tokens db entry
const token_snapshot = await db.collection('tokens')
.where('client_id', '==', client_id)
.where('user_id', '==', user_id)
.get();
if (token_snapshot.empty) {
// Add new db entry
await db.collection('tokens').add({
client_id: client_id,
user_id: user_id,
scope: [], // TODO (nevmital@): Introduce scoping?
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
} else {
// Update db entry
await token_snapshot.docs[0].ref.set({
client_id: client_id,
user_id: user_id,
scope: [], // TODO (nevmital@): Introduce scoping?
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
}
// Return tokens if database write is successful
res.status(200).send({
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
refresh_token: refresh_token,
token_type: 'Bearer'
});
} catch (err) {
// Return linking_error if database write unsuccessful
console.log(err);
res.status(401).send({error: 'linking_error', error_description: err});
}
}
/**
* This endpoint handles revoking a Access + Refresh token pair.
* @param token The token to revoke
* @param client_id The ID given to the client that was issued the token
* @param client_secret The secret given to the client that was issued the token
*/
export const token_revocation = functions.https.onRequest(async (req, res) => {
// NOTE: This log statement is for demonstrative/testing purposes only. It is
// recommended that you do not display/store the client secret in
// plaintext anywhere.
console.log(`method: ${req.method}
client_id: ${req.body.client_id}
client_secret: ${req.body.client_secret}
token: ${req.body.token}`);
if (req.method !== 'POST') {
// Only accept POST requests
res.status(405).send('Method not allowed');
return;
}
const token = req.body.token;
const client_id = req.body.client_id;
const client_secret = req.body.client_secret;
// Verify client
if(!await verifyClient(client_id, client_secret)) {
res.status(401).send({
error: 'invalid_client',
error_description: 'Invalid client ID or secret'
});
return;
}
// Verify token length
let token_type;
if (token.length === 32) {
// Access token
token_type = 'access';
} else if (token.length === 64) {
// Refresh token
token_type = 'refresh';
} else {
// Invalid token
res.status(200).send({
error: 'invalid_grant',
error_description: 'Invalid token'
});
return;
}
// Find token in database
const db = firebase.app().firestore();
const tokenSnapshot = await db.collection('tokens')
.where(`${token_type}_token`, '==', token).get();
if (tokenSnapshot.empty) {
res.status(200).send({
error: 'invalid_grant',
error_description: `Invalid ${token_type} token`
});
return;
}
const doc = tokenSnapshot.docs[0];
if (client_id !== doc.get('client_id')) {
// Error if client secret does not match token
res.status(401).send({
error: 'invalid_client',
error_description: 'Invalid client'
});
return;
}
try {
await doc.ref.delete();
} catch (err) {
res.status(503).send({
error: 'server_error',
error_description: 'Error when deleting tokens'
});
return;
}
res.status(200).send('Token revoked!');
});
/**
* This helper function verifies that the given client_id exists and that the
* given client_secret matches the client_id.
* Returns false if the client_id doesn't exist or if the client_secret doesn't
* match, returns true otherwise.
* @param client_id The ID given to the client
* @param client_secret The secret given to the client
*/
async function verifyClient(
client_id: string, client_secret: string): Promise<boolean> {
// Get client_id from client_secret
const db = firebase.app().firestore();
const snapshot = await db.collection('clients').doc(client_id).get();
if (!snapshot.exists) {
// Error if client ID is not found
return false;
}
// Verify client_secret
if (snapshot.get('client_secret') !== client_secret) {
// Error if client secret does not match
return false;
}
return true;
} | the_stack |
import { container, injectable } from "tsyringe";
import {
CancellationToken,
Connection,
Diagnostic as LspDiagnostic,
DiagnosticSeverity,
FileChangeType,
DidChangeTextDocumentParams,
} from "vscode-languageserver";
import { TextDocument } from "vscode-languageserver-textdocument";
import { URI } from "vscode-uri";
import { ServerCancellationToken } from "../../cancellation";
import { IProgram } from "../../compiler/program";
import { GetDiagnosticsRequest } from "../../protocol";
import { Delayer } from "../../util/delayer";
import { ElmWorkspaceMatcher } from "../../util/elmWorkspaceMatcher";
import { MultistepOperation } from "../../util/multistepOperation";
import { IClientSettings } from "../../util/settings";
import { TextDocumentEvents } from "../../util/textDocumentEvents";
import { Diagnostic } from "../../compiler/diagnostics";
import { ASTProvider } from "../astProvider";
import { DiagnosticSource } from "./diagnosticSource";
import { DiagnosticsRequest } from "./diagnosticsRequest";
import { ElmLsDiagnostics } from "./elmLsDiagnostics";
import { ElmMakeDiagnostics } from "./elmMakeDiagnostics";
import { DiagnosticKind, FileDiagnostics } from "./fileDiagnostics";
import { ISourceFile } from "../../compiler/forest";
import { ElmReviewDiagnostics } from "./elmReviewDiagnostics";
import { IElmAnalyseJsonService } from "./elmAnalyseJsonService";
export interface IElmIssueRegion {
start: { line: number; column: number };
end: { line: number; column: number };
}
export interface IElmIssue {
tag: string;
overview: string;
subregion: string;
details: string;
region: IElmIssueRegion;
type: string;
file: string;
}
export interface IDiagnostic extends Omit<LspDiagnostic, "code"> {
source: DiagnosticSource;
data: {
uri: string;
code: string;
};
}
export function convertFromCompilerDiagnostic(diag: Diagnostic): IDiagnostic {
return {
message: diag.message,
source: diag.source,
severity: diag.severity,
range: diag.range,
data: {
uri: diag.uri,
code: diag.code,
},
tags: diag.tags,
};
}
export function convertToCompilerDiagnostic(diag: IDiagnostic): Diagnostic {
return {
message: diag.message,
source: diag.source,
severity: diag.severity ?? DiagnosticSeverity.Warning,
range: diag.range,
code: diag.data.code,
uri: diag.data.uri,
tags: diag.tags,
};
}
class PendingDiagnostics extends Map<string, number> {
public getOrderedFiles(): string[] {
return Array.from(this.entries())
.sort((a, b) => a[1] - b[1])
.map((a) => a[0]);
}
}
@injectable()
export class DiagnosticsProvider {
private elmMakeDiagnostics: ElmMakeDiagnostics;
private elmReviewDiagnostics: ElmReviewDiagnostics;
private elmLsDiagnostics: ElmLsDiagnostics;
private currentDiagnostics: Map<string, FileDiagnostics>;
private events: TextDocumentEvents;
private connection: Connection;
private clientSettings: IClientSettings;
private workspaces: IProgram[];
private elmWorkspaceMatcher: ElmWorkspaceMatcher<URI>;
private documentEvents: TextDocumentEvents;
private pendingRequest: DiagnosticsRequest | undefined;
private pendingDiagnostics: PendingDiagnostics;
private diagnosticsDelayer: Delayer<any>;
private diagnosticsOperation: MultistepOperation;
private changeSeq = 0;
private elmAnalyseJsonService: IElmAnalyseJsonService;
constructor() {
this.clientSettings = container.resolve("ClientSettings");
this.elmMakeDiagnostics = container.resolve(ElmMakeDiagnostics);
this.elmReviewDiagnostics = container.resolve(ElmReviewDiagnostics);
this.elmLsDiagnostics = container.resolve(ElmLsDiagnostics);
this.documentEvents = container.resolve(TextDocumentEvents);
this.connection = container.resolve("Connection");
this.events = container.resolve(TextDocumentEvents);
this.elmWorkspaceMatcher = new ElmWorkspaceMatcher((uri) => uri);
this.diagnosticsOperation = new MultistepOperation(this.connection);
this.workspaces = container.resolve("ElmWorkspaces");
this.elmAnalyseJsonService = container.resolve<IElmAnalyseJsonService>(
"ElmAnalyseJsonService",
);
const astProvider = container.resolve(ASTProvider);
this.currentDiagnostics = new Map<string, FileDiagnostics>();
this.pendingDiagnostics = new PendingDiagnostics();
this.diagnosticsDelayer = new Delayer(300);
const clientInitiatedDiagnostics =
this.clientSettings.extendedCapabilities?.clientInitiatedDiagnostics ??
false;
const disableDiagnosticsOnChange =
this.clientSettings.onlyUpdateDiagnosticsOnSave;
const handleSaveOrOpen = (d: { document: TextDocument }): void => {
const program = this.elmWorkspaceMatcher.getProgramFor(
URI.parse(d.document.uri),
);
const sourceFile = program.getSourceFile(d.document.uri);
if (!sourceFile) {
return;
}
void this.getElmMakeDiagnostics(sourceFile).then((hasElmMakeErrors) => {
if (hasElmMakeErrors) {
this.currentDiagnostics.forEach((_, uri) => {
this.updateDiagnostics(uri, DiagnosticKind.ElmReview, []);
});
} else {
void this.getElmReviewDiagnostics(sourceFile);
}
});
// If we aren't doing them on change, we need to trigger them here
if (disableDiagnosticsOnChange) {
this.updateDiagnostics(
sourceFile.uri,
DiagnosticKind.ElmLS,
this.elmLsDiagnostics.createDiagnostics(sourceFile, program),
);
}
};
this.events.on("open", handleSaveOrOpen);
this.events.on("save", handleSaveOrOpen);
this.connection.onDidChangeWatchedFiles((event) => {
const newDeleteEvents = event.changes
.filter((a) => a.type === FileChangeType.Deleted)
.map((a) => a.uri);
newDeleteEvents.forEach((uri) => {
this.deleteDiagnostics(uri);
});
});
if (clientInitiatedDiagnostics) {
this.connection.onRequest(
GetDiagnosticsRequest,
(params, cancellationToken) =>
this.getDiagnostics(params.files, params.delay, cancellationToken),
);
}
this.connection.onDidChangeConfiguration((params) => {
this.clientSettings = <IClientSettings>params.settings;
if (this.clientSettings.disableElmLSDiagnostics) {
this.currentDiagnostics.forEach((_, uri) =>
this.updateDiagnostics(uri, DiagnosticKind.ElmLS, []),
);
} else {
this.workspaces.forEach((program) => {
if (!program.getForest(false)) {
return;
}
program.getForest().treeMap.forEach((sourceFile) => {
if (sourceFile.writeable) {
this.updateDiagnostics(
sourceFile.uri,
DiagnosticKind.ElmLS,
this.elmLsDiagnostics.createDiagnostics(sourceFile, program),
);
}
});
});
}
});
if (!clientInitiatedDiagnostics && !disableDiagnosticsOnChange) {
this.requestAllDiagnostics();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
astProvider.onTreeChange(({ sourceFile, declaration }) => {
if (!clientInitiatedDiagnostics && !disableDiagnosticsOnChange) {
this.requestDiagnostics(sourceFile.uri);
}
});
this.documentEvents.on("change", (params: DidChangeTextDocumentParams) => {
this.change();
this.updateDiagnostics(
params.textDocument.uri,
DiagnosticKind.ElmReview,
[],
);
// We need to cancel the request as soon as possible
if (!clientInitiatedDiagnostics && !disableDiagnosticsOnChange) {
if (this.pendingRequest) {
this.pendingRequest.cancel();
this.pendingRequest = undefined;
}
}
});
}
public interruptDiagnostics<T>(f: () => T): T {
if (!this.pendingRequest) {
return f();
}
this.pendingRequest.cancel();
this.pendingRequest = undefined;
const result = f();
this.triggerDiagnostics();
return result;
}
public getCurrentDiagnostics(
uri: string,
kind?: DiagnosticKind,
): IDiagnostic[] {
if (kind) {
return this.currentDiagnostics.get(uri)?.getForKind(kind) ?? [];
}
return this.currentDiagnostics.get(uri)?.get() ?? [];
}
/**
* Used for tests only
*/
public forceElmLsDiagnosticsUpdate(
sourceFile: ISourceFile,
program: IProgram,
): void {
this.updateDiagnostics(
sourceFile.uri,
DiagnosticKind.ElmLS,
this.elmLsDiagnostics.createDiagnostics(sourceFile, program),
);
}
private requestDiagnostics(uri: string): void {
this.pendingDiagnostics.set(uri, Date.now());
this.triggerDiagnostics();
}
private requestAllDiagnostics(): void {
this.workspaces.forEach((program) => {
if (!program.getForest(false)) {
return;
}
program.getForest().treeMap.forEach(({ uri, writeable }) => {
if (writeable) {
this.pendingDiagnostics.set(uri, Date.now());
}
});
});
this.triggerDiagnostics();
}
private triggerDiagnostics(delay = 200): void {
const sendPendingDiagnostics = (): void => {
const orderedFiles = this.pendingDiagnostics.getOrderedFiles();
if (this.pendingRequest) {
this.pendingRequest.cancel();
this.pendingRequest.files.forEach((file) => {
if (!orderedFiles.includes(file)) {
orderedFiles.push(file);
}
});
this.pendingRequest = undefined;
}
// Add all open files to request
const openFiles = this.events.getManagedUris();
openFiles.forEach((file) => {
if (!orderedFiles.includes(file)) {
orderedFiles.push(file);
}
});
if (orderedFiles.length) {
const request = (this.pendingRequest = DiagnosticsRequest.execute(
this.getDiagnostics.bind(this),
orderedFiles,
() => {
if (request === this.pendingRequest) {
this.pendingRequest = undefined;
}
},
));
}
this.pendingDiagnostics.clear();
};
void this.diagnosticsDelayer.trigger(sendPendingDiagnostics, delay);
}
private updateDiagnostics(
uri: string,
kind: DiagnosticKind,
diagnostics: IDiagnostic[],
): void {
let didUpdate = false;
let fileDiagnostics = this.currentDiagnostics.get(uri);
if (fileDiagnostics) {
didUpdate = fileDiagnostics.update(kind, diagnostics);
} else if (diagnostics.length > 0) {
fileDiagnostics = new FileDiagnostics(uri);
fileDiagnostics.update(kind, diagnostics);
this.currentDiagnostics.set(uri, fileDiagnostics);
didUpdate = true;
}
if (didUpdate) {
const fileDiagnostics = this.currentDiagnostics.get(uri);
this.connection.sendDiagnostics({
uri,
diagnostics: fileDiagnostics ? fileDiagnostics.get() : [],
});
}
}
private deleteDiagnostics(uri: string): void {
this.currentDiagnostics.delete(uri);
this.connection.sendDiagnostics({
uri,
diagnostics: [],
});
}
private getDiagnostics(
files: string[],
delay: number,
cancellationToken: CancellationToken,
): Promise<void> {
const followMs = Math.min(delay, 200);
const serverCancellationToken = new ServerCancellationToken(
cancellationToken,
);
return new Promise((resolve) =>
this.diagnosticsOperation.startNew(
cancellationToken,
(next) => {
const seq = this.changeSeq;
let index = 0;
const goNext = (): void => {
index++;
if (files.length > index) {
next.delay(followMs, checkOne);
}
};
const checkOne = (): void => {
if (this.changeSeq !== seq) {
return;
}
const uri = files[index];
const program = this.elmWorkspaceMatcher.getProgramFor(
URI.parse(uri),
);
const sourceFile = program.getForest().getByUri(uri);
if (!sourceFile) {
goNext();
return;
}
next.immediate(() => {
this.updateDiagnostics(uri, DiagnosticKind.ElmMake, []);
this.updateDiagnostics(
uri,
DiagnosticKind.Syntactic,
program
.getSyntacticDiagnostics(sourceFile)
.map(convertFromCompilerDiagnostic),
);
if (this.changeSeq !== seq) {
return;
}
next.promise(async () => {
const diagnostics = await program.getSemanticDiagnosticsAsync(
sourceFile,
serverCancellationToken,
);
if (this.changeSeq !== seq) {
return;
}
this.updateDiagnostics(
uri,
DiagnosticKind.Semantic,
diagnostics.map(convertFromCompilerDiagnostic),
);
next.immediate(() => {
this.updateDiagnostics(
uri,
DiagnosticKind.Suggestion,
this.elmLsDiagnostics.createSuggestionDiagnostics(
sourceFile,
program,
serverCancellationToken,
),
);
if (this.changeSeq !== seq) {
return;
}
if (!this.clientSettings.disableElmLSDiagnostics) {
next.immediate(() => {
this.updateDiagnostics(
uri,
DiagnosticKind.ElmLS,
this.elmLsDiagnostics.createDiagnostics(
sourceFile,
program,
),
);
goNext();
});
} else {
goNext();
}
});
});
});
};
if (files.length > 0 && this.changeSeq === seq) {
next.delay(delay, checkOne);
}
},
resolve,
),
);
}
private async getElmMakeDiagnostics(
sourceFile: ISourceFile,
): Promise<boolean> {
const elmMakeDiagnostics = await this.elmMakeDiagnostics.createDiagnostics(
sourceFile,
);
this.resetDiagnostics(elmMakeDiagnostics, DiagnosticKind.ElmMake);
elmMakeDiagnostics.forEach((diagnostics, diagnosticsUri) => {
this.updateDiagnostics(diagnosticsUri, DiagnosticKind.Syntactic, []);
this.updateDiagnostics(diagnosticsUri, DiagnosticKind.Semantic, []);
this.updateDiagnostics(
diagnosticsUri,
DiagnosticKind.ElmMake,
diagnostics,
);
});
this.currentDiagnostics.forEach((_, uri) => {
if (!elmMakeDiagnostics.has(uri)) {
this.updateDiagnostics(uri, DiagnosticKind.ElmMake, []);
}
});
// return true if elm make returned non empty results,
// it returns `new Map([[sourceFile.uri, []]])` in case of no errors
return !(
elmMakeDiagnostics.size === 1 &&
elmMakeDiagnostics.get(sourceFile.uri)?.length === 0
);
}
private async getElmReviewDiagnostics(
sourceFile: ISourceFile,
): Promise<void> {
const elmReviewDiagnostics =
await this.elmReviewDiagnostics.createDiagnostics(sourceFile);
// remove old elm-review diagnostics
this.resetDiagnostics(elmReviewDiagnostics, DiagnosticKind.ElmReview);
// add new elm-review diagnostics
elmReviewDiagnostics.forEach((diagnostics, uri) => {
this.updateDiagnostics(uri, DiagnosticKind.ElmReview, diagnostics);
});
}
private resetDiagnostics(
diagnosticList: Map<string, IDiagnostic[]>,
diagnosticKind: DiagnosticKind,
): void {
this.currentDiagnostics.forEach((fileDiagnostics, diagnosticsUri) => {
if (
!diagnosticList.has(diagnosticsUri) &&
fileDiagnostics.getForKind(diagnosticKind).length > 0
) {
diagnosticList.set(diagnosticsUri, []);
}
});
}
private change(): void {
this.changeSeq++;
}
} | the_stack |
import { unique, isGloballyInstalled } from './util'
import { Manifest } from './manifest'
import { parseopt, die, prog, FlagSpec } from './cli'
import { PluginTarget } from './plugin'
import * as Path from 'path'
import * as fs from 'fs'
import { readfile, isDir } from './fs'
import { BuildCtx } from './ctx'
import { initPlugin, InitOptions } from './init'
import { checkForNewVersion, VersionCheckResult } from "./check-version"
async function buildPlugin(manifest :Manifest, c :BuildCtx) {
if (DEBUG) {
Object.freeze(c)
}
let p = new PluginTarget(manifest, c)
return p.build(c)
}
const baseCliOptions :FlagSpec[] = [
[["v", "verbose"], "Print additional information to stdout"],
["debug", "Print a lot of information to stdout. Implies -v"],
["version", "Print figplug version information"],
["no-check-version", "Do not check for new version"],
]
function updateBaseCliOptions(baseopt: {[k:string]:any}={}, opt: {[k:string]:any}={}) {
baseopt.debug = opt.debug || baseopt.debug
baseopt.verbose = opt.v || opt.verbose || baseopt.verbose || opt.debug || baseopt.debug
}
async function main(argv :string[]) :Promise<void> {
const [opt, args] = parseopt(argv.slice(1),
"Usage: $prog [options] <command> [<command-arg> ...]\n" +
"\n" +
"commands:\n" +
" init [<dir>] Initialize a plugin\n" +
" build [<dir>] Build a plugin\n" +
" version Print figplug version information\n" +
" help [<cmd>] Equivalent to $prog command -help\n"
,
...baseCliOptions
)
if (args.length == 0) {
die(`missing <command>. Try ${prog} -help`)
}
// normalize options (-debug implies -verbose; -v => -verbose)
opt.verbose = opt.verbose2 || opt.v || opt.verbose
let command = args[0]
if (command == "help") {
// convert "prog help command" => "prog command -help"
command = args[1]
if (!command) {
return main([argv[0], "-h"])
}
args[0] = command
args[1] = "-help"
}
if (opt.version) {
return main_version(args, opt)
}
// start version check in background
if (!DEBUG && command != "version" && !opt["no-check-version"] && isGloballyInstalled()) {
// Note: "version" command checks for version in a custom way
checkForNewVersion()
}
switch (command) {
case "init": return main_init(args, opt)
case "build": return main_build(args, opt)
case "version": return main_version(args, opt)
default: {
die(`unknown command ${repr(command)}. Try ${prog} -help`)
}
}
}
async function main_version(argv :string[], baseopt: {[k:string]:any}={}) {
const [opt, ] = parseopt(argv.slice(1),
`Usage: $prog ${argv[0]} [-v|-verbose]\n` +
"Print figplug version information."
,
...baseCliOptions.filter(f => !Array.isArray(f) || f[0] != "version")
)
updateBaseCliOptions(baseopt, opt)
opt.verbose = opt.verbose || opt.v || baseopt.verbose
print(`figplug ${VERSION}` + (VERSION_TAG ? ` (${VERSION_TAG})` : ""))
print(
`Supported Figma Plugin API versions:` +
`\n ${FIGMA_API_VERSIONS.join("\n ")}`
)
if (!opt.verbose) {
process.exit(0)
}
print(`System and library info:`)
let p = JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8"))
let nmdir = __dirname + "/../node_modules/"
let extraInfo = [
["arch", process.arch],
["platform", process.platform],
] as string[][]
for (let k of Object.keys(process.versions)) {
extraInfo.push([k, (process.versions as any)[k]])
}
let longestName = extraInfo.reduce((a, e) => Math.max(a, e[0].length), 0)
let spaces = " "
for (let [k,v] of extraInfo) {
k += spaces.substr(0, longestName - k.length)
print(` ${k} ${v}`)
}
extraInfo.splice(0, extraInfo.length)
for (let dn of Object.keys(p.dependencies)) {
try {
let p2 = JSON.parse(
fs.readFileSync(`${nmdir}/${dn}/package.json`, "utf8")
)
extraInfo.push([dn, p2.version])
} catch (_) {
extraInfo.push([dn, "(unavailable)"])
}
}
longestName = extraInfo.reduce((a, e) => Math.max(a, e[0].length), 0)
print(` deps:`)
for (let [k,v] of extraInfo) {
k += spaces.substr(0, longestName - k.length)
print(` ${k} ${v}`)
}
if (opt["no-check-version"] || !isGloballyInstalled()) {
process.exit(0)
}
if (!DEBUG) {
console.log("Checking for new version...")
switch (await checkForNewVersion()) {
case VersionCheckResult.UsingLatest:
console.log(`You are using the latest version of figplug.`)
break
case VersionCheckResult.UsingFuture:
console.log(`You are using a future, unreleased version of figplug.`)
break
case VersionCheckResult.Error:
console.log(`An error occured while checking for new version.`)
break
case VersionCheckResult.UsingOld:
break
}
}
}
async function main_init(argv :string[], baseopt: {[k:string]:any}={}) {
const [opt, args] = parseopt(argv.slice(1),
`Usage: $prog ${argv[0]} [<dir> ...]\n` +
"Initialize Figma plugins in directories provided as <dir>, or the current directory."
,
["ui", "Generate UI written in TypeScript & HTML"],
["html", "Generate UI written purely in HTML"],
["react", "Generate UI written in React"],
[["f", "force"], "Overwrite or replace existing files"],
["api", `Specify Figma Plugin API version. Defaults to "${FIGMA_API_VERSIONS[0]}".`, "<version>"],
["name", "Name of plugin. Defaults to directory name.", "<name>"],
["srcdir", "Where to put source files, relative to <dir>. Defaults to \".\".", "<dirname>"],
...baseCliOptions
)
updateBaseCliOptions(baseopt, opt)
let dirs = args.length == 0 ? ["."] : args
let baseOptions :Partial<InitOptions> = {
verbose: baseopt.verbose,
debug: baseopt.verbose2,
name: opt.name,
overwrite: !!opt.force,
srcdir: opt.srcdir as string|undefined,
apiVersion: opt.api as string|undefined,
ui: (
opt["react"] ? "react" :
opt["html"] ? "html" :
opt.ui ? "ts+html" :
undefined
),
}
let allSuccess = await Promise.all(
dirs.map(dir =>
initPlugin({ ...baseOptions, dir })
)
).then(v => v.every(r => r))
if (!allSuccess) {
console.error(
`Remove files you'd like to be re-created, `+
`or run with -force to overwrite all files.`
)
process.exit(1)
} else {
process.exit(0)
}
}
async function main_build(argv :string[], baseopt: {[k:string]:any}={}) {
const [opt, args] = parseopt(argv.slice(1),
`Usage: $prog ${argv[0]} [options] [<path> ...]\n` +
"Builds Figma plugins.\n" +
"\n" +
"<path> Path to a plugin directory or a manifest file. Defaults to \".\".\n" +
" You can optionally specify an output directory for every path through\n" +
" <path>:<outdir>. Example: src:build.\n" +
" This is useful when building multiple plugins at the same time.\n"
,
["w", "Watch sources for changes and rebuild incrementally"],
["g", "Generate debug code (assertions and DEBUG branches)."],
["O", "Generate optimized code."],
["lib", "Include a global JS library in plugin code. " +
"Can be set multiple times.", "<file>:string[]"],
["uilib", "Include a global JS library in UI code. " +
"Can be set multiple times.", "<file>:string[]"],
["clean", "Force rebuilding of everything, ignoring cache. Implied with -O."],
["nomin", "Do not minify or mangle optimized code when -O is enabled."],
["no-manifest", "Do not generate manifest.json"],
["no-source-map", "Do not generate a source map."],
["ext-source-map", "Place source map in separate file instead of inlining."],
[["o", "output"], "Write output to directory. Defaults to ./build", "<dir>"],
...baseCliOptions
)
updateBaseCliOptions(baseopt, opt)
// create build context object
const c = new BuildCtx()
c.verbose2 = baseopt.debug || c.verbose2
c.verbose = baseopt.verbose || c.verbose
c.watch = opt.w || c.watch
c.debug = opt.g || c.debug
c.optimize = opt.O || c.optimize
c.clean = opt.clean || c.clean
c.nomin = opt.nomin || c.nomin
c.outdir = opt.o || opt.outdir || c.outdir
c.libs = opt.lib || []
c.uilibs = opt.uilib || []
c.noGenManifest = !!opt["no-manifest"]
c.noSourceMap = !!opt["no-source-map"]
c.externalSourceMap = !!opt["ext-source-map"]
// set manifest locations based on CLI arguments
let manifestPaths = unique(
(args.length == 0 ? [process.cwd() + Path.sep] : args)
.map(s => Path.resolve(s))
)
// build a plugin for each input manifest location
return Promise.all(manifestPaths.map(async (path) => {
let c2 :BuildCtx = c
let i = path.indexOf(":")
if (i != -1) {
let outdir = path.substr(i+1)
path = path.substr(0, i)
c2 = new BuildCtx(c2)
c2.outdir = outdir
}
let manifest = await Manifest.load(path)
c2.version = (await findVersion(c2, manifest)) || c2.version
return buildPlugin(manifest, c2)
})).then(() => {
process.exit(0)
})
}
async function findVersion(c :BuildCtx, manifest :Manifest) :Promise<string> {
if (manifest.props.figplug && manifest.props.figplug.version) {
return manifest.props.figplug.version
}
// look for package.json
let manifestdir = Path.dirname(manifest.file)
let srcdir = Path.dirname(Path.resolve(manifestdir, manifest.props.main))
let longestUnionPath = (
manifestdir.startsWith(srcdir) ? manifestdir :
srcdir.startsWith(manifestdir) ? srcdir :
""
)
let dirs = longestUnionPath ? [ longestUnionPath ] : [ manifestdir, srcdir ]
let versionFound = ""
await Promise.all(dirs.map(async dir => {
let maxdepth = 5
while (maxdepth-- && dir != "/" && dir.indexOf(":\\") != 1 && !versionFound) {
let packageFile = Path.join(dir, "package.json")
let packageJson :{version?:string}|undefined
try {
packageJson = JSON.parse(await readfile(packageFile, "utf8"))
if (packageJson && packageJson.version) {
if (!versionFound) {
versionFound = packageJson.version
}
break
}
} catch (_) {
// ignore non-existing, unreadable or unparsable file
}
// if dir contains VCS dir, stop.
if ((await Promise.all([ ".git", ".hg", ".svn" ].map(vcsDir =>
isDir(Path.join(dir, vcsDir))
))).some(v => v)) {
break
}
dir = Path.dirname(dir)
}
}))
return versionFound
}
function onError(err :any) {
if (typeof err != "object" || !(err as any)._wasReported) {
die(err)
} else {
process.exit(1)
}
}
process.on('unhandledRejection', onError)
main(process.argv.slice(1)).catch(onError) | the_stack |
import React from 'react';
import classnames from 'classnames';
import {MDCListFoundation} from '@material/list/foundation';
import {MDCListIndex} from '@material/list/types';
import {MDCListAdapter} from '@material/list/adapter';
// @ts-ignore @types cannot be used on dist files
import memoizeOne from 'memoize-one/dist/memoize-one.cjs.js';
import ListItem, {ListItemProps} from './ListItem'; // eslint-disable-line @typescript-eslint/no-unused-vars
import ListItemGraphic from './ListItemGraphic';
import ListItemText from './ListItemText';
import ListItemMeta from './ListItemMeta';
import ListDivider from './ListDivider';
import ListGroup from './ListGroup';
import ListGroupSubheader from './ListGroupSubheader';
const HORIZONTAL = 'horizontal';
export interface ListProps extends React.HTMLProps<HTMLElement> {
className?: string;
checkboxList?: boolean;
radioList?: boolean;
nonInteractive?: boolean;
dense?: boolean;
avatarList?: boolean;
twoLine?: boolean;
singleSelection?: boolean;
selectedIndex?: MDCListIndex;
handleSelect?: (activatedItemIndex: number, selected: MDCListIndex) => void;
wrapFocus?: boolean;
tag?: string;
ref?: React.Ref<any>;
orientation?: 'vertical' | 'horizontal';
}
interface ListState {
listItemClassNames: {[listItemIndex: number]: string[]};
}
export interface ListItemContextShape {
checkboxList?: boolean;
radioList?: boolean;
handleClick?: (e: React.MouseEvent<any>, index: number) => void;
handleKeyDown?: (e: React.KeyboardEvent<any>, index: number) => void;
handleBlur?: (e: React.FocusEvent<any>, index: number) => void;
handleFocus?: (e: React.FocusEvent<any>, index: number) => void;
onDestroy?: (index: number) => void;
getListItemInitialTabIndex?: (index: number) => number;
getClassNamesFromList?: () => ListState['listItemClassNames'];
tabIndex?: number;
}
function isSelectedIndexType(
selectedIndex: unknown
): selectedIndex is MDCListIndex {
return (
(typeof selectedIndex === 'number' && !isNaN(selectedIndex)) ||
Array.isArray(selectedIndex)
);
}
export const defaultListItemContext: ListItemContextShape = {
handleClick: () => {},
handleKeyDown: () => {},
handleBlur: () => {},
handleFocus: () => {},
onDestroy: () => {},
getListItemInitialTabIndex: () => -1,
getClassNamesFromList: () => ({}),
};
export const ListItemContext = React.createContext(defaultListItemContext);
export default class List extends React.Component<ListProps, ListState> {
foundation!: MDCListFoundation;
hasInitializedListItemTabIndex = false;
private listElement = React.createRef<HTMLElement>();
state: ListState = {
listItemClassNames: {},
};
static defaultProps: Partial<ListProps> = {
className: '',
checkboxList: false,
radioList: false,
nonInteractive: false,
dense: false,
avatarList: false,
twoLine: false,
singleSelection: false,
selectedIndex: -1,
handleSelect: () => {},
wrapFocus: true,
tag: 'ul',
};
componentDidMount() {
const {singleSelection, wrapFocus, selectedIndex} = this.props;
this.foundation = new MDCListFoundation(this.adapter);
this.foundation.init();
this.foundation.setSingleSelection(singleSelection!);
this.foundation.layout();
if (isSelectedIndexType(selectedIndex)) {
this.foundation.setSelectedIndex(selectedIndex);
}
this.foundation.setWrapFocus(wrapFocus!);
// Vertical is the default so true unless explicitly horizontal.
this.foundation.setVerticalOrientation(
this.props.orientation !== HORIZONTAL
);
this.initializeListType();
}
componentDidUpdate(prevProps: ListProps) {
const {singleSelection, wrapFocus, selectedIndex} = this.props;
const hasSelectedIndexUpdated = selectedIndex !== prevProps.selectedIndex;
if (singleSelection !== prevProps.singleSelection) {
this.foundation.setSingleSelection(singleSelection!);
}
if (hasSelectedIndexUpdated && isSelectedIndexType(selectedIndex)) {
this.foundation.setSelectedIndex(selectedIndex);
}
if (wrapFocus !== prevProps.wrapFocus) {
this.foundation.setWrapFocus(wrapFocus!);
}
if (this.props.orientation !== prevProps.orientation) {
this.foundation.setVerticalOrientation(
this.props.orientation !== HORIZONTAL
);
}
}
componentWillUnmount() {
this.foundation.destroy();
}
initializeListType = () => {
const {singleSelection} = this.props;
const {cssClasses, strings} = MDCListFoundation;
if (!this.listElement.current) return;
const checkboxListItems = this.listElement.current.querySelectorAll(
strings.ARIA_ROLE_CHECKBOX_SELECTOR
);
const radioSelectedListItem = this.listElement.current.querySelector(
strings.ARIA_CHECKED_RADIO_SELECTOR
);
if (checkboxListItems.length) {
const preselectedItems = this.listElement.current.querySelectorAll(
strings.ARIA_CHECKED_CHECKBOX_SELECTOR
);
const selectedIndex = [].map.call(preselectedItems, (listItem: Element) =>
this.listElements.indexOf(listItem)
) as number[];
this.foundation.setSelectedIndex(selectedIndex);
} else if (singleSelection) {
const isActivated = this.listElement.current.querySelector(
cssClasses.LIST_ITEM_ACTIVATED_CLASS
);
if (isActivated) {
this.foundation.setUseActivatedClass(true);
}
} else if (radioSelectedListItem) {
this.foundation.setSelectedIndex(
this.listElements.indexOf(radioSelectedListItem)
);
}
};
get listElements(): Element[] {
if (this.listElement.current) {
return [].slice.call(
this.listElement.current.querySelectorAll(
MDCListFoundation.strings.ENABLED_ITEMS_SELECTOR
)
);
}
return [];
}
get classes() {
const {className, nonInteractive, dense, avatarList, twoLine} = this.props;
return classnames('mdc-list', className, {
'mdc-list--non-interactive': nonInteractive,
'mdc-list--dense': dense,
'mdc-list--avatar-list': avatarList,
'mdc-list--two-line': twoLine,
});
}
get adapter(): MDCListAdapter {
return {
getListItemCount: () => this.listElements.length,
getFocusedElementIndex: () =>
this.listElements.indexOf(document.activeElement as HTMLLIElement),
getAttributeForElementIndex: (index, attr) => {
const listItem = this.listElements[index];
return listItem.getAttribute(attr);
},
setAttributeForElementIndex: (index, attr, value) => {
const listItem = this.listElements[index];
if (listItem) {
listItem.setAttribute(attr, value);
}
},
/**
* Pushes class name to state.listItemClassNames[listItemIndex] if it doesn't yet exist.
*/
addClassForElementIndex: (index, className) => {
const {listItemClassNames} = this.state;
if (
listItemClassNames[index] &&
listItemClassNames[index].indexOf(className) === -1
) {
listItemClassNames[index].push(className);
} else {
listItemClassNames[index] = [className];
}
this.setState({listItemClassNames});
},
/**
* Finds the className within state.listItemClassNames[listItemIndex], and removes it
* from the array.
*/
removeClassForElementIndex: (index, className) => {
const {listItemClassNames} = this.state;
if (listItemClassNames[index]) {
const removalIndex = listItemClassNames[index].indexOf(className);
if (removalIndex !== -1) {
listItemClassNames[index].splice(removalIndex, 1);
this.setState({listItemClassNames});
}
}
},
setTabIndexForListItemChildren: (listItemIndex, tabIndexValue) => {
const listItem = this.listElements[listItemIndex];
const selector =
MDCListFoundation.strings.CHILD_ELEMENTS_TO_TOGGLE_TABINDEX;
const listItemChildren: Element[] = [].slice.call(
listItem.querySelectorAll(selector)
);
listItemChildren.forEach((el) =>
el.setAttribute('tabindex', tabIndexValue)
);
},
focusItemAtIndex: (index) => {
const element = this.listElements[index] as HTMLElement | undefined;
if (element) {
element.focus();
}
},
setCheckedCheckboxOrRadioAtIndex: () => {
// TODO: implement when this issue is fixed:
// https://github.com/material-components/material-components-web-react/issues/438
// not implemented since MDC React Radio/Checkbox has events to
// handle toggling checkbox to correct state
},
hasCheckboxAtIndex: (index) => {
const listItem = this.listElements[index];
return !!listItem.querySelector(
MDCListFoundation.strings.CHECKBOX_SELECTOR
);
},
hasRadioAtIndex: (index) => {
const listItem = this.listElements[index];
return !!listItem.querySelector(
MDCListFoundation.strings.RADIO_SELECTOR
);
},
isCheckboxCheckedAtIndex: (index) => {
const listItem = this.listElements[index];
const selector = MDCListFoundation.strings.CHECKBOX_SELECTOR;
const toggleEl = listItem.querySelector<HTMLInputElement>(selector);
return toggleEl!.checked;
},
isFocusInsideList: () => {
if (!this.listElement.current) return false;
return this.listElement.current.contains(document.activeElement);
},
notifyAction: (index) => {
this.props.handleSelect!(index, this.foundation.getSelectedIndex());
},
};
}
get role() {
const {checkboxList, radioList, role} = this.props;
if (role) return role;
if (checkboxList) {
return 'group';
} else if (radioList) {
return 'radiogroup';
}
return null;
}
/**
* Called from ListItem.
* Initializes the tabIndex prop for the listItems. tabIndex is determined by:
* 1. if selectedIndex is an array, and the index === selectedIndex[0]
* 2. if selectedIndex is a number, and the the index === selectedIndex
* 3. if there is no selectedIndex
*/
getListItemInitialTabIndex = (index: number) => {
const {selectedIndex} = this.props;
let tabIndex = -1;
if (!this.hasInitializedListItemTabIndex) {
const isSelectedIndexArray =
Array.isArray(selectedIndex) &&
selectedIndex.length > 0 &&
index === selectedIndex[0];
const isSelected = selectedIndex === index;
if (isSelectedIndexArray || isSelected || selectedIndex === -1) {
tabIndex = 0;
this.hasInitializedListItemTabIndex = true;
}
}
return tabIndex;
};
/**
* Method checks if the list item at `index` contains classes. If true,
* method merges state.listItemClassNames[index] with listItem.props.className.
* The return value is used as the listItem's className.
*/
private getListItemClassNames = () => {
const {listItemClassNames} = this.state;
return listItemClassNames;
};
handleKeyDown = (e: React.KeyboardEvent<any>, index: number) => {
e.persist(); // Persist the synthetic event to access its `key`
this.foundation.handleKeydown(
e.nativeEvent,
true /* isRootListItem is true if index >= 0 */,
index
);
};
handleClick = (_e: React.MouseEvent<any>, index: number) => {
// TODO: fix https://github.com/material-components/material-components-web-react/issues/728
// Hardcoding toggleCheckbox to false for now since we want the checkbox to handle checkbox logic.
// The List Foundation tries to toggle the checkbox and radio, but its difficult to turn that off for checkbox
// or radio.
this.foundation.handleClick(index, false);
};
// Use onFocus as workaround because onFocusIn is not yet supported in React
// https://github.com/facebook/react/issues/6410
handleFocus = (e: React.FocusEvent, index: number) => {
this.foundation.handleFocusIn(e.nativeEvent, index);
};
// Use onBlur as workaround because onFocusOut is not yet supported in React
// https://github.com/facebook/react/issues/6410
handleBlur = (e: React.FocusEvent, index: number) => {
this.foundation.handleFocusOut(e.nativeEvent, index);
};
onDestroy = (index: number) => {
const {listItemClassNames} = this.state;
delete listItemClassNames[index];
this.setState({listItemClassNames});
};
private getListProps = (checkboxList?: boolean, radioList?: boolean) => ({
checkboxList: Boolean(checkboxList),
radioList: Boolean(radioList),
handleKeyDown: this.handleKeyDown,
handleClick: this.handleClick,
handleFocus: this.handleFocus,
handleBlur: this.handleBlur,
onDestroy: this.onDestroy,
getClassNamesFromList: this.getListItemClassNames,
getListItemInitialTabIndex: this.getListItemInitialTabIndex,
});
// decreases rerenders
// https://overreacted.io/writing-resilient-components/#dont-stop-the-data-flow-in-rendering
getListPropsMemoized = memoizeOne(this.getListProps);
render() {
const {
/* eslint-disable @typescript-eslint/no-unused-vars */
className,
checkboxList,
radioList,
nonInteractive,
dense,
avatarList,
twoLine,
singleSelection,
role,
selectedIndex,
handleSelect,
wrapFocus,
/* eslint-enable @typescript-eslint/no-unused-vars */
children,
tag: Tag,
orientation,
...otherProps
} = this.props;
return (
// https://github.com/Microsoft/TypeScript/issues/28892
// @ts-ignore
<Tag
className={this.classes}
ref={this.listElement}
role={this.role}
// Only specify aria-orientation if:
// - orientation is horizontal (vertical is implicit)
// - props.role is falsy (not overridden)
// - this.role is truthy (we are applying role for checkboxList/radiogroup that supports aria-orientation)
// https://github.com/material-components/material-components-web/tree/master/packages/mdc-list#accessibility
aria-orientation={
orientation === HORIZONTAL && !role && this.role
? HORIZONTAL
: undefined
}
{...otherProps}
>
<ListItemContext.Provider
value={this.getListPropsMemoized(checkboxList, radioList)}
>
{children}
</ListItemContext.Provider>
</Tag>
);
}
}
/* eslint-enable quote-props */
export {
ListItem,
ListItemGraphic,
ListItemText,
ListItemMeta,
ListDivider,
ListGroup,
ListGroupSubheader,
ListItemProps,
}; | the_stack |
import { Request, Response } from 'express'
import Crowi from 'server/crowi'
import Debug from 'debug'
import ApiResponse from 'server/util/apiResponse'
import { UserDocument } from 'server/models/user'
import { getPath } from 'server/util/ssr'
import { getAppContext } from 'server/util/view'
import { registrationMode, hasSlackConfig, hasSlackToken } from 'server/models/config'
export default (crowi: Crowi) => {
const debug = Debug('crowi:routes:admin')
const models = crowi.models
const User = models.User
const Config = models.Config
const MAX_PAGE_LIST = 5
const actions = {} as any
actions.api = {} as any
const searchEvent = crowi.event('Search')
function createPager(total, limit, page, pagesCount, maxPageList) {
const pager: {
page: any
pagesCount: number
pages: number[]
total: number
previous: number | null
previousDots: boolean
next: number | null
nextDots: boolean
} = {
page,
pagesCount,
pages: [],
total,
previous: null,
previousDots: false,
next: null,
nextDots: false,
}
if (page > 1) {
pager.previous = page - 1
}
if (page < pagesCount) {
pager.next = page + 1
}
let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2))
let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2))
if (pagerMin === 1) {
if (MAX_PAGE_LIST < pagesCount) {
pagerMax = MAX_PAGE_LIST
} else {
pagerMax = pagesCount
}
}
if (pagerMax === pagesCount) {
if (pagerMax - MAX_PAGE_LIST < 1) {
pagerMin = 1
} else {
pagerMin = pagerMax - MAX_PAGE_LIST
}
}
if (pagerMin > 1) {
pager.previousDots = true
}
if (pagerMax < pagesCount) {
pager.nextDots = true
}
for (let i = pagerMin; i <= pagerMax; i++) {
pager.pages.push(i)
}
return pager
}
actions.index = function (req: Request, res: Response) {
return res.render(getPath(crowi, 'AdminPage'), { i18n: req.i18n, context: getAppContext(crowi, req) })
}
actions.api.index = function (req: Request, res: Response) {
const searcher = crowi.getSearcher()
return res.json(ApiResponse.success({ searchConfigured: !!searcher }))
}
actions.api.app = {}
actions.api.app.index = async function (req: Request, res: Response) {
const config = crowi.getConfig()
const settingForm = config.crowi
const isUploadable = Config.isUploadable(config)
return res.json(ApiResponse.success({ settingForm, registrationMode, isUploadable }))
}
actions.notification = {}
actions.api.notification = {}
actions.api.notification.index = async function (req: Request, res: Response) {
const config = crowi.getConfig()
const UpdatePost = crowi.model('UpdatePost')
const hasSlackConfigValue = hasSlackConfig(config)
const hasSlackTokenValue = hasSlackToken(config)
const slack = crowi.slack
const appUrl = config.crowi['app:url']
const defaultSlackSetting = { 'slack:clientId': '', 'slack:clientSecret': '' }
const slackSetting = hasSlackConfigValue ? config.notification : defaultSlackSetting
const slackAuthUrl = hasSlackConfigValue ? slack.getAuthorizeURL() : ''
const settings = await UpdatePost.findAll()
return res.json(
ApiResponse.success({
settings,
slackSetting,
hasSlackConfig: hasSlackConfigValue,
hasSlackToken: hasSlackTokenValue,
slackAuthUrl,
appUrl,
}),
)
}
actions.api.notification.slackSetting = async function (req: Request, res: Response) {
const configService = crowi.getConfigService()
const { slackSetting } = req.form
if (!req.form.isValid) {
return res.json(ApiResponse.error(req.form.errors.join('\n')))
}
try {
await configService.saveConfig('notification', slackSetting)
return res.json(ApiResponse.success({ message: 'Updated Slack setting.' }))
} catch (err) {
return res.json(ApiResponse.error(err.message))
}
}
actions.api.notification.removeSlackSetting = async function (req: Request, res: Response) {
const configService = crowi.getConfigService()
try {
await Promise.all([
configService.deleteConfig('notification', 'slack:clientId'),
configService.deleteConfig('notification', 'slack:clientSecret'),
configService.deleteConfig('notification', 'slack:token'),
])
} catch (err) {
return res.json(ApiResponse.error(err.message))
}
return res.json(ApiResponse.success({ message: 'Successfully remove slack setting.' }))
}
actions.notification.slackAuth = async function (req: Request, res: Response) {
const code = req.query.code
const configService = crowi.getConfigService()
if (!code || !hasSlackConfig(req.config)) {
return res.redirect('/admin/notification')
}
const slack = crowi.slack
try {
const token = await slack.getOauthAccessToken(code)
try {
await configService.saveConfig('notification', { 'slack:token': token })
req.flash('successMessage', ['Successfully Connected!'])
} catch (err) {
req.flash('errorMessage', ['Failed to save access_token. Please try again.'])
}
return res.redirect('/admin/notification')
} catch (error) {
debug('oauth response ERROR', error)
req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.'])
return res.redirect('/admin/notification')
}
}
actions.api.search = {}
actions.api.search.buildIndex = async function (req: Request, res: Response) {
const search = crowi.getSearcher()
if (!search) {
return res.json(ApiResponse.error('Searcher is not ready.'))
}
searchEvent.on('addPageProgress', (total, current, skip) => {
crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip })
})
searchEvent.on('finishAddPage', (total, current, skip) => {
crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip })
})
search
.buildIndex()
.then(() => {
debug('Data is successfully indexed. ------------------ ✧✧')
})
.catch((err) => {
debug('Error caught.', err)
})
return res.json(ApiResponse.success({ message: 'Now re-building index ... this takes a while.' }))
}
actions.user = {}
actions.api.user = {}
actions.api.user.index = function (req: Request, res: Response) {
const page = parseInt(req.query.page) || 1
// uq means user query
// q used by search box on header
const uq = req.query.uq
const query: {
$or?: any
} = {}
if (uq) {
const $regex = uq.trim().replace(' ', '|')
query.$or = ['username', 'name', 'email'].map((v) => ({
[v]: {
$regex,
$options: 'i',
},
}))
}
User.findUsersWithPagination({ page: page }, query, (err, result) => {
if (err) {
debug(err)
return res.json(
ApiResponse.success({
users: [],
pager: null,
uq: uq,
error: err.message,
}),
)
}
const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST)
return res.json(
ApiResponse.success({
users: result.docs,
pager: pager,
uq,
}),
)
})
}
actions.api.user.invite = function (req: Request, res: Response) {
const { emailList, sendEmail } = req.form.inviteForm
const toSendEmail = sendEmail || false
if (!req.form.isValid) {
return res.json(ApiResponse.error(req.form.errors.join('\n')))
}
User.createUsersByInvitation(emailList.split('\n'), toSendEmail, function (err, userList) {
if (err === null) {
return res.json(ApiResponse.success({ userList }))
}
debug(err, userList)
return res.json(ApiResponse.error('招待に失敗しました。'))
})
}
actions.api.user.makeAdmin = function (req: Request, res: Response) {
const id = req.params.id
User.findById(id, function (err, userData) {
;(userData as UserDocument).makeAdmin(function (err, userData) {
if (err === null) {
return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを管理者に設定しました。` }))
}
debug(err, userData)
return res.json(ApiResponse.error('更新に失敗しました。'))
})
})
}
actions.api.user.removeFromAdmin = function (req: Request, res: Response) {
const id = req.params.id
User.findById(id, function (err, userData) {
;(userData as UserDocument).removeFromAdmin(function (err, userData) {
if (err === null) {
return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを管理者から外しました。` }))
}
debug(err, userData)
return res.json(ApiResponse.error('更新に失敗しました。'))
})
})
}
actions.api.user.activate = function (req: Request, res: Response) {
const id = req.params.id
User.findById(id, function (err, userData) {
;(userData as UserDocument).statusActivate(function (err, userData) {
if (err === null) {
return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを承認しました。` }))
}
debug(err, userData)
return res.json(ApiResponse.error('更新に失敗しました。'))
})
})
}
actions.api.user.suspend = function (req: Request, res: Response) {
const id = req.params.id
User.findById(id, function (err, userData) {
;(userData as UserDocument).statusSuspend(function (err, userData) {
if (err === null) {
return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを利用停止にしました。` }))
}
debug(err, userData)
return res.json(ApiResponse.error('更新に失敗しました。'))
})
})
}
actions.user.remove = function (req: Request, res: Response) {
// 未実装
return res.redirect('/admin/users')
}
// これやったときの relation の挙動未確認
actions.user.removeCompletely = function (req: Request, res: Response) {
// ユーザーの物理削除
const id = req.params.id
User.removeCompletelyById(id, function (err, removed) {
if (err) {
debug('Error while removing user.', err, id)
req.flash('errorMessage', '完全な削除に失敗しました。')
} else {
req.flash('successMessage', '削除しました')
}
return res.redirect('/admin/users')
})
}
actions.api.user.resetPassword = function (req: Request, res: Response) {
const id = req.body.user_id
const User = crowi.model('User')
User.resetPasswordByRandomString(id)
.then(function (data) {
return res.json(ApiResponse.success(data))
})
.catch(function (err) {
debug('Error on reseting password', err)
return res.json(ApiResponse.error('Error'))
})
}
actions.api.user.updateEmail = async function (req: Request, res: Response) {
const { user_id: id, email } = req.body
const User = crowi.model('User')
try {
const user = await User.findById(id)
if (!user) {
throw new Error('User not found')
}
await user.updateEmail(email)
return res.json(ApiResponse.success())
} catch (err) {
debug('Error on updating email', err)
return res.json(ApiResponse.error('Error'))
}
}
actions.api.top = {}
actions.api.top.index = function (req: Request, res: Response) {
const { version: crowiVersion } = crowi
const searcher = crowi.getSearcher()
const searchInfo = searcher
? {
node: searcher.node,
indexName: searcher.indexNames.base,
esVersion: searcher.esVersion,
}
: {}
return res.json(ApiResponse.success({ crowiVersion, searchInfo }))
}
actions.api.postSettings = function (req: Request, res: Response) {
const user = req.user as UserDocument
const form = req.form.settingForm
if (req.form.isValid) {
debug('form content', form)
// mail setting ならここで validation
if (form['mail:from']) {
validateMailSetting(req, form, function (err, data) {
debug('Error validate mail setting: ', err, data)
if (err) {
req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。')
return res.json(ApiResponse.error(req.form.errors.join('\n')))
}
return saveSetting(req, res, form)
})
}
if (form['auth:disablePasswordAuth'] && !user.hasValidThirdPartyId()) {
return res.json(ApiResponse.error('パスワードによるログインを禁止するには管理者が有効な外部サービスと連携している必要があります。'))
}
return saveSetting(req, res, form)
} else {
return res.json(ApiResponse.error(req.form.errors.join('\n')))
}
}
actions.api.notificationAdd = function (req: Request, res: Response) {
const user = req.user as UserDocument
const UpdatePost = crowi.model('UpdatePost')
const pathPattern = req.body.pathPattern
const channel = req.body.channel
debug('notification.add', pathPattern, channel)
UpdatePost.createUpdatePost(pathPattern, channel, user._id)
.then(function (doc) {
debug('Successfully save updatePost', doc)
// fixme: うーん
doc.creator = ((doc.creator as any) as UserDocument)._id.toString() as any
return res.json(ApiResponse.success({ updatePost: doc }))
})
.catch(function (err) {
debug('Failed to save updatePost', err)
return res.json(ApiResponse.error())
})
}
// app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
actions.api.notificationRemove = async function (req: Request, res: Response) {
const UpdatePost = crowi.model('UpdatePost')
const id = req.body.id
try {
await UpdatePost.findOneAndRemove({ _id: id })
debug('Successfully remove updatePost')
return res.json(ApiResponse.success({}))
} catch (err) {
debug('Failed to remove updatePost', err)
return res.json(ApiResponse.error())
}
}
// app.get('/_api/admin/users.search' , admin.api.userSearch);
actions.api.usersSearch = function (req: Request, res: Response) {
const User = crowi.model('User')
const email = req.query.email
User.findUsersByPartOfEmail(email, {})
.then((users) => {
const result = {
data: users,
}
return res.json(ApiResponse.success(result))
})
.catch((err) => {
return res.json(ApiResponse.error())
})
}
async function saveSetting(req, res, form) {
const configService = crowi.getConfigService()
await configService.saveConfig('crowi', form)
return res.json(ApiResponse.success())
}
function validateMailSetting(req, form, callback) {
const mailer = crowi.mailer
const option: {
host: string
port: number
auth?: any
secure?: boolean
} = {
host: form['mail:smtpHost'],
port: form['mail:smtpPort'],
}
if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
option.auth = {
user: form['mail:smtpUser'],
pass: form['mail:smtpPassword'],
}
}
if (option.port === 465) {
option.secure = true
}
const smtpClient = mailer.createSMTPClient(option)
debug('mailer setup for validate SMTP setting', smtpClient)
smtpClient.sendMail(
{
to: req.user.email,
subject: 'Wiki管理設定のアップデートによるメール通知',
text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
},
callback,
)
}
actions.api.backlink = {}
actions.api.backlink.buildBacklinks = function (req: Request, res: Response) {
const Backlink = crowi.model('Backlink')
// In background
Backlink.createByAllPages()
return res.json(ApiResponse.success({ message: 'Now re-building backlinks ... this takes a while.' }))
}
actions.api.user.edit = async function (req: Request, res: Response) {
const id = req.params.id
const { name, emailToBeChanged } = req.form.userEditForm
try {
const user = await User.findById(id)
if (!user) {
throw new Error('User not found')
}
const emailDuplicateUser = await User.findUserByEmail(emailToBeChanged)
if (emailDuplicateUser && !user.equals(emailDuplicateUser)) {
throw new Error('Email duplicated')
}
await user.updateNameAndEmail(name, emailToBeChanged)
return res.json(ApiResponse.success({ message: 'Successfully updated' }))
} catch (err) {
if (err.message) {
return res.json(ApiResponse.error(err.message))
} else {
return res.json(ApiResponse.error('Failed to update name or email'))
}
}
}
return actions
} | the_stack |
import { Equatable } from "@siteimprove/alfa-equatable";
import { Hash, Hashable } from "@siteimprove/alfa-hash";
import { Iterable } from "@siteimprove/alfa-iterable";
import { Serializable } from "@siteimprove/alfa-json";
import { Option, None } from "@siteimprove/alfa-option";
import { Result, Err } from "@siteimprove/alfa-result";
import { Sequence } from "@siteimprove/alfa-sequence";
import * as json from "@siteimprove/alfa-json";
import * as builtin from "./builtin";
const { isEmpty } = Iterable;
/**
* {@link https://url.spec.whatwg.org/}
*
* @public
*/
export class URL implements Equatable, Hashable, Serializable<URL.JSON> {
public static of(
scheme: string,
username: Option<string> = None,
password: Option<string> = None,
host: Option<string> = None,
port: Option<number> = None,
path: Iterable<string> = [],
query: Option<string> = None,
fragment: Option<string> = None,
cannotBeABase: boolean = false
): URL {
return new URL(
scheme,
username,
password,
host,
port,
Sequence.from(path),
query,
fragment,
cannotBeABase
);
}
/**
* {@link https://tools.ietf.org/html/rfc2606#section-3}
*/
public static example(): URL {
return URL.parse("https://example.com").get();
}
/**
* {@link https://tools.ietf.org/html/rfc6694#section-3}
*/
public static blank(): URL {
return URL.parse("about:blank").get();
}
private readonly _scheme: string;
private readonly _username: Option<string>;
private readonly _password: Option<string>;
private readonly _host: Option<string>;
private readonly _port: Option<number>;
private readonly _path: Sequence<string>;
private readonly _query: Option<string>;
private readonly _fragment: Option<string>;
private readonly _cannotBeABase: boolean;
private constructor(
scheme: string,
username: Option<string>,
password: Option<string>,
host: Option<string>,
port: Option<number>,
path: Sequence<string>,
query: Option<string>,
fragment: Option<string>,
cannotBeABase: boolean
) {
this._scheme = scheme;
this._username = username;
this._password = password;
this._host = host;
this._port = port;
this._path = path;
this._query = query;
this._fragment = fragment;
this._cannotBeABase = cannotBeABase;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-scheme}
*/
public get scheme(): string {
return this._scheme;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-username}
*/
public get username(): Option<string> {
return this._username;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-password}
*/
public get password(): Option<string> {
return this._password;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-host}
*/
public get host(): Option<string> {
return this._host;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-port}
*/
public get port(): Option<number> {
return this._port;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-path}
*/
public get path(): Sequence<string> {
return this._path;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-query}
*/
public get query(): Option<string> {
return this._query;
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-fragment}
*/
public get fragment(): Option<string> {
return this._fragment;
}
/**
* {@link https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag}
*/
public get cannotBeABase(): boolean {
return this._cannotBeABase;
}
/**
* {@link https://url.spec.whatwg.org/#is-special}
*/
public isSpecial(): boolean {
return URL.isSpecialScheme(this._scheme);
}
/**
* {@link https://url.spec.whatwg.org/#include-credentials}
*/
public hasCredentials(): boolean {
return this._username.isSome() || this._password.isSome();
}
/**
* Remove the fragment portion of this URL.
*
* @remarks
* This method is useful for contexts in which the fragment portion of the URL,
* which isn't passed from client to server, is of no interest.
*/
public withoutFragment(): URL {
if (this._fragment.isNone()) {
return this;
}
return new URL(
this._scheme,
this._username,
this._password,
this._host,
this._port,
this._path,
this._query,
None,
this._cannotBeABase
);
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-equals}
*/
public equals(value: URL): boolean;
/**
* {@link https://url.spec.whatwg.org/#concept-url-equals}
*/
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return (
value instanceof URL &&
value._scheme === this._scheme &&
value._username.equals(this._username) &&
value._password.equals(this._password) &&
value._host.equals(this._host) &&
value._port.equals(this._port) &&
value._path.equals(this._path) &&
value._query.equals(this._query) &&
value._fragment.equals(this._fragment) &&
value._cannotBeABase === this._cannotBeABase
);
}
public hash(hash: Hash): void {
hash
.writeString(this._scheme)
.writeHashable(this._username)
.writeHashable(this._password)
.writeHashable(this._host)
.writeHashable(this._port)
.writeHashable(this._path)
.writeHashable(this._query)
.writeHashable(this._fragment)
.writeBoolean(this._cannotBeABase);
}
public toJSON(): URL.JSON {
return {
scheme: this._scheme,
username: this._username.getOr(null),
password: this._password.getOr(null),
host: this._host.getOr(null),
port: this._port.getOr(null),
path: this._path.toArray(),
query: this._query.getOr(null),
fragment: this._fragment.getOr(null),
cannotBeABase: this._cannotBeABase,
};
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-serializer}
*/
public toString(): string {
let output = this._scheme + ":";
for (const host of this._host) {
output += "//";
if (this.hasCredentials()) {
for (const username of this._username) {
output += username;
}
for (const password of this._password) {
output += ":" + password;
}
output += "@";
}
output += host;
for (const port of this._port) {
output += ":" + port.toString(10);
}
}
if (this._cannotBeABase) {
output += this._path.get(0).get();
} else {
if (
this._host.isNone() &&
this._path.size > 1 &&
this._path.first().includes("")
) {
output += "/.";
}
for (const segment of this._path) {
output += "/" + segment;
}
}
for (const query of this._query) {
output += "?" + query;
}
for (const fragment of this._fragment) {
output += "#" + fragment;
}
return output;
}
}
/**
* @public
*/
export namespace URL {
export interface JSON {
[key: string]: json.JSON;
scheme: string;
username: string | null;
password: string | null;
host: string | null;
port: number | null;
path: Array<string>;
query: string | null;
fragment: string | null;
cannotBeABase: boolean;
}
export function from(json: JSON): URL {
return URL.of(
json.scheme,
Option.from(json.username),
Option.from(json.password),
Option.from(json.host),
Option.from(json.port),
json.path,
Option.from(json.query),
Option.from(json.fragment)
);
}
/**
* {@link https://url.spec.whatwg.org/#concept-url-parser}
*
* @remarks
* Parsing URLs is tricky business and so this function relies on the presence
* of a globally available WHATWG URL class. This API is available in both
* browsers, Node.js, and Deno.
*/
export function parse(url: string, base?: string | URL): Result<URL, string> {
if (typeof base === "string") {
const result = parse(base);
if (result.isErr()) {
return result;
}
base = result.get();
}
try {
const {
// https://url.spec.whatwg.org/#dom-url-protocol
protocol,
// https://url.spec.whatwg.org/#dom-url-username
username,
// https://url.spec.whatwg.org/#dom-url-password
password,
// https://url.spec.whatwg.org/#dom-url-hostname
hostname,
// https://url.spec.whatwg.org/#dom-url-port
port,
// https://url.spec.whatwg.org/#dom-url-pathname
pathname,
// https://url.spec.whatwg.org/#dom-url-search
search,
// https://url.spec.whatwg.org/#dom-url-hash
hash,
} = new builtin.URL(url, base?.toString());
// `URL#protocol` appends a ":" to the scheme which we need to remove.
const scheme = protocol.replace(/:$/, "");
return Result.of(
URL.of(
scheme,
// `URL#username` `URL#password` expose the username and password
// as-is and so the only thing we need to do is reject them when
// empty.
Option.of(username).reject(isEmpty),
Option.of(password).reject(isEmpty),
// `URL#hostname` exposes the host as an empty string if the host is
// `null`. For the `file` scheme, however, the empty string is
// significant and we therefore don't translate it into `None`.
scheme === "file"
? Option.of(hostname)
: Option.of(hostname).reject(isEmpty),
// `URL#port` exposes the port number as a string to we convert it to
// a number.
Option.of(port).reject(isEmpty).map(Number),
// `URL#pathname` exposes the path segments with a leading "/" and
// joins the segments with "/". We therefore remove the leading "/"
// and split the segments by "/" into an array.
pathname.replace(/^\//, "").split("/"),
// `URL#search` exposes the query portion of the URL with a leading
// "?" which we need to remove.
Option.of(search)
.reject(isEmpty)
.map((search) => search.replace(/^\?/, "")),
// `URL#hash` exposes the fragment portion of the URL with a leading
// "#" which we need to remove.
Option.of(hash)
.reject(isEmpty)
.map((hash) => hash.replace(/^#/, "")),
// The URL cannot be used as a base URL when the scheme isn't
// special and the pathname doesn't start with a leading "/".
!isSpecialScheme(scheme) && pathname[0] !== "/"
)
);
} catch (err) {
if (err instanceof Error) {
return Err.of(err.message);
} else {
return Err.of(`${err}`);
}
}
}
/**
* {@link https://url.spec.whatwg.org/#special-scheme}
*/
export function isSpecialScheme(scheme: string): boolean {
switch (scheme) {
case "ftp":
case "file":
case "http":
case "https":
case "ws":
case "wss":
return true;
default:
return false;
}
}
} | the_stack |
import * as React from "react";
import * as Blessed from "blessed";
export {};
/* RENDERER *****************************************************************/
export type Callback = () => void | null | undefined;
export type renderer = (c: JSX.Element, s: Blessed.Widgets.Screen, callback?: Callback) => React.Component | null;
export function render(c: JSX.Element, s: Blessed.Widgets.Screen, callback?: Callback): React.Component | null;
export function createBlessedRenderer(bls: any): renderer;
/* BLESSED ELEMENTS **********************************************************/
export type Element = Blessed.Widgets.BlessedElement;
export type ScrollableBoxElement = Blessed.Widgets.ScrollableBoxElement;
export type ScrollableTextElement = Blessed.Widgets.ScrollableTextElement;
export type BoxElement = Blessed.Widgets.BoxElement;
export type TextElement = Blessed.Widgets.TextElement;
export type LineElement = Blessed.Widgets.LineElement;
export type BigTextElement = Blessed.Widgets.BigTextElement;
export type ListElement = Blessed.Widgets.ListElement;
export type FileManagerElement = Blessed.Widgets.FileManagerElement;
export type ListTableElement = Blessed.Widgets.ListTableElement;
export type ListbarElement = Blessed.Widgets.ListbarElement;
export type InputElement = Blessed.Widgets.InputElement;
export type TextareaElement = Blessed.Widgets.TextareaElement;
export type TextboxElement = Blessed.Widgets.TextboxElement;
export type ButtonElement = Blessed.Widgets.ButtonElement;
export type CheckboxElement = Blessed.Widgets.CheckboxElement;
export type RadioSetElement = Blessed.Widgets.RadioSetElement;
export type RadioButtonElement = Blessed.Widgets.RadioButtonElement;
export type TableElement = Blessed.Widgets.TableElement;
export type PromptElement = Blessed.Widgets.PromptElement;
export type QuestionElement = Blessed.Widgets.QuestionElement;
export type MessageElement = Blessed.Widgets.MessageElement;
export type LoadingElement = Blessed.Widgets.LoadingElement;
export type LogElement = Blessed.Widgets.Log;
export type ProgressBarElement = Blessed.Widgets.ProgressBarElement;
export type TerminalElement = Blessed.Widgets.TerminalElement;
export type LayoutElement = Blessed.Widgets.LayoutElement;
/* EVENTS *******************************************************************/
type Prefix<T extends string, P extends string> = `${T}${P}`;
// create event handlers that map to 'blessed' events. see
// https://github.com/Yomguithereal/react-blessed/blob/f5e1f791dea1788745695d557040b91f573f9ef5/src/fiber/events.js
type EventHandlerProp<T extends string, E extends (...args: never) => void> = {
[key in `on${Capitalize<T>}`]?: E;
};
// 'react-blessed' handles 'blessed' events by matching event names to
// handlers by prefixing event names with with "on" and camelCasing the
// result. this cannot be fully recreated in TS so we must manually map them
// here.
type ScreenElement = "click" | "mouseover" | "mouseout" | "mouseup";
type ScreenElementPrefix = "element";
type ExludedScreenEventNames = Prefix<ScreenElementPrefix, Prefix<" ", ScreenElement>>;
type CamelCasedScreenEventNames = Prefix<ScreenElementPrefix, Capitalize<ScreenElement>>;
type ScreenEventNames =
| Exclude<Blessed.Widgets.NodeScreenEventType, ExludedScreenEventNames>
| CamelCasedScreenEventNames;
type GenericContentPrefix = "set" | "parsed";
type GenericContent = "content";
type ExludedGenericEventNames = Prefix<GenericContentPrefix, Prefix<" ", GenericContent>>;
type CamelCasedGenericEventNames = Prefix<GenericContentPrefix, Capitalize<GenericContent>>;
type GenericEventNames =
| Exclude<Blessed.Widgets.NodeGenericEventType, ExludedGenericEventNames>
| CamelCasedGenericEventNames;
type ProgressBarEventNames = Parameters<Blessed.Widgets.ProgressBarElement["on"]>[0];
type SpreadableArgs<T, K = T extends unknown[] ? T : [T]> = K;
interface EventHandler<T> {
(...args: SpreadableArgs<T>): void;
}
// event args need to be manually typed because Blessed.Widgets.NodeWithEvents
// overloads the event handlers (making it impossible? to extract the
// parameters with TS utils) and does not expose the event callbacks as
// importable types
export type ScreenEvent = Blessed.Widgets.Screen;
export type ScreenEventHandler = EventHandler<ScreenEvent>;
type ScreenEventProps = EventHandlerProp<ScreenEventNames, ScreenEventHandler>;
export type MouseEvent = Blessed.Widgets.Events.IMouseEventArg;
export type MouseEventHandler = EventHandler<MouseEvent>;
type MouseEventProps = EventHandlerProp<Blessed.Widgets.NodeMouseEventType, MouseEventHandler>;
export type GenericEvent = undefined;
export type GenericEventHandler = EventHandler<GenericEvent>;
type GenericEventProps = EventHandlerProp<GenericEventNames, GenericEventHandler>;
export type KeyPressEvent = [key: any, event: Blessed.Widgets.Events.IKeyEventArg];
export type KeyPressEventHandler = EventHandler<KeyPressEvent>;
type KeyPressEventProps = EventHandlerProp<"keypress", KeyPressEventHandler>;
export type WarningEvent = string;
export type WarningEventHandler = EventHandler<WarningEvent>;
type WarningEventProps = EventHandlerProp<"warning", WarningEventHandler>;
export type ProgressBarEvent = undefined;
export type ProgressBarEventHandler = EventHandler<ProgressBarEvent>;
type ProgressBarEventProps = EventHandlerProp<ProgressBarEventNames, ProgressBarEventHandler>;
interface EventProps
extends ScreenEventProps,
GenericEventProps,
MouseEventProps,
KeyPressEventProps,
WarningEventProps {}
/* BLESSED-REACT LOCALLY DEFINED PROPS **************************************/
// @types/blessed defines 'styles' as 'any' but 'blessed' can only can only
// take certain values. define them here.
interface BorderStyle {
type?: "line" | "bg";
ch?: string;
bg?: string;
fg?: string;
bold?: boolean;
underline?: boolean;
}
interface ItemStyle {
bg?: string;
fg?: string;
bold?: boolean;
underline?: boolean;
blink?: boolean;
inverse?: boolean;
invisible?: boolean;
}
interface ListStyle extends ElementStyle {
selected?: ItemStyle;
item?: ItemStyle;
}
interface ProgressBarStyle extends ElementStyle {
bar?: { bg?: string; fg?: string };
}
interface ElementStyle extends ItemStyle {
border?: BorderStyle;
focus?: { bg?: string; fg?: string };
hover?: { bg?: string; fg?: string };
transparent?: boolean;
scrollbar?: { bg?: string; fg?: string; track?: { bg?: string; fg?: string } };
}
// remove indexers
// https://stackoverflow.com/questions/51465182/how-to-remove-index-signature-using-mapped-types
type KnownKeys<T> = {
[K in keyof T as string extends K ? never : number extends K ? never : K]: T[K];
};
type WithClassProp<T, K = T | undefined | false | null> = T & { class?: K | K[] };
type ProgressBarProps<T> = T extends ProgressBarElement ? ProgressBarEventProps & { style?: ProgressBarStyle } : {};
type ListProps<T> = T extends ListElement ? ProgressBarEventProps & { style?: ListStyle; selected?: number } : {};
// layout does not require prop 'layout' in Blessed.Widgets.LayoutOptions--make it optional
type LayoutProps<T> = T extends LayoutElement ? Partial<Blessed.Widgets.LayoutOptions> : {};
// remove {[key: string]: any} indexer defined in Blessed.Widgets.IOptions.
// 'blessed' doesn't exist in a DOM so it probably doesn't make sense to allow any property
type FilterOptions<T extends Record<any, any>> = Partial<Omit<KnownKeys<T>, "style" | "children">>;
type ModifiedBlessedOptions<T> = FilterOptions<T> & { children?: React.ReactNode; style?: ElementStyle } & EventProps;
/* REACT-BLESSED JSX ********************************************************/
/**
*
* this type can be used to get props for 'react-blessed' elements in the same
* manner that React.HTMLProps can be used to get DOM element props. e.g.
* ```ts
* import { FC } from 'react'
* import { BlessedProps, BoxElement } from 'react-blessed';
* type MyBoxProps = BlessedProps<BoxElement>;
* const MyBox: React.FC<MyBoxProps> = props => <box {...props} />;
* ```
* @see DetailedBlessedProps
* @see React.HTMLAttributes
*/
export type BlessedAttributes<E extends Element> = WithClassProp<
ModifiedBlessedOptions<E["options"]> & ProgressBarProps<E> & ListProps<E> & LayoutProps<E>
>;
/**
* mirrors react prop generation for HTML JSX.IntrinsicElements.
* @see React.DetailedHTMLProps
*/
export type DetailedBlessedProps<E extends Element> = BlessedAttributes<E> & React.ClassAttributes<E>;
export interface BlessedIntrinsicElements {
element: DetailedBlessedProps<Element>;
box: DetailedBlessedProps<BoxElement>;
text: DetailedBlessedProps<TextElement>;
line: DetailedBlessedProps<LineElement>;
scrollablebox: DetailedBlessedProps<ScrollableBoxElement>;
scrollabletext: DetailedBlessedProps<ScrollableTextElement>;
bigtext: DetailedBlessedProps<BigTextElement>;
list: DetailedBlessedProps<ListElement>;
filemanager: DetailedBlessedProps<FileManagerElement>;
listtable: DetailedBlessedProps<ListTableElement>;
listbar: DetailedBlessedProps<ListbarElement>;
input: DetailedBlessedProps<InputElement>;
textarea: DetailedBlessedProps<TextareaElement>;
textbox: DetailedBlessedProps<TextboxElement>;
button: DetailedBlessedProps<ButtonElement>;
checkbox: DetailedBlessedProps<CheckboxElement>;
radioset: DetailedBlessedProps<RadioSetElement>;
radiobutton: DetailedBlessedProps<RadioButtonElement>;
table: DetailedBlessedProps<TableElement>;
prompt: DetailedBlessedProps<PromptElement>;
question: DetailedBlessedProps<QuestionElement>;
message: DetailedBlessedProps<MessageElement>;
loading: DetailedBlessedProps<LoadingElement>;
log: DetailedBlessedProps<LogElement>;
progressbar: DetailedBlessedProps<ProgressBarElement>;
terminal: DetailedBlessedProps<Blessed.Widgets.TerminalElement>;
layout: DetailedBlessedProps<Blessed.Widgets.LayoutElement>;
// escape: Blessed.escape is not an element
// program: Blessed.Widgets.Program is not an element
}
// 'react-blessed' accepts JSX with 'blessed' element names with and without
// a 'blessed-' prefix. see
// https://github.com/Yomguithereal/react-blessed/blob/f5e1f791dea1788745695d557040b91f573f9ef5/src/fiber/fiber.js#L49
export type BlessedIntrinsicElementsPrefixed = {
[Key in keyof BlessedIntrinsicElements as Prefix<"blessed-", Key>]: BlessedIntrinsicElements[Key];
};
// it isn't possible to use the global JSX namespace because some 'blessed'
// elements will collide with ones set in react defs.
// augment react JSX when old JSX transform is used
declare module "react" {
namespace JSX {
// set IntrinsicElements to 'react-blessed' elements both with and without
// 'blessed-' prefix
interface IntrinsicElements extends BlessedIntrinsicElementsPrefixed, BlessedIntrinsicElements {}
}
}
// augment react/jsx-runtime JSX when new JSX transform is used
declare module "react/jsx-runtime" {
namespace JSX {
// copy React JSX, otherwise class refs won't type as expected
type IntrinsicAttributes = React.Attributes;
interface IntrinsicClassAttributes<T> extends React.ClassAttributes<T> {}
interface IntrinsicElements extends BlessedIntrinsicElementsPrefixed, BlessedIntrinsicElements {}
}
}
declare module "react/jsx-dev-runtime" {
namespace JSX {
type IntrinsicAttributes = React.Attributes;
interface IntrinsicClassAttributes<T> extends React.ClassAttributes<T> {}
interface IntrinsicElements extends BlessedIntrinsicElementsPrefixed, BlessedIntrinsicElements {}
}
} | the_stack |
import * as MongoDB from "mongodb";
import * as Bluebird from "bluebird";
import * as util from "util";
import * as _ from "lodash";
import * as Skmatc from "skmatc";
import {Core} from "./Core";
import {Instance} from "./Instance";
import {Schema} from "./Schema";
import {Hooks} from "./Hooks";
import {Plugin} from "./Plugins";
import {Cache} from "./Cache";
import {CacheDirector} from "./CacheDirector";
import {CacheOnID} from "./cacheControllers/IDDirector";
import * as General from "./General";
import {Cursor} from "./Cursor";
import * as Index from "./Index";
import * as ModelOptions from "./ModelOptions";
import {Conditions} from "./Conditions";
import {Changes} from "./Changes";
import {Omnom} from "./utils/Omnom";
import {ModelCache} from "./ModelCache";
import {ModelHelpers} from "./ModelHelpers";
import {ModelHandlers} from "./ModelHandlers";
import * as ModelInterfaces from "./ModelInterfaces";
import {ModelSpecificInstance} from "./ModelSpecificInstance";
import {InstanceImplementation} from "./InstanceInterface";
import {Transforms, DefaultTransforms} from "./Transforms";
import * as AggregationPipeline from "./Aggregate";
import {MapFunction, ReduceFunction, MapReducedDocument, MapReduceFunctions, MapReduceOptions} from "./MapReduce";
/**
* An Iridium Model which represents a structured MongoDB collection.
* Models expose the methods you will generally use to query those collections, and ensure that
* the results of those queries are returned as {TInstance} instances.
*
* @param TDocument The interface used to determine the schema of documents in the collection.
* @param TInstance The interface or class used to represent collection documents in the JS world.
*
* @class
*/
export class Model<TDocument extends { _id?: any }, TInstance> {
/**
* Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified
* @param core The Iridium core that this model should use for database access
* @param instanceType The class which will be instantiated for each document retrieved from the database
* @constructor
*/
constructor(core: Core, instanceType: InstanceImplementation<TDocument, TInstance>) {
if (!(core instanceof Core)) throw new Error("You failed to provide a valid Iridium core for this model");
if (typeof instanceType !== "function") throw new Error("You failed to provide a valid instance constructor for this model");
if (typeof instanceType.collection !== "string" || !instanceType.collection) throw new Error("You failed to provide a valid collection name for this model");
if (!_.isPlainObject(instanceType.schema) || instanceType.schema._id === undefined) throw new Error("You failed to provide a valid schema for this model");
this._core = core;
this.loadExternal(instanceType);
this.onNewModel();
this.loadInternal();
}
/**
* Loads any externally available properties (generally accessed using public getters/setters).
*/
private loadExternal(instanceType: InstanceImplementation<TDocument, TInstance>) {
this._collection = instanceType.collection;
this._schema = instanceType.schema;
this._hooks = instanceType;
this._cacheDirector = instanceType.cache || new CacheOnID();
this._transforms = instanceType.transforms || {};
this._validators = instanceType.validators || [];
this._indexes = instanceType.indexes || [];
if(!this._schema._id) this._schema._id = MongoDB.ObjectID;
if(this._schema._id === MongoDB.ObjectID && !this._transforms._id)
this._transforms._id = DefaultTransforms.ObjectID;
if ((<Function>instanceType).prototype instanceof Instance)
this._Instance = ModelSpecificInstance(this, instanceType);
else
this._Instance = instanceType.bind(undefined, this);
}
/**
* Loads any internally (protected/private) properties and helpers only used within Iridium itself.
*/
private loadInternal() {
this._cache = new ModelCache(this);
this._helpers = new ModelHelpers(this);
this._handlers = new ModelHandlers(this);
}
/**
* Process any callbacks and plugin delegation for the creation of this model.
* It will generally be called whenever a new Iridium Core is created, however is
* more specifically tied to the lifespan of the models themselves.
*/
private onNewModel() {
this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this));
}
private _helpers: ModelHelpers<TDocument, TInstance>;
/**
* Provides helper methods used by Iridium for common tasks
* @returns A set of helper methods which are used within Iridium for common tasks
*/
get helpers(): ModelHelpers<TDocument, TInstance> {
return this._helpers;
}
private _handlers: ModelHandlers<TDocument, TInstance>;
/**
* Provides helper methods used by Iridium for hook delegation and common processes
* @returns A set of helper methods which perform common event and response handling tasks within Iridium.
*/
get handlers(): ModelHandlers<TDocument, TInstance> {
return this._handlers;
}
private _hooks: Hooks<TDocument, TInstance> = {};
/**
* Gets the even hooks subscribed on this model for a number of different state changes.
* These hooks are primarily intended to allow lifecycle manipulation logic to be added
* in the user's model definition, allowing tasks such as the setting of default values
* or automatic client-side joins to take place.
*/
get hooks(): Hooks<TDocument, TInstance> {
return this._hooks;
}
private _schema: Schema;
/**
* Gets the schema dictating the data structure represented by this model.
* The schema is used by skmatc to validate documents before saving to the database, however
* until MongoDB 3.1 becomes widely available (with server side validation support) we are
* limited in our ability to validate certain types of updates. As such, these validations
* act more as a data-integrity check than anything else, unless you purely make use of Omnom
* updates within instances.
* @public
* @returns The defined validation schema for this model
*/
get schema(): Schema {
return this._schema;
}
private _core: Core;
/**
* Gets the Iridium core that this model is associated with.
* @public
* @returns The Iridium core that this model is bound to
*/
get core(): Core {
return this._core;
}
private _collection: string;
/**
* Gets the underlying MongoDB collection from which this model's documents are retrieved.
* You can make use of this object if you require any low level access to the MongoDB collection,
* however we recommend you make use of the Iridium methods whereever possible, as we cannot
* guarantee the accuracy of the type definitions for the underlying MongoDB driver.
* @public
* @returns {Collection}
*/
get collection(): MongoDB.Collection {
return this.core.connection.collection(this._collection);
}
/**
* Gets the name of the underlying MongoDB collection from which this model's documents are retrieved
* @public
*/
get collectionName(): string {
return this._collection;
}
/**
* Sets the name of the underlying MongoDB collection from which this model's documents are retrieved
* @public
*/
set collectionName(value: string) {
this._collection = value;
}
private _cacheDirector: CacheDirector;
/**
* Gets the cache controller which dictates which queries will be cached, and under which key
* @public
* @returns {CacheDirector}
*/
get cacheDirector(): CacheDirector {
return this._cacheDirector;
}
private _cache: ModelCache;
/**
* Gets the cache responsible for storing objects for quick retrieval under certain conditions
* @public
* @returns {ModelCache}
*/
get cache(): ModelCache {
return this._cache;
}
private _Instance: ModelInterfaces.ModelSpecificInstanceConstructor<TDocument, TInstance>;
/**
* Gets the constructor responsible for creating instances for this model
*/
get Instance(): ModelInterfaces.ModelSpecificInstanceConstructor<TDocument, TInstance> {
return this._Instance;
}
private _transforms: Transforms;
/**
* Gets the transforms which are applied whenever a document is received from the database, or
* prior to storing a document in the database. Tasks such as converting an ObjectID to a string
* and vice versa are all listed in this object.
*/
get transforms() {
return this._transforms;
}
private _validators: Skmatc.Validator[];
/**
* Gets the custom validation types available for this model. These validators are added to the
* default skmatc validators, as well as those available through plugins, for use when checking
* your instances.
*/
get validators() {
return this._validators;
}
private _indexes: (Index.Index | Index.IndexSpecification)[];
/**
* Gets the indexes which Iridium will manage on this model's database collection.
*/
get indexes() {
return this._indexes;
}
/**
* Retrieves all documents in the collection and wraps them as instances
* @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available
* @returns {Promise<TInstance[]>}
*/
find(): Cursor<TDocument, TInstance>;
/**
* Returns all documents in the collection which match the conditions and wraps them as instances
* @param {Object} conditions The MongoDB query dictating which documents to return
* @returns {Promise<TInstance[]>}
*/
find(conditions: { _id?: string; } | Conditions | string): Cursor<TDocument, TInstance>;
/**
* Returns all documents in the collection which match the conditions
* @param {Object} conditions The MongoDB query dictating which documents to return
* @param {Object} fields The fields to include or exclude from the document
* @returns {Promise<TInstance[]>}
*/
find(conditions: { _id?: string; } | Conditions | string, fields: { [name: string]: number }): Cursor<TDocument, TInstance>;
find(conditions?: { _id?: string; } | Conditions | string, fields?: any): Cursor<TDocument, TInstance> {
conditions = conditions || {};
if (!_.isPlainObject(conditions)) conditions = { _id: conditions };
conditions = this._helpers.convertToDB(conditions);
let cursor = this.collection.find(conditions);
if(fields)
cursor = cursor.project(fields);
return new Cursor<TDocument, TInstance>(this, conditions, cursor);
}
/**
* Retrieves a single document from the collection and wraps it as an instance
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
get(callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Retrieves a single document from the collection with the given ID and wraps it as an instance
* @param {any} id The document's unique _id field value in downstream format
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
get(id: string, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Retrieves a single document from the collection which matches the conditions
* @param {Object} conditions The MongoDB query dictating which document to return
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
get(conditions: { _id?: string; } | Conditions, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Retrieves a single document from the collection with the given ID and wraps it as an instance
* @param {any} id The document's unique _id field value in downstream format
* @param {QueryOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
get(id: string, options: ModelOptions.QueryOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Retrieves a single document from the collection which matches the conditions
* @param {Object} conditions The MongoDB query dictating which document to return
* @param {QueryOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
get(conditions: { _id?: string; } | Conditions, options: ModelOptions.QueryOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
get(...args: any[]): Bluebird<TInstance> {
return this.findOne.apply(this, args);
}
/**
* Retrieves a single document from the collection and wraps it as an instance
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
findOne(callback?: General.Callback<TInstance>): Bluebird<TInstance|null>;
/**
* Retrieves a single document from the collection with the given ID and wraps it as an instance
* @param {any} id The document's unique _id field value in downstream format
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
findOne(id: string, callback?: General.Callback<TInstance>): Bluebird<TInstance|null>;
/**
* Retrieves a single document from the collection which matches the conditions
* @param {Object} conditions The MongoDB query dictating which document to return
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
findOne(conditions: { _id?: string; } | Conditions, callback?: General.Callback<TInstance>): Bluebird<TInstance|null>;
/**
* Retrieves a single document from the collection with the given ID and wraps it as an instance
* @param {any} id The document's unique _id field value in downstream format
* @param {QueryOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
findOne(id: string, options: ModelOptions.QueryOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance|null>;
/**
* Retrieves a single document from the collection which matches the conditions
* @param {Object} conditions The MongoDB query dictating which document to return
* @param {QueryOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available
* @returns {Promise<TInstance>}
*/
findOne(conditions: { _id?: string; } | Conditions, options: ModelOptions.QueryOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance|null>;
findOne(...args: any[]): Bluebird<TInstance|null> {
let conditions: { _id?: any, [key: string]: any }|undefined;
let options: ModelOptions.QueryOptions|undefined;
let callback: General.Callback<TInstance>|undefined;
for (let argI = 0; argI < args.length; argI++) {
if (typeof args[argI] === "function") callback = callback || args[argI];
else if (_.isPlainObject(args[argI])) {
if (conditions) options = args[argI];
else conditions = args[argI];
}
else conditions = { _id: args[argI] };
}
conditions = conditions || {};
options = options || {};
_.defaults(options, {
cache: true
});
return Bluebird.resolve().bind(this).then(() => {
conditions = this._helpers.convertToDB(conditions);
return this._cache.get<TDocument>(conditions);
}).then((cachedDocument: TDocument) => {
if (cachedDocument) return cachedDocument;
return new Bluebird<TDocument|null>((resolve, reject) => {
let cursor = this.collection.find(conditions);
if(options!.sort)
cursor = cursor.sort(options!.sort!);
if(typeof options!.skip === "number")
cursor = cursor.skip(options!.skip!);
cursor = cursor.limit(1);
if(options!.fields)
cursor = cursor.project(options!.fields!);
return cursor.next((err, result) => {
if (err) return reject(err);
return resolve(<TDocument|null>result);
});
});
}).then((document) => {
if (!document) return Bluebird.resolve(null);
return this._handlers.documentReceived(conditions, document, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), options);
}).nodeify(callback);
}
/**
* Inserts an object into the collection after validating it against this model's schema
* @param {Object} object The object to insert into the collection
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
create(objects: TDocument, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Inserts an object into the collection after validating it against this model's schema
* @param {Object} object The object to insert into the collection
* @param {CreateOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Inserts the objects into the collection after validating them against this model's schema
* @param {Object[]} objects The objects to insert into the collection
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
create(objects: TDocument[], callback?: General.Callback<TInstance[]>): Bluebird<TInstance[]>;
/**
* Inserts the objects into the collection after validating them against this model's schema
* @param {Object[]} objects The objects to insert into the collection
* @param {CreateOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback<TInstance[]>): Bluebird<TInstance[]>;
create(...args: any[]): Bluebird<any> {
return this.insert.apply(this, args);
}
/**
* Inserts an object into the collection after validating it against this model's schema
* @param {Object} object The object to insert into the collection
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
insert(objects: TDocument, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Inserts an object into the collection after validating it against this model's schema
* @param {Object} object The object to insert into the collection
* @param {CreateOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Inserts the objects into the collection after validating them against this model's schema
* @param {Object[]} objects The objects to insert into the collection
* @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
insert(objects: TDocument[], callback?: General.Callback<TInstance[]>): Bluebird<TInstance[]>;
/**
* Inserts the objects into the collection after validating them against this model's schema
* @param {Object[]} objects The objects to insert into the collection
* @param {CreateOptions} options The options dictating how this function behaves
* @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback<TInstance[]>): Bluebird<TInstance[]>;
insert(objs: TDocument | TDocument[], ...args: any[]): Bluebird<any> {
let objects: TDocument[];
let options: ModelOptions.CreateOptions = {};
let callback: General.Callback<any>|undefined = undefined;
if (typeof args[0] === "function") callback = args[0];
else {
options = args[0];
callback = args[1];
}
if (Array.isArray(objs))
objects = <TDocument[]>objs;
else
objects = <TDocument[]>[objs];
options = options || {};
_.defaults(options, <ModelOptions.CreateOptions>{
w: "majority",
forceServerObjectId: true
});
return Bluebird.resolve().then(() => {
let queryOptions = { w: options.w, upsert: options.upsert, new: true };
if (options.upsert) {
let docs = this._handlers.creatingDocuments(objects);
return docs.map((object: { _id: any; }) => {
return new Bluebird<any[]>((resolve, reject) => {
this.collection.findOneAndUpdate({ _id: object._id || { $exists: false }}, object, {
upsert: options.upsert,
returnOriginal: false
}, (err, result) => {
if (err) return reject(err);
return resolve(result.value);
});
});
});
}
else
return this._handlers.creatingDocuments(objects).then(objects => _.chunk(objects, 1000)).map((objects: any[]) => {
return new Bluebird<any[]>((resolve, reject) => {
this.collection.insertMany(objects, queryOptions, (err, result) => {
if (err) return reject(err);
return resolve(result.ops);
});
});
}).then(results => _.flatten(results));
}).map((inserted: any) => {
return this._handlers.documentReceived(null, inserted, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), { cache: options.cache });
}).then((results: TInstance[]) => {
if (Array.isArray(objs)) return results;
return results[0];
}).nodeify(callback);
}
/**
* Updates the documents in the backing collection which match the conditions using the given update instructions
* @param {Object} conditions The conditions which determine which documents will be updated
* @param {Object} changes The changes to make to the documents
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
*/
update(conditions: { _id?: string; } | Conditions | string, changes: Changes, callback?: General.Callback<number>): Bluebird<number>;
/**
* Updates the documents in the backing collection which match the conditions using the given update instructions
* @param {Object} conditions The conditions which determine which documents will be updated
* @param {Object} changes The changes to make to the documents
* @param {UpdateOptions} options The options which dictate how this function behaves
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
*/
update(conditions: { _id?: string; } | Conditions | string, changes: Changes, options: ModelOptions.UpdateOptions, callback?: General.Callback<number>): Bluebird<number>;
update(conditions: { _id?: string; } | Conditions | string, changes: Changes, options?: ModelOptions.UpdateOptions, callback?: General.Callback<number>): Bluebird<number> {
if (typeof options === "function") {
callback = <General.Callback<number>>options;
options = {};
}
const opts = options || {};
if (!_.isPlainObject(conditions)) conditions = {
_id: conditions
};
_.defaults(opts, {
w: "majority",
multi: true
});
return Bluebird.resolve().then(() => {
conditions = this._helpers.convertToDB(conditions);
return new Bluebird<number>((resolve, reject) => {
const callback = (err: Error, response: MongoDB.UpdateWriteOpResult) => {
if (err) return reject(err);
// New MongoDB 2.6+ response type
if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified);
// Legacy response type
return resolve(response.result.n);
}
if (opts.multi)
return this.collection.updateMany(conditions, changes, opts, callback);
return this.collection.updateOne(conditions, changes, opts, callback)
})
}).nodeify(callback);
}
/**
* Counts the number of documents in the collection
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
* @returns {Promise<number>}
*/
count(callback?: General.Callback<number>): Bluebird<number>;
/**
* Counts the number of documents in the collection which match the conditions provided
* @param {Object} conditions The conditions which determine whether an object is counted or not
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
* @returns {Promise<number>}
*/
count(conditions: { _id?: string; } | Conditions, callback?: General.Callback<number>): Bluebird<number>;
count(conds?: any, callback?: General.Callback<number>): Bluebird<number> {
let conditions: { _id?: string; } | Conditions = conds;
if (typeof conds === "function") {
callback = <General.Callback<number>>conds;
conditions = {};
}
conditions = conditions || {};
if (!_.isPlainObject(conditions)) conditions = {
_id: conditions
};
return Bluebird.resolve().then(() => {
conditions = this._helpers.convertToDB(conditions);
return new Bluebird<number>((resolve, reject) => {
this.collection.count(conditions, (err, results) => {
if (err) return reject(err);
return resolve(results);
});
});
}).nodeify(callback);
}
/**
* Removes all documents from the collection
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
* @returns {Promise<number>}
*/
remove(callback?: General.Callback<number>): Bluebird<number>;
/**
* Removes all documents from the collection which match the conditions
* @param {Object} conditions The conditions determining whether an object is removed or not
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
* @returns {Promise<number>}
*/
remove(conditions: { _id?: string; } | Conditions | any, callback?: General.Callback<number>): Bluebird<number>;
/**
* Removes all documents from the collection which match the conditions
* @param {Object} conditions The conditions determining whether an object is removed or not
* @param {Object} options The options controlling the way in which the function behaves
* @param {function(Error, Number)} callback A callback which is triggered when the operation completes
* @returns {Promise<number>}
*/
remove(conditions: { _id?: string; } | Conditions | string, options: ModelOptions.RemoveOptions, callback?: General.Callback<number>): Bluebird<number>;
remove(conds?: any, options?: ModelOptions.RemoveOptions, callback?: General.Callback<number>): Bluebird<number> {
let conditions: { _id?: string; } | Conditions = conds;
if (typeof options === "function") {
callback = <General.Callback<number>>options;
options = {};
}
if (typeof conds === "function") {
callback = <General.Callback<number>>conds;
options = {};
conditions = {};
}
conditions = conditions || {};
options = options || {};
_.defaults(options, {
w: "majority"
});
if (!_.isPlainObject(conditions)) conditions = {
_id: conditions
};
return Bluebird.resolve().then(() => {
conditions = this._helpers.convertToDB(conditions);
return new Bluebird<number|undefined>((resolve, reject) => {
if(options!.single) return this.collection.deleteOne(conditions, options!, (err, response) => {
if (err) return reject(err);
return resolve(response.result.n);
});
this.collection.deleteMany(conditions, options!, (err, response) => {
if (err) return reject(err);
return resolve(response.result.n);
});
});
}).then((count) => {
if (count === undefined) return Bluebird.resolve<number>(0);
if (count === 1) this._cache.clear(conditions);
return Bluebird.resolve<number>(count);
}).nodeify(callback);
}
aggregate<T>(pipeline: AggregationPipeline.Stage[]): Bluebird<T[]> {
return new Bluebird<T[]>((resolve, reject) => {
this.collection.aggregate(pipeline, (err, results) => {
if(err) return reject(err);
return resolve(results);
});
});
}
/**
* Runs a mapReduce operation in MongoDB and returns the contents of the resulting collection.
* @param functions The mapReduce functions which will be passed to MongoDB to complete the operation.
* @param options Options used to configure how MongoDB runs the mapReduce operation on your collection.
* @return A promise which completes when the mapReduce operation has written its results to the provided collection.
*/
mapReduce<Key, Value>(functions: MapReduceFunctions<TDocument, Key, Value>, options: MapReduceOptions): Bluebird<MapReducedDocument<Key, Value>[]>;
/**
* Runs a mapReduce operation in MongoDB and writes the results to a collection.
* @param instanceType An Iridium.Instance type whichThe mapReduce functions which will be passed to MongoDB to complete the operation.
* @param options Options used to configure how MongoDB runs the mapReduce operation on your collection.
* @return A promise which completes when the mapReduce operation has written its results to the provided collection.
*/
mapReduce<Key, Value>(instanceType: InstanceImplementation<MapReducedDocument<Key, Value>, any>,
options: MapReduceOptions): Bluebird<void>;
mapReduce<Key, Value>(functions: InstanceImplementation<MapReducedDocument<Key, Value>, any> |
MapReduceFunctions<TDocument, Key, Value>, options: MapReduceOptions) {
type fn = MapReduceFunctions<TDocument, Key, Value>;
type instance = InstanceImplementation<MapReducedDocument<Key, Value>, any>
if ((<fn>functions).map) {
return new Bluebird<MapReducedDocument<Key, Value>[]>((resolve, reject) => {
if (options.out && options.out != "inline")
return reject(new Error("Expected inline mapReduce output mode for this method signature"));
let opts = <MongoDB.MapReduceOptions>options;
opts.out = { inline: 1 };
this.collection.mapReduce((<fn>functions).map, (<fn>functions).reduce, opts, function (err, data) {
if (err) return reject(err);
return resolve(data);
});
})
}
else {
let instanceType = <instance>functions;
return new Bluebird<void>((resolve, reject) => {
if (options.out && options.out == "inline")
return reject(new Error("Expected a non-inline mapReduce output mode for this method signature"));
if (!instanceType.mapReduceOptions)
return reject(new Error("Expected mapReduceOptions to be specified on the instance type"));
let opts = <MongoDB.MapReduceOptions>options;
let out : {[op: string]: string} = {};
out[(<string>options.out)] = instanceType.collection;
opts.out = out;
this.collection.mapReduce(instanceType.mapReduceOptions.map, instanceType.mapReduceOptions.reduce, opts, (err, data) => {
if (err) return reject(err);
return resolve();
});
})
}
}
/**
* Ensures that the given index is created for the collection
* @param {Object} specification The index specification object used by MongoDB
* @param {function(Error, String)} callback A callback which is triggered when the operation completes
* @returns {Promise<String>} The name of the index
*/
ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback<string>): Bluebird<string>;
/**
* Ensures that the given index is created for the collection
* @param {Object} specification The index specification object used by MongoDB
* @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves
* @param {function(Error, String)} callback A callback which is triggered when the operation completes
* @returns {Promise<String>} The name of the index
*/
ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback<string>): Bluebird<string>;
ensureIndex(specification: Index.IndexSpecification, options?: MongoDB.IndexOptions, callback?: General.Callback<string>): Bluebird<string> {
if (typeof options === "function") {
callback = <General.Callback<any>>options;
options = {};
}
return new Bluebird<string>((resolve, reject) => {
this.collection.createIndex(specification, options || {}, (err: Error, name: any) => {
if (err) return reject(err);
return resolve(name);
});
}).nodeify(callback);
}
/**
* Ensures that all indexes defined in the model's options are created
* @param {function(Error, String[])} callback A callback which is triggered when the operation completes
* @returns {Promise<String[]>} The names of the indexes
*/
ensureIndexes(callback?: General.Callback<string[]>): Bluebird<string[]> {
return Bluebird.resolve(this._indexes).map((index: Index.Index | Index.IndexSpecification) => {
return this.ensureIndex((<Index.Index>index).spec || <Index.IndexSpecification>index, (<Index.Index>index).options || {});
}).nodeify(callback);
}
/**
* Drops the index with the specified name if it exists in the collection
* @param {String} name The name of the index to remove
* @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes
* @returns {Promise<Boolean>} Whether the index was dropped
*/
dropIndex(name: string, callback?: General.Callback<boolean>): Bluebird<boolean>;
/**
* Drops the index if it exists in the collection
* @param {IndexSpecification} index The index to remove
* @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes
* @returns {Promise<Boolean>} Whether the index was dropped
*/
dropIndex(index: Index.IndexSpecification, callback?: General.Callback<boolean>): Bluebird<boolean>;
dropIndex(specification: string | Index.IndexSpecification, callback?: General.Callback<boolean>): Bluebird<boolean> {
let index: string|undefined;
if (typeof (specification) === "string") index = <string>specification;
else {
index = _(<Index.IndexSpecification>specification).map((direction: number, key: string) => `${key}_${direction}`).reduce<string>((x, y) => `${x}_${y}`);
}
if (!index)
return Bluebird.reject(new Error("Expected a valid index name to be provided"));
return new Bluebird<boolean>((resolve, reject) => {
this.collection.dropIndex(index!, (err: Error, result: { ok: number }) => {
if (err) return reject(err);
return resolve(<any>!!result.ok);
});
}).nodeify(callback);
}
/**
* Removes all indexes (except for _id) from the collection
* @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes
* @returns {Promise<Boolean>} Whether the indexes were dropped
*/
dropIndexes(callback?: General.Callback<boolean>): Bluebird<boolean> {
return new Bluebird<any>((resolve, reject) => {
this.collection.dropIndexes((err, count) => {
if (err) return reject(err);
return resolve(count);
});
}).nodeify(callback);
}
} | the_stack |
import { Injectable, Autowired, Injector, INJECTOR_TOKEN } from '@opensumi/di';
import {
Event,
formatLocalize,
IProblemMatcherRegistry,
Disposable,
Deferred,
ProblemMatcher,
isString,
strings,
Emitter,
DisposableCollection,
ProblemMatch,
ProblemMatchData,
objects,
path,
} from '@opensumi/ide-core-common';
import {
TerminalOptions,
ITerminalController,
ITerminalGroupViewService,
ITerminalClient,
ITerminalService,
} from '@opensumi/ide-terminal-next/lib/common';
import { IVariableResolverService } from '@opensumi/ide-variable';
import {
ITaskSystem,
ITaskExecuteResult,
ITaskExecutor,
TaskExecuteKind,
IActivateTaskExecutorData,
TaskTerminateResponse,
} from '../common';
import {
Task,
ContributedTask,
CommandString,
CommandConfiguration,
TaskEvent,
TaskEventKind,
RuntimeType,
} from '../common/task';
import { CustomTask } from '../common/task';
import { ProblemCollector } from './problem-collector';
const { deepClone } = objects;
const { removeAnsiEscapeCodes } = strings;
const { Path } = path;
enum TaskStatus {
PROCESS_INIT,
PROCESS_READY,
PROCESS_RUNNING,
PROCESS_EXITED,
}
function rangeAreEqual(a, b) {
return (
a.start.line === b.start.line &&
a.start.character === b.start.character &&
a.end.line === b.end.line &&
a.end.character === b.end.character
);
}
function problemAreEquals(a: ProblemMatchData | ProblemMatch, b: ProblemMatchData | ProblemMatch) {
return (
a.resource?.toString() === b.resource?.toString() &&
a.description.owner === b.description.owner &&
a.description.severity === b.description.severity &&
a.description.source === b.description.source &&
(a as ProblemMatchData)?.marker.code === (b as ProblemMatchData)?.marker.code &&
(a as ProblemMatchData)?.marker.message === (b as ProblemMatchData)?.marker.message &&
(a as ProblemMatchData)?.marker.source === (b as ProblemMatchData)?.marker.source &&
rangeAreEqual((a as ProblemMatchData).marker.range, (b as ProblemMatchData).marker.range)
);
}
@Injectable({ multiple: true })
export class TerminalTaskExecutor extends Disposable implements ITaskExecutor {
@Autowired(ITerminalGroupViewService)
protected readonly terminalView: ITerminalGroupViewService;
@Autowired(ITerminalController)
protected readonly terminalController: ITerminalController;
@Autowired(ITerminalService)
protected readonly terminalService: ITerminalService;
private terminalClient: ITerminalClient | undefined;
private pid: number | undefined;
private exitDefer: Deferred<{ exitCode?: number }> = new Deferred();
private _onDidTerminalCreated: Emitter<string> = new Emitter();
private _onDidTaskProcessExit: Emitter<number | undefined> = new Emitter();
private _onDidBackgroundTaskBegin: Emitter<void> = new Emitter();
public onDidBackgroundTaskBegin: Event<void> = this._onDidBackgroundTaskBegin.event;
private _onDidBackgroundTaskEnd: Emitter<void> = new Emitter();
public onDidBackgroundTaskEnd: Event<void> = this._onDidBackgroundTaskEnd.event;
private _onDidProblemMatched: Emitter<ProblemMatch[]> = new Emitter();
public onDidProblemMatched: Event<ProblemMatch[]> = this._onDidProblemMatched.event;
private _onDidTerminalWidgetRemove: Emitter<void> = new Emitter();
public onDidTerminalCreated: Event<string> = this._onDidTerminalCreated.event;
public onDidTerminalWidgetRemove: Event<void> = this._onDidTerminalWidgetRemove.event;
public onDidTaskProcessExit: Event<number | undefined> = this._onDidTaskProcessExit.event;
public processReady: Deferred<void> = new Deferred<void>();
private processExited = false;
private disposableCollection: DisposableCollection = new DisposableCollection();
public taskStatus: TaskStatus = TaskStatus.PROCESS_INIT;
constructor(
private task: Task,
private terminalOptions: TerminalOptions,
private collector: ProblemCollector,
public executorId: number,
) {
super();
this.addDispose(
this.terminalView.onWidgetDisposed((e) => {
if (this.terminalClient && e.id === this.terminalClient.id) {
this._onDidTerminalWidgetRemove.fire();
}
}),
);
}
terminate(): Promise<{ success: boolean }> {
return new Promise((resolve) => {
if (this.terminalClient) {
this.terminalClient.dispose();
if (this.processExited) {
// 如果在调 terminate 之前进程已经退出,直接删掉 terminalWidget 即可
this.terminalView.removeWidget(this.terminalClient.id);
resolve({ success: true });
} else {
this.terminalService.onExit((e) => {
if (e.sessionId === this.terminalClient?.id) {
this.terminalView.removeWidget(this.terminalClient.id);
resolve({ success: true });
}
});
}
} else {
resolve({ success: true });
}
});
}
private onTaskExit(code?: number) {
const { term, id } = this.terminalClient!;
term.setOption('disableStdin', true);
term.writeln(formatLocalize('terminal.integrated.exitedWithCode', code));
term.writeln(`\r\n\x1b[1m${formatLocalize('reuseTerminal')}\x1b[0m`);
this._onDidTaskProcessExit.fire(code);
this.disposableCollection.push(
term.onKey(() => {
this.terminalView.removeWidget(id);
}),
);
}
private bindTerminalClientEvent() {
this.addDispose(
this.terminalClient?.onOutput((e) => {
const output = removeAnsiEscapeCodes(e.data.toString());
const isBegin = this.collector.matchBeginMatcher(output);
if (isBegin) {
this._onDidBackgroundTaskBegin.fire();
}
// process multi-line output
const lines = output.split(/\r?\n/g).filter((e) => e);
const markerResults: ProblemMatch[] = [];
for (const l of lines) {
const markers = this.collector.processLine(l);
if (markers && markers.length > 0) {
for (const marker of markers) {
const existing = markerResults.findIndex((e) => problemAreEquals(e, marker));
if (existing === -1) {
markerResults.push(marker);
}
}
}
}
if (markerResults.length > 0) {
this._onDidProblemMatched.fire(markerResults);
}
const isEnd = this.collector.matchEndMatcher(output);
if (isEnd) {
this._onDidBackgroundTaskEnd.fire();
}
}) || Disposable.NULL,
);
this.disposableCollection.push(
this.terminalClient?.onExit(async (e) => {
if (e.id === this.terminalClient?.id) {
this.onTaskExit(e.code);
this.processExited = true;
this.taskStatus = TaskStatus.PROCESS_EXITED;
this.exitDefer.resolve({ exitCode: e.code });
}
}) || Disposable.NULL,
);
this.disposableCollection.push(
this.terminalService.onExit(async (e) => {
if (e.sessionId === this.terminalClient?.id) {
await this.processReady.promise;
this.onTaskExit(e.code);
this.processExited = true;
this.taskStatus = TaskStatus.PROCESS_EXITED;
this.exitDefer.resolve({ exitCode: e.code });
}
}),
);
}
private async createTerminal(reuse?: boolean) {
if (reuse && this.terminalClient) {
this.terminalClient.updateOptions(this.terminalOptions);
this.terminalClient.reset();
} else {
this.terminalClient = await this.terminalController.createClientWithWidget2({
terminalOptions: this.terminalOptions,
closeWhenExited: false,
isTaskExecutor: true,
taskId: this.task._id,
beforeCreate: (terminalId) => {
this._onDidTerminalCreated.fire(terminalId);
},
});
}
this.terminalController.showTerminalPanel();
this.bindTerminalClientEvent();
}
async attach(terminalClient: ITerminalClient): Promise<{ exitCode?: number }> {
this.taskStatus = TaskStatus.PROCESS_READY;
this.terminalClient = terminalClient;
this.terminalOptions = terminalClient.options;
this.bindTerminalClientEvent();
this.taskStatus = TaskStatus.PROCESS_RUNNING;
this.pid = await this.terminalClient?.pid;
this.processReady.resolve();
this._onDidTerminalCreated.fire(terminalClient.id);
return this.exitDefer.promise;
}
async execute(task: Task, reuse?: boolean): Promise<{ exitCode?: number }> {
this.taskStatus = TaskStatus.PROCESS_READY;
await this.createTerminal(reuse);
this.terminalClient?.term.writeln(`\x1b[3m> Executing task: ${task._label} <\x1b[0m\n`);
const { shellArgs } = this.terminalOptions;
// extensionTerminal 由插件自身接管,不需要执行和输出 Command
if (!this.terminalOptions.isExtensionTerminal && shellArgs) {
this.terminalClient?.term.writeln(
`\x1b[3m> Command: ${typeof shellArgs === 'string' ? shellArgs : shellArgs[1]} <\x1b[0m\n`,
);
}
await this.terminalClient?.attached.promise;
this.taskStatus = TaskStatus.PROCESS_RUNNING;
this.pid = await this.terminalClient?.pid;
this.processReady.resolve();
this.terminalClient?.term.write('\n\x1b[G');
return this.exitDefer.promise;
}
get processId(): number | undefined {
return this.pid;
}
get terminalId(): string | undefined {
return this.terminalClient && this.terminalClient.id;
}
get widgetId(): string | undefined {
return this.terminalClient && this.terminalClient.widget.id;
}
public updateTerminalOptions(terminalOptions: TerminalOptions) {
this.terminalOptions = terminalOptions;
}
public updateProblemCollector(collector: ProblemCollector) {
this.collector = collector;
}
public reset() {
this.disposableCollection.dispose();
this.taskStatus = TaskStatus.PROCESS_INIT;
this.exitDefer = new Deferred();
}
}
@Injectable()
export class TerminalTaskSystem extends Disposable implements ITaskSystem {
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(IProblemMatcherRegistry)
problemMatcher: IProblemMatcherRegistry;
@Autowired(IVariableResolverService)
variableResolver: IVariableResolverService;
private executorId = 0;
protected currentTask: Task;
private activeTaskExecutors: Map<string, IActivateTaskExecutorData> = new Map();
private _onDidStateChange: Emitter<TaskEvent> = new Emitter();
private _onDidBackgroundTaskBegin: Emitter<TaskEvent> = new Emitter();
private _onDidBackgroundTaskEnded: Emitter<TaskEvent> = new Emitter();
private _onDidProblemMatched: Emitter<TaskEvent> = new Emitter();
private taskExecutors: TerminalTaskExecutor[] = [];
onDidStateChange: Event<TaskEvent> = this._onDidStateChange.event;
onDidBackgroundTaskBegin: Event<TaskEvent> = this._onDidBackgroundTaskBegin.event;
onDidBackgroundTaskEnded: Event<TaskEvent> = this._onDidBackgroundTaskEnded.event;
onDidProblemMatched: Event<TaskEvent> = this._onDidProblemMatched.event;
run(task: CustomTask | ContributedTask): Promise<ITaskExecuteResult> {
this.currentTask = task;
return this.executeTask(task);
}
attach(task: CustomTask | ContributedTask, terminalClient: ITerminalClient): Promise<ITaskExecuteResult> {
this.currentTask = task;
return this.attachTask(task, terminalClient);
}
private async buildShellConfig(command: CommandConfiguration) {
let subCommand = '';
const commandName = command.name;
const commandArgs = command.args;
const subArgs: string[] = [];
const result: string[] = [];
if (commandName) {
if (typeof commandName === 'string') {
subCommand = commandName;
} else {
subCommand = commandName.value;
}
}
subArgs.push(subCommand);
if (commandArgs) {
for (const arg of commandArgs) {
if (typeof arg === 'string') {
subArgs.push(arg);
} else {
subArgs.push(arg.value);
}
}
}
for (const arg of subArgs) {
if (arg.indexOf(Path.separator) > -1) {
result.push(await this.resolveVariables(arg.split(Path.separator)));
} else {
result.push(await this.resolveVariable(arg));
}
}
return { shellArgs: ['-c', `${result.join(' ')}`] };
}
private findAvailableExecutor(): TerminalTaskExecutor | undefined {
return this.taskExecutors.find((e) => e.taskStatus === TaskStatus.PROCESS_EXITED);
}
private async createTaskExecutor(task: CustomTask | ContributedTask, options: TerminalOptions) {
const matchers = await this.resolveMatchers(task.configurationProperties.problemMatchers);
const collector = new ProblemCollector(matchers);
const executor = this.injector.get(TerminalTaskExecutor, [task, options, collector, this.executorId]);
this.executorId += 1;
this.taskExecutors.push(executor);
this.addDispose(
executor.onDidTerminalWidgetRemove(() => {
this.taskExecutors = this.taskExecutors.filter((t) => t.executorId !== executor.executorId);
}),
);
return executor;
}
private async attachTask(
task: CustomTask | ContributedTask,
terminalClient: ITerminalClient,
): Promise<ITaskExecuteResult> {
const taskExecutor = await this.createTaskExecutor(task, terminalClient.options);
const p = taskExecutor.attach(terminalClient);
return {
task,
kind: TaskExecuteKind.Started,
promise: p,
};
}
private async executeTask(task: CustomTask | ContributedTask): Promise<ITaskExecuteResult> {
// CustomExecution
const isCustomExecution = task.command && task.command.runtime === RuntimeType.CustomExecution;
const matchers = await this.resolveMatchers(task.configurationProperties.problemMatchers);
const collector = new ProblemCollector(matchers);
const { shellArgs } = await this.buildShellConfig(task.command);
const terminalOptions: TerminalOptions = {
name: this.createTerminalName(task),
shellArgs,
isExtensionTerminal: isCustomExecution,
env: task.command.options?.env || {},
cwd: task.command.options?.cwd
? await this.resolveVariable(task.command.options?.cwd)
: await this.resolveVariable('${workspaceFolder}'),
};
let executor: TerminalTaskExecutor | undefined = this.findAvailableExecutor();
let reuse = false;
if (!executor) {
executor = await this.createTaskExecutor(task, terminalOptions);
} else {
reuse = true;
executor.updateProblemCollector(collector);
executor.updateTerminalOptions(terminalOptions);
executor.reset();
}
if (reuse) {
// 插件进程中 CustomExecution 会等待前台终端实例创建完成后进行 attach
// 重用终端的情况下,要再次发出事件确保 attach 成功 (ext.host.task.ts#$onDidStartTask)
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, executor.terminalId));
} else {
this.addDispose(
executor.onDidTerminalCreated((terminalId) => {
// 当 task 使用 CustomExecution 时,发出 TaskEventKind.Start 事件后
// 插件进程将尝试 attach 这个 Pseudoterminal (ext.host.task.ts#$onDidStartTask)
// attach 成功便会创建一个 ExtensionTerminal 实例
// 确保后续调用 $startExtensionTerminal 时已经建立了连接
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, terminalId));
}),
);
}
if (!reuse) {
this.addDispose(
executor.onDidTaskProcessExit((code) => {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, code));
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
}),
);
this.addDispose(
executor.onDidBackgroundTaskBegin(() =>
this._onDidBackgroundTaskBegin.fire(TaskEvent.create(TaskEventKind.BackgroundTaskBegin, task)),
),
);
this.addDispose(
executor.onDidBackgroundTaskEnd(() =>
this._onDidBackgroundTaskEnded.fire(TaskEvent.create(TaskEventKind.BackgroundTaskEnded, task)),
),
);
this.addDispose(
executor.onDidProblemMatched((problems) =>
this._onDidProblemMatched.fire(TaskEvent.create(TaskEventKind.ProblemMatched, task, problems)),
),
);
}
const result = executor.execute(task, reuse);
const mapKey = task.getMapKey();
this.activeTaskExecutors.set(mapKey, { promise: Promise.resolve(result), task, executor });
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task));
await executor.processReady.promise;
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, executor.processId));
return {
task,
kind: TaskExecuteKind.Started,
promise: result,
};
}
private createTerminalName(task: CustomTask | ContributedTask): string {
return formatLocalize(
'TerminalTaskSystem.terminalName',
task.getQualifiedLabel() || task.configurationProperties.name,
);
}
private async resolveVariables(value: string[]): Promise<string> {
const result: string[] = [];
for (const item of value) {
result.push(await this.resolveVariable(item));
}
return result.join(Path.separator);
}
private async resolveVariable(value: string | undefined): Promise<string>;
private async resolveVariable(value: CommandString | undefined): Promise<CommandString>;
private async resolveVariable(value: CommandString | undefined): Promise<CommandString> {
if (isString(value)) {
return await this.variableResolver.resolve<string>(value);
} else if (value !== undefined) {
return {
value: await this.variableResolver.resolve<string>(value.value),
quoting: value.quoting,
};
} else {
// This should never happen
throw new Error('Should never try to resolve undefined.');
}
}
private async resolveMatchers(values: Array<string | ProblemMatcher> | undefined): Promise<ProblemMatcher[]> {
if (values === undefined || values === null || values.length === 0) {
return [];
}
const result: ProblemMatcher[] = [];
for (const value of values) {
let matcher: ProblemMatcher | undefined;
if (isString(value)) {
if (value[0].startsWith('$')) {
matcher = this.problemMatcher.get(value.substring(1));
} else {
matcher = this.problemMatcher.get(value);
}
} else {
matcher = value;
}
if (!matcher) {
continue;
}
const hasFilePrefix = matcher.filePrefix !== undefined;
if (!hasFilePrefix) {
result.push(matcher);
} else {
const copy = deepClone(matcher);
if (hasFilePrefix) {
copy.filePrefix = await this.resolveVariable(copy.filePrefix);
}
result.push(copy);
}
}
return result;
}
getActiveTasks(): Task[] {
return Array.from(this.activeTaskExecutors.values()).map((e) => e.task);
}
async terminate(task: Task): Promise<TaskTerminateResponse> {
const key = task.getMapKey();
const activeExecutor = this.activeTaskExecutors.get(key);
if (!activeExecutor) {
return Promise.resolve({ task: undefined, success: true });
}
const { success } = await activeExecutor.executor.terminate();
this.activeTaskExecutors.delete(key);
return { task, success };
}
rerun(): import('../common').ITaskExecuteResult | undefined {
throw new Error('Method not implemented.');
}
isActive(): Promise<boolean> {
throw new Error('Method not implemented.');
}
isActiveSync(): boolean {
throw new Error('Method not implemented.');
}
getBusyTasks(): import('../common/task').Task[] {
throw new Error('Method not implemented.');
}
canAutoTerminate(): boolean {
throw new Error('Method not implemented.');
}
terminateAll(): Promise<import('../common').TaskTerminateResponse[]> {
throw new Error('Method not implemented.');
}
revealTask(task: import('../common/task').Task): boolean {
throw new Error('Method not implemented.');
}
customExecutionComplete(task: import('../common/task').Task, result: number): Promise<void> {
throw new Error('Method not implemented.');
}
} | the_stack |
import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from "@angular/core";
import { GlobalVarsService } from "../../global-vars.service";
import { BackendApiService, User } from "../../backend-api.service";
import { ActivatedRoute, Router } from "@angular/router";
import * as _ from "lodash";
@Component({
selector: "messages-inbox",
templateUrl: "./messages-inbox.component.html",
styleUrls: ["./messages-inbox.component.scss"],
})
export class MessagesInboxComponent implements OnInit, OnChanges {
static CONTACT_US_USERNAME = "clippy";
static QUERYTOTAB = {
all: "All",
"my-holders": "My Holders",
custom: "Custom",
};
static TABTOQUERY = {
All: "all",
"My Holders": "my-holders",
Custom: "custom",
};
@Input() messageThreads: any;
@Input() profileMap: any;
@Input() isMobile = false;
@Output() selectedThreadEmitter = new EventEmitter<any>();
selectedThread: any;
fetchingMoreMessages: boolean = false;
activeTab: string;
startingSearchText: string;
// The contact to select by default, passed in via query param. Note: if the current user
// doesn't have a conversation with the contact, these parameters do nothing.
defaultContactPublicKey: any;
defaultContactUsername: any;
contactUsername: any;
constructor(
private globalVars: GlobalVarsService,
private backendApi: BackendApiService,
private route: ActivatedRoute,
private router: Router
) {
// Based on the route path set the tab and update filter/sort params
this.route.queryParams.subscribe((params) => {
let storedTab = this.backendApi.GetStorage("mostRecentMessagesTab");
this.activeTab =
params.messagesTab && params.messagesTab in MessagesInboxComponent.QUERYTOTAB
? MessagesInboxComponent.QUERYTOTAB[params.messagesTab]
: storedTab;
// Set the default active tab if there's nothing saved in local storage
if (this.activeTab === null) {
this.activeTab = "My Holders";
}
// Handle the tab click if the stored messages are from a different tab
if (this.activeTab !== storedTab) {
this._handleTabClick(this.activeTab);
}
if (params.username) {
this.startingSearchText = params.username;
}
});
}
ngOnInit() {
if (!this.isMobile) {
this._setSelectedThreadBasedOnDefaultThread();
}
}
ngOnChanges(changes: any) {
// If messageThreads were not loaded when the component initialized, we handle them here.
if (changes.messageThreads.previousValue === null && changes.messageThreads.currentValue.length > 0) {
this.updateReadMessagesForSelectedThread();
}
}
showMoreButton() {
return !(
this.globalVars.newMessagesFromPage != null &&
this.globalVars.newMessagesFromPage < this.globalVars.messagesPerFetch
);
}
loadMoreMessages() {
// If we're currently fetching messages
if (this.fetchingMoreMessages) {
return;
}
this.fetchingMoreMessages = true;
if (!this.globalVars.loggedInUser) {
return;
}
if (this.globalVars.newMessagesFromPage != null && this.globalVars.newMessagesFromPage == 0) {
return;
}
let fetchAfterPubKey = "";
if (this.globalVars.messageResponse.OrderedContactsWithMessages) {
fetchAfterPubKey = this.globalVars.messageResponse.OrderedContactsWithMessages[
this.globalVars.messageResponse.OrderedContactsWithMessages.length - 1
].PublicKeyBase58Check;
}
this.backendApi
.GetMessages(
this.globalVars.localNode,
this.globalVars.loggedInUser.PublicKeyBase58Check,
fetchAfterPubKey,
this.globalVars.messagesPerFetch,
this.globalVars.messagesRequestsHoldersOnly,
this.globalVars.messagesRequestsHoldingsOnly,
this.globalVars.messagesRequestsFollowersOnly,
this.globalVars.messagesRequestsFollowedOnly,
this.globalVars.messagesSortAlgorithm
)
.toPromise()
.then(
(res) => {
if (this.globalVars.pauseMessageUpdates) {
// We pause message updates when a user sends a messages so that we can
// wait for it to be sent before updating the thread. If we do not do this the
// temporary message place holder would disappear until "GetMessages()" finds it.
} else {
if (!this.globalVars.messageResponse) {
this.globalVars.messageResponse = res;
// If globalVars already has a messageResponse, we need to consolidate.
} else if (JSON.stringify(this.globalVars.messageResponse) !== JSON.stringify(res)) {
// Add the new contacts
this.globalVars.messageResponse.OrderedContactsWithMessages = this.globalVars.messageResponse.OrderedContactsWithMessages.concat(
res.OrderedContactsWithMessages
);
// If they're a new contact, add their read/unread status mapping
for (let key in res.UnreadStateByContact) {
this.globalVars.messageResponse.UnreadStateByContact[key] = res.UnreadStateByContact[key];
}
// Update the number of unread threads
this.globalVars.messageResponse.NumberOfUnreadThreads =
this.globalVars.messageResponse.NumberOfUnreadThreads + res.NumberOfUnreadThreads;
// Update the number of new messages so we know when to stop scrolling
this.globalVars.newMessagesFromPage = res.OrderedContactsWithMessages.length;
}
}
},
(err) => {
console.error(this.backendApi.stringifyError(err));
}
)
.finally(() => {
this.fetchingMoreMessages = false;
});
}
_handleTabClick(tabName: any) {
// Clear the current messages
this.globalVars.messageResponse = null;
// Make sure the tab is set in the url
this.activeTab = tabName;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { messagesTab: MessagesInboxComponent.TABTOQUERY[tabName] },
queryParamsHandling: "merge",
});
// Set the most recent tab in local storage
this.backendApi.SetStorage("mostRecentMessagesTab", tabName);
// Fetch initial messages for the new tab
this.globalVars.SetupMessages();
}
_toggleSettingsTray() {
this.globalVars.openSettingsTray = !this.globalVars.openSettingsTray;
}
_settingsTrayIsOpen() {
return this.globalVars.openSettingsTray;
}
// This sets the thread based on the defaultContactPublicKey or defaultContactUsername URL
// parameter
_setSelectedThreadBasedOnDefaultThread() {
// To figure out the default thread, we have to wait for globalVars to get a messagesResponse,
// so we set an interval and repeat until we get it. It might be better to use
// an explicit subscription, but this is less cruft, so not sure.
// TODO: refactor silly setInterval
let interval = setInterval(() => {
// If we don't have the messageResponse yet, return
let orderedContactsWithMessages = this.globalVars.messageResponse?.OrderedContactsWithMessages;
if (orderedContactsWithMessages == null) {
return;
}
// Check if the query params are set, otherwise default to the first thread
let defaultThread = null;
if (this.defaultContactUsername || this.defaultContactPublicKey) {
defaultThread = _.find(orderedContactsWithMessages, (messageContactResponse) => {
let responseUsername = messageContactResponse.ProfileEntryResponse?.Username;
let matchesUsername = responseUsername && responseUsername === this.contactUsername;
let matchesPublicKey = this.contactUsername === messageContactResponse.PublicKeyBase58Check;
return (responseUsername && matchesUsername) || matchesPublicKey;
});
} else if (orderedContactsWithMessages.length > 0) {
defaultThread = orderedContactsWithMessages[0];
}
if (!this.selectedThread) {
this._handleMessagesThreadClick(defaultThread);
}
clearInterval(interval);
}, 50);
}
// This marks all messages as read and relays this request to the server.
_markAllMessagesRead() {
for (let thread of this.messageThreads) {
this.globalVars.messageResponse.UnreadStateByContact[thread.PublicKeyBase58Check] = false;
}
// Send an update back to the server noting that we want to mark all threads read.
this.backendApi
.MarkAllMessagesRead(this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check)
.subscribe(
() => {
this.globalVars.logEvent("user : all-message-read");
},
(err) => {
console.log(err);
const parsedError = this.backendApi.stringifyError(err);
this.globalVars.logEvent("user : all-message-read : error", { parsedError });
this.globalVars._alertError(parsedError);
}
);
// Reflect this change in NumberOfUnreadThreads.
this.globalVars.messageResponse.NumberOfUnreadThreads = 0;
}
_getThreadWithPubKey(pubKey: string) {
for (let thread of this.messageThreads) {
// Public keys without a profile can message so use safe navigation
if (thread.ProfileEntryResponse?.PublicKeyBase58Check === pubKey) {
return thread;
}
}
return false;
}
_handleCreatorSelectedInSearch(creator: any) {
// If we haven't gotten the user's message state yet, bail.
if (!this.globalVars.messageResponse) {
return;
}
// If a thread with this creator already exists, select it.
let existingThread = this._getThreadWithPubKey(creator.PublicKeyBase58Check);
if (existingThread) {
this._handleMessagesThreadClick(existingThread);
return;
}
// Add the creator to the inbox as a new thread.
let newThread = {
PublicKeyBase58Check: creator.PublicKeyBase58Check,
Messages: [],
ProfileEntryResponse: creator,
NumMessagesRead: 0,
};
// This gets appeneded to the front of the ordered contacts list in the message inbox.
this.messageThreads.unshift(newThread);
// Make this the new selected thread.
this._handleMessagesThreadClick(newThread);
}
_handleMessagesThreadClick(thread: any) {
this.selectedThread = thread;
this.selectedThreadEmitter.emit(thread);
this.updateReadMessagesForSelectedThread();
}
updateReadMessagesForSelectedThread() {
// If selectedThread is undefined, we return
if (!this.selectedThread) {
return;
}
let contactPubKey = this.messageThreads[0]?.PublicKeyBase58Check;
if (this.selectedThread && this.selectedThread.PublicKeyBase58Check) {
contactPubKey = this.selectedThread.PublicKeyBase58Check;
}
// We update the read message state on global vars before sending the request so it is more instant.
if (this.globalVars.messageResponse.UnreadStateByContact[contactPubKey]) {
this.globalVars.messageResponse.UnreadStateByContact[contactPubKey] = false;
this.globalVars.messageResponse.NumberOfUnreadThreads -= 1;
// Send an update back to the server noting that we read this thread.
this.backendApi
.MarkContactMessagesRead(
this.globalVars.localNode,
this.globalVars.loggedInUser.PublicKeyBase58Check,
this.selectedThread.PublicKeyBase58Check
)
.subscribe(
() => {
this.globalVars.logEvent("user : message-read");
},
(err) => {
console.log(err);
const parsedError = this.backendApi.stringifyError(err);
this.globalVars.logEvent("user : message-read : error", { parsedError });
this.globalVars._alertError(parsedError);
}
);
}
}
} | the_stack |
import * as atomIde from 'atom-ide';
import Convert from '../convert';
import * as Utils from '../utils';
import { CancellationTokenSource } from 'vscode-jsonrpc';
import {
LanguageClientConnection,
SymbolKind,
ServerCapabilities,
SymbolInformation,
DocumentSymbol,
} from '../languageclient';
import {
Point,
TextEditor,
} from 'atom';
/**
* Public: Adapts the documentSymbolProvider of the language server to the Outline View
* supplied by Atom IDE UI.
*/
export default class OutlineViewAdapter {
private _cancellationTokens: WeakMap<LanguageClientConnection, CancellationTokenSource> = new WeakMap();
/**
* Public: Determine whether this adapter can be used to adapt a language server
* based on the serverCapabilities matrix containing a documentSymbolProvider.
*
* @param serverCapabilities The {ServerCapabilities} of the language server to consider.
* @returns A {Boolean} indicating adapter can adapt the server based on the
* given serverCapabilities.
*/
public static canAdapt(serverCapabilities: ServerCapabilities): boolean {
return serverCapabilities.documentSymbolProvider === true;
}
/**
* Public: Obtain the Outline for document via the {LanguageClientConnection} as identified
* by the {TextEditor}.
*
* @param connection A {LanguageClientConnection} to the language server that will be queried
* for the outline.
* @param editor The Atom {TextEditor} containing the text the Outline should represent.
* @returns A {Promise} containing the {Outline} of this document.
*/
public async getOutline(connection: LanguageClientConnection, editor: TextEditor): Promise<atomIde.Outline | null> {
const results = await Utils.doWithCancellationToken(connection, this._cancellationTokens, (cancellationToken) =>
connection.documentSymbol({ textDocument: Convert.editorToTextDocumentIdentifier(editor) }, cancellationToken),
);
if (results.length === 0) {
return {
outlineTrees: [],
};
}
if ((results[0] as DocumentSymbol).selectionRange !== undefined) {
// If the server is giving back the newer DocumentSymbol format.
return {
outlineTrees: OutlineViewAdapter.createHierarchicalOutlineTrees(
results as DocumentSymbol[]),
};
} else {
// If the server is giving back the original SymbolInformation format.
return {
outlineTrees: OutlineViewAdapter.createOutlineTrees(
results as SymbolInformation[]),
};
}
}
/**
* Public: Create an {Array} of {OutlineTree}s from the Array of {DocumentSymbol} recieved
* from the language server. This includes converting all the children nodes in the entire
* hierarchy.
*
* @param symbols An {Array} of {DocumentSymbol}s received from the language server that
* should be converted to an {Array} of {OutlineTree}.
* @returns An {Array} of {OutlineTree} containing the given symbols that the Outline View can display.
*/
public static createHierarchicalOutlineTrees(symbols: DocumentSymbol[]): atomIde.OutlineTree[] {
// Sort all the incoming symbols
symbols.sort((a, b) => {
if (a.range.start.line !== b.range.start.line) {
return a.range.start.line - b.range.start.line;
}
if (a.range.start.character !== b.range.start.character) {
return a.range.start.character - b.range.start.character;
}
if (a.range.end.line !== b.range.end.line) {
return a.range.end.line - b.range.end.line;
}
return a.range.end.character - b.range.end.character;
});
return symbols.map((symbol) => {
const tree = OutlineViewAdapter.hierarchicalSymbolToOutline(symbol);
if (symbol.children != null) {
tree.children = OutlineViewAdapter.createHierarchicalOutlineTrees(
symbol.children);
}
return tree;
});
}
/**
* Public: Create an {Array} of {OutlineTree}s from the Array of {SymbolInformation} recieved
* from the language server. This includes determining the appropriate child and parent
* relationships for the hierarchy.
*
* @param symbols An {Array} of {SymbolInformation}s received from the language server that
* should be converted to an {OutlineTree}.
* @returns An {OutlineTree} containing the given symbols that the Outline View can display.
*/
public static createOutlineTrees(symbols: SymbolInformation[]): atomIde.OutlineTree[] {
symbols.sort(
(a, b) =>
(a.location.range.start.line === b.location.range.start.line
? a.location.range.start.character - b.location.range.start.character
: a.location.range.start.line - b.location.range.start.line),
);
// Temporarily keep containerName through the conversion process
// Also filter out symbols without a name - it's part of the spec but some don't include it
const allItems = symbols.filter((symbol) => symbol.name).map((symbol) => ({
containerName: symbol.containerName,
outline: OutlineViewAdapter.symbolToOutline(symbol),
}));
// Create a map of containers by name with all items that have that name
const containers = allItems.reduce((map, item) => {
const name = item.outline.representativeName;
if (name != null) {
const container = map.get(name);
if (container == null) {
map.set(name, [item.outline]);
} else {
container.push(item.outline);
}
}
return map;
}, new Map());
const roots: atomIde.OutlineTree[] = [];
// Put each item within its parent and extract out the roots
for (const item of allItems) {
const containerName = item.containerName;
const child = item.outline;
if (containerName == null || containerName === '') {
roots.push(item.outline);
} else {
const possibleParents = containers.get(containerName);
let closestParent = OutlineViewAdapter._getClosestParent(possibleParents, child);
if (closestParent == null) {
closestParent = {
plainText: containerName,
representativeName: containerName,
startPosition: new Point(0, 0),
children: [child],
};
roots.push(closestParent);
if (possibleParents == null) {
containers.set(containerName, [closestParent]);
} else {
possibleParents.push(closestParent);
}
} else {
closestParent.children.push(child);
}
}
}
return roots;
}
private static _getClosestParent(
candidates: atomIde.OutlineTree[] | null,
child: atomIde.OutlineTree,
): atomIde.OutlineTree | null {
if (candidates == null || candidates.length === 0) {
return null;
}
let parent: atomIde.OutlineTree | undefined;
for (const candidate of candidates) {
if (
candidate !== child &&
candidate.startPosition.isLessThanOrEqual(child.startPosition) &&
(candidate.endPosition === undefined ||
(child.endPosition && candidate.endPosition.isGreaterThanOrEqual(child.endPosition)))
) {
if (
parent === undefined ||
(parent.startPosition.isLessThanOrEqual(candidate.startPosition) ||
(parent.endPosition != null &&
candidate.endPosition &&
parent.endPosition.isGreaterThanOrEqual(candidate.endPosition)))
) {
parent = candidate;
}
}
}
return parent || null;
}
/**
* Public: Convert an individual {DocumentSymbol} from the language server
* to an {OutlineTree} for use by the Outline View. It does NOT recursively
* process the given symbol's children (if any).
*
* @param symbol The {DocumentSymbol} to convert to an {OutlineTree}.
* @returns The {OutlineTree} corresponding to the given {DocumentSymbol}.
*/
public static hierarchicalSymbolToOutline(symbol: DocumentSymbol): atomIde.OutlineTree {
const icon = OutlineViewAdapter.symbolKindToEntityKind(symbol.kind);
return {
tokenizedText: [
{
kind: OutlineViewAdapter.symbolKindToTokenKind(symbol.kind),
value: symbol.name,
},
],
icon: icon != null ? icon : undefined,
representativeName: symbol.name,
startPosition: Convert.positionToPoint(symbol.selectionRange.start),
endPosition: Convert.positionToPoint(symbol.selectionRange.end),
children: [],
};
}
/**
* Public: Convert an individual {SymbolInformation} from the language server
* to an {OutlineTree} for use by the Outline View.
*
* @param symbol The {SymbolInformation} to convert to an {OutlineTree}.
* @returns The {OutlineTree} equivalent to the given {SymbolInformation}.
*/
public static symbolToOutline(symbol: SymbolInformation): atomIde.OutlineTree {
const icon = OutlineViewAdapter.symbolKindToEntityKind(symbol.kind);
return {
tokenizedText: [
{
kind: OutlineViewAdapter.symbolKindToTokenKind(symbol.kind),
value: symbol.name,
},
],
icon: icon != null ? icon : undefined,
representativeName: symbol.name,
startPosition: Convert.positionToPoint(symbol.location.range.start),
endPosition: Convert.positionToPoint(symbol.location.range.end),
children: [],
};
}
/**
* Public: Convert a symbol kind into an outline entity kind used to determine
* the styling such as the appropriate icon in the Outline View.
*
* @param symbol The numeric symbol kind received from the language server.
* @returns A string representing the equivalent OutlineView entity kind.
*/
public static symbolKindToEntityKind(symbol: number): string | null {
switch (symbol) {
case SymbolKind.Array:
return 'type-array';
case SymbolKind.Boolean:
return 'type-boolean';
case SymbolKind.Class:
return 'type-class';
case SymbolKind.Constant:
return 'type-constant';
case SymbolKind.Constructor:
return 'type-constructor';
case SymbolKind.Enum:
return 'type-enum';
case SymbolKind.Field:
return 'type-field';
case SymbolKind.File:
return 'type-file';
case SymbolKind.Function:
return 'type-function';
case SymbolKind.Interface:
return 'type-interface';
case SymbolKind.Method:
return 'type-method';
case SymbolKind.Module:
return 'type-module';
case SymbolKind.Namespace:
return 'type-namespace';
case SymbolKind.Number:
return 'type-number';
case SymbolKind.Package:
return 'type-package';
case SymbolKind.Property:
return 'type-property';
case SymbolKind.String:
return 'type-string';
case SymbolKind.Variable:
return 'type-variable';
case SymbolKind.Struct:
return 'type-class';
case SymbolKind.EnumMember:
return 'type-constant';
default:
return null;
}
}
/**
* Public: Convert a symbol kind to the appropriate token kind used to syntax
* highlight the symbol name in the Outline View.
*
* @param symbol The numeric symbol kind received from the language server.
* @returns A string representing the equivalent syntax token kind.
*/
public static symbolKindToTokenKind(symbol: number): atomIde.TokenKind {
switch (symbol) {
case SymbolKind.Class:
return 'type';
case SymbolKind.Constructor:
return 'constructor';
case SymbolKind.Method:
case SymbolKind.Function:
return 'method';
case SymbolKind.String:
return 'string';
default:
return 'plain';
}
}
} | the_stack |
import {isObject} from 'datalib/src/util';
import {AggregateOp} from 'vega';
import {Axis} from 'vega-lite/build/src/axis';
import {BinParams} from 'vega-lite/build/src/bin';
import {ExtendedChannel} from 'vega-lite/build/src/channel';
import * as vlChannelDef from 'vega-lite/build/src/channeldef';
import {ValueDef} from 'vega-lite/build/src/channeldef';
import {scaleType as compileScaleType} from 'vega-lite/build/src/compile/scale/type';
import {Encoding} from 'vega-lite/build/src/encoding';
import {Legend} from 'vega-lite/build/src/legend';
import {Mark} from 'vega-lite/build/src/mark';
import {Scale} from 'vega-lite/build/src/scale';
import {EncodingSortField, SortOrder} from 'vega-lite/build/src/sort';
import {StackOffset} from 'vega-lite/build/src/stack';
import {TimeUnit} from 'vega-lite/build/src/timeunit';
import * as TYPE from 'vega-lite/build/src/type';
import {Type as VLType} from 'vega-lite/build/src/type';
import {FlatProp, isEncodingNestedParent, Property} from '../property';
import {Schema} from '../schema';
import {isWildcard, SHORT_WILDCARD, Wildcard, WildcardProperty} from '../wildcard';
import {ExpandedType} from './expandedtype';
import {PROPERTY_SUPPORTED_CHANNELS} from './shorthand';
export type EncodingQuery = FieldQuery | ValueQuery | AutoCountQuery;
export interface EncodingQueryBase {
channel: WildcardProperty<ExtendedChannel>;
description?: string;
}
export interface ValueQuery extends EncodingQueryBase {
value: WildcardProperty<boolean | number | string>;
}
export function isValueQuery(encQ: EncodingQuery): encQ is ValueQuery {
return encQ !== null && encQ !== undefined && encQ['value'] !== undefined;
}
export function isFieldQuery(encQ: EncodingQuery): encQ is FieldQuery {
return encQ !== null && encQ !== undefined && (encQ['field'] || encQ['aggregate'] === 'count');
}
export function isAutoCountQuery(encQ: EncodingQuery): encQ is AutoCountQuery {
return encQ !== null && encQ !== undefined && 'autoCount' in encQ;
}
export function isDisabledAutoCountQuery(encQ: EncodingQuery) {
return isAutoCountQuery(encQ) && encQ.autoCount === false;
}
export function isEnabledAutoCountQuery(encQ: EncodingQuery) {
return isAutoCountQuery(encQ) && encQ.autoCount === true;
}
/**
* A special encoding query that gets added internally if the `config.autoCount` flag is on. See SpecQueryModel.build for its generation.
*
* __Note:__ this type of query should not be specified by users.
*/
export interface AutoCountQuery extends EncodingQueryBase {
/**
* A count function that gets added internally if the config.autoCount flag in on.
* This allows us to add one extra encoding mapping if needed when the query produces
* plot that only have discrete fields.
* In such cases, adding count make the output plots way more meaningful.
*/
autoCount: WildcardProperty<boolean>;
type: 'quantitative';
}
export interface FieldQueryBase {
// FieldDef
aggregate?: WildcardProperty<AggregateOp>;
timeUnit?: WildcardProperty<TimeUnit>;
/**
* Special flag for enforcing that the field should have a fuction (one of timeUnit, bin, or aggregate).
*
* For example, if you enumerate both bin and aggregate then you need `undefined` for both.
*
* ```
* {aggregate: {enum: [undefined, 'mean', 'sum']}, bin: {enum: [false, true]}}
* ```
*
* This would enumerate a fieldDef with "mean", "sum", bin:true, and no function at all.
* If you want only "mean", "sum", bin:true, then use `hasFn: true`
*
* ```
* {aggregate: {enum: [undefined, 'mean', 'sum']}, bin: {enum: [false, true]}, hasFn: true}
* ```
*/
hasFn?: boolean;
bin?: boolean | BinQuery | SHORT_WILDCARD;
scale?: boolean | ScaleQuery | SHORT_WILDCARD;
sort?: SortOrder | EncodingSortField<string>;
stack?: StackOffset | SHORT_WILDCARD;
field?: WildcardProperty<string>;
type?: WildcardProperty<ExpandedType>;
axis?: boolean | AxisQuery | SHORT_WILDCARD;
legend?: boolean | LegendQuery | SHORT_WILDCARD;
format?: string;
}
export type FieldQuery = EncodingQueryBase & FieldQueryBase;
// Using Mapped Type from TS2.1 to declare query for an object without nested property
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#mapped-types
export type FlatQuery<T> = {[P in keyof T]: WildcardProperty<T[P]>};
export type FlatQueryWithEnableFlag<T> = (Wildcard<boolean> | {}) & FlatQuery<T>;
export type BinQuery = FlatQueryWithEnableFlag<BinParams>;
export type ScaleQuery = FlatQueryWithEnableFlag<Scale>;
export type AxisQuery = FlatQueryWithEnableFlag<Axis>;
export type LegendQuery = FlatQueryWithEnableFlag<Legend<any>>;
const DEFAULT_PROPS = [
Property.AGGREGATE,
Property.BIN,
Property.TIMEUNIT,
Property.FIELD,
Property.TYPE,
Property.SCALE,
Property.SORT,
Property.AXIS,
Property.LEGEND,
Property.STACK,
Property.FORMAT,
];
export interface ConversionParams {
schema?: Schema;
props?: FlatProp[];
wildcardMode?: 'skip' | 'null';
}
export function toEncoding(encQs: EncodingQuery[], params: ConversionParams): Encoding<string> {
const {wildcardMode = 'skip'} = params;
const encoding: Encoding<string> = {};
for (const encQ of encQs) {
if (isDisabledAutoCountQuery(encQ)) {
continue; // Do not include this in the output.
}
const {channel} = encQ;
// if channel is a wildcard, return null
if (isWildcard(channel)) {
throw new Error('Cannot convert wildcard channel to a fixed channel');
}
const channelDef = isValueQuery(encQ) ? toValueDef(encQ) : toFieldDef(encQ, params);
if (channelDef === null) {
if (params.wildcardMode === 'null') {
// contains invalid property (e.g., wildcard, thus cannot return a proper spec.)
return null;
}
continue;
}
// Otherwise, we can set the channelDef
encoding[channel] = channelDef;
}
return encoding;
}
export function toValueDef(valueQ: ValueQuery): ValueDef {
const {value} = valueQ;
if (isWildcard(value)) {
return null;
}
return {value};
}
export function toFieldDef(
encQ: FieldQuery | AutoCountQuery,
params: ConversionParams = {}
): vlChannelDef.TypedFieldDef<string> {
const {props = DEFAULT_PROPS, schema, wildcardMode = 'skip'} = params;
if (isFieldQuery(encQ)) {
const fieldDef = {} as vlChannelDef.TypedFieldDef<string>;
for (const prop of props) {
let encodingProperty = encQ[prop];
if (isWildcard(encodingProperty)) {
if (wildcardMode === 'skip') continue;
return null;
}
if (encodingProperty !== undefined) {
// if the channel supports this prop
const isSupportedByChannel =
!PROPERTY_SUPPORTED_CHANNELS[prop] || PROPERTY_SUPPORTED_CHANNELS[prop][encQ.channel as ExtendedChannel];
if (!isSupportedByChannel) {
continue;
}
if (isEncodingNestedParent(prop) && isObject(encodingProperty)) {
encodingProperty = {...encodingProperty}; // Make a shallow copy first
for (const childProp in encodingProperty) {
// ensure nested properties are not wildcard before assigning to field def
if (isWildcard(encodingProperty[childProp])) {
if (wildcardMode === 'null') {
return null;
}
delete encodingProperty[childProp]; // skip
}
}
}
if (prop === 'bin' && encodingProperty === false) {
continue;
} else if (prop === 'type' && encodingProperty === 'key') {
fieldDef.type = 'nominal';
} else {
fieldDef[prop] = encodingProperty;
}
}
if (prop === Property.SCALE && schema && encQ.type === TYPE.ORDINAL) {
const scale = encQ.scale;
const {ordinalDomain} = schema.fieldSchema(encQ.field as string);
if (scale !== null && ordinalDomain) {
fieldDef[Property.SCALE] = {
domain: ordinalDomain,
// explicitly specfied domain property should override ordinalDomain
...(isObject(scale) ? scale : {}),
};
}
}
}
return fieldDef;
} else {
if (encQ.autoCount === false) {
throw new Error(`Cannot convert {autoCount: false} into a field def`);
} else {
return {
aggregate: 'count',
field: '*',
type: 'quantitative',
};
}
}
}
/**
* Is a field query continuous field?
* This method is applicable only for fieldQuery without wildcard
*/
export function isContinuous(encQ: EncodingQuery) {
if (isFieldQuery(encQ)) {
return vlChannelDef.isContinuous(toFieldDef(encQ, {props: ['bin', 'timeUnit', 'field', 'type']}));
}
return isAutoCountQuery(encQ);
}
export function isMeasure(encQ: EncodingQuery) {
if (isFieldQuery(encQ)) {
return !isDimension(encQ) && encQ.type !== 'temporal';
}
return isAutoCountQuery(encQ);
}
/**
* Is a field query discrete field?
* This method is applicable only for fieldQuery without wildcard
*/
export function isDimension(encQ: EncodingQuery) {
if (isFieldQuery(encQ)) {
const props: FlatProp[] = encQ['field'] ? ['field', 'bin', 'timeUnit', 'type'] : ['bin', 'timeUnit', 'type'];
const fieldDef = toFieldDef(encQ, {props: props});
return vlChannelDef.isDiscrete(fieldDef) || !!fieldDef.timeUnit;
}
return false;
}
/**
* Returns the true scale type of an encoding.
* @returns {ScaleType} If the scale type was not specified, it is inferred from the encoding's TYPE.
* @returns {undefined} If the scale type was not specified and Type (or TimeUnit if applicable) is a Wildcard, there is no clear scale type
*/
export function scaleType(fieldQ: FieldQuery) {
const scale: ScaleQuery = fieldQ.scale === true || fieldQ.scale === SHORT_WILDCARD ? {} : fieldQ.scale || {};
const {type, channel, timeUnit, bin} = fieldQ;
// HACK: All of markType, and scaleConfig only affect
// sub-type of ordinal to quantitative scales (point or band)
// Currently, most of scaleType usage in CompassQL doesn't care about this subtle difference.
// Thus, instead of making this method requiring the global mark,
// we will just call it with mark = undefined .
// Thus, currently, we will always get a point scale unless a CompassQuery specifies band.
const markType: Mark = undefined;
if (isWildcard(scale.type) || isWildcard(type) || isWildcard(channel) || isWildcard(bin)) {
return undefined;
}
if (channel === 'row' || channel === 'column' || channel === 'facet') {
return undefined;
}
// If scale type is specified, then use scale.type
if (scale.type) {
return scale.type;
}
// if type is fixed and it's not temporal, we can ignore time unit.
if (type === 'temporal' && isWildcard(timeUnit)) {
return undefined;
}
// if type is fixed and it's not quantitative, we can ignore bin
if (type === 'quantitative' && isWildcard(bin)) {
return undefined;
}
const vegaLiteType: VLType = type === ExpandedType.KEY ? 'nominal' : type;
const fieldDef = {
type: vegaLiteType,
timeUnit: timeUnit as TimeUnit,
bin: bin as BinParams,
};
return compileScaleType({type: scale.type}, channel, fieldDef, markType);
} | the_stack |
import React, {PureComponent} from 'react';
import {
Animated,
Easing,
I18nManager,
Image,
ImageSourcePropType,
LayoutChangeEvent,
PanResponder,
PanResponderInstance,
View,
ViewStyle,
} from 'react-native';
// styles
import {defaultStyles as styles} from './styles';
import type {Dimensions, SliderProps, SliderState} from './types';
type RectReturn = {
containsPoint: (nativeX: number, nativeY: number) => boolean;
height: number;
trackDistanceToPoint: (nativeX: number) => number;
width: number;
x: number;
y: number;
};
const Rect = ({
height,
width,
x,
y,
}: {
height: number;
width: number;
x: number;
y: number;
}) => ({
containsPoint: (nativeX: number, nativeY: number) =>
nativeX >= x &&
nativeY >= y &&
nativeX <= x + width &&
nativeY <= y + height,
height,
trackDistanceToPoint: (nativeX: number) => {
if (nativeX < x) {
return x - nativeX;
}
if (nativeX > x + width) {
return nativeX - (x + width);
}
return 0;
},
width,
x,
y,
});
const DEFAULT_ANIMATION_CONFIGS = {
spring: {
friction: 7,
tension: 100,
},
timing: {
duration: 150,
easing: Easing.inOut(Easing.ease),
delay: 0,
},
};
const normalizeValue = (
props: SliderProps,
value?: number | Array<number>,
): Array<number> => {
if (!value || (Array.isArray(value) && value.length === 0)) {
return [0];
}
const {maximumValue, minimumValue} = props;
const getBetweenValue = (inputValue: number) =>
Math.max(Math.min(inputValue, maximumValue), minimumValue);
if (!Array.isArray(value)) {
return [getBetweenValue(value)];
}
return value.map(getBetweenValue).sort((a, b) => a - b);
};
const updateValues = ({
values,
newValues = values,
}: {
values: number | Array<number> | Animated.Value | Array<Animated.Value>;
newValues?: number | Array<number> | Animated.Value | Array<Animated.Value>;
}): Animated.Value[] => {
if (
Array.isArray(newValues) &&
Array.isArray(values) &&
newValues.length !== values.length
) {
return updateValues({values: newValues});
}
if (Array.isArray(values) && Array.isArray(newValues)) {
return values?.map((value: number | Animated.Value, index: number) => {
let valueToSet = newValues[index];
if (value instanceof Animated.Value) {
if (valueToSet instanceof Animated.Value) {
valueToSet = valueToSet.__getValue();
}
value.setValue(valueToSet);
return value;
}
if (valueToSet instanceof Animated.Value) {
return valueToSet;
}
return new Animated.Value(valueToSet);
});
}
return [new Animated.Value(0)];
};
const indexOfLowest = (values: Array<number>): number => {
let lowestIndex = 0;
values.forEach((value, index, array) => {
if (value < array[lowestIndex]) {
lowestIndex = index;
}
});
return lowestIndex;
};
export class Slider extends PureComponent<SliderProps, SliderState> {
constructor(props: SliderProps) {
super(props);
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder:
this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminationRequest:
this._handlePanResponderRequestEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
});
this.state = {
allMeasured: false,
containerSize: {
width: 0,
height: 0,
},
thumbSize: {
width: 0,
height: 0,
},
trackMarksValues: updateValues({
values: normalizeValue(this.props, this.props.trackMarks),
}),
values: updateValues({
values: normalizeValue(
this.props,
this.props.value instanceof Animated.Value
? this.props.value.__getValue()
: this.props.value,
),
}),
};
}
static defaultProps = {
animationType: 'timing',
debugTouchArea: false,
trackMarks: [],
maximumTrackTintColor: '#b3b3b3',
maximumValue: 1,
minimumTrackTintColor: '#3f3f3f',
minimumValue: 0,
step: 0,
thumbTintColor: '#343434',
trackClickable: true,
value: 0,
vertical: false,
};
static getDerivedStateFromProps(props: SliderProps, state: SliderState) {
if (
props.trackMarks &&
!!state.trackMarksValues &&
state.trackMarksValues.length > 0
) {
const newTrackMarkValues = normalizeValue(props, props.trackMarks);
const statePatch = {} as SliderState;
if (
state.trackMarksValues &&
newTrackMarkValues.length !== state.trackMarksValues.length
) {
statePatch.trackMarksValues = updateValues({
values: state.trackMarksValues,
newValues: newTrackMarkValues,
});
}
return statePatch;
}
}
componentDidUpdate() {
const newValues = normalizeValue(
this.props,
this.props.value instanceof Animated.Value
? this.props.value.__getValue()
: this.props.value,
);
newValues.forEach((value, i) => {
if (!this.state.values[i]) {
this._setCurrentValue(value, i);
} else if (value !== this.state.values[i].__getValue()) {
if (this.props.animateTransitions) {
this._setCurrentValueAnimated(value, i);
} else {
this._setCurrentValue(value, i);
}
}
});
}
_getRawValues(
values: Array<Animated.Value> | Array<Animated.AnimatedInterpolation>,
) {
return values.map((value) => value.__getValue());
}
_handleStartShouldSetPanResponder = (
e: any,
): /* gestureState: GestureState */
boolean => this._thumbHitTest(e); // Should we become active when the user presses down on the thumb?
_handleMoveShouldSetPanResponder(): /* e, gestureState: GestureState */
boolean {
// Should we become active when the user moves a touch over the thumb?
return false;
}
_handlePanResponderGrant = (e: {nativeEvent: any}) => {
const {thumbSize} = this.state;
const {nativeEvent} = e;
this._previousLeft = this.props.trackClickable
? nativeEvent.locationX - thumbSize.width
: this._getThumbLeft(this._getCurrentValue(this._activeThumbIndex));
this.props?.onSlidingStart?.(this._getRawValues(this.state.values));
};
_handlePanResponderMove = (_e: any, gestureState: any) => {
if (this.props.disabled) {
return;
}
this._setCurrentValue(
this._getValue(gestureState),
this._activeThumbIndex,
() => {
this.props?.onValueChange?.(
this._getRawValues(this.state.values),
);
},
);
};
_handlePanResponderRequestEnd = () =>
/* e, gestureState: GestureState */
{
// Should we allow another component to take over this pan?
return false;
};
_handlePanResponderEnd = (_e: any, gestureState: any) => {
if (this.props.disabled) {
return;
}
this._setCurrentValue(
this._getValue(gestureState),
this._activeThumbIndex,
() => {
if (this.props.trackClickable) {
this.props?.onValueChange?.(
this._getRawValues(this.state.values),
);
}
this.props?.onSlidingComplete?.(
this._getRawValues(this.state.values),
);
},
);
this._activeThumbIndex = 0;
};
_measureContainer = (e: LayoutChangeEvent) => {
this._handleMeasure('_containerSize', e);
};
_measureTrack = (e: LayoutChangeEvent) => {
this._handleMeasure('_trackSize', e);
};
_measureThumb = (e: LayoutChangeEvent) => {
this._handleMeasure('_thumbSize', e);
};
_handleMeasure = (
name: '_containerSize' | '_trackSize' | '_thumbSize',
e: LayoutChangeEvent,
) => {
const {width, height} = e.nativeEvent.layout;
const size = {
width,
height,
};
const currentSize = this[name];
if (
currentSize &&
width === currentSize.width &&
height === currentSize.height
) {
return;
}
this[name] = size;
if (this._containerSize && this._thumbSize) {
this.setState({
containerSize: this._containerSize,
thumbSize: this._thumbSize,
allMeasured: true,
});
}
};
_getRatio = (value: number) => {
const {maximumValue, minimumValue} = this.props;
return (value - minimumValue) / (maximumValue - minimumValue);
};
_getThumbLeft = (value: number) => {
const {containerSize, thumbSize} = this.state;
const {vertical} = this.props;
const standardRatio = this._getRatio(value);
const ratio = I18nManager.isRTL ? 1 - standardRatio : standardRatio;
return ratio * ((vertical ? containerSize.height : containerSize.width) - thumbSize.width);
};
_getValue = (gestureState: {dx: number, dy: number}) => {
const {containerSize, thumbSize, values} = this.state;
const {maximumValue, minimumValue, step, vertical} = this.props;
const length = containerSize.width - thumbSize.width;
const thumbLeft = vertical ? this._previousLeft + (gestureState.dy * -1) : this._previousLeft + gestureState.dx;
const nonRtlRatio = thumbLeft / length;
const ratio = I18nManager.isRTL ? 1 - nonRtlRatio : nonRtlRatio;
let minValue = minimumValue;
let maxValue = maximumValue;
const rawValues = this._getRawValues(values);
const buffer = step ? step : 0.1;
if (values.length === 2) {
if (this._activeThumbIndex === 1) {
minValue = rawValues[0] + buffer;
} else {
maxValue = rawValues[1] - buffer;
}
}
if (step) {
return Math.max(
minValue,
Math.min(
maxValue,
minimumValue +
Math.round(
(ratio * (maximumValue - minimumValue)) / step,
) *
step,
),
);
}
return Math.max(
minValue,
Math.min(
maxValue,
ratio * (maximumValue - minimumValue) + minimumValue,
),
);
};
_getCurrentValue = (thumbIndex: number = 0) =>
this.state.values[thumbIndex].__getValue();
_setCurrentValue = (
value: number,
thumbIndex: number | null | undefined,
callback?: () => void,
) => {
const safeIndex = thumbIndex ?? 0;
const animatedValue = this.state.values[safeIndex];
if (animatedValue) {
animatedValue.setValue(value);
if (callback) {
callback();
}
} else {
this.setState((prevState: SliderState) => {
const newValues = [...prevState.values];
newValues[safeIndex] = new Animated.Value(value);
return {
values: newValues,
};
}, callback);
}
};
_setCurrentValueAnimated = (value: number, thumbIndex: number = 0) => {
const {animationType} = this.props;
const animationConfig = {
...DEFAULT_ANIMATION_CONFIGS[animationType],
...this.props.animationConfig,
toValue: value,
useNativeDriver: false,
};
Animated[animationType](
this.state.values[thumbIndex],
animationConfig,
).start();
};
_getTouchOverflowSize = (): {
width: number;
height: number;
} => {
const {allMeasured, containerSize, thumbSize} = this.state;
const {thumbTouchSize} = this.props;
const size = {
width: 40,
height: 40,
};
if (allMeasured) {
size.width = Math.max(
0,
thumbTouchSize?.width || 0 - thumbSize.width,
);
size.height = Math.max(
0,
thumbTouchSize?.height || 0 - containerSize.height,
);
}
return size;
};
_getTouchOverflowStyle = () => {
const {width, height} = this._getTouchOverflowSize();
const touchOverflowStyle = {} as ViewStyle;
if (width !== undefined && height !== undefined) {
const verticalMargin = -height / 2;
touchOverflowStyle.marginTop = verticalMargin;
touchOverflowStyle.marginBottom = verticalMargin;
const horizontalMargin = -width / 2;
touchOverflowStyle.marginLeft = horizontalMargin;
touchOverflowStyle.marginRight = horizontalMargin;
}
if (this.props.debugTouchArea === true) {
touchOverflowStyle.backgroundColor = 'orange';
touchOverflowStyle.opacity = 0.5;
}
return touchOverflowStyle;
};
_thumbHitTest = (e: {nativeEvent: any}) => {
const {nativeEvent} = e;
const {trackClickable} = this.props;
const {values} = this.state;
const hitThumb = values.find((_, i) => {
const thumbTouchRect = this._getThumbTouchRect(i);
const containsPoint = thumbTouchRect.containsPoint(
nativeEvent.locationX,
nativeEvent.locationY,
);
if (containsPoint) {
this._activeThumbIndex = i;
}
return containsPoint;
});
if (hitThumb) {
return true;
}
if (trackClickable) {
// set the active thumb index
if (values.length === 1) {
this._activeThumbIndex = 0;
} else {
// we will find the closest thumb and that will be the active thumb
const thumbDistances = values.map((_value, index) => {
const thumbTouchRect = this._getThumbTouchRect(index);
return thumbTouchRect.trackDistanceToPoint(
nativeEvent.locationX,
);
});
this._activeThumbIndex = indexOfLowest(thumbDistances);
}
return true;
}
return false;
};
_getThumbTouchRect = (thumbIndex: number = 0): RectReturn => {
const {containerSize, thumbSize} = this.state;
const {thumbTouchSize} = this.props;
const {height, width} = thumbTouchSize || {height: 40, width: 40};
const touchOverflowSize = this._getTouchOverflowSize();
return Rect({
height,
width,
x:
touchOverflowSize.width / 2 +
this._getThumbLeft(this._getCurrentValue(thumbIndex)) +
(thumbSize.width - width) / 2,
y:
touchOverflowSize.height / 2 +
(containerSize.height - height) / 2,
});
};
_activeThumbIndex: number = 0;
_containerSize: Dimensions | null | undefined;
_panResponder: PanResponderInstance;
_previousLeft: number = 0;
_thumbSize: Dimensions | null | undefined;
_trackSize: Dimensions | null | undefined;
_renderDebugThumbTouchRect = (
thumbLeft: Animated.AnimatedInterpolation,
index: number,
) => {
const {height, y, width} = this._getThumbTouchRect() || {};
const positionStyle = {
height,
left: thumbLeft,
top: y,
width,
};
return (
<Animated.View
key={`debug-thumb-${index}`}
pointerEvents="none"
style={[styles.debugThumbTouchArea, positionStyle]}
/>
);
};
_renderThumbImage = (thumbIndex: number = 0) => {
const {thumbImage} = this.props;
if (!thumbImage) {
return null;
}
return (
<Image
source={
(Array.isArray(thumbImage)
? thumbImage[thumbIndex]
: thumbImage) as ImageSourcePropType
}
/>
);
};
render() {
const {
containerStyle,
debugTouchArea,
maximumTrackTintColor,
maximumValue,
minimumTrackTintColor,
minimumValue,
renderAboveThumbComponent,
renderTrackMarkComponent,
renderThumbComponent,
thumbStyle,
thumbTintColor,
trackStyle,
vertical,
...other
} = this.props;
const {
allMeasured,
containerSize,
thumbSize,
trackMarksValues,
values,
} = this.state;
const interpolatedThumbValues = values.map((value) =>
value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: I18nManager.isRTL
? [0, -(containerSize.width - thumbSize.width)]
: [0, containerSize.width - thumbSize.width],
}),
);
const interpolatedTrackValues = values.map((value) =>
value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [0, containerSize.width - thumbSize.width],
}),
);
const interpolatedTrackMarksValues =
trackMarksValues &&
trackMarksValues.map((v) =>
v.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: I18nManager.isRTL
? [0, -(containerSize.width - thumbSize.width)]
: [0, containerSize.width - thumbSize.width],
}),
);
const valueVisibleStyle = {} as ViewStyle;
if (!allMeasured) {
valueVisibleStyle.opacity = 0;
}
const interpolatedRawValues = this._getRawValues(
interpolatedTrackValues,
);
const minThumbValue = new Animated.Value(
Math.min(...interpolatedRawValues),
);
const maxThumbValue = new Animated.Value(
Math.max(...interpolatedRawValues),
);
const minimumTrackStyle = {
position: 'absolute',
left:
interpolatedTrackValues.length === 1
? new Animated.Value(0)
: Animated.add(minThumbValue, thumbSize.width / 2),
width:
interpolatedTrackValues.length === 1
? Animated.add(
interpolatedTrackValues[0],
thumbSize.width / 2,
)
: Animated.add(
Animated.multiply(minThumbValue, -1),
maxThumbValue,
),
backgroundColor: minimumTrackTintColor,
...valueVisibleStyle,
} as ViewStyle;
const touchOverflowStyle = this._getTouchOverflowStyle();
return (
<>
{renderAboveThumbComponent && (
<View style={styles.aboveThumbComponentsContainer}>
{interpolatedThumbValues.map((value, i) => (
<Animated.View
key={`slider-above-thumb-${i}`}
style={[
styles.renderThumbComponent, // eslint-disable-next-line react-native/no-inline-styles
{
bottom: 0,
transform: [
{
translateX: value,
},
{
translateY: 0,
},
],
...valueVisibleStyle,
},
]}>
{renderAboveThumbComponent(i)}
</Animated.View>
))}
</View>
)}
<View
{...other}
style={[styles.container, vertical ? {transform: [{rotate: '-90deg' }]} : {}, containerStyle]}
onLayout={this._measureContainer}>
<View
renderToHardwareTextureAndroid
style={[
styles.track,
{
backgroundColor: maximumTrackTintColor,
},
trackStyle,
]}
onLayout={this._measureTrack}
/>
<Animated.View
renderToHardwareTextureAndroid
style={[styles.track, trackStyle, minimumTrackStyle]}
/>
{renderTrackMarkComponent &&
interpolatedTrackMarksValues &&
interpolatedTrackMarksValues.map((value, i) => (
<Animated.View
key={`track-mark-${i}`}
style={[
styles.renderThumbComponent,
{
transform: [
{
translateX: value,
},
{
translateY: 0,
},
],
...valueVisibleStyle,
},
]}>
{renderTrackMarkComponent(i)}
</Animated.View>
))}
{interpolatedThumbValues.map((value, i) => (
<Animated.View
key={`slider-thumb-${i}`}
style={[
renderThumbComponent
? styles.renderThumbComponent
: styles.thumb,
renderThumbComponent
? {}
: {
backgroundColor: thumbTintColor,
...thumbStyle,
},
{
transform: [
{
translateX: value,
},
{
translateY: 0,
},
],
...valueVisibleStyle,
},
]}
onLayout={this._measureThumb}>
{renderThumbComponent
? renderThumbComponent()
: this._renderThumbImage(i)}
</Animated.View>
))}
<View
style={[styles.touchArea, touchOverflowStyle]}
{...this._panResponder.panHandlers}>
{!!debugTouchArea &&
interpolatedThumbValues.map((value, i) =>
this._renderDebugThumbTouchRect(value, i),
)}
</View>
</View>
</>
);
}
} | the_stack |
import {ITextUtteranceLabelMapDataStructure} from '@microsoft/bf-dispatcher';
import {Example} from '@microsoft/bf-dispatcher';
import {Label} from '@microsoft/bf-dispatcher';
import {Span} from '@microsoft/bf-dispatcher';
import {Orchestrator} from '../src/orchestrator';
import {OrchestratorHelper} from '../src/orchestratorhelper';
import {OrchestratorBuild} from '../src/build';
import {OrchestratorBaseModel} from '../src/basemodel';
import {LabelResolver} from '../src/labelresolver';
import {Utility} from '../src/utility';
import {UnitTestHelper} from './utility.test';
import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher';
import assert = require('assert');
import * as path from 'path';
const baseModelPath: string = path.resolve('./resources/model/model_dte_bert_3l');
describe('OrchestratorBuildTests', function () {
beforeEach(async () => {
Utility.debuggingLog('Downloading a base neural network language model for unit test');
await UnitTestHelper.downloadModelFileForTest(
baseModelPath,
OrchestratorBaseModel.defaultHandler,
OrchestratorBaseModel.defaultHandler);
});
it('Test.0000 - getExamplesLR should pull examples from labelResolver', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
// const orchestrator: any = await LabelResolver.loadNlrAsync(baseModelPath);
const labelResolver: any = LabelResolver.createLabelResolver();
const example1: any = {
labels: [{name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{name: 'music',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'play some mozart and metallica.',
};
LabelResolver.addExample(example1, labelResolver);
LabelResolver.addExample(example2, labelResolver);
LabelResolver.addExample(example3, labelResolver);
const examples: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
assert.ok(examples !== null);
assert.ok(examples.utteranceLabelsMap.size === 3);
});
it('Test.0001 - getExamplesLU should parse lu content into Examples', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const filename: string =
'resources/data/LU/syncLabelResolver/same_as_code.lu';
const fileContents: string = OrchestratorHelper.readFile(filename);
const examples: ITextUtteranceLabelMapDataStructure =
await OrchestratorBuild.getExamplesLU(fileContents);
assert.ok(examples !== null);
assert.ok(examples.utteranceLabelsMap.size === 3);
});
it('Test.0002 - syncLabelResolver-no differences LabelResolver/LU', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
// Arrange
// Load up Label Resolver
const labelResolver: any = LabelResolver.createLabelResolver();
const example1: any = {
labels: [{name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{name: 'music',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'play some mozart and metallica.',
};
LabelResolver.addExample(example1, labelResolver);
LabelResolver.addExample(example2, labelResolver);
LabelResolver.addExample(example3, labelResolver);
// Load up LU
const filename: string =
'resources/data/LU/syncLabelResolver/same_as_code.lu';
const luContents: string = OrchestratorHelper.readFile(filename);
await OrchestratorBuild.syncLabelResolver(labelResolver, luContents);
// Assert
const examples_after_sync: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
assert.ok(examples_after_sync !== null);
assert.ok(examples_after_sync.utteranceLabelsMap.size === 3);
assert.ok(examples_after_sync.utteranceLabelsMap.has('book a flight to miami.'));
assert.ok(examples_after_sync.utteranceLabelsMap.has('play some mozart and metallica.'));
});
it('Test.0003 - syncLabelResolver-LU adds new travel intent', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
// Arrange
// Load up Label Resolver
const labelResolver: any = LabelResolver.createLabelResolver();
const example1: any = {
labels: [{name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{name: 'music',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'play some mozart and metallica.',
};
LabelResolver.addExample(example1, labelResolver);
LabelResolver.addExample(example2, labelResolver);
LabelResolver.addExample(example3, labelResolver);
// Check examples before sync
const examples_before_sync: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
Utility.debuggingLog('OrchestratorBuildTests Test.0003, checkpoint-A');
assert.ok(examples_before_sync !== null);
assert.ok(examples_before_sync.utteranceLabelsMap.size === 3);
Utility.debuggingLog('OrchestratorBuildTests Test.0003, checkpoint-B');
// Load up LU
const filename: string =
'resources/data/LU/syncLabelResolver/additional_travel.lu';
const luContents: string = OrchestratorHelper.readFile(filename);
// Action
await OrchestratorBuild.syncLabelResolver(labelResolver, luContents);
// Assert
const examples_after_sync: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
Utility.debuggingLog('OrchestratorBuildTests Test.0003, checkpoint-C');
assert.ok(examples_after_sync !== null);
Utility.debuggingLog(`OrchestratorBuildTests Test.0003, checkpoint-D: examples_after_sync.utteranceLabelsMap.size=${examples_after_sync.utteranceLabelsMap.size}`);
assert.ok(examples_after_sync.utteranceLabelsMap.size === 4);
Utility.debuggingLog('OrchestratorBuildTests Test.0003, checkpoint-E');
assert.ok(examples_after_sync.utteranceLabelsMap.has('book a flight to miami.'));
Utility.debuggingLog('OrchestratorBuildTests Test.0003, checkpoint-F');
});
it('Test.0004 - syncLabelResolver-LU removes travel intent', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
// Arrange
// Load up Label Resolver
const labelResolver: any = LabelResolver.createLabelResolver();
const example1: any = {
labels: [{name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{name: 'music',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'play some mozart and metallica.',
};
LabelResolver.addExample(example1, labelResolver);
LabelResolver.addExample(example2, labelResolver);
LabelResolver.addExample(example3, labelResolver);
// Check examples before sync
const examples_before_sync: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
assert.ok(examples_before_sync !== null);
assert.ok(examples_before_sync.utteranceLabelsMap.size === 3);
// Load up LU
const filename: string =
'resources/data/LU/syncLabelResolver/remove_travel.lu';
const luContents: string = OrchestratorHelper.readFile(filename);
// Action
await OrchestratorBuild.syncLabelResolver(labelResolver, luContents);
Utility.debuggingLog('OrchestratorBuildTests Test.0004, after calling OrchestratorBuild.syncLabelResolver()');
// Assert
const examples_after_sync: ITextUtteranceLabelMapDataStructure =
OrchestratorBuild.getExamplesLR(labelResolver);
assert.ok(examples_after_sync !== null);
// eslint-disable-next-line no-console
console.log(`>>>>>>>examples after sync: ${examples_after_sync.utteranceLabelsMap.size} (expected:2)`);
assert.ok(examples_after_sync.utteranceLabelsMap.size === 2);
assert.ok(examples_after_sync.utteranceLabelsMap.has('book meeting with architect for Monday.'));
});
it('Test.0005 - syncLabelResolver-detect multi-intent music label', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
// Arrange
// Load up Label Resolver.
// Note: LU file should override example3 - Composer can't see this type of
// multi-intent.
// const orchestrator: any = await LabelResolver.loadNlrAsync(baseModelPath);
const labelResolver: any = LabelResolver.createLabelResolver();
const example1: any = {
labels: [{name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{
name: 'travel',
span: {
length: 0,
offset: 0,
},
label_type: 1,
},
{
name: 'city',
span: {
length: 0,
offset: 0,
},
label_type: 1,
}],
text: 'play some mozart and metallica.',
label_type: 1,
};
LabelResolver.addExample(example1, labelResolver);
LabelResolver.addExample(example2, labelResolver);
LabelResolver.addExample(example3, labelResolver);
// Load up LU
const filename: string =
'resources/data/LU/syncLabelResolver/same_as_code.lu';
const luContents: string = OrchestratorHelper.readFile(filename);
await OrchestratorBuild.syncLabelResolver(labelResolver, luContents);
Utility.debuggingLog('OrchestratorBuildTests Test.0005, after calling OrchestratorBuild.syncLabelResolver()');
const examples_after_sync: Example[] = LabelResolver.getExamples(labelResolver).map(
(x: any) => new Example(
x.text,
x.labels.map((y: any) => new Label(
y.label_type,
y.name,
new Span(
y.span.offset,
y.span.length)))));
assert.ok(examples_after_sync !== null);
// eslint-disable-next-line no-console
console.log(`>>>>>>>examples after sync: ${examples_after_sync.length} (expected3)`);
assert.ok(examples_after_sync.length === 3);
examples_after_sync.sort(Example.sortFunction);
UtilityDispatcher.debuggingNamedLog1('OrchestratorBuildTests Test.0005', examples_after_sync, 'examples_after_sync');
assert.ok(examples_after_sync[2].labels.length === 1); // LU file has precedence over Label Resolver
// examples_after_sync.forEach(element => {
// console.log(` Intent ${element.text}`);
// console.log(` #Labels: ${element.labels.length}`);
// });
});
it('Test.0006 - runAsync should work', async function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const labelResolversById: Map<string, LabelResolver> = new Map<string, LabelResolver>();
const retPayload: any = await OrchestratorBuild.runAsync(
baseModelPath,
'',
OrchestratorHelper.getLuInputs('./test/fixtures/adaptive/'),
labelResolversById,
true,
null);
assert.ok(retPayload !== null);
assert.ok(retPayload.outputs !== null);
assert.ok(retPayload.outputs.length === 5);
assert.ok(retPayload.settings.orchestrator.modelFolder === baseModelPath.replace(/\\/g, '/'));
const payLoadOutputs: any[] = retPayload.outputs;
const snapshots: Map<string, Uint8Array> = new Map<string, Uint8Array>();
// eslint-disable-next-line guard-for-in
for (const output of payLoadOutputs) {
snapshots.set(output.id, output.snapshot);
}
assert.ok(snapshots.size === 5);
const resolvers: Map<string, LabelResolver> = await Orchestrator.getLabelResolversAsync(baseModelPath, '', snapshots);
assert.ok(resolvers.size === 5);
});
it('Test.0007 - runAsync with luConfig json', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const labelResolversById: Map<string, LabelResolver> = new Map<string, LabelResolver>();
const retPayload: any = await OrchestratorBuild.runAsync(
baseModelPath,
'',
[],
labelResolversById,
true,
JSON.parse(OrchestratorHelper.readFile('./test/fixtures/luconfig.json')));
assert.ok(retPayload !== null);
assert.ok(retPayload.outputs !== null);
OrchestratorHelper.writeBuildOutputFiles('./test/fixtures/output', retPayload);
assert.ok(Utility.exists('./test/fixtures/output/RootDialog.blu'));
assert.ok(Utility.exists('./test/fixtures/output/RootDialog.en-us.lu.dialog'));
assert.ok(Utility.exists('./test/fixtures/output/RootDialog.lu.dialog'));
const snapshotSettings: any = retPayload.settings.orchestrator.snapshots;
assert.ok(snapshotSettings.RootDialog === 'test/fixtures/output/RootDialog.blu');
});
it('Test.0008 - runAsync changing files', async function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const labelResolversById: Map<string, LabelResolver> = new Map<string, LabelResolver>();
const retPayload: any = await OrchestratorBuild.runAsync(
baseModelPath,
'',
OrchestratorHelper.getLuInputs('./test/fixtures/adaptive/'),
labelResolversById,
true,
JSON.parse(OrchestratorHelper.readFile('./test/fixtures/luconfig.json')));
// labelResolversById.forEach((labelResolver: LabelResolver, labelId: string) => {
// console.log(` id: ${labelId}`);
// let examples_after_sync: Example[] = LabelResolver.getExamples(labelResolver);
// console.log(` count of examples: ${examples_after_sync.length}`);
// });
assert.ok(labelResolversById.size === 5);
assert.ok(labelResolversById.has('AddToDoDialog'));
assert.ok(labelResolversById.get('AddToDoDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('AddToDoDialog')).length === 108);
assert.ok(labelResolversById.has('DeleteToDoDialog'));
assert.ok(labelResolversById.get('DeleteToDoDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('DeleteToDoDialog')).length === 112);
assert.ok(labelResolversById.has('GetUserProfileDialog'));
assert.ok(labelResolversById.get('GetUserProfileDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('GetUserProfileDialog')).length === 121);
assert.ok(labelResolversById.has('RootDialog'));
assert.ok(labelResolversById.get('RootDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('RootDialog')).length === 123);
assert.ok(labelResolversById.has('ViewToDoDialog'));
assert.ok(labelResolversById.get('ViewToDoDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('ViewToDoDialog')).length === 90);
assert.ok(retPayload !== null);
assert.ok(retPayload.outputs !== null);
const retPayload2: any = await OrchestratorBuild.runAsync(
baseModelPath,
'',
OrchestratorHelper.getLuInputs('./test/fixtures/adaptive/'),
labelResolversById,
true,
JSON.parse(OrchestratorHelper.readFile('./test/fixtures/luconfig.json')));
// labelResolversById.forEach((labelResolver: LabelResolver, labelId: string) => {
// console.log(` id: ${labelId}`);
// let examples_after_sync: Example[] = LabelResolver.getExamples(labelResolver);
// console.log(` count of examples: ${examples_after_sync.length}`);
// });
assert.ok(labelResolversById.size === 5);
assert.ok(labelResolversById.has('AddToDoDialog'));
assert.ok(labelResolversById.get('AddToDoDialog') !== undefined);
assert.ok(labelResolversById.get('AddToDoDialog') !== null);
assert.ok(labelResolversById.has('DeleteToDoDialog'));
assert.ok(labelResolversById.get('DeleteToDoDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('DeleteToDoDialog')).length === 112);
assert.ok(labelResolversById.has('GetUserProfileDialog'));
assert.ok(labelResolversById.get('GetUserProfileDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('GetUserProfileDialog')).length === 121);
assert.ok(labelResolversById.has('RootDialog'));
assert.ok(labelResolversById.get('RootDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('RootDialog')).length === 123);
assert.ok(labelResolversById.has('ViewToDoDialog'));
assert.ok(labelResolversById.get('ViewToDoDialog') !== null);
assert.ok(LabelResolver.getExamples(labelResolversById.get('ViewToDoDialog')).length === 90);
assert.ok(retPayload2 !== null);
assert.ok(retPayload2.outputs !== null);
});
it('Test.0100 - intent-only snapshot should not contain entity labels after calling syncLabelResolver()', async () => {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
await LabelResolver.createAsync(baseModelPath, '');
const example1: any = {
labels: [{
name: 'travel',
span: {
length: 0,
offset: 0},
label_type: 1}, {
name: 'city',
span: {
length: 5,
offset: 17},
label_type: 2}],
text: 'book a flight to miami.',
};
const example2: any = {
labels: [{name: 'schedule',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'book meeting with architect for Monday.',
};
const example3: any = {
labels: [{name: 'music',
span: {
length: 0,
offset: 0},
label_type: 1}],
text: 'play some mozart and metallica.',
};
LabelResolver.addExample(example1);
LabelResolver.addExample(example2);
LabelResolver.addExample(example3);
const snapshot: any = LabelResolver.createSnapshot();
Utility.debuggingLog('OrchestratorBuildTests Test.0100, after calling LabelResolver.createSnapshot() - A');
// ---- NOTE-FOR-DEBUGGING ---- Utility.debuggingLog(`OrchestratorBuildTests Test.0100, snapshot=${snapshot}`);
const snapshotInString: string = (new TextDecoder()).decode(snapshot);
Utility.debuggingLog(`OrchestratorBuildTests Test.0100, snapshotInString=${snapshotInString}`);
const luContent: string = `
> LUIS application information
> !# @app.versionId = 0.1
> !# @app.culture = en-us
> !# @app.luis_schema_version = 3.2.0
> # Intent definitions
## travel
- book a flight to {@city=miami}.
## schedule
- book meeting with architect for Monday.
## music
- play some mozart and metallica.
`;
await OrchestratorBuild.syncLabelResolver(LabelResolver.LabelResolver, luContent);
const snapshotAfterSync: any = LabelResolver.createSnapshot();
Utility.debuggingLog('OrchestratorBuildTests Test.0100, after calling LabelResolver.createSnapshot() - B');
// ---- NOTE-FOR-DEBUGGING ---- Utility.debuggingLog(`OrchestratorBuildTests Test.0100, snapshotAfterSync=${snapshotAfterSync}`);
const snapshotAfterSyncInString: string = (new TextDecoder()).decode(snapshotAfterSync);
Utility.debuggingLog(`OrchestratorBuildTests Test.0100, snapshotAfterSyncInString=${snapshotAfterSyncInString}`);
assert.ok(snapshot.length === snapshotAfterSync.length);
for (let i: number = 0; i < snapshot.length; i++) {
assert.ok(snapshot[i] === snapshotAfterSync[i]);
}
});
}); | the_stack |
import { click, currentRouteName, currentURL } from '@ember/test-helpers';
import { ModelInstance } from 'ember-cli-mirage';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { percySnapshot } from 'ember-percy';
import { TestContext } from 'ember-test-helpers';
import { module, test } from 'qunit';
import { RegistrationReviewStates } from 'ember-osf-web/models/registration';
import RegistrationProviderModel from 'ember-osf-web/models/registration-provider';
import { visit } from 'ember-osf-web/tests/helpers';
import { setupEngineApplicationTest } from 'ember-osf-web/tests/helpers/engines';
interface ModerationSubmissionsTestContext extends TestContext {
registrationProvider: ModelInstance<RegistrationProviderModel>;
}
module('Registries | Acceptance | branded.moderation | submissions', hooks => {
setupEngineApplicationTest(hooks, 'registries');
setupMirage(hooks);
hooks.beforeEach(function(this: ModerationSubmissionsTestContext) {
this.registrationProvider = server.create('registration-provider', { id: 'sbmit' });
});
test('logged out users are rerouted', async assert => {
await visit('/registries/sbmit/moderation/submissions');
assert.equal(currentRouteName(), 'registries.page-not-found', 'Logged out users are rerouted');
});
test('logged in, non-moderators are rerouted', async assert => {
server.create('user', 'loggedIn');
await visit('/registries/sbmit/moderation/submissions');
assert.equal(currentRouteName(), 'registries.page-not-found', 'Non-moderators are rerouted');
});
test('Submissions pending: no registrations', async function(this: ModerationSubmissionsTestContext, assert) {
this.registrationProvider.update({ permissions: ['view_submissions'] });
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', {
id: currentUser.id,
user: currentUser,
provider: this.registrationProvider,
}, 'asModerator');
await visit('/registries/sbmit/moderation/submissions');
await percySnapshot('moderation submissions page: no registrations');
assert.equal(currentRouteName(), 'registries.branded.moderation.submissions',
'On the submissions page of registries reviews');
// Pending tab
assert.ok(currentURL().includes('state=pending'), 'Default state is pending');
assert.dom('[data-test-submissions-type="pending"][data-test-is-selected="true"]')
.exists('Pending is selected by default for submissions page');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for pending submissions');
assert.dom('[data-test-registration-list-none]').containsText(
'No registrations pending approval have been found',
'Proper message is shown when no pending registrations found',
);
// Accepted tab
await click('[data-test-submissions-type="accepted"]');
assert.ok(currentURL().includes('state=accepted'), 'query param set to accepted');
assert.dom('[data-test-submissions-type="accepted"][data-test-is-selected="true"]')
.exists('Accepted tab has been selected');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for accepted submissions');
assert.dom('[data-test-registration-list-none]').containsText('No public registrations have been found',
'Proper message is shown when no accepted registrations found');
// Embargo tab
await click('[data-test-submissions-type="embargo"]');
assert.ok(currentURL().includes('state=embargo'), 'query param set to embargo');
assert.dom('[data-test-submissions-type="embargo"][data-test-is-selected="true"]')
.exists('Embargo tab has been selected');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for embargoed submissions');
assert.dom('[data-test-registration-list-none]').containsText('No embargoed registrations have been found',
'Proper message is shown when no accepted registrations found');
// Rejected tab
await click('[data-test-submissions-type="rejected"]');
assert.ok(currentURL().includes('state=rejected'), 'query param set to rejected');
assert.dom('[data-test-submissions-type="rejected"][data-test-is-selected="true"]')
.exists('Rejected tab has been selected');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for rejected submissions');
assert.dom('[data-test-registration-list-none]').containsText('No rejected registrations have been found',
'Proper message is shown when no rejected registrations found');
// Withdrawn tab
await click('[data-test-submissions-type="withdrawn"]');
assert.ok(currentURL().includes('state=withdrawn'), 'query param set to withdrawn');
assert.dom('[data-test-submissions-type="withdrawn"][data-test-is-selected="true"]')
.exists('Withdrawn tab has been selected');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for withdrawn submissions');
assert.dom('[data-test-registration-list-none]').containsText('No withdrawn registrations have been found',
'Proper message is shown when no withdrawn registrations found');
// Pending Withdrawal tab
await click('[data-test-submissions-type="pending-withdraw"]');
assert.ok(currentURL().includes('state=pending_withdraw'), 'query param set to pending withdraw');
assert.dom('[data-test-submissions-type="pending-withdraw"][data-test-is-selected="true"]')
.exists('Pending withdraw tab has been selected');
assert.dom('[data-test-registration-list-card]')
.doesNotExist('No cards shown for pending withdrawal submissions');
assert.dom('[data-test-registration-list-none]').containsText('No registrations found pending withdrawal',
'Proper message is shown when no registrations pending withdrawal found');
});
test('Submissions pending: many registrations', async function(this: ModerationSubmissionsTestContext, assert) {
server.createList(
'registration', 12, {
reviewsState: RegistrationReviewStates.Pending, provider: this.registrationProvider,
}, 'withReviewActions',
);
server.createList(
'registration', 2, {
reviewsState: RegistrationReviewStates.Accepted,
provider: this.registrationProvider,
}, 'withSingleReviewAction',
);
server.createList(
'registration', 5, {
provider: this.registrationProvider,
}, 'withSingleReviewAction', 'isEmbargo',
);
server.createList(
'registration', 3, {
reviewsState: RegistrationReviewStates.Rejected, provider: this.registrationProvider,
},
);
server.createList(
'registration', 4, {
reviewsState: RegistrationReviewStates.Withdrawn, provider: this.registrationProvider,
},
);
server.createList(
'registration', 2, {
reviewsState: RegistrationReviewStates.PendingWithdraw, provider: this.registrationProvider,
},
);
this.registrationProvider.update({ permissions: ['view_submissions'] });
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', {
id: currentUser.id,
user: currentUser,
provider: this.registrationProvider,
}, 'asAdmin');
await visit('/registries/sbmit/moderation/submissions');
await percySnapshot('moderation submissions page: many registrations');
assert.equal(currentRouteName(), 'registries.branded.moderation.submissions',
'On the submissions page of registries reviews');
// Pending tab
assert.ok(currentURL().includes('state=pending'), 'Default state is pending');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]').exists({ count: 10 }, '10 pending registrations shown');
assert.dom('[data-test-registration-list-card-icon="pending"]').exists({ count: 10 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 10 }, 'Title shown');
assert.dom('[data-test-registration-list-card-latest-action]').exists({ count: 10 }, 'Latest action shown');
assert.dom('[data-test-next-page-button]').exists('Pagination shown');
await click('[data-test-next-page-button]');
assert.dom('[data-test-next-page-button]').hasAttribute('disabled');
assert.dom('[data-test-registration-list-card]').exists({ count: 2 }, '2 more pending registrations shown');
assert.dom('[data-test-registration-card-toggle-actions]')
.exists({ count: 2 }, 'Toggle to show more review actions');
const toggleActions = this.element.querySelectorAll('[data-test-registration-card-toggle-actions]');
await click(toggleActions[0]);
assert.dom('[data-test-registration-list-card-more-actions]')
.exists({ count: 2 }, 'More actions shown after clicking the toggler');
// Accepted tab
await click('[data-test-submissions-type="accepted"]');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]').exists({ count: 2 }, '2 accepted registrations shown');
assert.dom('[data-test-registration-list-card-icon="accepted"]').exists({ count: 2 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 2 }, 'Title shown');
assert.dom('[data-test-registration-list-card-latest-action]').exists({ count: 2 }, 'Latest action shown');
assert.dom('[data-test-registration-card-toggle-actions]')
.doesNotExist('No toggle to show more review actions');
assert.dom('[data-test-next-page-button]').doesNotExist('No pagination shown');
// Embargo tab
await click('[data-test-submissions-type="embargo"]');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]').exists({ count: 5 }, '5 embargoed registrations shown');
assert.dom('[data-test-registration-list-card-icon="embargo"]').exists({ count: 5 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 5 }, 'Title shown');
assert.dom('[data-test-registration-list-card-latest-action]').exists({ count: 5 }, 'Latest action shown');
assert.dom('[data-test-registration-card-toggle-actions]')
.doesNotExist('No toggle to show more review actions');
assert.dom('[data-test-next-page-button]').doesNotExist('No pagination shown');
// Rejected tab
await click('[data-test-submissions-type="rejected"]');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]').exists({ count: 3 }, '3 rejected registrations shown');
assert.dom('[data-test-registration-list-card-icon="rejected"]').exists({ count: 3 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 3 }, 'Title shown');
assert.dom('[data-test-no-actions-found]').exists({ count: 3 }, 'No actions found');
assert.dom('[data-test-next-page-button]').doesNotExist('No pagination shown');
// Withdrawn tab
await click('[data-test-submissions-type="withdrawn"]');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]').exists({ count: 4 }, '4 withdrawn registrations shown');
assert.dom('[data-test-registration-list-card-icon="withdrawn"]').exists({ count: 4 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 4 }, 'Title shown');
assert.dom('[data-test-no-actions-found]').exists({ count: 4 }, 'No actions found');
assert.dom('[data-test-next-page-button]').doesNotExist('No pagination shown');
// Pending Withdrawal tab
await click('[data-test-submissions-type="pending-withdraw"]');
assert.dom('[data-test-ascending-sort]').exists({ count: 1 }, 'Ascending sort button exists');
assert.dom('[data-test-descending-sort]').exists({ count: 1 }, 'Descending sort button exists');
assert.dom('[data-test-registration-list-card]')
.exists({ count: 2 }, '2 registrations pending withdrawal shown');
assert.dom('[data-test-registration-list-card-icon="pending_withdraw"]')
.exists({ count: 2 }, 'Proper icons shown');
assert.dom('[data-test-registration-list-card-title]').exists({ count: 2 }, 'Title shown');
assert.dom('[data-test-no-actions-found]').exists({ count: 2 }, 'No actions found');
assert.dom('[data-test-next-page-button]').doesNotExist('No pagination shown');
await click('[data-test-registration-list-card-title]>a');
assert.equal(currentRouteName(), 'registries.overview.index',
'Clicking the registration title from moderation takes moderators to the overview page');
assert.ok(currentURL().includes('mode=moderator'), 'Mode query param set to moderator');
});
test('Submissions page: queryParams', async function(this: ModerationSubmissionsTestContext, assert) {
this.registrationProvider.update({ permissions: ['view_submissions'] });
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', {
id: currentUser.id,
user: currentUser,
provider: this.registrationProvider,
}, 'asModerator');
await visit('/registries/sbmit/moderation/submissions?state=embargo');
assert.equal(currentRouteName(), 'registries.branded.moderation.submissions',
'On the submissions page of registries reviews');
assert.ok(currentURL().includes('state=embargo'), 'current URL contains the state query param set');
assert.dom('[data-test-is-selected="true"]').hasText('Embargo', 'embargo tab selected');
});
test('Submissions page: invalid queryParam', async function(this: ModerationSubmissionsTestContext, assert) {
this.registrationProvider.update({ permissions: ['view_submissions'] });
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', {
id: currentUser.id,
user: currentUser,
provider: this.registrationProvider,
}, 'asModerator');
await visit('/registries/sbmit/moderation/submissions?state=embargooooo');
assert.equal(currentRouteName(), 'registries.branded.moderation.submissions',
'On the submissions page of registries reviews');
assert.notOk(currentURL().includes('state=embargooooo'), 'Invalid query param is gone');
assert.ok(currentURL().includes('state=pending'), 'Invalid query param replaced with pending');
assert.dom('[data-test-is-selected="true"]').hasText('Pending', 'Pending tab selected');
});
}); | the_stack |
import { Resolvers, ApolloClient } from '@apollo/client';
import {
ClientType,
ROOT_DOMAIN_ID,
getBlockTime,
getLogs,
} from '@colony/colony-js';
import { BigNumber, bigNumberify } from 'ethers/utils';
import { AddressZero, HashZero } from 'ethers/constants';
import { Context } from '~context/index';
import ENS from '~lib/ENS';
import ColonyManager from '~lib/ColonyManager';
import { Address } from '~types/index';
import { createAddress } from '~utils/web3';
import {
Transfer,
SubgraphColoniesQuery,
SubgraphColoniesQueryVariables,
SubgraphColoniesDocument,
UserLock,
UserToken,
} from '~data/index';
import { COLONY_TOTAL_BALANCE_DOMAIN_ID } from '~constants';
import {
SubgraphMotionRewardClaimedEventsDocument,
SubgraphMotionRewardClaimedEventsQuery,
SubgraphMotionRewardClaimedEventsQueryVariables,
SubgraphUserMotionStakedEventsDocument,
SubgraphUserMotionStakedEventsQuery,
SubgraphUserMotionStakedEventsQueryVariables,
} from '~data/generated';
import { parseSubgraphEvent } from '~utils/events';
import { getToken } from './token';
import { getProcessedColony } from './colony';
const getUserReputation = async (
colonyManager: ColonyManager,
address: Address,
colonyAddress: Address,
domainId: number,
rootHash?: string,
): Promise<BigNumber> => {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
const { skillId } = await colonyClient.getDomain(
/*
* If we have the "All Teams" domain selected, fetch reputation values from "Root"
*/
domainId === COLONY_TOTAL_BALANCE_DOMAIN_ID ? ROOT_DOMAIN_ID : domainId,
);
const { reputationAmount } = await colonyClient.getReputationWithoutProofs(
skillId,
address,
rootHash,
);
return reputationAmount;
};
const getUserStakedBalance = async (
apolloClient: ApolloClient<object>,
walletAddress: Address,
): Promise<BigNumber> => {
/**
* @NOTE If there will be more staking events
* on reputation voting extension we need to remember to filter them out
* in here for correct value of staked tokens.
*/
const { data: motionStakedEventsData } = await apolloClient.query<
SubgraphUserMotionStakedEventsQuery,
SubgraphUserMotionStakedEventsQueryVariables
>({
query: SubgraphUserMotionStakedEventsDocument,
fetchPolicy: 'network-only',
variables: {
walletAddress: walletAddress.toLowerCase(),
},
});
const motionStakedEvents = motionStakedEventsData?.motionStakedEvents || [];
const parsedMotionStakedEvents = motionStakedEvents.map(parseSubgraphEvent);
const groupedMotionStakeEvents = parsedMotionStakedEvents.reduce(
(acc, event) => {
const { vote, motionId } = event.values;
const key = `${motionId.toString()}-${vote.toString()}`;
if (!acc[key]) {
acc[key] = [event];
} else {
acc[key].push(event);
}
return acc;
},
{},
);
const { data: motionRewardClaimedEventsData } = await apolloClient.query<
SubgraphMotionRewardClaimedEventsQuery,
SubgraphMotionRewardClaimedEventsQueryVariables
>({
query: SubgraphMotionRewardClaimedEventsDocument,
fetchPolicy: 'network-only',
variables: {
walletAddress: walletAddress.toLowerCase(),
},
});
const motionRewardClaimedEvents =
motionRewardClaimedEventsData?.motionRewardClaimedEvents || [];
const parsedMotionRewardClaimedEvents = motionRewardClaimedEvents.map(
parseSubgraphEvent,
);
const filteredKeys = Object.keys(groupedMotionStakeEvents).filter((key) => {
const { motionId, vote } = groupedMotionStakeEvents[key][0].values;
const mappedMotionRewardClaimedEvent = parsedMotionRewardClaimedEvents.find(
(claimedEvent) =>
claimedEvent.values.motionId.toString() === motionId.toString() &&
claimedEvent.values.vote.toString() === vote.toString(),
);
return !mappedMotionRewardClaimedEvent;
});
const notClaimedEvents = filteredKeys.reduce((acc, key) => {
return [...acc, ...groupedMotionStakeEvents[key]];
}, []);
const totalStaked = notClaimedEvents.reduce((acc, event) => {
return acc.add(event.values.amount);
}, bigNumberify(0));
return totalStaked;
};
const getUserLock = async (
apolloClient: ApolloClient<object>,
colonyManager: ColonyManager,
walletAddress: Address,
tokenAddress: Address,
colonyAddress: Address,
): Promise<UserLock> => {
const tokenLockingClient = await colonyManager.getClient(
ClientType.TokenLockingClient,
colonyAddress,
);
const userLock = await tokenLockingClient.getUserLock(
tokenAddress,
walletAddress,
);
const totalObligation = await tokenLockingClient.getTotalObligation(
walletAddress,
tokenAddress,
);
const stakedTokens = await getUserStakedBalance(apolloClient, walletAddress);
const nativeToken = (await getToken(
{ colonyManager, client: apolloClient },
tokenAddress,
walletAddress,
)) as UserToken;
return {
balance: userLock.balance.toString(),
nativeToken: nativeToken || null,
totalObligation: totalObligation.add(stakedTokens).toString(),
activeTokens: userLock.balance.sub(totalObligation).toString(),
pendingBalance: userLock.pendingBalance.toString(),
};
};
export const userResolvers = ({
colonyManager: { networkClient },
colonyManager,
ens,
apolloClient,
ipfsWithFallback,
}: Required<Context>): Resolvers => ({
Query: {
async userAddress(_, { name }): Promise<Address> {
const address = await ens.getAddress(
ENS.getFullDomain('user', name),
networkClient,
);
return address;
},
async userReputation(
_,
{
address,
colonyAddress,
domainId = ROOT_DOMAIN_ID,
rootHash,
}: {
address: Address;
colonyAddress: Address;
domainId?: number;
rootHash?: string;
},
): Promise<string> {
const reputation = await getUserReputation(
colonyManager,
address,
colonyAddress,
domainId,
rootHash,
);
return reputation.toString();
},
async username(_, { address }): Promise<string> {
const domain = await ens.getDomain(address, networkClient);
return ENS.stripDomainParts('user', domain);
},
},
User: {
async reputation(
user,
{
colonyAddress,
domainId = ROOT_DOMAIN_ID,
}: { colonyAddress: Address; domainId: number },
): Promise<string> {
const {
profile: { walletAddress },
} = user;
const reputation = await getUserReputation(
colonyManager,
walletAddress,
colonyAddress,
domainId,
);
return reputation.toString();
},
async tokens(
{ tokenAddresses }: { tokenAddresses: Address[] },
{ walletAddress },
{ client },
) {
return Promise.all(
[AddressZero, ...tokenAddresses].map(async (tokenAddress) =>
getToken({ colonyManager, client }, tokenAddress, walletAddress),
),
);
},
async userLock(
_,
{ tokenAddress, walletAddress, colonyAddress },
{ client },
): Promise<UserLock> {
const userLock = await getUserLock(
client,
colonyManager,
walletAddress,
tokenAddress,
colonyAddress,
);
return userLock;
},
async tokenTransfers({
walletAddress,
colonyAddresses,
}): Promise<Transfer[]> {
const metaColonyClient = await colonyManager.getMetaColonyClient();
const { tokenClient } = metaColonyClient;
const transferFromFilter = tokenClient.filters.Transfer(
walletAddress,
null,
null,
);
const transferToFilter = tokenClient.filters.Transfer(
null,
walletAddress,
null,
);
const transferFromLogs = await getLogs(tokenClient, transferFromFilter);
const transferToLogs = await getLogs(tokenClient, transferToFilter);
const logs = [...transferFromLogs, ...transferToLogs].sort((a, b) => {
if (a.blockNumber && b.blockNumber) {
return a.blockNumber - b.blockNumber;
}
return 0;
});
return Promise.all(
logs.map(async (log) => {
const {
values: { src, dst, wad },
} = tokenClient.interface.parseLog(log);
const from = createAddress(src);
const to = createAddress(dst);
const date = log.blockHash
? await getBlockTime(tokenClient.provider, log.blockHash)
: 0;
const colonyAddress = colonyAddresses.find(
(address) => address === from || address === to,
);
return {
__typename: 'Transaction',
amount: wad.toString(),
colonyAddress,
date,
from: createAddress(src),
// I have no idea why this would ever by empty but we rely on this being there
hash: log.transactionHash || HashZero,
incoming: to === walletAddress,
to,
token: createAddress(log.address),
};
}),
);
},
async processedColonies({ colonyAddresses = [] }) {
try {
const { data } = await apolloClient.query<
SubgraphColoniesQuery,
SubgraphColoniesQueryVariables
>({
query: SubgraphColoniesDocument,
fetchPolicy: 'network-only',
variables: {
colonyAddresses: colonyAddresses.map((address) =>
address.toLowerCase(),
),
},
});
if (data?.colonies) {
return Promise.all(
data.colonies.map(async (colony) =>
getProcessedColony(
colony,
createAddress(colony.id),
ipfsWithFallback,
),
),
);
}
return null;
} catch (error) {
console.info(error);
return null;
}
},
},
}); | the_stack |
import React, { useState, useMemo, useEffect, useLayoutEffect } from "react";
import { OrgComponent } from "@ui_types";
import { Model, Api } from "@core/types";
import { stripUndefinedRecursive } from "@core/lib/utils/object";
import * as g from "@core/lib/graph";
import * as R from "ramda";
import * as ui from "@ui";
import * as styles from "@styles";
import { SmallLoader } from "@images";
import { MIN_ACTION_DELAY_MS } from "@constants";
import { wait } from "@core/lib/utils/wait";
import { style } from "typestyle";
import { logAndAlertError } from "@ui_lib/errors";
export const OrgSettings: OrgComponent = (props) => {
const { graph, graphUpdatedAt } = props.core;
const org = g.getOrg(graph);
const currentUserId = props.ui.loadedAccountId!;
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, []);
const { canRename, canUpdateSettings, canDelete } = useMemo(() => {
return {
canRename: g.authz.canRenameOrg(graph, currentUserId),
canUpdateSettings: g.authz.canUpdateOrgSettings(graph, currentUserId),
canDelete: g.authz.canDeleteOrg(graph, currentUserId),
};
}, [graphUpdatedAt, currentUserId]);
const [name, setName] = useState(org.name);
const [autoCaps, setAutoCaps] = useState(org.settings.envs?.autoCaps ?? true);
const [autoCommitLocals, setAutoCommitLocals] = useState(
org.settings.envs?.autoCommitLocals ?? false
);
const [requiresPassphrase, setRequiresPassphrase] = useState(
org.settings.crypto.requiresPassphrase
);
const [requiresLockout, setRequiresLockout] = useState(
org.settings.crypto.requiresLockout
);
const [lockoutMs, setLockoutMs] = useState(org.settings.crypto.lockoutMs);
const [inviteExpirationMs, setInviteExpirationMs] = useState(
org.settings.auth.inviteExpirationMs
);
const [deviceGrantExpirationMs, setDeviceGrantExpirationMs] = useState(
org.settings.auth.deviceGrantExpirationMs
);
const [tokenExpirationMs, setTokenExpirationMs] = useState(
org.settings.auth.tokenExpirationMs
);
const [confirmDeleteName, setConfirmDeleteName] = useState("");
const [updatingSettings, setUpdatingSettings] = useState(false);
const [updatingCryptoSettings, setUpdatingCryptoSettings] = useState(false);
const [updatingAuthSettings, setUpdatingAuthSettings] = useState(false);
const [updatingEnvsSettings, setUpdatingEnvsSettings] = useState(false);
const [renaming, setRenaming] = useState(false);
const [awaitingMinDelay, setAwaitingMinDelay] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const settingsFlagsState = {
autoCaps,
autoCommitLocals,
requiresPassphrase,
requiresLockout,
};
const settingsState: Model.OrgSettings = {
crypto: {
requiresPassphrase,
requiresLockout,
lockoutMs,
},
auth: {
inviteExpirationMs,
deviceGrantExpirationMs,
tokenExpirationMs,
},
envs: {
autoCommitLocals,
autoCaps,
},
};
useEffect(() => {
if (renaming && org.name == name && !awaitingMinDelay) {
setRenaming(false);
}
}, [org.name, awaitingMinDelay]);
const {
settingsUpdated,
cryptoSettingsUpdated,
authSettingsUpdated,
envsSettingsUpdated,
} = useMemo(() => {
const cryptoSettingsUpdated = !R.equals(
stripUndefinedRecursive(org.settings.crypto),
stripUndefinedRecursive(settingsState.crypto)
);
const authSettingsUpdated = !R.equals(
stripUndefinedRecursive(org.settings.auth),
stripUndefinedRecursive(settingsState.auth)
);
const envsSettingsUpdated = !R.equals(
stripUndefinedRecursive(org.settings.envs),
stripUndefinedRecursive(settingsState.envs)
);
return {
settingsUpdated:
cryptoSettingsUpdated || authSettingsUpdated || envsSettingsUpdated,
cryptoSettingsUpdated,
authSettingsUpdated,
envsSettingsUpdated,
};
}, [JSON.stringify(org.settings), JSON.stringify(settingsState)]);
const nameUpdated = name.trim() != org.name;
const dispatchSettingsUpdate = async () => {
if (updatingSettings || !settingsUpdated) {
return;
}
setUpdatingSettings(true);
if (cryptoSettingsUpdated) {
setUpdatingCryptoSettings(true);
}
if (authSettingsUpdated) {
setUpdatingAuthSettings(true);
}
if (envsSettingsUpdated) {
setUpdatingEnvsSettings(true);
}
setAwaitingMinDelay(true);
wait(MIN_ACTION_DELAY_MS).then(() => setAwaitingMinDelay(false));
await props
.dispatch({
type: Api.ActionType.UPDATE_ORG_SETTINGS,
payload: settingsState,
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem updating org settings.`,
(res.resultAction as any)?.payload
);
}
});
};
useEffect(() => {
dispatchSettingsUpdate();
}, [JSON.stringify(settingsFlagsState)]);
useEffect(() => {
if (updatingSettings && !awaitingMinDelay) {
setUpdatingSettings(false);
setUpdatingCryptoSettings(false);
setUpdatingAuthSettings(false);
setUpdatingEnvsSettings(false);
}
}, [JSON.stringify(org.settings), awaitingMinDelay]);
const renderRename = () => {
if (canRename) {
return (
<div className="field">
<label>Org Name</label>
<input
type="text"
disabled={renaming}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button
className="primary"
disabled={!name.trim() || !nameUpdated || renaming}
onClick={() => {
setRenaming(true);
setAwaitingMinDelay(true);
wait(MIN_ACTION_DELAY_MS).then(() => setAwaitingMinDelay(false));
props
.dispatch({
type: Api.ActionType.RENAME_ORG,
payload: { name: name.trim() },
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem renaming the org.`,
(res.resultAction as any)?.payload
);
}
});
}}
>
{renaming ? "Renaming..." : "Rename"}
</button>
</div>
);
} else {
return "";
}
};
const renderSettings = () => {
if (canUpdateSettings) {
return (
<div>
<div>
<h3>
Security <strong>Settings</strong>
{updatingCryptoSettings ? <SmallLoader /> : ""}
</h3>
<div
className={
"field checkbox" +
(requiresPassphrase ? " selected" : "") +
(updatingSettings ? " disabled" : "")
}
onClick={() => setRequiresPassphrase(!requiresPassphrase)}
>
<label>Require passphrase for all organization devices</label>
<input type="checkbox" checked={requiresPassphrase} />
</div>
{requiresPassphrase ? (
<div
className={
"field checkbox" +
(requiresLockout ? " selected" : "") +
(updatingSettings ? " disabled" : "")
}
onClick={() => setRequiresLockout(!requiresLockout)}
>
<label>Require lockout for all organization devices</label>
<input type="checkbox" checked={requiresLockout} />
</div>
) : (
""
)}
{requiresLockout ? (
<div>
<div className="field">
<label>Minimum required lockout (minutes) </label>
<input
disabled={updatingSettings}
type="number"
min="1"
value={
typeof lockoutMs == "number" ? lockoutMs / 1000 / 60 : 120
}
onChange={(e) => {
setLockoutMs(parseInt(e.target.value) * 60 * 1000);
}}
/>
</div>
<div className="field">
<input
type="submit"
className="primary"
disabled={updatingSettings || !cryptoSettingsUpdated}
onClick={dispatchSettingsUpdate}
value={
(updatingCryptoSettings ? "Updating " : "Update ") +
"Security Settings" +
(updatingCryptoSettings ? "..." : "")
}
/>
</div>
</div>
) : (
""
)}
</div>
<div>
<h3>
Authentication <strong>Settings</strong>
{updatingAuthSettings ? <SmallLoader /> : ""}
</h3>
<div className="field">
<label>User session expiration (days)</label>
<input
type="number"
disabled={updatingSettings}
min="1"
value={tokenExpirationMs / 1000 / 60 / 60 / 24}
onChange={(e) => {
setTokenExpirationMs(
parseInt(e.target.value) * 24 * 60 * 60 * 1000
);
}}
/>
</div>
<div className="field">
<label>User invitation expiration (hours)</label>
<input
type="number"
disabled={updatingSettings}
min="1"
value={inviteExpirationMs / 1000 / 60 / 60}
onChange={(e) => {
setInviteExpirationMs(
parseInt(e.target.value) * 60 * 60 * 1000
);
}}
/>
</div>
<div className="field">
<label>Device invitation expiration (hours)</label>
<input
type="number"
disabled={updatingSettings}
min="1"
value={deviceGrantExpirationMs / 1000 / 60 / 60}
onChange={(e) => {
setDeviceGrantExpirationMs(
parseInt(e.target.value) * 60 * 60 * 1000
);
}}
/>
</div>
<div className="field">
<input
type="submit"
className="primary"
disabled={updatingSettings || !authSettingsUpdated}
onClick={dispatchSettingsUpdate}
value={
(updatingAuthSettings ? "Updating " : "Update ") +
"Authentication Settings" +
(updatingAuthSettings ? "..." : "")
}
/>
</div>
</div>
<div>
<h3>
Environment <strong>Settings</strong>
{updatingEnvsSettings ? <SmallLoader /> : ""}
</h3>
<div
className={
"field checkbox no-margin" +
(autoCaps ? " selected" : "") +
(updatingSettings ? " disabled" : "")
}
onClick={() => setAutoCaps(!autoCaps)}
>
<label>Default Auto-Upcase Variable Names</label>
<input type="checkbox" checked={autoCaps} />
</div>
{/* <div
className={
"field checkbox" +
(autoCommitLocals ? " selected" : "") +
(updatingSettings ? " disabled" : "")
}
onClick={() => setAutoCommitLocals(!autoCommitLocals)}
>
<label>Default Auto-Commit Locals On Change</label>
<input type="checkbox" checked={autoCommitLocals} />
</div> */}
</div>
</div>
);
}
};
const renderDelete = () => {
if (canDelete) {
return (
<div className="field">
<label>Delete Organization</label>
<input
type="text"
value={confirmDeleteName}
onChange={(e) => setConfirmDeleteName(e.target.value)}
placeholder={"To confirm, enter organization name here..."}
/>
<button
className="primary"
disabled={isDeleting || confirmDeleteName != org.name}
onClick={async () => {
setIsDeleting(true);
const minDelayPromise = wait(MIN_ACTION_DELAY_MS);
const res = await props.dispatch({
type: Api.ActionType.DELETE_ORG,
payload: {},
});
await minDelayPromise;
if (res.success) {
alert("The organization was successfully deleted.");
props.history.replace("/home");
} else {
logAndAlertError(
"There was a problem deleting the organization.",
(res.resultAction as any)?.payload
);
}
}}
>
{isDeleting ? "Deleting Organization..." : "Delete Organization"}
</button>
</div>
);
}
};
const renderDangerZone = () => {
if (canDelete) {
return (
<div className="danger-zone">
<h3>Danger Zone</h3>
{renderDelete()}
</div>
);
}
};
return (
<div className={styles.OrgContainer}>
<h3>
{updatingSettings ||
renaming ||
settingsState.crypto.lockoutMs != org.settings.crypto.lockoutMs ? (
<SmallLoader />
) : (
""
)}
Org <strong>Settings</strong>
</h3>
{authSettingsUpdated || nameUpdated ? (
<span className="unsaved-changes">Unsaved changes</span>
) : (
""
)}
{renderRename()}
{renderSettings()}
{renderDangerZone()}
</div>
);
}; | the_stack |
import { Ripemd160, Secp256k1, Sha1, Sha256 } from '../../../crypto/crypto';
import { Operation } from '../../virtual-machine';
import {
AuthenticationProgramStateCommon,
AuthenticationProgramStateError,
AuthenticationProgramStateMinimum,
AuthenticationProgramStateStack,
} from '../../vm-types';
import { ConsensusBCH } from '../bch/bch-types';
import { serializeAuthenticationInstructions } from '../instruction-sets-utils';
import {
combineOperations,
pushToStack,
useOneScriptNumber,
useOneStackItem,
useTwoStackItems,
} from './combinators';
import { booleanToScriptNumber, ConsensusCommon } from './common';
import {
decodeBitcoinSignature,
isValidPublicKeyEncoding,
isValidSignatureEncodingBCHTransaction,
} from './encoding';
import { applyError, AuthenticationErrorCommon } from './errors';
import { opVerify } from './flow-control';
import { OpcodesCommon } from './opcodes';
import { generateSigningSerializationBCH } from './signing-serialization';
export { Ripemd160, Sha1, Sha256, Secp256k1 };
export const opRipemd160 = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> &
AuthenticationProgramStateStack &
AuthenticationProgramStateError<Errors>,
Errors
>({
ripemd160,
}: {
ripemd160: { hash: Ripemd160['hash'] };
}): Operation<State> => (state: State) =>
useOneStackItem(state, (nextState, [value]) =>
pushToStack(nextState, ripemd160.hash(value))
);
export const opSha1 = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> &
AuthenticationProgramStateStack &
AuthenticationProgramStateError<Errors>,
Errors
>({
sha1,
}: {
sha1: { hash: Sha1['hash'] };
}): Operation<State> => (state: State) =>
useOneStackItem(state, (nextState, [value]) =>
pushToStack(nextState, sha1.hash(value))
);
export const opSha256 = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> &
AuthenticationProgramStateStack &
AuthenticationProgramStateError<Errors>,
Errors
>({
sha256,
}: {
sha256: {
hash: Sha256['hash'];
};
}): Operation<State> => (state: State) =>
useOneStackItem(state, (nextState, [value]) =>
pushToStack(nextState, sha256.hash(value))
);
export const opHash160 = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> &
AuthenticationProgramStateStack &
AuthenticationProgramStateError<Errors>,
Errors
>({
ripemd160,
sha256,
}: {
sha256: { hash: Sha256['hash'] };
ripemd160: { hash: Ripemd160['hash'] };
}): Operation<State> => (state: State) =>
useOneStackItem(state, (nextState, [value]) =>
pushToStack(nextState, ripemd160.hash(sha256.hash(value)))
);
export const opHash256 = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> &
AuthenticationProgramStateStack &
AuthenticationProgramStateError<Errors>,
Errors
>({
sha256,
}: {
sha256: {
hash: Sha256['hash'];
};
}): Operation<State> => (state: State) =>
useOneStackItem(state, (nextState, [value]) =>
pushToStack(nextState, sha256.hash(sha256.hash(value)))
);
export const opCodeSeparator = <
Opcodes,
State extends AuthenticationProgramStateMinimum<Opcodes> & {
lastCodeSeparator: number;
}
>(): Operation<State> => (state: State) => {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
state.lastCodeSeparator = state.ip;
return state;
};
export const opCheckSig = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags,
secp256k1,
sha256,
}: {
sha256: { hash: Sha256['hash'] };
secp256k1: {
verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr'];
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: { requireNullSignatureFailures: boolean };
}): Operation<State> => (s: State) =>
// eslint-disable-next-line complexity
useTwoStackItems(s, (state, [bitcoinEncodedSignature, publicKey]) => {
if (!isValidPublicKeyEncoding(publicKey)) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidPublicKeyEncoding,
state
);
}
if (!isValidSignatureEncodingBCHTransaction(bitcoinEncodedSignature)) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidSignatureEncoding,
state
);
}
const coveredBytecode = serializeAuthenticationInstructions(
state.instructions
).subarray(state.lastCodeSeparator + 1);
const { signingSerializationType, signature } = decodeBitcoinSignature(
bitcoinEncodedSignature
);
const serialization = generateSigningSerializationBCH({
correspondingOutput: state.correspondingOutput,
coveredBytecode,
locktime: state.locktime,
outpointIndex: state.outpointIndex,
outpointTransactionHash: state.outpointTransactionHash,
outputValue: state.outputValue,
sequenceNumber: state.sequenceNumber,
sha256,
signingSerializationType,
transactionOutpoints: state.transactionOutpoints,
transactionOutputs: state.transactionOutputs,
transactionSequenceNumbers: state.transactionSequenceNumbers,
version: state.version,
});
const digest = sha256.hash(sha256.hash(serialization));
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
state.signedMessages.push(serialization);
const useSchnorr = signature.length === ConsensusBCH.schnorrSignatureLength;
const success = useSchnorr
? secp256k1.verifySignatureSchnorr(signature, publicKey, digest)
: secp256k1.verifySignatureDERLowS(signature, publicKey, digest);
return !success &&
flags.requireNullSignatureFailures &&
signature.length !== 0
? applyError<State, Errors>(
AuthenticationErrorCommon.nonNullSignatureFailure,
state
)
: pushToStack(state, booleanToScriptNumber(success));
});
const enum Multisig {
maximumPublicKeys = 20,
}
export const opCheckMultiSig = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags: {
requireMinimalEncoding,
requireBugValueZero,
requireNullSignatureFailures,
},
secp256k1,
sha256,
}: {
sha256: { hash: Sha256['hash'] };
secp256k1: {
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: {
requireBugValueZero: boolean;
requireMinimalEncoding: boolean;
requireNullSignatureFailures: boolean;
};
}) => (s: State) =>
useOneScriptNumber(
s,
(state, publicKeysValue) => {
const potentialPublicKeys = Number(publicKeysValue);
if (potentialPublicKeys < 0) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidNaturalNumber,
state
);
}
if (potentialPublicKeys > Multisig.maximumPublicKeys) {
return applyError<State, Errors>(
AuthenticationErrorCommon.exceedsMaximumMultisigPublicKeyCount,
state
);
}
const publicKeys =
// eslint-disable-next-line functional/immutable-data
potentialPublicKeys > 0 ? state.stack.splice(-potentialPublicKeys) : [];
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
state.operationCount += potentialPublicKeys;
return state.operationCount > ConsensusCommon.maximumOperationCount
? applyError<State, Errors>(
AuthenticationErrorCommon.exceededMaximumOperationCount,
state
)
: useOneScriptNumber(
state,
(nextState, approvingKeys) => {
const requiredApprovingPublicKeys = Number(approvingKeys);
if (requiredApprovingPublicKeys < 0) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidNaturalNumber,
nextState
);
}
if (requiredApprovingPublicKeys > potentialPublicKeys) {
return applyError<State, Errors>(
AuthenticationErrorCommon.insufficientPublicKeys,
nextState
);
}
const signatures =
requiredApprovingPublicKeys > 0
? // eslint-disable-next-line functional/immutable-data
nextState.stack.splice(-requiredApprovingPublicKeys)
: [];
return useOneStackItem(
nextState,
// eslint-disable-next-line complexity
(finalState, [protocolBugValue]) => {
if (requireBugValueZero && protocolBugValue.length !== 0) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidProtocolBugValue,
finalState
);
}
const coveredBytecode = serializeAuthenticationInstructions(
finalState.instructions
).subarray(finalState.lastCodeSeparator + 1);
let approvingPublicKeys = 0; // eslint-disable-line functional/no-let
let remainingSignatures = signatures.length; // eslint-disable-line functional/no-let
let remainingPublicKeys = publicKeys.length; // eslint-disable-line functional/no-let
// eslint-disable-next-line functional/no-loop-statement
while (
remainingSignatures > 0 &&
remainingPublicKeys > 0 &&
approvingPublicKeys + remainingPublicKeys >=
remainingSignatures &&
approvingPublicKeys !== requiredApprovingPublicKeys
) {
const publicKey = publicKeys[remainingPublicKeys - 1];
const bitcoinEncodedSignature =
signatures[remainingSignatures - 1];
if (!isValidPublicKeyEncoding(publicKey)) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidPublicKeyEncoding,
finalState
);
}
if (
!isValidSignatureEncodingBCHTransaction(
bitcoinEncodedSignature
)
) {
return applyError<State, Errors>(
AuthenticationErrorCommon.invalidSignatureEncoding,
finalState
);
}
const {
signingSerializationType,
signature,
} = decodeBitcoinSignature(bitcoinEncodedSignature);
const serialization = generateSigningSerializationBCH({
correspondingOutput: state.correspondingOutput,
coveredBytecode,
locktime: state.locktime,
outpointIndex: state.outpointIndex,
outpointTransactionHash: state.outpointTransactionHash,
outputValue: state.outputValue,
sequenceNumber: state.sequenceNumber,
sha256,
signingSerializationType,
transactionOutpoints: state.transactionOutpoints,
transactionOutputs: state.transactionOutputs,
transactionSequenceNumbers:
state.transactionSequenceNumbers,
version: state.version,
});
const digest = sha256.hash(sha256.hash(serialization));
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
finalState.signedMessages.push(serialization);
if (
signature.length === ConsensusBCH.schnorrSignatureLength
) {
return applyError<State, Errors>(
AuthenticationErrorCommon.schnorrSizedSignatureInCheckMultiSig,
finalState
);
}
const signed = secp256k1.verifySignatureDERLowS(
signature,
publicKey,
digest
);
// eslint-disable-next-line functional/no-conditional-statement
if (signed) {
approvingPublicKeys += 1; // eslint-disable-line functional/no-expression-statement
remainingSignatures -= 1; // eslint-disable-line functional/no-expression-statement
}
remainingPublicKeys -= 1; // eslint-disable-line functional/no-expression-statement
}
const success =
approvingPublicKeys === requiredApprovingPublicKeys;
if (
!success &&
requireNullSignatureFailures &&
!signatures.every((signature) => signature.length === 0)
) {
return applyError<State, Errors>(
AuthenticationErrorCommon.nonNullSignatureFailure,
finalState
);
}
return pushToStack(
finalState,
booleanToScriptNumber(success)
);
}
);
},
{ requireMinimalEncoding }
);
},
{ requireMinimalEncoding }
);
export const opCheckSigVerify = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags,
secp256k1,
sha256,
}: {
sha256: { hash: Sha256['hash'] };
secp256k1: {
verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr'];
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: {
requireNullSignatureFailures: boolean;
};
}): Operation<State> =>
combineOperations(
opCheckSig<Opcodes, State, Errors>({ flags, secp256k1, sha256 }),
opVerify<State, Errors>()
);
export const opCheckMultiSigVerify = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags,
secp256k1,
sha256,
}: {
sha256: { hash: Sha256['hash'] };
secp256k1: {
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: {
requireBugValueZero: boolean;
requireMinimalEncoding: boolean;
requireNullSignatureFailures: boolean;
};
}): Operation<State> =>
combineOperations(
opCheckMultiSig<Opcodes, State, Errors>({ flags, secp256k1, sha256 }),
opVerify<State, Errors>()
);
export const cryptoOperations = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags,
ripemd160,
secp256k1,
sha1,
sha256,
}: {
sha1: { hash: Sha1['hash'] };
sha256: { hash: Sha256['hash'] };
ripemd160: { hash: Ripemd160['hash'] };
secp256k1: {
verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr'];
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: {
requireBugValueZero: boolean;
requireMinimalEncoding: boolean;
requireNullSignatureFailures: boolean;
};
}) => ({
[OpcodesCommon.OP_RIPEMD160]: opRipemd160<Opcodes, State, Errors>({
ripemd160,
}),
[OpcodesCommon.OP_SHA1]: opSha1<Opcodes, State, Errors>({ sha1 }),
[OpcodesCommon.OP_SHA256]: opSha256<Opcodes, State, Errors>({ sha256 }),
[OpcodesCommon.OP_HASH160]: opHash160<Opcodes, State, Errors>({
ripemd160,
sha256,
}),
[OpcodesCommon.OP_HASH256]: opHash256<Opcodes, State, Errors>({ sha256 }),
[OpcodesCommon.OP_CODESEPARATOR]: opCodeSeparator<Opcodes, State>(),
[OpcodesCommon.OP_CHECKSIG]: opCheckSig<Opcodes, State, Errors>({
flags,
secp256k1,
sha256,
}),
[OpcodesCommon.OP_CHECKSIGVERIFY]: opCheckSigVerify<Opcodes, State, Errors>({
flags,
secp256k1,
sha256,
}),
[OpcodesCommon.OP_CHECKMULTISIG]: opCheckMultiSig<Opcodes, State, Errors>({
flags,
secp256k1,
sha256,
}),
[OpcodesCommon.OP_CHECKMULTISIGVERIFY]: opCheckMultiSigVerify<
Opcodes,
State,
Errors
>({ flags, secp256k1, sha256 }),
}); | the_stack |
import { assert } from "./assert";
import { isSigned, sizeOfNumber } from "./utils";
export function ByteArray_set16(array: ByteArray, index: number, value: number): void {
array.set(index, value);
array.set(index + 1, (value >> 8));
}
export function ByteArray_set32(array: ByteArray, index: number, value: number): void {
array.set(index, value);
array.set(index + 1, (value >> 8));
array.set(index + 2, (value >> 16));
array.set(index + 3, (value >> 24));
}
export function ByteArray_append32(array: ByteArray, value: number): void {
array.append(value);
array.append((value >> 8));
array.append((value >> 16));
array.append((value >> 24));
}
//
// export function ByteArray_append64(array: ByteArray, value: int64): void {
// array.append(value);
// array.append((value >> 8));
// array.append((value >> 16));
// array.append((value >> 24));
// array.append((value >> 32));
// array.append((value >> 40));
// array.append((value >> 48));
// array.append((value >> 56));
// }
//
// declare function Uint8Array_new(length: number): Uint8Array;
//
export function ByteArray_setString(data: ByteArray, index: number, text: string): void {
var length = text.length;
assert(index >= 0 && index + length * 2 <= data.length);
var array = data.array;
var i = 0;
while (i < length) {
var c = text.charCodeAt(i);
array[index] = c;
array[index + 1] = (c >> 8);
index = index + 2;
i = i + 1;
}
}
/**
* JavaScript ByteArray
* version : 0.2
* @author Nidin Vinayakan | nidinthb@gmail.com
*
* ActionScript3 ByteArray implementation in JavaScript
* limitation : size of ByteArray cannot be changed
*
*/
export class ByteArray {
static BIG_ENDIAN: string = "bigEndian";
static LITTLE_ENDIAN: string = "littleEndian";
static SIZE_OF_BOOLEAN: number = 1;
static SIZE_OF_INT8: number = 1;
static SIZE_OF_INT16: number = 2;
static SIZE_OF_INT32: number = 4;
static SIZE_OF_INT64: number = 8;
static SIZE_OF_UINT8: number = 1;
static SIZE_OF_UINT16: number = 2;
static SIZE_OF_UINT32: number = 4;
static SIZE_OF_UINT64: number = 8;
static SIZE_OF_FLOAT32: number = 4;
static SIZE_OF_FLOAT64: number = 8;
private BUFFER_EXT_SIZE: number = 1024;//Buffer expansion size
private _array: Uint8Array = null;
get array(): Uint8Array {
return this._array.subarray(0, this.length);
};
public log: string = "";
public data: DataView;
private _position: number;
public write_position: number;
public endian: string;
constructor(buffer?: ArrayBuffer, byteOffset: number = 0, byteLength: number = 0) {
if (buffer == undefined) {
buffer = new ArrayBuffer(this.BUFFER_EXT_SIZE);
this.write_position = 0;
}
else if (buffer == null) {
this.write_position = 0;
} else {
this.write_position = byteLength > 0 ? byteLength : buffer.byteLength;
}
this.data = new DataView(buffer, byteOffset, byteLength > 0 ? byteLength : buffer.byteLength);
this._array = new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);
this._position = 0;
this.endian = ByteArray.LITTLE_ENDIAN;
}
get(index: number): byte {
// assert((index) < (this._length));
return this._array[index];
}
set(index: number, value: byte): void {
//assert((index) < (this._length));
this._array[index] = value;
}
append(value: byte): number {
let index = this.position;
this.resize(index + 1);
this._array[index] = value;
this.position++;
return index;
}
resize(length: number): ByteArray {
if (length > this.data.byteLength) {
let pos = this.position;
let len = this.length;
let capacity = length * 2;
let data = new Uint8Array(capacity);
data.set(this.array);
this.setArray(data);
this._position = pos;
this.write_position = len;
}
return this;
}
copy(source: ByteArray, offset: number = 0, length: number = 0): ByteArray {
offset = offset > 0 ? offset : this.length;
if (offset + source.length > this._array.length) {
this.resize(offset + source.length);
}
this._array.set(source.array, offset);
this.position = offset + source.length;
return this;
}
// getter setter
get buffer(): ArrayBuffer {
return this.data.buffer;
}
set buffer(value: ArrayBuffer) {
this.data = new DataView(value);
}
get dataView(): DataView {
return this.data;
}
set dataView(value: DataView) {
this.data = value;
this.write_position = value.byteLength;
}
get phyPosition(): number {
return this._position + this.data.byteOffset;
}
get byteOffset(): number {
return this.data.byteOffset;
}
get byteLength(): number {
return this.data.byteLength;
}
get position(): number {
return this._position;
}
set position(value: number) {
if (this._position < value) {
if (!this.validate(this._position - value)) {
return;
}
}
this._position = value;
this.write_position = value > this.write_position ? value : this.write_position;
}
get length(): number {
return this.write_position;
}
set length(value: number) {
this.validateBuffer(value);
}
get bytesAvailable(): number {
return this.data.byteLength - this._position;
}
//end
public clear(): void {
this._position = 0;
}
public setArray(array: Uint8Array): void {
this._array = array;
this.setBuffer(array.buffer, array.byteOffset, array.byteLength);
}
public setBuffer(buffer: ArrayBuffer, offset: number = 0, length: number = 0) {
if (buffer) {
this.data = new DataView(buffer, offset, length > 0 ? length : buffer.byteLength);
} else {
}
}
readU8LEB() {
return this.readUnsignedLEB128(1)
}
readU16LEB() {
return this.readUnsignedLEB128(2)
}
readU32LEB() {
return this.readUnsignedLEB128(4)
}
readU64LEB() {
return this.readUnsignedLEB128(8)
}
readS8LEB() {
return this.readLEB128(1)
}
readS16LEB() {
return this.readLEB128(2)
}
readS32LEB() {
return this.readLEB128(4)
}
readS64LEB() {
return this.readLEB128(8)
}
/**
* Read unsigned Little Endian Base 128
*/
readUnsignedLEB128(size): number {
let value = 0;
let shift = 0;
let byte;
while (true) {
byte = this.readUnsignedByte();
let last: boolean = !(byte & 128);
let payload: number = byte & 127;
let shift_mask = 0 == shift ? ~0
: ((1 << (size * 8 - shift)) - 1);
let significant_payload = payload & shift_mask;
if (significant_payload != payload) {
if (!(value < 0 && last)) {
throw "LEB dropped bits only valid for signed LEB";
}
}
value |= significant_payload << shift;
if (last) break;
shift += 7;
if (sizeOfNumber(shift) >= size * 8) {
throw "LEB overflow";
}
}
return value;
}
/**
* Read signed Little Endian Base 128
*/
readLEB128(size): number {
let value = 0;
let shift = 0;
let sizeOfShift = 0;
let byte;
while (true) {
byte = this.readByte();
let last = !(byte & 128);
let payload = byte & 127;
let shift_mask = 0 == shift
? ~0
: ((1 << (size * 8 - shift)) - 1);
let significant_payload = payload & shift_mask;
if (significant_payload != payload) {
if (!(isSigned(value) && last)) {
throw "LEB dropped bits only valid for signed LEB";
}
}
value |= significant_payload << shift;
if (last) break;
shift += 7;
sizeOfShift = sizeOfNumber(shift);
if (sizeOfShift >= size * 8) {
throw "LEB overflow";
}
}
// If signed LEB, then we might need to sign-extend. (compile should
// optimize this out if not needed).
if (isSigned(value)) {
shift += 7;
sizeOfShift = sizeOfNumber(shift);
if ((byte & 64) && sizeOfShift < 8 * size) {
let sext_bits = 8 * size - sizeOfShift;
value <<= sext_bits;
value >>= sext_bits;
if (value >= 0) {
throw "LEB sign-extend should produce a negative value";
}
}
}
return value;
}
/**
* Write unsigned Little Endian Base 128
*/
writeUnsignedLEB128(value) {
let b = 0;
value |= 0;
do {
b = value & 0x7F;
value >>>= 7;
if (value)
b |= 0x80;
this.append(b);
} while (value);
}
/**
* Write signed Little Endian Base 128
*/
writeLEB128(value) {
let b;
value |= 0;
do {
b = value & 0x7F;
value >>= 7;
let signBit = (b & 0x40) !== 0;
if (
((value === 0) && !signBit) ||
((value === -1) && signBit)
) {
this.append(b);
break;
} else {
b |= 0x80;
this.append(b);
}
} while (true);
}
/**
* Read WASM String
*/
readWasmString(): string {
let length = this.readUnsignedLEB128(4);
return this.readUTFBytes(length);
}
/**
* Write WASM String
*/
writeWasmString(value: string) {
let length = value.length;
this.writeUnsignedLEB128(length);
let index = this.length;
this.resize(index + length);
let i = 0;
while (i < length) {
this.set(index + i, value.charCodeAt(i));
i = i + 1;
}
this.position = index + length;
}
/**
* Reads a Boolean value from the byte stream. A single byte is read,
* and true is returned if the byte is nonzero,
* false otherwise.
* @return Returns true if the byte is nonzero, false otherwise.
*/
public readBoolean(): boolean {
if (!this.validate(ByteArray.SIZE_OF_BOOLEAN)) return null;
return this.data.getUint8(this.position++) != 0;
}
/**
* Reads a signed byte from the byte stream.
* The returned value is in the range -128 to 127.
* @return An integer between -128 and 127.
*/
public readByte(): number {
if (!this.validate(ByteArray.SIZE_OF_INT8)) return null;
return this.data.getInt8(this.position++);
}
/**
* Reads the number of data bytes, specified by the length parameter, from the byte stream.
* The bytes are read into the ByteArray object specified by the bytes parameter,
* and the bytes are written into the destination ByteArray starting at the _position specified by offset.
* @param bytes The ByteArray object to read data into.
* @param offset The offset (_position) in bytes at which the read data should be written.
* @param length The number of bytes to read. The default value of 0 causes all available data to be read.
*/
public readBytes(_bytes: ByteArray = null, offset: number = 0, length: number = 0, createNewBuffer: boolean = false): ByteArray {
if (length == 0) {
length = this.bytesAvailable;
}
else if (!this.validate(length)) return null;
if (createNewBuffer) {
_bytes = _bytes == null ? new ByteArray(new ArrayBuffer(length)) : _bytes;
//This method is expensive
for (var i = 0; i < length; i++) {
_bytes.data.setUint8(i + offset, this.data.getUint8(this.position++));
}
} else {
//Offset argument ignored
_bytes = _bytes == null ? new ByteArray(null) : _bytes;
_bytes.dataView = new DataView(this.data.buffer, this.byteOffset + this.position, length);
this.position += length;
}
return _bytes;
}
/**
* Reads an IEEE 754 double-precision (64-bit) floating-point number from the byte stream.
* @return A double-precision (64-bit) floating-point number.
*/
public readDouble(): number {
if (!this.validate(ByteArray.SIZE_OF_FLOAT64)) return null;
var value: number = this.data.getFloat64(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_FLOAT64;
return value;
}
/**
* Reads an IEEE 754 single-precision (32-bit) floating-point number from the byte stream.
* @return A single-precision (32-bit) floating-point number.
*/
public readFloat(): number {
if (!this.validate(ByteArray.SIZE_OF_FLOAT32)) return null;
var value: number = this.data.getFloat32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_FLOAT32;
return value;
}
/**
* Reads a signed 32-bit integer from the byte stream.
*
* The returned value is in the range -2147483648 to 2147483647.
* @return A 32-bit signed integer between -2147483648 and 2147483647.
*/
public readInt(): number {
if (!this.validate(ByteArray.SIZE_OF_INT32)) return null;
var value = this.data.getInt32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_INT32;
return value;
}
/**
* Reads a signed 64-bit integer from the byte stream.
*
* The returned value is in the range −(2^63) to 2^63 − 1
* @return A 64-bit signed integer between −(2^63) to 2^63 − 1
*/
// public readInt64(): Int64 {
// if (!this.validate(ByteArray.SIZE_OF_UINT32)) return null;
//
// var low = this.data.getInt32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
// this.position += ByteArray.SIZE_OF_INT32;
// var high = this.data.getInt32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
// this.position += ByteArray.SIZE_OF_INT32;
// return new Int64(low, high);
// }
/**
* Reads a multibyte string of specified length from the byte stream using the
* specified character set.
* @param length The number of bytes from the byte stream to read.
* @param charSet The string denoting the character set to use to interpret the bytes.
* Possible character set strings include "shift-jis", "cn-gb",
* "iso-8859-1", and others.
* For a complete list, see Supported Character Sets.
* Note: If the value for the charSet parameter
* is not recognized by the current system, the application uses the system's default
* code page as the character set. For example, a value for the charSet parameter,
* as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of
* 1 might work on your development system, but not on another system.
* On the other system, the application will use the system's default code page.
* @return UTF-8 encoded string.
*/
public readMultiByte(length: number, charSet?: string): string {
if (!this.validate(length)) return null;
return "";
}
/**
* Reads a signed 16-bit integer from the byte stream.
*
* The returned value is in the range -32768 to 32767.
* @return A 16-bit signed integer between -32768 and 32767.
*/
public readShort(): number {
if (!this.validate(ByteArray.SIZE_OF_INT16)) return null;
var value = this.data.getInt16(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_INT16;
return value;
}
/**
* Reads an unsigned byte from the byte stream.
*
* The returned value is in the range 0 to 255.
* @return A 32-bit unsigned integer between 0 and 255.
*/
public readUnsignedByte(): number {
if (!this.validate(ByteArray.SIZE_OF_UINT8)) return null;
return this.data.getUint8(this.position++);
}
/**
* Reads an unsigned 32-bit integer from the byte stream.
*
* The returned value is in the range 0 to 4294967295.
* @return A 32-bit unsigned integer between 0 and 4294967295.
*/
public readUnsignedInt(): number {
if (!this.validate(ByteArray.SIZE_OF_UINT32)) return null;
var value = this.data.getUint32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_UINT32;
return value;
}
/**
* Reads a variable sized unsigned integer (VX -> 16-bit or 32-bit) from the byte stream.
*
* A VX is written as a variable length 2- or 4-byte element. If the index value is less than 65,280 (0xFF00),
* then the index is written as an unsigned two-byte integer. Otherwise the index is written as an unsigned
* four byte integer with bits 24-31 set. When reading an index, if the first byte encountered is 255 (0xFF),
* then the four-byte form is being used and the first byte should be discarded or masked out.
*
* The returned value is in the range 0 to 65279 or 0 to 2147483647.
* @return A VX 16-bit or 32-bit unsigned integer between 0 to 65279 or 0 and 2147483647.
*/
public readVariableSizedUnsignedInt(): number {
var value: number;
var c = this.readUnsignedByte();
if (c != 0xFF) {
value = c << 8;
c = this.readUnsignedByte();
value |= c;
}
else {
c = this.readUnsignedByte();
value = c << 16;
c = this.readUnsignedByte();
value |= c << 8;
c = this.readUnsignedByte();
value |= c;
}
return value;
}
/**
* Fast read for WebGL since only Uint16 numbers are expected
*/
public readU16VX(): number {
return (this.readUnsignedByte() << 8) | this.readUnsignedByte();
}
/**
* Reads an unsigned 64-bit integer from the byte stream.
*
* The returned value is in the range 0 to 2^64 − 1.
* @return A 64-bit unsigned integer between 0 and 2^64 − 1
*/
// public readUnsignedInt64(): UInt64 {
// if (!this.validate(ByteArray.SIZE_OF_UINT32)) return null;
//
// var low = this.data.getUint32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
// this.position += ByteArray.SIZE_OF_UINT32;
// var high = this.data.getUint32(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
// this.position += ByteArray.SIZE_OF_UINT32;
// return new UInt64(low, high);
// }
/**
* Reads an unsigned 16-bit integer from the byte stream.
*
* The returned value is in the range 0 to 65535.
* @return A 16-bit unsigned integer between 0 and 65535.
*/
public readUnsignedShort(): number {
if (!this.validate(ByteArray.SIZE_OF_UINT16)) return null;
var value = this.data.getUint16(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_UINT16;
return value;
}
/**
* Reads a UTF-8 string from the byte stream. The string
* is assumed to be prefixed with an unsigned int16 indicating
* the length in bytes.
* @return UTF-8 encoded string.
*/
public readUTF(): string {
if (!this.validate(ByteArray.SIZE_OF_UINT16)) return null;
var length: number = this.data.getUint16(this.position, this.endian == ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_UINT16;
if (length > 0) {
return this.readUTFBytes(length);
} else {
return "";
}
}
/**
* Reads a sequence of UTF-8 bytes specified by the length
* parameter from the byte stream and returns a string.
* @param length An unsigned int16 indicating the length of the UTF-8 bytes.
* @return A string composed of the UTF-8 bytes of the specified length.
*/
public readUTFBytes(length: number): string {
if (!this.validate(length)) return null;
var _bytes: Uint8Array = new Uint8Array(this.buffer, this.byteOffset + this.position, length);
this.position += length;
/*var _bytes: Uint8Array = new Uint8Array(new ArrayBuffer(length));
for (var i = 0; i < length; i++) {
_bytes[i] = this.data.getUint8(this.position++);
}*/
return this.decodeUTF8(_bytes);
}
public readStandardString(length: number): string {
if (!this.validate(length)) return null;
var str: string = "";
for (var i = 0; i < length; i++) {
str += String.fromCharCode(this.data.getUint8(this.position++));
}
return str;
}
public readStringTillNull(keepEvenByte: boolean = true): string {
var str: string = "";
var num: number = 0;
while (this.bytesAvailable > 0) {
var _byte: number = this.data.getUint8(this.position++);
num++;
if (_byte != 0) {
str += String.fromCharCode(_byte);
} else {
if (keepEvenByte && num % 2 != 0) {
this.position++;
}
break;
}
}
return str;
}
/**
* Writes a Boolean value. A single byte is written according to the value parameter,
* either 1 if true or 0 if false.
* @param value A Boolean value determining which byte is written. If the parameter is true,
* the method writes a 1; if false, the method writes a 0.
* @param offset optional start position to write
*/
public writeBoolean(value: boolean, offset: number = null): void {
offset = offset ? offset : this.position++;
this.validateBuffer(ByteArray.SIZE_OF_BOOLEAN, offset);
this.data.setUint8(offset, value ? 1 : 0);
}
/**
* Writes a byte to the byte stream.
* The low 8 bits of the
* parameter are used. The high 24 bits are ignored.
* @param value A 32-bit integer. The low 8 bits are written to the byte stream.
* @param offset optional start position to write
*/
public writeByte(value: number, offset: number = null): void {
offset = offset ? offset : this.position++;
this.validateBuffer(ByteArray.SIZE_OF_INT8, offset);
this.data.setInt8(offset, value);
}
public writeUnsignedByte(value: number, offset: number = null): void {
offset = offset ? offset : this.position++;
this.validateBuffer(ByteArray.SIZE_OF_UINT8, offset);
this.data.setUint8(offset, value);
}
/**
* Writes a sequence of length bytes from the
* specified byte array, bytes,
* starting offset(zero-based index) bytes
* into the byte stream.
*
* If the length parameter is omitted, the default
* length of 0 is used; the method writes the entire buffer starting at
* offset.
* If the offset parameter is also omitted, the entire buffer is
* written. If offset or length
* is out of range, they are clamped to the beginning and end
* of the bytes array.
* @param _bytes The ByteArray object.
* @param offset A zero-based index indicating the _position into the array to begin writing.
* @param length An unsigned integer indicating how far into the buffer to write.
*/
public writeBytes(_bytes: ByteArray, offset: number = 0, length: number = 0): void {
this.copy(_bytes);
// this.validateBuffer(length);
// var tmp_data = new DataView(_bytes.buffer);
// for (var i = 0; i < _bytes.length; i++) {
// this.data.setUint8(this.position++, tmp_data.getUint8(i));
// }
}
/**
* Writes an IEEE 754 double-precision (64-bit) floating-point number to the byte stream.
* @param value A double-precision (64-bit) floating-point number.
* @param offset optional start position to write
*/
public writeDouble(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_FLOAT64, position);
this.data.setFloat64(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_FLOAT64;
}
}
/**
* Writes an IEEE 754 single-precision (32-bit) floating-point number to the byte stream.
* @param value A single-precision (32-bit) floating-point number.
* @param offset optional start position to write
*/
public writeFloat(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_FLOAT32, position);
this.data.setFloat32(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_FLOAT32;
}
}
/**
* Writes a 32-bit signed integer to the byte stream.
* @param value An integer to write to the byte stream.
* @param offset optional start position to write
*/
public writeInt(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_INT32, position);
this.data.setInt32(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_INT32;
}
}
/**
* Writes a multibyte string to the byte stream using the specified character set.
* @param value The string value to be written.
* @param charSet The string denoting the character set to use. Possible character set strings
* include "shift-jis", "cn-gb", "iso-8859-1", and others.
* For a complete list, see Supported Character Sets.
*/
public writeMultiByte(value: string, charSet: string): void {
}
/**
* Writes a 16-bit integer to the byte stream. The low 16 bits of the parameter are used.
* The high 16 bits are ignored.
* @param value 32-bit integer, whose low 16 bits are written to the byte stream.
* @param offset optional start position to write
*/
public writeShort(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_INT16, position);
this.data.setInt16(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_INT16;
}
}
public writeUnsignedShort(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_UINT16, position);
this.data.setUint16(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_UINT16;
}
}
/**
* Writes a 32-bit unsigned integer to the byte stream.
* @param value An unsigned integer to write to the byte stream.
* @param offset optional start position to write
*/
public writeUnsignedInt(value: number, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_UINT32, position);
this.data.setUint32(position, value, this.endian == ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_UINT32;
}
}
/**
* Writes a UTF-8 string to the byte stream. The length of the UTF-8 string in bytes
* is written first, as a 16-bit integer, followed by the bytes representing the
* characters of the string.
* @param value The string value to be written.
* @param offset optional start position to write
*/
public writeUTF(value: string, offset: number = null): void {
let utf8bytes: Uint8Array = this.encodeUTF8(value);
let length: number = utf8bytes.length;
let position = offset != null ? offset : this.position;
this.validateBuffer(ByteArray.SIZE_OF_UINT16 + length, position);
this.data.setUint16(position, length, this.endian === ByteArray.LITTLE_ENDIAN);
if (!offset) {
this.position += ByteArray.SIZE_OF_UINT16;
this.writeUint8Array(utf8bytes);
} else {
offset += ByteArray.SIZE_OF_UINT16;
this.writeUint8Array(utf8bytes, offset);
}
}
/**
* Writes a UTF-8 string to the byte stream. Similar to the writeUTF() method,
* but writeUTFBytes() does not prefix the string with a 16-bit length word.
* @param value The string value to be written.
* @param offset optional start position to write
*/
public writeUTFBytes(value: string, offset: number = null): void {
this.writeUint8Array(this.encodeUTF8(value), offset);
}
public toString(): string {
return "[ByteArray] length:" + this.length + ", bytesAvailable:" + this.bytesAvailable;
}
/****************************/
/* EXTRA JAVASCRIPT APIs */
/****************************/
/**
* Writes a Uint8Array to the byte stream.
* @param _bytes The Uint8Array to be written.
* @param offset optional start position to write
*/
public writeUint8Array(_bytes: Uint8Array, offset: number = null): ByteArray {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length, position);
this._array.set(_bytes, position);
if (!offset) {
this.position += _bytes.length;
}
return this;
}
/**
* Writes a Uint16Array to the byte stream.
* @param _bytes The Uint16Array to be written.
* @param offset optional start position to write
*/
public writeUint16Array(_bytes: Uint16Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length * ByteArray.SIZE_OF_UINT16, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setUint16(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_UINT16;
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Uint32Array to the byte stream.
* @param _bytes The Uint32Array to be written.
* @param offset optional start position to write
*/
public writeUint32Array(_bytes: Uint32Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length * ByteArray.SIZE_OF_UINT32, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setUint32(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_UINT32;
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Int8Array to the byte stream.
* @param _bytes The Int8Array to be written.
* @param offset optional start position to write
*/
public writeInt8Array(_bytes: Int8Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setInt8(position++, _bytes[i]);
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Int16Array to the byte stream.
* @param _bytes The Int16Array to be written.
* @param offset optional start position to write
*/
public writeInt16Array(_bytes: Int16Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length * ByteArray.SIZE_OF_INT16, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setInt16(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_INT16;
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Int32Array to the byte stream.
* @param _bytes The Int32Array to be written.
* @param offset optional start position to write
*/
public writeInt32Array(_bytes: Int32Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length * ByteArray.SIZE_OF_INT32, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setInt32(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_INT32;
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Float32Array to the byte stream.
* @param _bytes The Float32Array to be written.
* @param offset optional start position to write
*/
public writeFloat32Array(_bytes: Float32Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length * ByteArray.SIZE_OF_FLOAT32, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setFloat32(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_FLOAT32;
}
if (!offset) {
this.position = position;
}
}
/**
* Writes a Float64Array to the byte stream.
* @param _bytes The Float64Array to be written.
* @param offset optional start position to write
*/
public writeFloat64Array(_bytes: Float64Array, offset: number = null): void {
let position = offset != null ? offset : this.position;
this.validateBuffer(_bytes.length, position);
for (let i = 0; i < _bytes.length; i++) {
this.data.setFloat64(position, _bytes[i], this.endian === ByteArray.LITTLE_ENDIAN);
position += ByteArray.SIZE_OF_FLOAT64;
}
if (!offset) {
this.position = position;
}
}
/**
* Read a Uint8Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Uint8Array.
*/
public readUint8Array(length: number, createNewBuffer: boolean = true): Uint8Array {
if (!this.validate(length)) return null;
if (!createNewBuffer) {
var result: Uint8Array = new Uint8Array(this.buffer, this.byteOffset + this.position, length);
this.position += length;
} else {
result = new Uint8Array(new ArrayBuffer(length));
for (var i = 0; i < length; i++) {
result[i] = this.data.getUint8(this.position);
this.position += ByteArray.SIZE_OF_UINT8;
}
}
return result;
}
/**
* Read a Uint16Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Uint16Array.
*/
public readUint16Array(length: number, createNewBuffer: boolean = true): Uint16Array {
var size: number = length * ByteArray.SIZE_OF_UINT16;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
var result: Uint16Array = new Uint16Array(this.buffer, this.byteOffset + this.position, length);
this.position += size;
}
else {
result = new Uint16Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getUint16(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_UINT16;
}
}
return result;
}
/**
* Read a Uint32Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Uint32Array.
*/
public readUint32Array(length: number, createNewBuffer: boolean = true): Uint32Array {
var size: number = length * ByteArray.SIZE_OF_UINT32;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
var result: Uint32Array = new Uint32Array(this.buffer, this.byteOffset + this.position, length);
this.position += size;
}
else {
result = new Uint32Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getUint32(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_UINT32;
}
}
return result;
}
/**
* Read a Int8Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Int8Array.
*/
public readInt8Array(length: number, createNewBuffer: boolean = true): Int8Array {
if (!this.validate(length)) return null;
if (!createNewBuffer) {
var result: Int8Array = new Int8Array(this.buffer, this.byteOffset + this.position, length);
this.position += length;
}
else {
result = new Int8Array(new ArrayBuffer(length));
for (var i = 0; i < length; i++) {
result[i] = this.data.getInt8(this.position);
this.position += ByteArray.SIZE_OF_INT8;
}
}
return result;
}
/**
* Read a Int16Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Int16Array.
*/
public readInt16Array(length: number, createNewBuffer: boolean = true): Int16Array {
var size: number = length * ByteArray.SIZE_OF_INT16;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
var result: Int16Array = new Int16Array(this.buffer, this.byteOffset + this.position, length);
this.position += size;
}
else {
result = new Int16Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getInt16(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_INT16;
}
}
return result;
}
/**
* Read a Int32Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Int32Array.
*/
public readInt32Array(length: number, createNewBuffer: boolean = true): Int32Array {
var size: number = length * ByteArray.SIZE_OF_INT32;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
if ((this.byteOffset + this.position) % 4 == 0) {
var result: Int32Array = new Int32Array(this.buffer, this.byteOffset + this.position, length);
this.position += size;
} else {
var tmp: Uint8Array = new Uint8Array(new ArrayBuffer(size));
for (var i = 0; i < size; i++) {
tmp[i] = this.data.getUint8(this.position);
this.position += ByteArray.SIZE_OF_UINT8;
}
result = new Int32Array(tmp.buffer);
}
}
else {
result = new Int32Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getInt32(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_INT32;
}
}
return result;
}
/**
* Read a Float32Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Float32Array.
*/
public readFloat32Array(length: number, createNewBuffer: boolean = true): Float32Array {
var size: number = length * ByteArray.SIZE_OF_FLOAT32;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
if ((this.byteOffset + this.position) % 4 == 0) {
var result: Float32Array = new Float32Array(this.buffer, this.byteOffset + this.position, length);
this.position += size;
} else {
var tmp: Uint8Array = new Uint8Array(new ArrayBuffer(size));
for (var i = 0; i < size; i++) {
tmp[i] = this.data.getUint8(this.position);
this.position += ByteArray.SIZE_OF_UINT8;
}
result = new Float32Array(tmp.buffer);
}
}
else {
result = new Float32Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getFloat32(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_FLOAT32;
}
}
return result;
}
/**
* Read a Float64Array from the byte stream.
* @param length An unsigned int16 indicating the length of the Float64Array.
*/
public readFloat64Array(length: number, createNewBuffer: boolean = true): Float64Array {
var size: number = length * ByteArray.SIZE_OF_FLOAT64;
if (!this.validate(size)) return null;
if (!createNewBuffer) {
var result: Float64Array = new Float64Array(this.buffer, this.position, length);
this.position += size;
} else {
result = new Float64Array(new ArrayBuffer(size));
for (var i = 0; i < length; i++) {
result[i] = this.data.getFloat64(this.position, this.endian === ByteArray.LITTLE_ENDIAN);
this.position += ByteArray.SIZE_OF_FLOAT64;
}
}
return result;
}
public validate(len: number): boolean {
//len += this.data.byteOffset;
if (this.data.byteLength > 0 && this._position + len <= this.data.byteLength) {
return true;
} else {
throw 'Error #2030: End of file was encountered.';
}
}
/**********************/
/* PRIVATE METHODS */
/**********************/
private validateBuffer(size: number, offset: number = 0): void {
let length = offset + size;
this.resize(length);
}
/**
* UTF-8 Encoding/Decoding
*/
private encodeUTF8(str: string): Uint8Array {
var pos: number = 0;
var codePoints = this.stringToCodePoints(str);
var outputBytes = [];
while (codePoints.length > pos) {
var code_point: number = codePoints[pos++];
if (this.inRange(code_point, 0xD800, 0xDFFF)) {
this.encoderError(code_point);
}
else if (this.inRange(code_point, 0x0000, 0x007f)) {
outputBytes.push(code_point);
} else {
var count, offset;
if (this.inRange(code_point, 0x0080, 0x07FF)) {
count = 1;
offset = 0xC0;
} else if (this.inRange(code_point, 0x0800, 0xFFFF)) {
count = 2;
offset = 0xE0;
} else if (this.inRange(code_point, 0x10000, 0x10FFFF)) {
count = 3;
offset = 0xF0;
}
outputBytes.push(this.div(code_point, Math.pow(64, count)) + offset);
while (count > 0) {
var temp = this.div(code_point, Math.pow(64, count - 1));
outputBytes.push(0x80 + (temp % 64));
count -= 1;
}
}
}
return new Uint8Array(outputBytes);
}
private decodeUTF8(data: Uint8Array): string {
var fatal: boolean = false;
var pos: number = 0;
var result: string = "";
var code_point: number;
var utf8_code_point = 0;
var utf8_bytes_needed = 0;
var utf8_bytes_seen = 0;
var utf8_lower_boundary = 0;
while (data.length > pos) {
var _byte = data[pos++];
if (_byte === this.EOF_byte) {
if (utf8_bytes_needed !== 0) {
code_point = this.decoderError(fatal);
} else {
code_point = this.EOF_code_point;
}
} else {
if (utf8_bytes_needed === 0) {
if (this.inRange(_byte, 0x00, 0x7F)) {
code_point = _byte;
} else {
if (this.inRange(_byte, 0xC2, 0xDF)) {
utf8_bytes_needed = 1;
utf8_lower_boundary = 0x80;
utf8_code_point = _byte - 0xC0;
} else if (this.inRange(_byte, 0xE0, 0xEF)) {
utf8_bytes_needed = 2;
utf8_lower_boundary = 0x800;
utf8_code_point = _byte - 0xE0;
} else if (this.inRange(_byte, 0xF0, 0xF4)) {
utf8_bytes_needed = 3;
utf8_lower_boundary = 0x10000;
utf8_code_point = _byte - 0xF0;
} else {
this.decoderError(fatal);
}
utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
code_point = null;
}
} else if (!this.inRange(_byte, 0x80, 0xBF)) {
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
pos--;
code_point = this.decoderError(fatal, _byte);
} else {
utf8_bytes_seen += 1;
utf8_code_point = utf8_code_point + (_byte - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
if (utf8_bytes_seen !== utf8_bytes_needed) {
code_point = null;
} else {
var cp = utf8_code_point;
var lower_boundary = utf8_lower_boundary;
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
if (this.inRange(cp, lower_boundary, 0x10FFFF) && !this.inRange(cp, 0xD800, 0xDFFF)) {
code_point = cp;
} else {
code_point = this.decoderError(fatal, _byte);
}
}
}
}
//Decode string
if (code_point !== null && code_point !== this.EOF_code_point) {
if (code_point <= 0xFFFF) {
if (code_point > 0) result += String.fromCharCode(code_point);
} else {
code_point -= 0x10000;
result += String.fromCharCode(0xD800 + ((code_point >> 10) & 0x3ff));
result += String.fromCharCode(0xDC00 + (code_point & 0x3ff));
}
}
}
return result;
}
private encoderError(code_point) {
throw 'EncodingError! The code point ' + code_point + ' could not be encoded.';
}
private decoderError(fatal, opt_code_point?): number {
if (fatal) {
throw 'DecodingError';
}
return opt_code_point || 0xFFFD;
}
private EOF_byte: number = -1;
private EOF_code_point: number = -1;
private inRange(a, min, max) {
return min <= a && a <= max;
}
private div(n, d) {
return Math.floor(n / d);
}
private stringToCodePoints(string: string) {
/** @type {Array.<number>} */
var cps = [];
// Based on http://www.w3.org/TR/WebIDL/#idl-DOMString
var i = 0, n = string.length;
while (i < string.length) {
var c = string.charCodeAt(i);
if (!this.inRange(c, 0xD800, 0xDFFF)) {
cps.push(c);
} else if (this.inRange(c, 0xDC00, 0xDFFF)) {
cps.push(0xFFFD);
} else { // (inRange(c, 0xD800, 0xDBFF))
if (i === n - 1) {
cps.push(0xFFFD);
} else {
var d = string.charCodeAt(i + 1);
if (this.inRange(d, 0xDC00, 0xDFFF)) {
var a = c & 0x3FF;
var b = d & 0x3FF;
i += 1;
cps.push(0x10000 + (a << 10) + b);
} else {
cps.push(0xFFFD);
}
}
}
i += 1;
}
return cps;
}
} | the_stack |
import util = require('util');
import Promise = require('bluebird');
import _ = require('lodash');
import should = require('should');
import io = require('socket.io-client');
import TestHelper = require('./lib/test-helper');
should(true).ok; // Added so ts won't get rid of should module
var url = 'http://localhost:3001/subscription';
var opt = {
reconnection: false,
multiplex: false
};
describe('Subscription-socket-io', (): void => {
var ipc: TestHelper.IOurSocket;
var socket: SocketIOClient.Socket;
// Create test server
// Use function instead of lambda to avoid ts capturing "this" in a variable
before(function(done: Function): void {
this.timeout(0); // Turn off timeout for before all hook
TestHelper.startServer()
.then((s: TestHelper.IOurSocket): void => {
ipc = s;
done();
});
});
// Shut-down server
after((): Promise<any> => {
return TestHelper.stopServer();
});
// Connect to the server for every test cases
beforeEach((): void => {
socket = io.connect(url, opt);
});
// Disconnect to the server if it is still connected
afterEach((): void => {
if (socket.connected) {
socket.disconnect();
}
});
describe('blpSession cannot be started', (): void => {
// Set instructions
beforeEach((): void => {
ipc.once('wait-to-start', (): void => {
ipc.emit('start-fail');
});
});
it('should disconnect client if blpSession cannot be started', (done: Function): void => {
socket.once('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('Unexpected error: Session Fail to Start.');
});
socket.once('disconnect', (): void => {
done();
});
});
});
describe('blpSession start successfully', (): void => {
// Set instructions
before((): Promise<void> => {
return ipc.emitAcknowledge('set-instructions', { start: true });
});
// Clear instructions
after((): Promise<void> => {
return ipc.emitAcknowledge('clear-instructions');
});
it('should let client connect successfully', (done: Function): void => {
socket.once('connect', (): void => {
done();
});
});
describe('validate subscription options', (): void => {
it('should send error if no subscription object sent', (done: Function): void => {
var counter = 0;
socket.emit('subscribe');
socket.emit('subscribe', []);
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('No valid subscriptions found.');
if (++counter === 2) {
done();
}
});
});
it('should send error if subscription object is invalid', (done: Function): void => {
var counter = 0;
socket.emit('subscribe', [{}]);
socket.emit('subscribe', [{ security: 'AAPL US Equity' }]);
socket.emit('subscribe', [{ correlationId: 0 }]);
socket.emit('subscribe', [{ fields: ['LAST_PRICE'] }]);
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('Invalid subscription option.');
if (++counter === 4) {
done();
}
});
});
it('should send error if duplicate correlationId found', (done: Function): void => {
socket.emit('subscribe',
[
{ security: 'AAPL', correlationId: 0, fields: ['LAST_PRICE'] },
{ security: 'AAPL', correlationId: 0, fields: ['LAST_PRICE'] }
]
);
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('Duplicate correlation Id received.');
done();
});
});
});
describe('service open failure', (): void => {
before((): void => {
ipc.on('wait-to-openService', (data: any): void => {
if ('//blp/mktdata' === data.uri) {
ipc.emit(util.format('openService-%d-fail', data.cid));
} else {
ipc.emit(util.format('openService-%d-success', data.cid));
}
});
});
after((): void => {
ipc.off('wait-to-openService');
});
it('should send error if all services cannot be opened', (done: Function): void => {
socket.emit('subscribe',
[
{ security: 'AAPL', correlationId: 0, fields: ['LAST_PRICE'] }
]
);
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('//blp/mktdata Service Fail to Open.');
done();
});
});
it('should send error if part of service cannot be opened', (done: Function): void => {
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['PRICE'] },
{ security: '//blp/mktvwap', correlationId: 1, fields: ['PRICE'] }
]
);
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('//blp/mktdata Service Fail to Open.');
done();
});
});
});
describe('service open successfully', (): void => {
before((): void => {
ipc.on('wait-to-openService', (data: any): void => {
ipc.emit(util.format('openService-%d-success', data.cid));
});
});
after((): void => {
ipc.off('wait-to-openService');
});
describe('#subscribe', (): void => {
it('should subscribe client successfully', (done: Function): void => {
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
done();
});
});
it('should emit 1 subscription data', (done: Function): void => {
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
if (++counter === 1) {
done();
}
});
});
it('should emit 3 consecutive subscription data', (done: Function): void => {
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
if (++counter === 3) {
done();
}
});
});
it('should emit 1 subscription data then another', (done: Function): void => {
var cid: number;
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
cid = subscriptions[0].correlation;
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
++counter;
if (counter === 1) {
ipc.emit(util.format('subscription-%d-MarketDataEvents', cid));
} else if (counter === 2) {
done();
}
});
});
it('should emit 1 subscription data for each event', (done: Function): void => {
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketBarStart',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketBarUpdate',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketBarEnd',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktbar', correlationId: 0, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
if (++counter === 3) {
done();
}
});
});
it('should emit 1 data for each subscription', (done: Function): void => {
var counter: number = 0;
var cids: number[] = [];
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[1].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
cids.push(data.correlationId);
if (++counter === 2) {
_.sortBy(cids).should.eql([0, 1]);
done();
}
});
});
it('should emit 2 data for only one subscription', (done: Function): void => {
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[1].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[1].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
data.correlationId.should.be.a.Number.and.equal(1);
if (++counter === 2) {
done();
}
});
});
it('should allow subsequent subscriptions', (done: Function): void => {
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.once('data', (data: any): void => {
data.correlationId.should.be.a.Number.and.equal(0);
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{
security: '//blp/mktdata',
correlationId: 1,
fields: ['P']
}
]
);
socket.once('data', (data: any): void => {
data.correlationId.should.be.a.Number.and.equal(1);
done();
});
});
});
it('should receive correlation ids with subscribed event',
(done: Function): void => {
var subscriptions = [
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 2, fields: ['P'] }
];
socket.emit('subscribe', subscriptions);
socket.on('subscribed', (correlationIds: number[]): void => {
correlationIds.sort().should.be.an.Array.and.eql([0, 1, 2]);
done();
});
});
});
describe('#unsubscribe', (): void => {
it('should error if no active subscription found', (done: Function): void => {
socket.emit('unsubscribe');
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('No active subscriptions');
done();
});
});
it('should unsubscribe all if body is empty', (done: Function): void => {
var subscriptions = [
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
];
socket.emit('subscribe', subscriptions);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe');
});
socket.on('unsubscribed', (correlationIds: number[]): void => {
correlationIds.sort().should.be.an.Array.and.eql([0, 1]);
done();
});
});
it('should error if unsubscribe data object is invalid', (done: Function): void => {
var counter: number = 0;
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe', {});
socket.emit('unsubscribe', { foo: 'bar' });
socket.emit('unsubscribe', { correlationIds: 'bar' });
socket.emit('unsubscribe', { correlationIds: [] });
});
socket.on('err', (err: Error): void => {
err.message.should.be.a.String
.and.equal('Invalid unsubscribe data received.');
if (++counter === 4) {
done();
}
});
});
it('should error if correlation id is incorrect', (done: Function): void => {
var counter: number = 0;
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe', { correlationIds: [2] });
socket.emit('unsubscribe', { correlationIds: [1, 2] });
});
socket.on('err', (err: Error): void => {
if (++counter === 2) {
done();
}
});
});
it('should unsubscribe all if all correlationIds', (done: Function): void => {
var subscriptions = [
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
];
socket.emit('subscribe', subscriptions);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe', { correlationIds: [0, 1] });
});
socket.on('unsubscribed', (correlationIds: number[]): void => {
correlationIds.should.be.an.Array.and.eql([0, 1]);
done();
});
});
it('should unsubscribe part if one correlationIds', (done: Function): void => {
var cids: number[] = [];
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
cids.push(subscriptions[0].correlation);
cids.push(subscriptions[1].correlation);
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe', { correlationIds: [0] });
});
socket.on('unsubscribed', (): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents', cids[1]));
});
socket.on('data', (data: any): void => {
data.correlationId.should.be.a.Number.and.equal(1);
if (++counter === 1) {
done();
}
});
});
it('should send 3 data then unsubscribe', (done: Function): void => {
var counter: number = 0;
ipc.once('wait-to-subscribe', (subscriptions: any): void => {
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
ipc.emit(util.format('subscription-%d-MarketDataEvents',
subscriptions[0].correlation));
});
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] }
]
);
socket.on('data', (data: any): void => {
if (++counter === 3) {
socket.emit('unsubscribe');
}
});
socket.on('unsubscribed', (correlationIds: number[]): void => {
correlationIds.should.be.an.Array.and.eql([0]);
socket.disconnect();
});
socket.on('disconnect', (): void => {
done();
});
});
it('should receive correlation ids with unsubscribed event',
(done: Function): void => {
var subscriptions = [
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 2, fields: ['P'] }
];
socket.emit('subscribe', subscriptions);
socket.on('subscribed', (): void => {
socket.emit('unsubscribe');
});
socket.on('unsubscribed', (correlationIds: number[]): void => {
correlationIds.sort().should.be.an.Array.and.eql([0, 1, 2]);
done();
});
});
});
describe('#session terminated', (): void => {
it('should disconnect existing connections', (done: Function): void => {
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
ipc.emit('terminate-session');
});
socket.on('disconnect', (): void => {
done();
});
});
it('should disconnect then reconnect', (done: Function): void => {
socket.emit('subscribe',
[
{ security: '//blp/mktdata', correlationId: 0, fields: ['P'] },
{ security: '//blp/mktdata', correlationId: 1, fields: ['P'] }
]
);
socket.on('subscribed', (): void => {
ipc.emit('terminate-session');
});
socket.on('disconnect', (): void => {
socket = io.connect(url, opt);
socket.on('connect', (): void => {
done();
});
});
});
});
});
});
}); | the_stack |
export { EUInformation } from "node-opcua-types";
/*jslint bitwise: true */
// tslint:disable:no-bitwise
// EngineeringUnit
// Units of measurement for AnalogItems that represent continuously- variable physical quantities ( e.g.,
// length, mass , time, temperature )
// NOTE This standard defines Properties to inform about the unit used for the DataI tem value and
// about the highest and lowest value likely to be obtained in normal operation
import { EUInformation } from "node-opcua-types";
const defaultUri = "http://www.opcfoundation.org/UA/units/un/cefact";
const schemaEUInformation = EUInformation.schema;
schemaEUInformation.fields[0].defaultValue = defaultUri;
schemaEUInformation.fields[0].documentation =
"Identifies the organization (company, standards organization) that defines the EUInformation.";
schemaEUInformation.fields[1].documentation = "Identifier for programmatic evaluation. −1 is used if a unitId is not available.";
schemaEUInformation.fields[2].documentation = "The displayName of the engineering ( for instance 'm/s' )";
schemaEUInformation.fields[3].documentation = "Contains the full name of the engineering unit such as ”hour” or ”meter per second";
// The displayName of the engineering unit is typically the abbreviation of the
// engineering unit, for example ”h” for hour or ”m/s” for meter per second." +
// "description LocalizedText Contains the full name of the engineering unit such as ”hour” or ”meter
// http://www.unece.org/fileadmin/DAM/cefact/recommendations/rec20/rec20_rev3_Annex2e.pdf
// To facilitate interoperability, OPC UA specifies how to apply the widely accepted "Codes for Units of Measurement
// (Recommendation N°. 20)” published by the "United Nations Centre for Trade
// Facilitation and Electronic Business” (see UN/CEFACT). It uses and is based on the International System of Units
// (SI Units) but in addition provides a fixed code that can be used for automated evaluation. This recommendation
// has been accepted by many industries on a global basis.
//
// Following is a small excerpt of the published Annex with Code Lists:
// Excerpt from Recommendation N°. 20, Annex 1
// Common Code Name Conversion Factor Symbol
// C81 radian rad
// C25 milliradian 1E-3 rad mrad
// MMT millimetre 1E−3 m mm
// HMT hectometre 1E2 m hm
// KTM kilometre 1E3 m km
// KMQ kilogram per cubic metre kg/m3 kg/m3
// FAH degree Fahrenheit 5/9 x K °F
// J23 degree Fahrenheit per hour 1,543 210 x 10− 4 K/s °F/h
// SEC second [unit of time]
// C26 millisecond 1E-3 S
// B98 microsecond 1E-6 S
// Specific columns of this table shall be used to create the EUInformation structure as defined by the following rules:
//
// The Common Code is represented as an alphanumeric variable length of 3 characters. It shall be used for the
// EUInformation.unitId. The following pseudo code specifies the algorithm
// to convert the Common Code into an Int32 as needed for EUInformation.unitId:
export function commonCodeToUInt(code: string): number {
// CEL =>
let unitId = 0;
let c;
const m = Math.min(4, code.length);
for (let i = 0; i < m; i++) {
c = code.charCodeAt(i);
/* istanbul ignore if*/
if (c === 0) {
return unitId;
}
unitId *= 256;
unitId |= c;
}
return unitId;
}
export function makeEUInformation(symbol: string, shortName: string, longName: string): EUInformation {
return new EUInformation({
description: { text: longName },
displayName: { text: shortName },
unitId: commonCodeToUInt(symbol)
});
}
export interface StandardUnits {
ampere: EUInformation;
bar: EUInformation;
becquerel: EUInformation;
byte: EUInformation;
centimetre: EUInformation;
cubic_centimetre: EUInformation;
cubic_centimetre_per_second: EUInformation;
cubic_metre: EUInformation;
cubic_metre_per_hour: EUInformation;
cubic_meter_per_minute: EUInformation;
curie: EUInformation;
curie_per_kilogram: EUInformation;
degree: EUInformation;
degree_celsius: EUInformation;
degree_fahrenheit: EUInformation;
dots_per_inch: EUInformation;
electron_volt: EUInformation;
farad: EUInformation;
gigabecquerel: EUInformation;
gigabyte: EUInformation;
gram: EUInformation;
hectopascal: EUInformation;
hertz: EUInformation;
joule: EUInformation;
kelvin: EUInformation;
kilo_electron_volt: EUInformation;
kilobecquerel: EUInformation;
kilobyte: EUInformation;
kilohertz: EUInformation;
kilogram: EUInformation;
kilogram_force: EUInformation;
kilogram_per_second: EUInformation;
kilogram_per_squared_centimeter: EUInformation;
kilometre_per_hour: EUInformation;
kilopascal: EUInformation;
kilowatt: EUInformation;
mega_electron_volt: EUInformation;
megabyte: EUInformation;
megahertz: EUInformation;
megapascal: EUInformation;
megawatt: EUInformation;
megawatt_per_minute: EUInformation;
metre: EUInformation;
metre_per_second: EUInformation;
metre_per_second_squared: EUInformation;
microsecond: EUInformation;
mile_per_hour: EUInformation;
millibar: EUInformation;
millimetre: EUInformation;
millipascal: EUInformation;
millisecond: EUInformation;
minute: EUInformation;
minute_angle: EUInformation;
newton: EUInformation;
pascal: EUInformation;
part_per_million: EUInformation;
percent: EUInformation;
pixel: EUInformation;
revolutions_per_minute: EUInformation;
revolutions_per_second: EUInformation;
second: EUInformation;
terabyte: EUInformation;
volt: EUInformation;
watt: EUInformation;
}
// http://www.unece.org/fileadmin/DAM/cefact/recommendations/rec20/rec20_rev3_Annex2e.pdf
export const standardUnits: StandardUnits = {
// pressure
bar: makeEUInformation("BAR", "bar", "bar [unit of pressure] = 1E5 Pa"),
hectopascal: makeEUInformation("A97", "hPa", "hectopascal [unit of pressure] = 1E2 Pa"),
millibar: makeEUInformation("MBR", "mbar", "millibar [unit of pressure] = 1E2 Pa"),
pascal: makeEUInformation("PAL", "Pa", "pascal [unit of pressure]"),
kilogram_per_squared_centimeter: makeEUInformation("D5", "kg/cm²", "kilogram per square centimetre"),
megapascal: makeEUInformation("MPA", "MPa", "1 megapascal = 10⁶ pascal [unit of pressure]"),
// time/duration
microsecond: makeEUInformation("B98", "μs", "microsecond =1E-6 second"),
millisecond: makeEUInformation("C26", "ms", "millisecond =1E-3 second"),
second: makeEUInformation("SEC", "s", "second"),
// distance
centimetre: makeEUInformation("CMT", "cm", "centimetre = 1E-2 m"),
metre: makeEUInformation("MTR", "m", "metre"),
millimetre: makeEUInformation("MMT", "mm", "millimetre = 1E-3 metre"),
// volume
cubic_centimetre: makeEUInformation("CMQ", "cm³", "Cubic centimetre = 1E-6 m³"),
cubic_metre: makeEUInformation("MTQ", "m³", "Cubic metre"),
// temperature
degree_celsius: makeEUInformation("CEL", "°C", "degree Celsius"),
degree_fahrenheit: makeEUInformation("FAH", "°F", "degree Fahrenheit 9/5(°C) + 32°"),
kelvin: makeEUInformation("KEL", "K", "degree Kelvin"),
// weight
gram: makeEUInformation("GRM", "g", "gramme 1E-3 kg"),
kilogram: makeEUInformation("KGM", "kg", "A unit of mass equal to one thousand grams"),
// speed
metre_per_second: makeEUInformation("MTS", "m/s", "meter per second"),
mile_per_hour: makeEUInformation("HM", "mile/h", "mile per hour = 2 0,447 04 m/s"),
kilometre_per_hour: makeEUInformation("KMH", "km/h", "kilometre per hour = 0,277 778 m/s"),
// acceleration
metre_per_second_squared: makeEUInformation("MSK", "m/s²", "meter per second square"),
// frequency
kilohertz: makeEUInformation("KHZ", "kHz", "kilo hertz = 1E3 Hertz"),
hertz: makeEUInformation("HTZ", "Hz", "Hertz"),
megahertz: makeEUInformation("MHZ", "MHz", "megahertz"),
revolutions_per_minute: makeEUInformation("RPM", "r/min", "revolutions per minute 1,047198 rad/(60 x s)"),
revolutions_per_second: makeEUInformation("RPS", "r/s", "revolutions per minute 1,047198 rad/s"),
// force
newton: makeEUInformation("NEW", "N", "Newton (kg x m)/s² "),
kilogram_force: makeEUInformation("B37", "kgf", "kilogram-force 1 kgf = 9.80665 N"),
// power
kilowatt: makeEUInformation("KWT", "kW", "kilowatt 1kW = 10³ W"),
megawatt: makeEUInformation("MAW", "MW", "Mega Watt"),
watt: makeEUInformation("WTT", "W", "Watt"),
// rate of flow
cubic_centimetre_per_second: makeEUInformation("2J", "cm³/s", "Cubic centimetre per second"),
cubic_metre_per_hour: makeEUInformation("MQH", "m³/h", "Cubic metre per hours = 2,777 78 x 10⁻⁴ m³/s"),
cubic_meter_per_minute: makeEUInformation("G53", "m³/min", "m³/min cubic metre per minute"),
// angle
degree: makeEUInformation("DD", "°", "degree [unit of angle]"),
//
ampere: makeEUInformation("AMP", "A", "ampere"),
becquerel: makeEUInformation("BQL", "Bq", "becquerel = 27,027E-12 Ci"),
curie: makeEUInformation("CUR", "Ci", "Curie = 3,7E-10 Bq"),
curie_per_kilogram: makeEUInformation("A42", "Ci/kg", "Curie per kilogram = 3,7E-10 Bq/kg"),
dots_per_inch: makeEUInformation("E39", "dpi", "dot per inch"),
electron_volt: makeEUInformation("A53", "eV", "electron volt"),
farad: makeEUInformation("FAR", "F", "Farad = kg⁻¹ x m⁻² x s⁴ x A²"),
gigabecquerel: makeEUInformation("GBQ", "GBq", "Giga becquerel = 1E9 Bq"),
joule: makeEUInformation("JOU", "J", "Joule"),
kilo_electron_volt: makeEUInformation("B29", "keV", "kilo electron volt"),
kilogram_per_second: makeEUInformation("KGS", "kg/s", "kilogram per second"),
kilopascal: makeEUInformation("KPA", "kPa", "1 kilopascal = 10³ Pa"),
millipascal: makeEUInformation("74", "mPa", "1 millipascal = 10⁻³ Pa"),
kilobecquerel: makeEUInformation("2Q", "kBq", "kilo becquerel = 1E3 Bq"),
mega_electron_volt: makeEUInformation("B71", "MeV", "mega electron volt"),
megawatt_per_minute: makeEUInformation(
"Q35",
"MW/min",
"A unit of power defining the total amount of bulk energy transferred or consumer per minute."
),
percent: makeEUInformation("P1", "%", "Percent, a unit of proportion equal to 0.01. "),
pixel: makeEUInformation("E37", "", "pixel: unit of count defining the number of pixels (pixel: picture element)"),
volt: makeEUInformation("VLT", "V", "Volt"),
byte: makeEUInformation("AD", "byte", "byte = A unit of information equal to 8 bits."),
kilobyte: makeEUInformation("2P", "kbyte", "kilobyte = A unit of information equal to 10³ (1000) bytes."),
megabyte: makeEUInformation("4L", "Mbyte", "megabyte = A unit of information equal to 10⁶ (1000000) bytes."),
gigabyte: makeEUInformation("E34", "Gbyte", "gigabyte = A unit of information equal to 10⁹ bytes."),
terabyte: makeEUInformation("E35", "Tbyte", "terabyte = A unit of information equal to 10¹² bytes."),
minute: makeEUInformation("MIN", "min", " minute (unit of time) 1min = 60 s"),
minute_angle: makeEUInformation("D61", "'", "minute [unit of angle]"),
part_per_million: makeEUInformation("59", "ppm", "A unit of proportion equal to 10⁻⁶.")
// to be continued
}; | the_stack |
import { expect } from 'chai';
import { CodeEditor } from "@jupyterlab/codeeditor";
import { CodeMirrorEditor } from '@jupyterlab/codemirror';
import { CodeMirrorTokensProvider } from "../editors/codemirror/tokens";
import { QueryFunction, RuleFunction, TokenContext } from "./analyzer";
import { PythonAnalyzer } from './python';
import { Jumper, matchToken } from "../testutils";
import IToken = CodeEditor.IToken;
describe('PythonAnalyzer', () => {
let analyzer: PythonAnalyzer;
let editor: CodeMirrorEditor;
let tokensProvider: CodeMirrorTokensProvider;
let model: CodeEditor.Model;
let host: HTMLElement;
function runWithSelectedToken(method: RuleFunction, tokenName: string, tokenOccurrence = 1, tokenType = 'variable') {
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, tokenName, tokenOccurrence, tokenType);
let tokenId = tokens.indexOf(token);
analyzer.tokens = tokens;
return method.bind(analyzer)(new TokenContext(token, tokens, tokenId));
}
function queryWithSelectedToken(method: QueryFunction, tokenName: string, tokenOccurrence = 1, tokenType = 'variable') {
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, tokenName, tokenOccurrence, tokenType);
let tokenId = tokens.indexOf(token);
analyzer.tokens = tokens;
return method.bind(analyzer)(new TokenContext(token, tokens, tokenId));
}
beforeEach(() => {
host = document.createElement('div');
document.body.appendChild(host);
model = new CodeEditor.Model({mimeType: 'text/x-python'});
editor = new CodeMirrorEditor({host, model, config: {mode: 'python'}});
tokensProvider = new CodeMirrorTokensProvider(editor);
analyzer = new PythonAnalyzer(tokensProvider);
});
afterEach(() => {
editor.dispose();
document.body.removeChild(host);
});
describe('#isStandaloneAssignment()', () => {
it('should recognize assignments', () => {
model.value.text = 'x = 1';
expect(runWithSelectedToken(analyzer.isStandaloneAssignment, 'x')).to.be.true;
});
it('should recognize transitive assignments', () => {
model.value.text = 'x = y = 1';
expect(runWithSelectedToken(analyzer.isStandaloneAssignment, 'x')).to.be.true;
expect(runWithSelectedToken(analyzer.isStandaloneAssignment, 'y')).to.be.true;
});
it('should ignore increments', () => {
model.value.text = 'x += 1';
expect(runWithSelectedToken(analyzer.isStandaloneAssignment, 'x')).to.be.false;
});
});
// TODO: output of R cell magic (%%R), which usually comes along many other parameters:
// %%R -o x # simple case
// %%R -i y -o x -w 800 # case with other parameters
// should this be handled by R or Python analyzer?
// in broader terms, should the variables scopes be separated between languages?
describe('#isRMagicOutput()', () => {
it('should simple line magic export from R', () => {
model.value.text = '%R -o x';
expect(runWithSelectedToken(analyzer.isRMagicOutput, 'x')).to.be.true;
model.value.text = '%R -o x x = 1';
expect(runWithSelectedToken(analyzer.isRMagicOutput, 'x')).to.be.true;
expect(runWithSelectedToken(analyzer.isRMagicOutput, 'x', 2)).to.be.false;
});
});
describe('#isStoreMagic()', () => {
it('should recognize IPython %store -r magic function', () => {
model.value.text = '%store -r x';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.true;
model.value.text = '%store -r x y';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.true;
expect(runWithSelectedToken(analyzer.isStoreMagic, 'y')).to.be.true;
model.value.text = '%store -r r store';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'r', 1)).to.be.false;
expect(runWithSelectedToken(analyzer.isStoreMagic, 'store', 1)).to.be.false;
expect(runWithSelectedToken(analyzer.isStoreMagic, 'r', 2)).to.be.true;
expect(runWithSelectedToken(analyzer.isStoreMagic, 'store', 2)).to.be.true;
});
it('should ignore other look-alikes', () => {
model.value.text = '%store x';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.false;
model.value.text = '%store -r xx';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.false;
model.value.text = 'store -r x';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.false;
model.value.text = '# %store -r x';
expect(runWithSelectedToken(analyzer.isStoreMagic, 'x')).to.be.false;
});
});
describe('#isTupleUnpacking', () => {
it('should recognize simple tuples', () => {
model.value.text = 'a, b = 1, 2';
expect(runWithSelectedToken(analyzer.isTupleUnpacking, 'a')).to.be.true;
expect(runWithSelectedToken(analyzer.isTupleUnpacking, 'b')).to.be.true;
});
it('should handle brackets', () => {
const cases = [
'x, (y, z) = a, [b, c]',
'x, (y, z) = a, (b, c)',
'(x, y), z = (a, b), c',
'(x, y), z = [a, b], c',
];
for (let testCase of cases) {
model.value.text = testCase;
for (let definition of ['x', 'y', 'z']) {
expect(runWithSelectedToken(analyzer.isTupleUnpacking, definition)).to.be.true;
}
for (let usage of ['a', 'b', 'c']) {
expect(runWithSelectedToken(analyzer.isTupleUnpacking, usage)).to.be.false;
}
}
});
it('should not be mistaken with a simple function call', () => {
model.value.text = 'x = y(a, b, c=1)';
for (let notATupleMember of ['a', 'b', 'c', 'y']) {
expect(runWithSelectedToken(analyzer.isTupleUnpacking, notATupleMember)).to.be.false;
}
// this is a very trivial tuple with just one member
expect(runWithSelectedToken(analyzer.isTupleUnpacking, 'x')).to.be.true;
});
it('should not be mistaken with a complex function call', () => {
model.value.text = 'x = y(a, b, c=(1, 2), d=[(1, 3)], e={})';
for (let notATupleMember of ['a', 'b', 'c', 'd', 'e', 'y']) {
expect(runWithSelectedToken(analyzer.isTupleUnpacking, notATupleMember)).to.be.false;
}
// see above
expect(runWithSelectedToken(analyzer.isTupleUnpacking, 'x')).to.be.true;
});
});
describe('#isForLoopOrComprehension', () => {
it('should recognize variables declared inside of loops', () => {
model.value.text = 'for x in range(10): pass';
expect(runWithSelectedToken(analyzer.isForLoopOrComprehension, 'x')).to.be.true;
});
it('should recognize list and set comprehensions', () => {
// list
model.value.text = '[x for x in range(10)]';
expect(runWithSelectedToken(analyzer.isForLoopOrComprehension, 'x', 2)).to.be.true;
// with new lines
model.value.text = '[\nx\nfor x in range(10)\n]';
expect(runWithSelectedToken(analyzer.isForLoopOrComprehension, 'x', 2)).to.be.true;
// set
model.value.text = '{x for x in range(10)}';
expect(runWithSelectedToken(analyzer.isForLoopOrComprehension, 'x', 2)).to.be.true;
});
});
describe('#isCrossFileReference', () => {
it('should handle "from y import x" upon clicking on "y"', () => {
model.value.text = 'from y import x';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'y')).to.be.true;
// this will be handled separately as it requires opening cross-referenced file AND jumping to a position in it
model.value.text = 'from y import x';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'x')).to.be.false;
expect(queryWithSelectedToken(analyzer.guessReferencePath, 'y')).to.eql(['y.py', 'y/__init__.py']);
});
it('should handle "import y" upon clicking on "y"', () => {
model.value.text = 'import y';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'y')).to.be.true;
});
it('should handle "from a.b import c" when clicking on "b" (open a/b.py) or "a" (open a/__init__.py)', () => {
model.value.text = 'from a.b import c';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'a')).to.be.true;
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'b', 1, 'property')).to.be.true;
expect(queryWithSelectedToken(analyzer.guessReferencePath, 'b', 1, 'property')).to.eql(
['a/b.py', 'a/b/__init__.py']
);
});
it('should handle import all, relatives and underscores', () => {
model.value.text = 'a_b = 1; from .a_b import *';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'a_b', 1, 'property')).to.be.true;
expect(queryWithSelectedToken(analyzer.guessReferencePath, 'a_b', 1, 'property')).to.eql(
['a_b.py', 'a_b/__init__.py']
);
});
it('should handle "import a.b" upon clicking on "a" or "b"', () => {
model.value.text = 'import a.b';
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'a')).to.be.true;
expect(runWithSelectedToken(analyzer.isCrossFileReference, 'b')).to.be.true;
expect(queryWithSelectedToken(analyzer.guessReferencePath, 'a')).to.eql(
['a.py', 'a/__init__.py']
);
expect(queryWithSelectedToken(analyzer.guessReferencePath, 'b', 1, 'property')).to.eql(
['a/b.py', 'a/b/__init__.py']
);
});
// TODO:
// from . import b
// %run helpers/notebook_setup.ipynb
// %R source('a.R') # line magic of R in Python
})
});
describe('Jumper with PythonAnalyzer', () => {
let editor: CodeMirrorEditor;
let tokensProvider: CodeMirrorTokensProvider;
let model: CodeEditor.Model;
let host: HTMLElement;
let jumper: Jumper;
beforeEach(() => {
host = document.createElement('div');
document.body.appendChild(host);
model = new CodeEditor.Model({mimeType: 'text/x-python'});
editor = new CodeMirrorEditor({host, model, config: {mode: 'python'}});
tokensProvider = new CodeMirrorTokensProvider(editor);
jumper = new Jumper(editor);
});
afterEach(() => {
editor.dispose();
document.body.removeChild(host);
});
function test_jump(token: IToken, first_position: CodeEditor.IPosition, second_position: CodeEditor.IPosition) {
editor.setCursorPosition(first_position);
expect(editor.getCursorPosition()).to.deep.equal(first_position);
expect(editor.getTokenForPosition(first_position)).to.deep.equal(token);
jumper.jump_to_definition({token: token, origin: null, mouseEvent: null});
expect(editor.getCursorPosition()).to.deep.equal(second_position);
}
describe('Jumper', () => {
it('should handle simple jumps', () => {
model.value.text = 'a = 1\nx = a';
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, 'a', 2);
let firstAPosition = {line: 0, column: 0};
let secondAPosition = {line: 1, column: 5};
test_jump(token, secondAPosition, firstAPosition);
});
it('handles variable usage inside definitions overriding the same variable', () => {
model.value.text = 'a = 1\na = a + 1';
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, 'a', 3);
let firstAPosition = {line: 0, column: 0};
let thirdAPosition = {line: 1, column: 5};
test_jump(token, thirdAPosition, firstAPosition);
});
it('should work in functions', () => {
model.value.text = `def x():
a = 1
x = a
a = 2`;
// note: the 'a = 2' was good enough to confuse script in previous version
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, 'a', 2);
let firstAPosition = {line: 1, column: 4};
let secondAPosition = {line: 2, column: 4 + 5};
test_jump(token, secondAPosition, firstAPosition);
});
it('should recognize namespaces', () => {
model.value.text = `def x():
a = 1
x = a
a = 2
y = a`;
let tokens = tokensProvider.getTokens();
let token = matchToken(tokens, 'a', 4);
let thirdAPosition = {line: 4, column: 0};
let fourthAPosition = {line: 5, column: 5};
test_jump(token, fourthAPosition, thirdAPosition);
});
});
}); | the_stack |
import { DualAxes } from '../../../../src';
import { PV_DATA, UV_DATA, PV_DATA_MULTI, UV_DATA_MULTI } from '../../../data/pv-uv';
import { createDiv } from '../../../utils/dom';
import { LEFT_AXES_VIEW, RIGHT_AXES_VIEW } from '../../../../src/plots/dual-axes/constant';
describe('Legend', () => {
it('Legend: single line and column', () => {
const options = {
width: 400,
height: 500,
data: [PV_DATA, UV_DATA],
xField: 'date',
yField: ['pv', 'uv'],
geometryOptions: [
{
geometry: 'line',
color: '#f00',
},
{
geometry: 'line',
color: '#0f0',
},
],
};
const dualAxes = new DualAxes(createDiv('Legend: single line and column'), options);
dualAxes.render();
const dualLineLegendComponentCfg = dualAxes.chart.getController('legend').getComponents()[0].component.cfg;
expect(dualLineLegendComponentCfg.items.length).toBe(2);
expect(dualLineLegendComponentCfg.items[0].name).toBe('pv');
expect(typeof dualLineLegendComponentCfg.items[0].marker.symbol).toBe('function');
expect(dualLineLegendComponentCfg.items[0].marker.style.stroke).toBe('#f00');
expect(dualLineLegendComponentCfg.items[1].name).toBe('uv');
expect(typeof dualLineLegendComponentCfg.items[1].marker.symbol).toBe('function');
expect(dualLineLegendComponentCfg.items[1].marker.style.stroke).toBe('#0f0');
dualAxes.update({
...options,
geometryOptions: [
{
geometry: 'column',
color: '#f00',
},
{
geometry: 'line',
color: '#0f0',
},
],
legend: {
itemName: {
formatter: (value) => `_${value}`,
},
},
});
const columnLineLegendComponentCfg = dualAxes.chart.getController('legend').getComponents()[0].component.cfg;
expect(columnLineLegendComponentCfg.items.length).toBe(2);
expect(columnLineLegendComponentCfg.items[0].name).toBe('pv');
expect(columnLineLegendComponentCfg.items[0].marker.symbol).toBe('square');
expect(columnLineLegendComponentCfg.items[0].marker.style.fill).toBe('#f00');
expect(columnLineLegendComponentCfg.items[1].name).toBe('uv');
expect(typeof columnLineLegendComponentCfg.items[1].marker.symbol).toBe('function');
expect(columnLineLegendComponentCfg.items[1].marker.style.stroke).toBe('#0f0');
dualAxes.update({
...dualAxes.options,
legend: false,
});
// 隐藏就没有图例了
expect(dualAxes.chart.views[0].getComponents().find((co) => co.type === 'legend')).toBeUndefined();
expect(dualAxes.chart.views[1].getComponents().find((co) => co.type === 'legend')).toBeUndefined();
expect(dualAxes.chart.getEvents().beforepaint).toBeUndefined();
dualAxes.destroy();
});
it('Legend: multi line and column', () => {
const options = {
width: 400,
height: 500,
data: [PV_DATA_MULTI, UV_DATA_MULTI],
xField: 'date',
yField: ['pv', 'uv'],
geometryOptions: [
{
geometry: 'line',
seriesField: 'site',
color: ['#f00', '#f11', '#f22'],
},
{
geometry: 'line',
seriesField: 'site',
color: ['#0f0', '#1f1', '#2f2'],
},
],
};
// 双折线
const dualAxes = new DualAxes(createDiv('Legend: multi line and column'), options);
dualAxes.render();
const dualLineLegendComponentCfg = dualAxes.chart.getController('legend').getComponents()[0].component.cfg;
expect(dualLineLegendComponentCfg.items.length).toBe(5);
expect(dualLineLegendComponentCfg.items[0].name).toBe('a');
expect(typeof dualLineLegendComponentCfg.items[0].marker.symbol).toBe('function');
expect(dualLineLegendComponentCfg.items[0].marker.style.stroke).toBe('#f00');
expect(dualLineLegendComponentCfg.items[2].name).toBe('a');
expect(typeof dualLineLegendComponentCfg.items[2].marker.symbol).toBe('function');
expect(dualLineLegendComponentCfg.items[2].marker.style.stroke).toBe('#0f0');
dualAxes.update({
...options,
geometryOptions: [
{
geometry: 'line',
seriesField: 'site',
color: ['#f00', '#f11', '#f22'],
},
{
geometry: 'column',
seriesField: 'site',
isGroup: true,
color: ['#0f0', '#1f1', '#2f2'],
},
],
});
const columnLineLegendComponentCfg = dualAxes.chart.getController('legend').getComponents()[0].component.cfg;
expect(columnLineLegendComponentCfg.items.length).toBe(5);
expect(columnLineLegendComponentCfg.items[0].name).toBe('a');
expect(typeof columnLineLegendComponentCfg.items[0].marker.symbol).toBe('function');
expect(columnLineLegendComponentCfg.items[0].marker.style.stroke).toBe('#f00');
expect(columnLineLegendComponentCfg.items[2].name).toBe('a');
expect(columnLineLegendComponentCfg.items[2].marker.symbol).toBe('square');
expect(columnLineLegendComponentCfg.items[2].marker.style.fill).toBe('#0f0');
dualAxes.destroy();
});
it('Legend with click', () => {
const dualAxes = new DualAxes(createDiv('test DualAxes doubal line', undefined, 'click_legend'), {
width: 400,
height: 500,
data: [PV_DATA, UV_DATA_MULTI],
xField: 'date',
yField: ['pv', 'uv'],
meta: {
pv: {
alias: '页面访问量',
},
},
geometryOptions: [
{
geometry: 'line',
color: '#f00',
},
{
geometry: 'line',
seriesField: 'site',
color: ['#5B8FF9', '#5AD8A6', '#5D7092'],
},
],
legend: {
itemName: {
formatter: (val) => `${val}_test`,
},
},
});
dualAxes.render();
const legendController = dualAxes.chart.getController('legend');
const legendComponent = legendController.getComponents()[0];
const legendContainer = legendComponent.component.get('container');
const cfgItems = legendComponent.component.cfg.items;
expect(cfgItems.length).toBe(4);
expect(cfgItems[0].name).toBe('页面访问量');
expect(cfgItems[1].name).toBe('a');
expect(cfgItems[2].name).toBe('b');
expect(cfgItems[3].name).toBe('c');
dualAxes.chart.once('afterrender', () => {
// 点击页面访问量,期望单折线图 visible 隐藏, 图例 unchecked 为 true
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-页面访问量-name'),
gEvent: {
delegateObject: {
item: {
id: '页面访问量',
value: 'pv',
isGeometry: true,
viewId: LEFT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[0].geometries[0].visible).toEqual(false);
expect(cfgItems.find((item) => item.id === '页面访问量').unchecked).toEqual(true);
// 点击分类数据 A,期望多折线图 view 过滤掉数据 a
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-a-name'),
gEvent: {
delegateObject: {
item: {
id: 'a',
name: 'a',
value: 'a',
viewId: RIGHT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'a').length === 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'a').unchecked).toEqual(true);
// 点击分类数据 B,期望多折线图 view 过滤掉数据 b
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-b-name'),
gEvent: {
delegateObject: {
item: {
id: 'b',
name: 'b',
value: 'b',
viewId: RIGHT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'b').length === 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'b').unchecked).toEqual(true);
// 点击分类数据 C,期望多折线图 view 过滤掉数据 c, yaxis 右侧仅留 0 一个刻度
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-c-name'),
gEvent: {
delegateObject: {
item: {
id: 'c',
name: 'c',
value: 'c',
viewId: RIGHT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'c').length === 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'c').unchecked).toEqual(true);
expect(dualAxes.chart.views[1].getController('axis').getComponents()[0].component.cfg.ticks.length).toBe(1);
// 再次点击页面访问量,期望单折线图 visible 出现, 图例 unchecked 为 false
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-页面访问量-name'),
gEvent: {
delegateObject: {
item: {
id: '页面访问量',
value: 'pv',
isGeometry: true,
viewId: LEFT_AXES_VIEW,
unchecked: false,
},
},
},
});
expect(dualAxes.chart.views[0].geometries[0].visible).toEqual(true);
expect(cfgItems.find((item) => item.id === '页面访问量').unchecked).toEqual(false);
expect(dualAxes.chart.views[1].getController('axis').getComponents()[0].component.cfg.ticks.length).toBe(1);
// 再次点击分类数据 A,期望多折线图 view 重新包含数据 a,右轴出现多个刻度
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-a-name'),
gEvent: {
delegateObject: {
item: {
id: 'a',
name: 'a',
value: 'a',
viewId: RIGHT_AXES_VIEW,
unchecked: false,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'a').length > 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'a').unchecked).toEqual(false);
expect(
dualAxes.chart.views[1].getController('axis').getComponents()[0].component.cfg.ticks.length > 1
).toBeTruthy();
// 再次点击分类数据 B,期望多折线图 view 重新包含数据 B
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-b-name'),
gEvent: {
delegateObject: {
item: {
id: 'b',
name: 'b',
value: 'b',
viewId: RIGHT_AXES_VIEW,
unchecked: false,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'b').length > 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'b').unchecked).toEqual(false);
// 再次点击分类数据 C,期望多折线图 view 重新包含数据 C
dualAxes.chart.emit('legend-item:click', {
target: legendContainer.findById('-legend-item-c-name'),
gEvent: {
delegateObject: {
item: {
id: 'c',
name: 'c',
value: 'c',
viewId: RIGHT_AXES_VIEW,
unchecked: false,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'c').length > 0).toEqual(true);
expect(cfgItems.find((item) => item.id === 'c').unchecked).toEqual(false);
// 提高if else 覆盖率,事件为空,不受影响
dualAxes.chart.emit('legend-item:click', {});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'a').length > 0).toEqual(true);
// 提高if else 覆盖率,传入一个 id 错误的 item,不受影响
dualAxes.chart.emit('legend-item:click', {
gEvent: {
delegateObject: {
item: {
id: 'test',
name: 'test',
value: 'test',
isGeometry: true,
viewId: LEFT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[0].geometries[0].visible).toEqual(true);
// 提高if else 覆盖率,传入一个 id 错误的 item,不受影响
dualAxes.chart.emit('legend-item:click', {
gEvent: {
delegateObject: {
item: {
id: 'test',
name: 'test',
value: 'test',
viewId: RIGHT_AXES_VIEW,
unchecked: true,
},
},
},
});
expect(dualAxes.chart.views[1].geometries[0].data.filter((item) => item.site === 'a').length > 0).toEqual(true);
dualAxes.destroy();
});
});
it('Legend custom', () => {
const dualAxes = new DualAxes(createDiv('Legend custom '), {
width: 400,
height: 500,
data: [PV_DATA, UV_DATA],
xField: 'date',
yField: ['pv', 'uv'],
legend: {
marker: {
symbol: 'diamond',
},
},
});
dualAxes.render();
const legendController = dualAxes.chart.getController('legend');
const legendComponent = legendController.getComponents()[0];
const cfg = legendComponent.component.cfg;
expect(cfg.items[0].marker.symbol).toBe('diamond');
expect(cfg.items[1].marker.symbol).toBe('diamond');
expect(cfg.items[0].marker.style.fill).toBe('#5B8FF9');
expect(cfg.items[1].marker.style.fill).toBe('#5AD8A6');
dualAxes.destroy();
});
it('Legend custom', () => {
const dualAxes = new DualAxes(createDiv('Legend custom '), {
width: 400,
height: 500,
data: [PV_DATA, UV_DATA],
xField: 'date',
yField: ['pv', 'uv'],
legend: {
custom: true,
layout: 'vertical',
position: 'right',
items: [
{
value: 'test',
name: '测试1',
marker: { symbol: 'square', style: { fill: '#B4EBBF', r: 5 } },
},
{
value: 'test2',
name: '测试2',
marker: { symbol: 'square', style: { fill: '#FFB1AC', r: 5 } },
},
],
},
});
dualAxes.render();
const legendController = dualAxes.chart.getController('legend');
const legendComponent = legendController.getComponents()[0];
const cfg = legendComponent.component.cfg;
expect(cfg.items.length).toBe(2);
expect(cfg.items[0].name).toBe('测试1');
expect(cfg.items[0].marker.symbol).toBe('square');
expect(cfg.items[1].name).toBe('测试2');
expect(cfg.items[1].marker.symbol).toBe('square');
expect(legendComponent.direction).toEqual('right');
dualAxes.destroy();
});
});
describe('color callback', () => {
const uvBillData = [
{ time: '2019-03', value: 350, type: 'uv' },
{ time: '2019-04', value: 900, type: 'uv' },
{ time: '2019-05', value: 300, type: 'uv' },
{ time: '2019-06', value: 450, type: 'uv' },
{ time: '2019-07', value: 470, type: 'uv' },
{ time: '2019-03', value: 220, type: 'bill' },
{ time: '2019-04', value: 300, type: 'bill' },
{ time: '2019-05', value: 250, type: 'bill' },
{ time: '2019-06', value: 220, type: 'bill' },
{ time: '2019-07', value: 362, type: 'bill' },
];
const transformData = [
{ time: '2019-03', count: 800 },
{ time: '2019-04', count: 600 },
{ time: '2019-05', count: 400 },
{ time: '2019-06', count: 380 },
{ time: '2019-07', count: 220 },
];
const plot = new DualAxes(createDiv(), {
data: [uvBillData, transformData],
xField: 'time',
yField: ['value', 'count'],
geometryOptions: [
{
geometry: 'column',
isStack: true,
isPercent: true,
seriesField: 'type',
color: ({ type }) => (type === 'uv' ? 'red' : 'yellow'),
},
{
geometry: 'line',
color: () => 'green',
},
],
});
plot.render();
it('color callback apply to multi-column, and single line', () => {
const markers = plot.chart
.getController('legend')
// @ts-ignore
.components[0].component.get('container')
.findAllByName('legend-item-marker');
expect(markers[0].attr('fill')).toBe('red');
expect(markers[1].attr('fill')).toBe('yellow');
expect(markers[2].attr('stroke')).toBe('green');
});
it('color callback apply to multi-line', () => {
const transformData = [
{ time: '2019-03', count: 800, name: 'a' },
{ time: '2019-04', count: 600, name: 'a' },
{ time: '2019-05', count: 400, name: 'a' },
{ time: '2019-06', count: 380, name: 'a' },
{ time: '2019-07', count: 220, name: 'a' },
{ time: '2019-03', count: 750, name: 'b' },
{ time: '2019-04', count: 650, name: 'b' },
{ time: '2019-05', count: 450, name: 'b' },
{ time: '2019-06', count: 400, name: 'b' },
{ time: '2019-07', count: 320, name: 'b' },
{ time: '2019-03', count: 900, name: 'c' },
{ time: '2019-04', count: 600, name: 'c' },
{ time: '2019-05', count: 450, name: 'c' },
{ time: '2019-06', count: 300, name: 'c' },
{ time: '2019-07', count: 200, name: 'c' },
];
plot.update({
data: [uvBillData, transformData],
theme: {
defaultColor: '#FF6B3B',
},
geometryOptions: [
{
geometry: 'column',
isStack: true,
seriesField: 'type',
columnWidthRatio: 0.4,
},
{
geometry: 'line',
seriesField: 'name',
color: ({ name }) => (name === 'a' ? 'red' : undefined),
},
],
});
const markers = plot.chart
.getController('legend')
// @ts-ignore
.components[0].component.get('container')
.findAllByName('legend-item-marker');
expect(markers[2].attr('stroke')).toBe('red');
// default-color
expect(markers[3].attr('stroke')).toBe('#FF6B3B');
expect(markers[4].attr('stroke')).toBe('#FF6B3B');
});
afterAll(() => {
plot.destroy();
});
}); | the_stack |
import {
GraphQLEntityFields,
LoaderOptions,
QueryMeta,
QueryPagination,
QueueItem,
SearchOptions,
WhereExpression,
} from "./types";
import { LoaderSearchMethod } from "./enums/LoaderSearchMethod";
import * as crypto from "crypto";
import {
Brackets,
Connection,
EntityManager,
OrderByCondition,
SelectQueryBuilder,
} from "typeorm";
import { GraphQLQueryResolver } from "./GraphQLQueryResolver";
import { Formatter } from "./lib/Formatter";
import { LoaderNamingStrategyEnum } from "./enums/LoaderNamingStrategy";
/**
* The query manager for the loader. Is an internal class
* that should not be used by anything except the loader
* @hidden
*/
export class GraphQLQueryManager {
private _queue: QueueItem[] = [];
private _cache: Map<string, Promise<any>> = new Map();
private _immediate?: NodeJS.Immediate;
private readonly _defaultLoaderSearchMethod: LoaderSearchMethod;
private _resolver: GraphQLQueryResolver;
private _formatter: Formatter;
constructor(private _connection: Connection, options: LoaderOptions = {}) {
const { defaultSearchMethod } = options;
this._defaultLoaderSearchMethod =
defaultSearchMethod ?? LoaderSearchMethod.ANY_POSITION;
this._resolver = new GraphQLQueryResolver(options);
this._formatter = new Formatter(
options.namingStrategy ?? LoaderNamingStrategyEnum.CAMELCASE
);
}
/**
* Helper method to generate a TypeORM query builder
* @param entityManager
* @param name
* @param alias
*/
private static createTypeORMQueryBuilder(
entityManager: EntityManager,
name: string,
alias: string
): SelectQueryBuilder<{}> {
return entityManager
.getRepository<{}>(name)
.createQueryBuilder(alias)
.select([]);
}
/**
* Takes a condition and formats into a type that TypeORM can
* read
* @param where
* @private
*/
private static _breakDownWhereExpression(where: WhereExpression) {
if (where instanceof Brackets) {
return { where: where, params: undefined };
} else {
const asExpression = where;
return { where: asExpression.condition, params: asExpression.params };
}
}
/**
* Looks up a query in the cache and returns
* the existing promise if found.
* @param fields
* @param where
* @param alias
*/
public processQueryMeta(
fields: GraphQLEntityFields | null,
where: Array<WhereExpression>,
alias: string
): QueryMeta {
// Create a new md5 hash function
const hash = crypto.createHash("md5");
// Use the query parameters to generate a new hash for caching
const key = hash
.update(JSON.stringify([where, fields, alias]))
.digest()
.toString("hex");
// If this key already exists in the cache, just return the found value
if (this._cache.has(key)) {
return {
fields,
key: "",
item: this._cache.get(key),
found: true,
};
}
// Cancel any scheduled immediates so we can add more
// items to the queue
if (this._immediate) {
clearImmediate(this._immediate);
}
// return the new cache key
return {
fields,
key,
found: false,
};
}
/**
* Pushes a new item to the queue and sets a new immediate
* @param item
*/
public addQueueItem(item: QueueItem) {
this._queue.push(item);
this._setImmediate();
}
/**
* Adds a new promise to the cache. It can now be looked up by processQueryMeta
* if an identical request comes through
* @param key
* @param value
*/
public addCacheItem<T>(key: string, value: Promise<T | undefined>) {
this._cache.set(key, value);
}
/**
* Helper to set an immediate that will process the queue
* @private
*/
private _setImmediate() {
this._immediate = setImmediate(() => this._processQueue());
}
/**
* Where the magic happens
* Goes through the queue and resoles each query
* @private
*/
private async _processQueue(): Promise<any> {
// Clear and capture the current queue
const queue = this._queue.splice(0, this._queue.length);
const queryRunner = this._connection.createQueryRunner("slave");
try {
await queryRunner.connect();
await Promise.all(queue.map(this._resolveQueueItem(queryRunner.manager)));
} catch (e) {
queue.forEach((q) => {
q.reject(e);
this._cache.delete(q.key);
});
}
await queryRunner.release();
}
/**
* Returns a closure that will be used to resolve
* a query from the cache
* @param entityManager
*/
private _resolveQueueItem(entityManager: EntityManager) {
return async (item: QueueItem) => {
const name =
typeof item.entity == "string" ? item.entity : item.entity.name;
const alias = item.alias ?? name;
let queryBuilder: SelectQueryBuilder<{}> = GraphQLQueryManager.createTypeORMQueryBuilder(
entityManager,
name,
alias
);
queryBuilder = this._resolver.createQuery(
name,
item.fields,
entityManager.connection,
queryBuilder,
alias,
item.context
);
queryBuilder = this._addSelectFields(
queryBuilder,
alias,
item.predicates.selectFields
);
queryBuilder = this._addAndWhereConditions(
queryBuilder,
item.predicates.andWhere
);
queryBuilder = this._addOrWhereConditions(
queryBuilder,
item.predicates.orWhere
);
queryBuilder = this._addSearchConditions(
queryBuilder,
alias,
item.predicates.search
);
queryBuilder = this._addOrderByCondition(
queryBuilder,
item.predicates.order
);
queryBuilder = this._addPagination(queryBuilder, item.pagination);
queryBuilder = item.ejectQueryCallback(queryBuilder);
let promise;
if (item.pagination) {
promise = queryBuilder.getManyAndCount();
} else if (item.many) {
promise = queryBuilder.getMany();
} else {
promise = queryBuilder.getOne();
}
return promise
.then(item.resolve, item.reject)
.finally(() => this._cache.delete(item.key));
};
}
/**
* Given a set of conditions, ANDs them onto the SQL WHERE expression
* via the TypeORM QueryBuilder.
* Will handle the initial where statement as per TypeORM style
* @param qb
* @param conditions
* @private
*/
private _addAndWhereConditions(
qb: SelectQueryBuilder<{}>,
conditions: Array<WhereExpression>
): SelectQueryBuilder<{}> {
const initialWhere = conditions.shift();
if (!initialWhere) return qb;
const { where, params } = GraphQLQueryManager._breakDownWhereExpression(
initialWhere
);
qb = qb.where(where, params);
conditions.forEach((condition) => {
const { where, params } = GraphQLQueryManager._breakDownWhereExpression(
condition
);
qb = qb.andWhere(where, params);
});
return qb;
}
/**
* Given a set of conditions, ORs them onto the SQL WHERE expression
* via the TypeORM QueryBuilder
* @param qb
* @param conditions
* @private
*/
private _addOrWhereConditions(
qb: SelectQueryBuilder<{}>,
conditions: Array<WhereExpression>
): SelectQueryBuilder<{}> {
conditions.forEach((condition) => {
const { where, params } = GraphQLQueryManager._breakDownWhereExpression(
condition
);
qb = qb.orWhere(where, params);
});
return qb;
}
/**
* Given a list of search conditions, adds them to the query builder.
* If multiple sets of search conditions are passed, the will be ANDed together
* @param qb
* @param alias
* @param searchConditions
* @private
*/
private _addSearchConditions(
qb: SelectQueryBuilder<{}>,
alias: string,
searchConditions: Array<SearchOptions>
): SelectQueryBuilder<{}> {
// Add an andWhere for each formatted search condition
this._formatSearchConditions(searchConditions, alias).forEach(
({ query, params }) => {
qb = qb.andWhere(query, params);
}
);
return qb;
}
/**
* Maps over a list of given search conditions and formats them into
* a query and param object to be added to a query builder.
* @param conditions
* @param alias
* @private
*/
private _formatSearchConditions(
conditions: Array<SearchOptions>,
alias: string
) {
return conditions.map(
({ searchColumns, searchMethod, searchText, caseSensitive }) => {
// Determine which search method we should use (can be customized per request)
const method = searchMethod || this._defaultLoaderSearchMethod;
// Generates a list of 'column LIKE :searchText' in accordance with the
// SearchOptions type definition
const likeQueryStrings = this._formatter.formatSearchColumns(
searchColumns,
alias,
caseSensitive
);
// Depending on our search method, we need to place our wild card
// in a different part of the string. This handles that.
const searchTextParam = this._formatter.getSearchMethodMapping(
method,
searchText
);
// Returns this structure so they can be safely added
// to the query builder without providing for SQL injection
return {
query: `(${likeQueryStrings.join(" OR ")})`,
params: { searchText: searchTextParam },
};
}
);
}
/**
* Adds pagination to the query builder
* @param queryBuilder
* @param pagination
* @private
*/
private _addPagination(
queryBuilder: SelectQueryBuilder<{}>,
pagination: QueryPagination | undefined
): SelectQueryBuilder<{}> {
if (pagination) {
queryBuilder = queryBuilder.offset(pagination.offset);
queryBuilder = queryBuilder.limit(pagination.limit);
}
return queryBuilder;
}
/**
* Adds OrderBy condition to the query builder
* @param queryBuilder
* @param order
* @private
*/
private _addOrderByCondition(
queryBuilder: SelectQueryBuilder<{}>,
order: OrderByCondition
): SelectQueryBuilder<{}> {
return queryBuilder.orderBy(order);
}
/**
* makes sure given fields are selected
* by the query builder
* @param queryBuilder
* @param alias
* @param selectFields
* @private
*/
private _addSelectFields(
queryBuilder: SelectQueryBuilder<{}>,
alias: string,
selectFields: Array<string>
): SelectQueryBuilder<{}> {
selectFields.forEach((field) => {
queryBuilder = queryBuilder.addSelect(
this._formatter.columnSelection(alias, field),
this._formatter.aliasField(alias, field)
);
});
return queryBuilder;
}
} | the_stack |
import 'jasmine';
import {range} from './utils';
import {
ColorValue, MinorColorValue,
BRAND_COLORS, getBrandColor, LitBrandPaletteKey,
MAJOR_TONAL_COLORS, getMajorTonalColor, LitMajorTonalPaletteKey,
MINOR_TONAL_COLORS, getMinorTonalColor, LitTonalPaletteKey,
ERROR_COLORS, getErrorColor,
VIZ_COLORS, getVizColor, VizPaletteKey, VizColorKey,
DEFAULT, OTHER, LOADING, HOVER,
CATEGORICAL_NORMAL,
CYEA_DISCRETE, MAGE_DISCRETE, CYEA_CONTINUOUS, MAGE_CONTINUOUS,
DIVERGING_4, DIVERGING_5, DIVERGING_6,
labBrandColors, labVizColors
} from './colors';
const STANDARD_COLOR_VALUE_NAMES: ColorValue[] = [ '50', '500', '600', '700' ];
const MINOR_COLOR_VALUE_NAMES: MinorColorValue[] = [ '1', '2', '3', '4', '5'];
const VIZ_COLOR_VALUE_NAMES: VizColorKey[] =[
'orange', 'blue', 'yellow', 'purple', 'coral', 'teal', 'magenta', 'other'
];
describe('Brand Palettes Test', () => {
it('exports a BRAND_COLORS library', () => {
expect(BRAND_COLORS).toBeDefined();
expect(Object.keys(BRAND_COLORS))
.toEqual(['cyea', 'mage', 'bric', 'neutral']);
for (const palette of Object.values(BRAND_COLORS)) {
expect(palette.length).toBe(10);
}
});
it('provides a function to get a Brand color', () => {
expect(getBrandColor).toBeDefined();
for (const key of Object.keys(BRAND_COLORS)) {
const palette = key as LitBrandPaletteKey;
// It returns a ColorEntry for ids in the range [0,9]
for (const id of range(10)) {
const color = getBrandColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns a ColorEntry when id > palette.length
const over = getBrandColor(palette, BRAND_COLORS[palette].length);
const first = getBrandColor(palette, 0);
expect(over).toEqual(first);
// It returns a ColorEntry when id < 0
const under = getBrandColor(palette, -1);
const last = getBrandColor(palette, BRAND_COLORS[palette].length - 1);
expect(under).toEqual(last);
// It returns a ColorEntry for standard color value names
for (const id of STANDARD_COLOR_VALUE_NAMES) {
const color = getBrandColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
}
});
});
describe('Major Tonal Palettes Test', () => {
it('exports a MAJOR_TONAL_COLORS library', () => {
expect(MAJOR_TONAL_COLORS).toBeDefined();
expect(Object.keys(MAJOR_TONAL_COLORS))
.toEqual(['primary', 'secondary', 'tertiary', 'neutral-variant']);
for (const palette of Object.values(MAJOR_TONAL_COLORS)) {
expect(palette.length).toBe(10);
}
});
it('provides a function to get a Major Tonal color', () => {
expect(getMajorTonalColor).toBeDefined();
for (const key of Object.keys(MAJOR_TONAL_COLORS)) {
const palette = key as LitMajorTonalPaletteKey;
// It returns a ColorEntry for ids in the range [0,9]
for (const id of range(10)) {
const color = getMajorTonalColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns a ColorEntry when id > palette.length
const over = getMajorTonalColor(palette,
MAJOR_TONAL_COLORS[palette].length);
const first = getMajorTonalColor(palette, 0);
expect(over).toEqual(first);
// It returns a ColorEntry when id < 0
const under = getMajorTonalColor(palette, -1);
const last = getMajorTonalColor(palette,
MAJOR_TONAL_COLORS[palette].length - 1);
expect(under).toEqual(last);
// It returns a ColorEntry for standard color value names
for (const id of STANDARD_COLOR_VALUE_NAMES) {
const color = getMajorTonalColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
}
});
});
describe('Minor Tonal Palettes Test', () => {
it('exports a MINOR_TONAL_COLORS library', () => {
expect(MINOR_TONAL_COLORS).toBeDefined();
expect(Object.keys(MINOR_TONAL_COLORS))
.toEqual(['primary', 'secondary', 'tertiary']);
for (const palette of Object.values(MINOR_TONAL_COLORS)) {
expect(palette.length).toBe(5);
}
});
it('provides a function to get a Minor Tonal color', () => {
expect(getMinorTonalColor).toBeDefined();
for (const key of Object.keys(MINOR_TONAL_COLORS)) {
const palette = key as LitTonalPaletteKey;
// It returns a ColorEntry for ids in the range [0,4]
for (const id of range(5)) {
const color = getMinorTonalColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns a ColorEntry when id > palette.length
const over = getMinorTonalColor(palette,
MINOR_TONAL_COLORS[palette].length);
const first = getMinorTonalColor(palette, 0);
expect(over).toEqual(first);
// It returns a ColorEntry when id < 0
const under = getMinorTonalColor(palette, -1);
const last = getMinorTonalColor(palette,
MINOR_TONAL_COLORS[palette].length - 1);
expect(under).toEqual(last);
// It returns a ColorEntry for minor color value names
for (const id of MINOR_COLOR_VALUE_NAMES) {
const color = getMinorTonalColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
}
});
});
describe('Error Colors Test', () => {
it('exports a ERROR_COLORS library', () => {
expect(ERROR_COLORS).toBeDefined();
expect(ERROR_COLORS.length).toBe(4);
});
it('provides a function to get a Major Tonal color', () => {
expect(getErrorColor).toBeDefined();
// It returns a ColorEntry for ids in the range [0,3]
for (const id of range(4)) {
const color = getErrorColor(id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns a ColorEntry when id > palette.length
const over = getErrorColor(ERROR_COLORS.length);
const first = getErrorColor(0);
expect(over).toEqual(first);
// It returns a ColorEntry when id < 0
const under = getErrorColor(-1);
const last = getErrorColor(ERROR_COLORS.length - 1);
expect(under).toEqual(last);
// It returns a ColorEntry for minor color value names
for (const id of STANDARD_COLOR_VALUE_NAMES) {
const color = getErrorColor(id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
});
});
describe('VizColors Palettes Test', () => {
it('exports a VIZ_COLORS library', () => {
expect(VIZ_COLORS).toBeDefined();
expect(Object.keys(VIZ_COLORS))
.toEqual(['pastel', 'bright', 'deep', 'dark']);
for (const palette of Object.values(VIZ_COLORS)) {
expect(palette.length).toBe(8);
}
});
it('provides a function to get a VizColor color', () => {
expect(getVizColor).toBeDefined();
for (const key of Object.keys(VIZ_COLORS)) {
const palette = key as VizPaletteKey;
// It returns a ColorEntry for ids in the range [0,7]
for (const id of range(8)) {
const color = getVizColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns a ColorEntry for minor color value names
for (const id of VIZ_COLOR_VALUE_NAMES) {
const color = getVizColor(palette, id);
expect(color).toBeDefined();
expect(color.color).toBeDefined();
expect(color.textColor).toBeDefined();
}
// It returns the "other" ColorEntry for any other id value
const under = getVizColor(palette, -1);
const other = VIZ_COLORS[palette][7];
expect(under).toEqual(other);
}
});
});
describe('Pre-baked Colors, Palettes, and Ramps Test', () => {
it('provides default, other, loading, and hover colors', () => {
expect(DEFAULT).toEqual(getBrandColor('cyea', '400').color);
expect(OTHER).toEqual(getVizColor('deep', 'other').color);
expect(LOADING).toEqual(getBrandColor('neutral', '500').color);
expect(HOVER).toEqual(getBrandColor('mage', '400').color);
});
it('provides a categorical color palette with 7 classes', () => {
expect(CATEGORICAL_NORMAL).toBeDefined();
expect(CATEGORICAL_NORMAL.length).toBe(7);
});
it('provides 2 sequential palettes with 3 classes', () => {
expect(CYEA_DISCRETE).toBeDefined();
expect(CYEA_DISCRETE.length).toBe(3);
expect(MAGE_DISCRETE).toBeDefined();
expect(MAGE_DISCRETE.length).toBe(3);
});
it('provides 3 diverging palettes', () => {
expect(DIVERGING_4).toBeDefined();
expect(DIVERGING_4.length).toBe(4);
expect(DIVERGING_5).toBeDefined();
expect(DIVERGING_5.length).toBe(5);
expect(DIVERGING_6).toBeDefined();
expect(DIVERGING_6.length).toBe(6);
});
it('provides 2 sequential color ramps', () => {
expect(CYEA_CONTINUOUS).toBeDefined();
expect(MAGE_CONTINUOUS).toBeDefined();
});
it('can generate linear color lists through the LAB space', () => {
const purpleLAB = labVizColors('purple');
expect(purpleLAB).toBeInstanceOf(Array);
expect(purpleLAB.length).toEqual(256);
expect(purpleLAB[0]).toEqual('rgb(255, 255, 255)');
expect(purpleLAB[purpleLAB.length - 1]).toEqual('rgb(40, 1, 135)');
const coralTealLAB = labVizColors('teal', 'coral');
expect(coralTealLAB).toBeInstanceOf(Array);
expect(coralTealLAB.length).toEqual(256);
expect(coralTealLAB[0]).toEqual('rgb(177, 45, 51)');
expect(coralTealLAB[coralTealLAB.length - 1]).toEqual('rgb(1, 98, 104)');
const bricLAB = labBrandColors('bric');
expect(bricLAB).toBeInstanceOf(Array);
expect(bricLAB.length).toEqual(256);
expect(bricLAB[0]).toEqual('rgb(255, 255, 255)');
expect(bricLAB[bricLAB.length - 1]).toEqual('rgb(72, 0, 0)');
const mageCyeaLAB = labBrandColors('cyea', 'mage');
expect(mageCyeaLAB).toBeInstanceOf(Array);
expect(mageCyeaLAB.length).toEqual(256);
expect(mageCyeaLAB[0]).toEqual('rgb(71, 0, 70)');
expect(mageCyeaLAB[mageCyeaLAB.length - 1]).toEqual('rgb(4, 30, 53)');
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_project_Information {
interface Header extends DevKit.Controls.IHeader {
/** Shows the actual cost divided by the estimated cost at completion. System Field - For PSA Use Only. */
msdyn_CostConsumption: DevKit.Controls.Decimal;
/** Shows the aggregate of the planned labor cost of all the associated tasks. */
msdyn_plannedlaborcost: DevKit.Controls.Money;
/** Shows the actual hours divided by effort at estimate. */
msdyn_Progress: DevKit.Controls.Decimal;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend: DevKit.Controls.Date;
}
interface tab_Assignments_Tab_Sections {
Assignments_Section: DevKit.Controls.Section;
}
interface tab_Estimates_Tab_Sections {
Estimates_Section: DevKit.Controls.Section;
}
interface tab_Expense_Estimates_Tab_Sections {
Expense_Estimates_Section: DevKit.Controls.Section;
}
interface tab_Reconciliation_Tab_Sections {
Reconciliation_Section: DevKit.Controls.Section;
}
interface tab_Sales_Sections {
Sales: DevKit.Controls.Section;
}
interface tab_Schedule_Tab_Sections {
Schedule_Section: DevKit.Controls.Section;
}
interface tab_Status_Sections {
Status_section_1: DevKit.Controls.Section;
Status_section_2: DevKit.Controls.Section;
}
interface tab_Summary_Sections {
_31843965_2614_4DEC_B525_872D76E16B92: DevKit.Controls.Section;
_AC4158D2_008D_4B6D_8E11_58C9AB47B14B_SECTION_4: DevKit.Controls.Section;
_AC4158D2_008D_4B6D_8E11_58C9AB47B14B_SECTION_5: DevKit.Controls.Section;
}
interface tab_Team_Sections {
_AC4158D2_008D_4B6D_8E11_58C9AB47B14B_SECTION_3: DevKit.Controls.Section;
}
interface tab_Tracking_Tab_Sections {
Tracking_Section: DevKit.Controls.Section;
}
interface tab_Assignments_Tab extends DevKit.Controls.ITab {
Section: tab_Assignments_Tab_Sections;
}
interface tab_Estimates_Tab extends DevKit.Controls.ITab {
Section: tab_Estimates_Tab_Sections;
}
interface tab_Expense_Estimates_Tab extends DevKit.Controls.ITab {
Section: tab_Expense_Estimates_Tab_Sections;
}
interface tab_Reconciliation_Tab extends DevKit.Controls.ITab {
Section: tab_Reconciliation_Tab_Sections;
}
interface tab_Sales extends DevKit.Controls.ITab {
Section: tab_Sales_Sections;
}
interface tab_Schedule_Tab extends DevKit.Controls.ITab {
Section: tab_Schedule_Tab_Sections;
}
interface tab_Status extends DevKit.Controls.ITab {
Section: tab_Status_Sections;
}
interface tab_Summary extends DevKit.Controls.ITab {
Section: tab_Summary_Sections;
}
interface tab_Team extends DevKit.Controls.ITab {
Section: tab_Team_Sections;
}
interface tab_Tracking_Tab extends DevKit.Controls.ITab {
Section: tab_Tracking_Tab_Sections;
}
interface Tabs {
Assignments_Tab: tab_Assignments_Tab;
Estimates_Tab: tab_Estimates_Tab;
Expense_Estimates_Tab: tab_Expense_Estimates_Tab;
Reconciliation_Tab: tab_Reconciliation_Tab;
Sales: tab_Sales;
Schedule_Tab: tab_Schedule_Tab;
Status: tab_Status;
Summary: tab_Summary;
Team: tab_Team;
Tracking_Tab: tab_Tracking_Tab;
}
interface Body {
Tab: Tabs;
/** Enter the actual end time of the project. */
msdyn_actualend: DevKit.Controls.Date;
/** Shows the aggregate of actual expense cost on the project. System Field - For PSA Use Only. */
msdyn_actualexpensecost: DevKit.Controls.Money;
/** Shows the total actual hours of the project. System Field - For PSA Use Only. */
msdyn_actualhours: DevKit.Controls.Decimal;
/** Shows the aggregate of actual labor cost on the project. System Field - For PSA Use Only. */
msdyn_actuallaborcost: DevKit.Controls.Money;
/** Enter the actual start time of the project. */
msdyn_actualstart: DevKit.Controls.Date;
/** Enter the comments that are used to describe the current project status. */
msdyn_comments: DevKit.Controls.String;
/** Select the organizational unit sponsoring the project. */
msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup;
/** System Field - For PSA Use Only. */
msdyn_CostPerformence: DevKit.Controls.OptionSet;
/** Enter the customer who the project is associated with. */
msdyn_customer: DevKit.Controls.Lookup;
/** Enter a description of the project. */
msdyn_description: DevKit.Controls.String;
/** Shows if the project is a project template. System Field - For PSA Use Only. */
msdyn_istemplate: DevKit.Controls.Boolean;
/** Describes the project status. */
msdyn_overallprojectstatus: DevKit.Controls.OptionSet;
/** Shows the aggregate of the planned expense cost of all the associated tasks. */
msdyn_plannedexpensecost: DevKit.Controls.Money;
/** Shows the total estimate hours of the project. */
msdyn_plannedhours: DevKit.Controls.Decimal;
/** Shows the aggregate of the planned labor cost of all the associated tasks. */
msdyn_plannedlaborcost: DevKit.Controls.Money;
/** Shows the project manager assigned to the project. */
msdyn_projectmanager: DevKit.Controls.Lookup;
/** Select the project template behind the project. */
msdyn_ProjectTemplate: DevKit.Controls.Lookup;
/** Select the project template behind the project. */
msdyn_ProjectTemplate_1: DevKit.Controls.Lookup;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend: DevKit.Controls.Date;
/** Enter the scheduled start time of the project. */
msdyn_scheduledstart: DevKit.Controls.Date;
/** Describes the schedule performance of the project. */
msdyn_scheduleperformance: DevKit.Controls.OptionSet;
/** Shows the most recent update on a status field(comments or overall project status). */
msdyn_statusupdatedon: DevKit.Controls.DateTime;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.Controls.String;
/** Shows the aggregated cost from actuals on the project. */
msdyn_TotalActualCost: DevKit.Controls.Money;
/** Shows the aggregate of the total planned cost of all the associated tasks. */
msdyn_TotalPlannedCost: DevKit.Controls.Money;
/** Select the work hour template used to create the project calendar. */
msdyn_workhourtemplate: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_project_bookableresourcebooking_projectid: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_bookableresourcebookingheader_projectid: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_actual_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_contractlinescheduleofvalue_project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_estimate_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_estimateline_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_expense_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_journal_DefaultProject: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_journalline_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_project_ProjectTemplate: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_projectapproval_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_projectpricelist_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_projecttask_project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_projectteam_project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_projecttransactioncategory_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_resourceassignment_projectid: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_msdyn_timeentry_project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_opportunityproduct_Project: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_project_quotedetail_Project: DevKit.Controls.NavigationItem,
nav_msdyn_project_resourcerequirement: DevKit.Controls.NavigationItem,
navAsyncOperations: DevKit.Controls.NavigationItem,
navAudit: DevKit.Controls.NavigationItem,
navConnections: DevKit.Controls.NavigationItem,
navDocument: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface ProcessProject_Service_Project_Stages {
/** Enter the actual end time of the project. */
msdyn_actualend: DevKit.Controls.Date;
/** Enter the actual end time of the project. */
msdyn_actualend_1: DevKit.Controls.Date;
/** Enter the actual start time of the project. */
msdyn_actualstart: DevKit.Controls.Date;
/** Enter a description of the project. */
msdyn_description: DevKit.Controls.String;
/** Shows the contract for this project. */
msdyn_salesorderid: DevKit.Controls.Lookup;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend: DevKit.Controls.Date;
/** Enter the scheduled start time of the project. */
msdyn_scheduledstart: DevKit.Controls.Date;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.Controls.String;
}
interface Process extends DevKit.Controls.IProcess {
Project_Service_Project_Stages: ProcessProject_Service_Project_Stages;
}
interface Grid {
Schedule: DevKit.Controls.Grid;
SubGrid_TeamMember: DevKit.Controls.Grid;
Assignments: DevKit.Controls.Grid;
Reconciliation: DevKit.Controls.Grid;
Estimates: DevKit.Controls.Grid;
Tracking: DevKit.Controls.Grid;
SchedulePerformanceEffort: DevKit.Controls.Grid;
SchedulePerformanceCost: DevKit.Controls.Grid;
ProjectContract: DevKit.Controls.Grid;
ProjectQuote: DevKit.Controls.Grid;
ExpenseEstimates: DevKit.Controls.Grid;
}
}
class Formmsdyn_project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_project_Information
* @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 msdyn_project_Information */
Body: DevKit.Formmsdyn_project_Information.Body;
/** The Header section of form msdyn_project_Information */
Header: DevKit.Formmsdyn_project_Information.Header;
/** The Navigation of form msdyn_project_Information */
Navigation: DevKit.Formmsdyn_project_Information.Navigation;
/** The Process of form msdyn_project_Information */
Process: DevKit.Formmsdyn_project_Information.Process;
/** The Grid of form msdyn_project_Information */
Grid: DevKit.Formmsdyn_project_Information.Grid;
}
namespace FormCreate_Project {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Select the organizational unit sponsoring the project. */
msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup;
/** Enter a description of the project. */
msdyn_description: DevKit.Controls.String;
/** Shows if the project is a project template. System Field - For PSA Use Only. */
msdyn_istemplate: DevKit.Controls.Boolean;
/** Shows the aggregate of the planned expense cost of all the associated tasks. */
msdyn_plannedexpensecost: DevKit.Controls.Money;
/** Shows the total estimate hours of the project. */
msdyn_plannedhours: DevKit.Controls.Decimal;
/** Shows the aggregate of the planned labor cost of all the associated tasks. */
msdyn_plannedlaborcost: DevKit.Controls.Money;
/** Shows the project manager assigned to the project. */
msdyn_projectmanager: DevKit.Controls.Lookup;
/** Select the project template behind the project. */
msdyn_ProjectTemplate: DevKit.Controls.Lookup;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend: DevKit.Controls.Date;
/** Enter the scheduled start time of the project. */
msdyn_scheduledstart: DevKit.Controls.Date;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.Controls.String;
/** Shows the aggregate of the total planned cost of all the associated tasks. */
msdyn_TotalPlannedCost: DevKit.Controls.Money;
/** Select the work hour template used to create the project calendar. */
msdyn_workhourtemplate: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
}
class FormCreate_Project extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Create_Project
* @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 Create_Project */
Body: DevKit.FormCreate_Project.Body;
}
class msdyn_projectApi {
/**
* DynamicsCrm.DevKit msdyn_projectApi
* @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;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
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;
/** 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;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the actual duration of the project in minutes. */
msdyn_actualdurationminutes: DevKit.WebApi.IntegerValue;
/** Enter the actual end time of the project. */
msdyn_actualend_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Shows the aggregate of actual expense cost on the project. System Field - For PSA Use Only. */
msdyn_actualexpensecost: DevKit.WebApi.MoneyValue;
/** Value of the Actual Expense Cost in base currency. System Field - For PSA Use Only. */
msdyn_actualexpensecost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the aggregate of actual expense sales on the project - For PSA use only */
msdyn_ActualExpenseSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the actual expense sales in the base currency. System Field - For PSA Use Only. */
msdyn_actualexpensesales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total actual hours of the project. System Field - For PSA Use Only. */
msdyn_actualhours: DevKit.WebApi.DecimalValue;
/** Shows the aggregate of actual labor cost on the project. System Field - For PSA Use Only. */
msdyn_actuallaborcost: DevKit.WebApi.MoneyValue;
/** Value of the Actual Labor Cost in base currency. System Field - For PSA Use Only. */
msdyn_actuallaborcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the aggregate of actual labor sales on the project - For PSA use only */
msdyn_ActualSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the actual labor sales in the base currency. System Field - For PSA Use Only. */
msdyn_actualsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the actual start time of the project. */
msdyn_actualstart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** The status of the bulk generation operations running on the project entity. If no operation is running, the value is null. System Field - For PSA Use Only. */
msdyn_BulkGenerationStatus: DevKit.WebApi.OptionSetValue;
/** Id of the calendar for the project. */
msdyn_calendarid: DevKit.WebApi.StringValue;
/** Enter the comments that are used to describe the current project status. */
msdyn_comments: DevKit.WebApi.StringValue;
/** Select the organizational unit sponsoring the project. */
msdyn_ContractOrganizationalUnitId: DevKit.WebApi.LookupValue;
/** Shows the actual cost divided by the estimated cost at completion. System Field - For PSA Use Only. */
msdyn_CostConsumption: DevKit.WebApi.DecimalValue;
/** Sum of Actual Cost and Remaining cost. System Field - For PSA Use Only. */
msdyn_CostEstimateAtComplete: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Cost estimate at completion (EAC) in base currency. System Field - For PSA Use Only. */
msdyn_costestimateatcomplete_Base: DevKit.WebApi.MoneyValueReadonly;
/** System Field - For PSA Use Only. */
msdyn_CostPerformence: DevKit.WebApi.OptionSetValueReadonly;
/** Variance between the estimated cost and the forecasted cost based on the estimate at completion (EAC). System Field - For PSA Use Only. */
msdyn_CostVariance: DevKit.WebApi.MoneyValueReadonly;
/** Shows the value of the cost variance in the base currency. System Field - For PSA Use Only. */
msdyn_costvariance_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the customer who the project is associated with. */
msdyn_customer: DevKit.WebApi.LookupValue;
/** Enter a description of the project. */
msdyn_description: DevKit.WebApi.StringValue;
/** This is an internal field, mainly used during import so that we don't create a team member record for the project manager. System Field - For PSA Use Only. */
msdyn_disablecreateofteammemberformanager: DevKit.WebApi.BooleanValue;
/** Shows the total of actual hours and the remaining hours. */
msdyn_EffortestimateatcompleteEAC: DevKit.WebApi.DoubleValue;
/** Exchange rate for the currency associated with the project with respect to the base currency. */
msdyn_exchangerate: DevKit.WebApi.DecimalValue;
/** Specifies if the project is linked to a project in MS Project. System Field - For PSA Use Only. */
msdyn_IsLinkedToMSProjectClient: DevKit.WebApi.BooleanValue;
/** Shows if the project is a project template. System Field - For PSA Use Only. */
msdyn_istemplate: DevKit.WebApi.BooleanValue;
/** The URL for the linked document. System Field - For PSA Use Only. */
msdyn_linkeddocumenturl: DevKit.WebApi.StringValue;
/** Describes the project status. */
msdyn_overallprojectstatus: DevKit.WebApi.OptionSetValue;
/** Shows the aggregate of the planned expense cost of all the associated tasks. */
msdyn_plannedexpensecost: DevKit.WebApi.MoneyValue;
/** Value of the Estimated Expense Cost in base currency. System Field - For PSA Use Only. */
msdyn_plannedexpensecost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the aggregate of estimated expense sales on the project - For PSA use only */
msdyn_PlannedExpenseSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimated expense sales in the base currency. System Field - For PSA Use Only. */
msdyn_plannedexpensesales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total estimate hours of the project. */
msdyn_plannedhours: DevKit.WebApi.DecimalValue;
/** Shows the aggregate of the planned labor cost of all the associated tasks. */
msdyn_plannedlaborcost: DevKit.WebApi.MoneyValue;
/** Value of the Estimated Labor Cost in base currency. System Field - For PSA Use Only. */
msdyn_plannedlaborcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the aggregate of estimated labor sales on the project - For PSA use only */
msdyn_PlannedSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimated labor sales in the base currency. System Field - For PSA Use Only. */
msdyn_plannedsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the actual hours divided by effort at estimate. */
msdyn_Progress: DevKit.WebApi.DecimalValue;
/** Shows the entity instances. */
msdyn_projectId: DevKit.WebApi.GuidValue;
/** Shows the project manager assigned to the project. */
msdyn_projectmanager: DevKit.WebApi.LookupValue;
/** Indicates if the project resource requirements are visible to the resources assigned to the project. */
msdyn_projectresourcerequirementsvisibletore: DevKit.WebApi.BooleanValue;
/** Select the Team associated with Project. */
msdyn_projectteamid: DevKit.WebApi.LookupValue;
/** Select the project template behind the project. */
msdyn_ProjectTemplate: DevKit.WebApi.LookupValue;
/** Shows the difference between the estimated labor cost and the actual labor cost. */
msdyn_RemainingCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the remaining labor cost in the base currency. */
msdyn_remainingcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the difference between the estimate at completion (EAC) and the actual hours. */
msdyn_RemainingHours: DevKit.WebApi.DoubleValue;
/** Shows the difference between the estimated labor sales and the actual labor sales. */
msdyn_RemainingSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the remaining labor sales in the base currency. */
msdyn_remainingsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the actual sales divided by the estimated sales. */
msdyn_SalesConsumption: DevKit.WebApi.DecimalValueReadonly;
/** Shows the total of actual and remaining sales. */
msdyn_SalesEstimateAtCompleteEAC: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Sales Estimate At Complete (EAC) in base currency. */
msdyn_salesestimateatcompleteeac_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the contract for this project. */
msdyn_salesorderid: DevKit.WebApi.LookupValue;
/** Shows the difference between the planned sales and the sales estimate at completion (EAC). */
msdyn_SalesVariance: DevKit.WebApi.MoneyValueReadonly;
/** Shows the value of the sales variance in the base currency. */
msdyn_salesvariance_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the scheduled duration of the project, specified in minutes. */
msdyn_scheduleddurationminutes: DevKit.WebApi.IntegerValue;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the scheduled start time of the project. */
msdyn_scheduledstart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Describes the schedule performance of the project. */
msdyn_scheduleperformance: DevKit.WebApi.OptionSetValue;
/** Shows the difference between the planned effort and the estimate at completion (EAC). */
msdyn_ScheduleVariance: DevKit.WebApi.DoubleValue;
/** Shows the stage of the project (Deprecated in v3.0). */
msdyn_StageName: DevKit.WebApi.StringValue;
/** Shows the most recent update on a status field(comments or overall project status). */
msdyn_statusupdatedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.WebApi.StringValue;
/** Shows the total number of team members assigned to this project */
msdyn_teamsize: DevKit.WebApi.IntegerValueReadonly;
/** Last Updated time of rollup field Team Size. */
msdyn_teamsize_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Team Size. */
msdyn_teamsize_State: DevKit.WebApi.IntegerValueReadonly;
/** Shows the aggregated cost from actuals on the project. */
msdyn_TotalActualCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the total actual cost in the base currency. */
msdyn_totalactualcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows aggregated sales values from all project actuals - For PSA use only */
msdyn_TotalActualSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the actual total sales in the base currency. System Field - For PSA Use Only. */
msdyn_totalactualsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the aggregate of the total planned cost of all the associated tasks. */
msdyn_TotalPlannedCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the total planned cost in the base currency. */
msdyn_totalplannedcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows aggregate of estimated sales values on the project - For PSA use only */
msdyn_TotalPlannedSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the estimated total sales in the base currency. System Field - For PSA Use Only. */
msdyn_totalplannedsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the work breakdown structure (WBS) duration in days. */
msdyn_wbsduration: DevKit.WebApi.IntegerValue;
/** Select the work hour template used to create the project calendar. */
msdyn_workhourtemplate: DevKit.WebApi.LookupValue;
/** 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;
/** Contains the id of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Contains the id of the stage where the entity is located. */
stageid: DevKit.WebApi.GuidValue;
/** Status of the Project */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Project */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** 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_project {
enum msdyn_BulkGenerationStatus {
/** 192350001 */
Failed,
/** 192350000 */
Processing
}
enum msdyn_CostPerformence {
/** 192350000 */
On_Budget,
/** 192350001 */
Over_Budget,
/** 192350002 */
Under_Budget
}
enum msdyn_overallprojectstatus {
/** 1 */
Green,
/** 3 */
Red,
/** 2 */
Yellow
}
enum msdyn_scheduleperformance {
/** 192350001 */
Ahead,
/** 192350002 */
Behind,
/** 192350000 */
On_Time
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 192350000 */
Closed_Sets_project_to_read_only_and_cancels_future_bookings,
/** 2 */
Inactive_Sets_project_to_read_only
}
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':['Create Project','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
function Stream(str: string) {
var position = 0;
function read(length: number) {
var result = str.substr(position, length);
position += length;
return result;
}
/* read a big-endian 32-bit integer */
function readInt32() {
var result = (
(str.charCodeAt(position) << 24)
+ (str.charCodeAt(position + 1) << 16)
+ (str.charCodeAt(position + 2) << 8)
+ str.charCodeAt(position + 3));
position += 4;
return result;
}
/* read a big-endian 16-bit integer */
function readInt16() {
var result = (
(str.charCodeAt(position) << 8)
+ str.charCodeAt(position + 1));
position += 2;
return result;
}
/* read an 8-bit integer */
function readInt8(signed?: boolean) {
var result = str.charCodeAt(position);
if (signed && result > 127) result -= 256;
position += 1;
return result;
}
function eof() {
return position >= str.length;
}
/* read a MIDI-style variable-length integer
(big-endian value in groups of 7 bits,
with top bit set to signify that another byte follows)
*/
function readVarInt() {
var result = 0;
while (true) {
var b = readInt8();
if (b & 0x80) {
result += (b & 0x7f);
result <<= 7;
} else {
/* b is the last byte */
return result + b;
}
}
}
return {
'eof': eof,
'read': read,
'readInt32': readInt32,
'readInt16': readInt16,
'readInt8': readInt8,
'readVarInt': readVarInt
}
}
/*
class to parse the .mid file format
(depends on stream.js)
*/
export function MidiFile(data: any) {
function readChunk(stream: any) {
var id = stream.read(4);
var length = stream.readInt32();
return {
'id': id,
'length': length,
'data': stream.read(length)
};
}
var lastEventTypeByte: any;
function readEvent(stream: any) {
var event: any = {};
event.deltaTime = stream.readVarInt();
var eventTypeByte = stream.readInt8();
if ((eventTypeByte & 0xf0) == 0xf0) {
/* system / meta event */
if (eventTypeByte == 0xff) {
/* meta event */
event.type = 'meta';
var subtypeByte = stream.readInt8();
var length = stream.readVarInt();
switch (subtypeByte) {
case 0x00:
event.subtype = 'sequenceNumber';
if (length != 2) throw "Expected length for sequenceNumber event is 2, got " + length;
event.number = stream.readInt16();
return event;
case 0x01:
event.subtype = 'text';
event.text = stream.read(length);
return event;
case 0x02:
event.subtype = 'copyrightNotice';
event.text = stream.read(length);
return event;
case 0x03:
event.subtype = 'trackName';
event.text = stream.read(length);
return event;
case 0x04:
event.subtype = 'instrumentName';
event.text = stream.read(length);
return event;
case 0x05:
event.subtype = 'lyrics';
event.text = stream.read(length);
return event;
case 0x06:
event.subtype = 'marker';
event.text = stream.read(length);
return event;
case 0x07:
event.subtype = 'cuePoint';
event.text = stream.read(length);
return event;
case 0x20:
event.subtype = 'midiChannelPrefix';
if (length != 1) throw "Expected length for midiChannelPrefix event is 1, got " + length;
event.channel = stream.readInt8();
return event;
case 0x2f:
event.subtype = 'endOfTrack';
if (length != 0) throw "Expected length for endOfTrack event is 0, got " + length;
return event;
case 0x51:
event.subtype = 'setTempo';
if (length != 3) throw "Expected length for setTempo event is 3, got " + length;
event.microsecondsPerBeat = (
(stream.readInt8() << 16)
+ (stream.readInt8() << 8)
+ stream.readInt8()
)
return event;
case 0x54:
event.subtype = 'smpteOffset';
if (length != 5) throw "Expected length for smpteOffset event is 5, got " + length;
var hourByte = stream.readInt8();
event.frameRate = ({
0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30
}as any)[hourByte & 0x60];
event.hour = hourByte & 0x1f;
event.min = stream.readInt8();
event.sec = stream.readInt8();
event.frame = stream.readInt8();
event.subframe = stream.readInt8();
return event;
case 0x58:
event.subtype = 'timeSignature';
if (length != 4) throw "Expected length for timeSignature event is 4, got " + length;
event.numerator = stream.readInt8();
event.denominator = Math.pow(2, stream.readInt8());
event.metronome = stream.readInt8();
event.thirtyseconds = stream.readInt8();
return event;
case 0x59:
event.subtype = 'keySignature';
if (length != 2) throw "Expected length for keySignature event is 2, got " + length;
event.key = stream.readInt8(true);
event.scale = stream.readInt8();
return event;
case 0x7f:
event.subtype = 'sequencerSpecific';
event.data = stream.read(length);
return event;
default:
// console.log("Unrecognised meta event subtype: " + subtypeByte);
event.subtype = 'unknown'
event.data = stream.read(length);
return event;
}
} else if (eventTypeByte == 0xf0) {
event.type = 'sysEx';
var length = stream.readVarInt();
event.data = stream.read(length);
return event;
} else if (eventTypeByte == 0xf7) {
event.type = 'dividedSysEx';
var length = stream.readVarInt();
event.data = stream.read(length);
return event;
} else {
throw "Unrecognised MIDI event type byte: " + eventTypeByte;
}
} else {
/* channel event */
var param1;
if ((eventTypeByte & 0x80) == 0) {
/* running status - reuse lastEventTypeByte as the event type.
eventTypeByte is actually the first parameter
*/
param1 = eventTypeByte;
eventTypeByte = lastEventTypeByte;
} else {
param1 = stream.readInt8();
lastEventTypeByte = eventTypeByte;
}
var eventType = eventTypeByte >> 4;
event.channel = eventTypeByte & 0x0f;
event.type = 'channel';
switch (eventType) {
case 0x08:
event.subtype = 'noteOff';
event.noteNumber = param1;
event.velocity = stream.readInt8();
return event;
case 0x09:
event.noteNumber = param1;
event.velocity = stream.readInt8();
if (event.velocity == 0) {
event.subtype = 'noteOff';
} else {
event.subtype = 'noteOn';
}
return event;
case 0x0a:
event.subtype = 'noteAftertouch';
event.noteNumber = param1;
event.amount = stream.readInt8();
return event;
case 0x0b:
event.subtype = 'controller';
event.controllerType = param1;
event.value = stream.readInt8();
return event;
case 0x0c:
event.subtype = 'programChange';
event.programNumber = param1;
return event;
case 0x0d:
event.subtype = 'channelAftertouch';
event.amount = param1;
return event;
case 0x0e:
event.subtype = 'pitchBend';
event.value = param1 + (stream.readInt8() << 7);
return event;
default:
throw "Unrecognised MIDI event type: " + eventType
/*
console.log("Unrecognised MIDI event type: " + eventType);
stream.readInt8();
event.subtype = 'unknown';
return event;
*/
}
}
}
var stream = Stream(data);
var headerChunk = readChunk(stream);
if (headerChunk.id != 'MThd' || headerChunk.length != 6) {
throw "Bad .mid file - header not found";
}
var headerStream = Stream(headerChunk.data);
var formatType = headerStream.readInt16();
var trackCount = headerStream.readInt16();
var timeDivision = headerStream.readInt16();
if (timeDivision & 0x8000) {
throw "Expressing time division in SMTPE frames is not supported yet"
}
var header = {
'formatType': formatType,
'trackCount': trackCount,
'ticksPerBeat': timeDivision
}
var tracks: any[] = [];
for (var i = 0; i < header.trackCount; i++) {
tracks[i] = [];
var trackChunk = readChunk(stream);
if (trackChunk.id != 'MTrk') {
throw "Unexpected chunk - expected MTrk, got " + trackChunk.id;
}
var trackStream = Stream(trackChunk.data);
while (!trackStream.eof()) {
var event = readEvent(trackStream);
tracks[i].push(event);
//console.log(event);
}
}
return {
'header': header,
'tracks': tracks
}
} | the_stack |
import { LinkReferenceType } from '@yozora/ast'
import type { INodePoint } from '@yozora/character'
import { AsciiCodePoint } from '@yozora/character'
import { eatLinkLabel, genFindDelimiter, isLinkToken } from '@yozora/core-tokenizer'
import type {
IMatchInlineHookCreator,
IResultOfIsDelimiterPair,
IResultOfProcessDelimiterPair,
IResultOfProcessSingleDelimiter,
IYastInlineToken,
} from '@yozora/core-tokenizer'
import { checkBalancedBracketsStatus } from '@yozora/tokenizer-link'
import type { IDelimiter, ILinkReferenceDelimiterBracket, IThis, IToken, T } from './types'
/**
* There are three kinds of reference links:
* - full: A full reference link consists of a link text immediately followed
* by a link label that matches a link reference definition elsewhere in the
* document.
*
* A link label begins with a left bracket '[' and ends with the first right
* bracket ']' that is not backslash-escaped. Between these brackets there
* must be at least one non-whitespace character. Unescaped square bracket
* characters are not allowed inside the opening and closing square brackets
* of link labels. A link label can have at most 999 characters inside the
* square brackets.
*
* One label matches another just in case their normalized forms are equal.
* To normalize a label, strip off the opening and closing brackets, perform
* the Unicode case fold, strip leading and trailing whitespace and collapse
* consecutive internal whitespace to a single space. If there are multiple
* matching reference link definitions, the one that comes first in the
* document is used. (It is desirable in such cases to emit a warning.)
*
* - collapsed: A collapsed reference link consists of a link label that
* matches a link reference definition elsewhere in the document, followed
* by the string '[]'. The contents of the first link label are parsed as
* inlines, which are used as the link’s text. The link’s URI and title are
* provided by the matching reference link definition.
* Thus, '[foo][]' is equivalent to '[foo][foo]'.
*
* - shortcut (not support): A shortcut reference link consists of a link label
* that matches a link reference definition elsewhere in the document and is
* not followed by '[]' or a link label. The contents of the first link label
* are parsed as inlines, which are used as the link’s text. The link’s URI
* and title are provided by the matching link reference definition.
* Thus, '[foo]' is equivalent to '[foo][]'.
*
* ------
*
* A 'opener' type delimiter is one of the following forms:
*
* - '['
* - '[identifier]['
* - '[identifier][identifier2]...[identifierN]['
*
* A 'closer' type delimiter is one of the following forms:
*
* - '][identifier]'
* - '][identifier][]'
* - '][identifier][identifier2]....[identifierN]'
* - '][identifier][identifier2]....[identifierN][]'
*
* A 'both' type delimiter is one of the following forms:
*
* - '][identifier]['
* - '][identifier][identifier2]...[identifierN]['
*
* A 'full' type delimiter is one of the following forms:
*
* - '[]'
* - '[identifier]'
* - '[identifier][]'
* - '][identifier][identifier2]....[identifierN]'
* - '][identifier][identifier2]....[identifierN][]'
*
* @see https://github.com/syntax-tree/mdast#linkreference
* @see https://github.github.com/gfm/#reference-link
*/
export const match: IMatchInlineHookCreator<T, IDelimiter, IToken, IThis> = function (api) {
return {
findDelimiter: () => genFindDelimiter<IDelimiter>(_findDelimiter),
isDelimiterPair,
processDelimiterPair,
processSingleDelimiter,
}
function _findDelimiter(startIndex: number, endIndex: number): IDelimiter | null {
const nodePoints: ReadonlyArray<INodePoint> = api.getNodePoints()
for (let i = startIndex; i < endIndex; ++i) {
const c = nodePoints[i].codePoint
switch (c) {
case AsciiCodePoint.BACKSLASH:
i += 1
break
/**
* A link text consists of a sequence of zero or more inline elements
* enclosed by square brackets ([ and ])
* @see https://github.github.com/gfm/#link-text
*/
case AsciiCodePoint.OPEN_BRACKET: {
const brackets: ILinkReferenceDelimiterBracket[] = []
const delimiter: IDelimiter = {
type: 'opener',
startIndex: i,
endIndex: i + 1,
brackets,
}
const result1 = eatLinkLabel(nodePoints, i, endIndex)
if (result1.nextIndex < 0) return delimiter
// preceding '[]' is useless.
if (result1.labelAndIdentifier == null) {
i = result1.nextIndex - 1
break
}
brackets.push({
startIndex: i,
endIndex: result1.nextIndex,
label: result1.labelAndIdentifier.label,
identifier: result1.labelAndIdentifier.identifier,
})
for (i = result1.nextIndex; i < endIndex; ) {
if (nodePoints[i].codePoint !== AsciiCodePoint.OPEN_BRACKET) break
const { labelAndIdentifier, nextIndex } = eatLinkLabel(nodePoints, i, endIndex)
// It's something like '[identifier][' or '[identifier1][identifier2]...['
if (nextIndex === -1) {
delimiter.type = 'opener'
delimiter.endIndex = i + 1
return delimiter
}
// It's something like '[identifier][]' or '[identifier1][identifier2]...[]'
// or '[identifier]' or '[identifier1][identifier2]...[identifierN]'
const bracket: ILinkReferenceDelimiterBracket = {
startIndex: i,
endIndex: nextIndex,
}
delimiter.type = 'full'
delimiter.endIndex = nextIndex
brackets.push(bracket)
if (labelAndIdentifier == null) break
bracket.label = labelAndIdentifier.label
bracket.identifier = labelAndIdentifier.identifier
i = nextIndex
}
return delimiter
}
case AsciiCodePoint.CLOSE_BRACKET: {
if (i + 1 >= endIndex || nodePoints[i + 1].codePoint !== AsciiCodePoint.OPEN_BRACKET) {
break
}
const result1 = eatLinkLabel(nodePoints, i + 1, endIndex)
// It's something like ']['
if (result1.nextIndex === -1) {
return {
type: 'opener',
startIndex: i + 1,
endIndex: i + 2,
brackets: [],
}
}
// It's something like '][]'
if (result1.labelAndIdentifier == null) {
i = result1.nextIndex - 1
break
}
const brackets: ILinkReferenceDelimiterBracket[] = [
{
startIndex: i + 1,
endIndex: result1.nextIndex,
label: result1.labelAndIdentifier.label,
identifier: result1.labelAndIdentifier.identifier,
},
]
const delimiter: IDelimiter = {
type: 'closer',
startIndex: i,
endIndex: result1.nextIndex,
brackets,
}
for (i = result1.nextIndex; i < endIndex; ) {
if (nodePoints[i].codePoint !== AsciiCodePoint.OPEN_BRACKET) break
const { labelAndIdentifier, nextIndex } = eatLinkLabel(nodePoints, i, endIndex)
// It's something like '][identifier][' or '][identifier1][identifier2]...['
if (nextIndex === -1) {
delimiter.type = 'both'
delimiter.endIndex = i + 1
return delimiter
}
// It's something like '][identifier][]' or '][identifier1][identifier2]...[]'
// or '][identifier]' or '][identifier1][identifier2]...[identifierN]'
const bracket: ILinkReferenceDelimiterBracket = {
startIndex: i,
endIndex: nextIndex,
}
delimiter.type = 'full'
delimiter.endIndex = nextIndex
brackets.push(bracket)
if (labelAndIdentifier == null) break
bracket.label = labelAndIdentifier.label
bracket.identifier = labelAndIdentifier.identifier
i = nextIndex
}
return delimiter
}
}
}
return null
}
function isDelimiterPair(
openerDelimiter: IDelimiter,
closerDelimiter: IDelimiter,
internalTokens: ReadonlyArray<IYastInlineToken>,
): IResultOfIsDelimiterPair {
/**
* Links may not contain other links, at any level of nesting.
* @see https://github.github.com/gfm/#example-540
* @see https://github.github.com/gfm/#example-541
*/
const hasInternalLinkToken: boolean = internalTokens.find(isLinkToken) != null
if (hasInternalLinkToken) {
return { paired: false, opener: false, closer: false }
}
const nodePoints: ReadonlyArray<INodePoint> = api.getNodePoints()
const balancedBracketsStatus: -1 | 0 | 1 = checkBalancedBracketsStatus(
openerDelimiter.endIndex,
closerDelimiter.startIndex,
internalTokens,
nodePoints,
)
switch (balancedBracketsStatus) {
case -1:
return { paired: false, opener: false, closer: true }
case 0: {
// The closer delimiter should provide a valid link label, only in this
// way can it be connected with the opener delimiter to form a complete
// linkReference.
const bracket = closerDelimiter.brackets[0]
if (
bracket == null ||
bracket.identifier == null ||
!api.hasDefinition(bracket.identifier)
) {
return { paired: false, opener: false, closer: false }
}
return { paired: true }
}
case 1: {
return { paired: false, opener: true, closer: false }
}
}
}
function processDelimiterPair(
openerDelimiter: IDelimiter,
closerDelimiter: IDelimiter,
internalTokens: ReadonlyArray<IYastInlineToken>,
): IResultOfProcessDelimiterPair<T, IToken, IDelimiter> {
const tokens: IToken[] = processSingleDelimiter(openerDelimiter)
/**
* Shortcut link reference cannot following with a link label
* (even though it is not defined).
* @see https://github.github.com/gfm/#example-579
*/
const [bracket, ...brackets] = closerDelimiter.brackets
tokens.push({
nodeType: LinkReferenceType,
startIndex: openerDelimiter.endIndex - 1,
endIndex: bracket.endIndex,
referenceType: 'full',
label: bracket.label!,
identifier: bracket.identifier!,
children: api.resolveInternalTokens(
internalTokens,
openerDelimiter.endIndex,
closerDelimiter.startIndex,
),
})
return {
tokens,
remainCloserDelimiter: {
type: closerDelimiter.type === 'both' ? 'opener' : 'full',
startIndex: bracket.endIndex,
endIndex: closerDelimiter.endIndex,
brackets,
},
}
}
/**
* Shortcut link reference cannot following with a link label
* (even though it is not defined).
* @see https://github.github.com/gfm/#example-579
*/
function processSingleDelimiter(
delimiter: IDelimiter,
): IResultOfProcessSingleDelimiter<T, IToken> {
const tokens: IToken[] = []
const brackets = delimiter.brackets
if (brackets.length <= 0) return tokens
let bracketIndex = 0
let lastBracketIndex = -1
for (; bracketIndex < brackets.length; ++bracketIndex) {
let bracket: ILinkReferenceDelimiterBracket | null = null
for (; bracketIndex < brackets.length; ++bracketIndex) {
bracket = brackets[bracketIndex]
if (bracket.identifier != null && api.hasDefinition(bracket.identifier)) break
}
if (bracket == null || bracketIndex >= brackets.length) break
// full
if (lastBracketIndex + 1 < bracketIndex) {
const bracket0 = brackets[bracketIndex - 1]
tokens.push({
nodeType: LinkReferenceType,
startIndex: bracket0.startIndex,
endIndex: bracket.endIndex,
referenceType: 'full',
label: bracket.label!,
identifier: bracket.identifier!,
children: api.resolveInternalTokens([], bracket0.startIndex + 1, bracket0.endIndex - 1),
})
lastBracketIndex = bracketIndex
continue
}
// shortcut
if (bracketIndex + 1 === brackets.length) {
tokens.push({
nodeType: LinkReferenceType,
startIndex: bracket.startIndex,
endIndex: bracket.endIndex,
referenceType: 'shortcut',
label: bracket.label!,
identifier: bracket.identifier!,
children: api.resolveInternalTokens([], bracket.startIndex + 1, bracket.endIndex - 1),
})
break
}
// collapsed
if (bracketIndex + 1 < brackets.length && brackets[bracketIndex + 1].identifier == null) {
const bracket1 = brackets[bracketIndex + 1]
tokens.push({
nodeType: LinkReferenceType,
startIndex: bracket.startIndex,
endIndex: bracket1.endIndex,
referenceType: 'collapsed',
label: bracket.label!,
identifier: bracket.identifier!,
children: api.resolveInternalTokens([], bracket.startIndex + 1, bracket.endIndex - 1),
})
break
}
}
return tokens
}
} | the_stack |
import test from 'tape'
import BN from 'bn.js'
import { LocalAddress, CryptoUtils } from '../../index'
import { createTestClient, waitForMillisecondsAsync, createWeb3TestClient, rejectOnTimeOut } from '../helpers'
import { LoomProvider } from '../../loom-provider'
import { deployContract } from '../evm-helpers'
import { ecrecover, privateToPublic, fromRpcSig } from 'ethereumjs-util'
import { soliditySha3 } from '../../solidity-helpers'
import { bytesToHexAddr } from '../../crypto-utils'
import Web3 from 'web3'
import { AbiItem } from 'web3-utils';
import { ContractSendMethod, Contract } from 'web3-eth-contract'
import { PromiEvent, TransactionReceipt } from "web3-core"
import { Client, ClientEvent } from "../../client"
import { debug } from "console"
/**
* Requires the SimpleStore solidity contract deployed on a loomchain.
* go-loom/examples/plugins/evmexample/contract/SimpleStore.sol
*
* pragma solidity ^0.4.22;
*
* contract SimpleStore {
* uint value;
* constructor() public {
* value = 10;
* }
*
* event NewValueSet(uint indexed _value);
*
* function set(uint _value) public {
* value = _value;
* emit NewValueSet(value);
* }
*
* function get() public view returns (uint) {
* return value;
* }
* }
*
*
*/
const newContractAndClient = async (useEthEndpoint: boolean) => {
const privKey = CryptoUtils.generatePrivateKey()
const client = useEthEndpoint ? createWeb3TestClient() : createTestClient()
const from = LocalAddress.fromPublicKey(CryptoUtils.publicKeyFromPrivateKey(privKey)).toString()
const loomProvider = new LoomProvider(client, privKey)
const web3 = new Web3(loomProvider)
web3.eth.transactionConfirmationBlocks = 3
client.on('error', console.log)
const contractData =
'0x608060405234801561001057600080fd5b50600a60008190555061010e806100286000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60d9565b6040518082815260200191505060405180910390f35b806000819055506000547fb922f092a64f1a076de6f21e4d7c6400b6e55791cc935e7bb8e7e90f7652f15b60405160405180910390a250565b600080549050905600a165627a7a72305820b76f6c855a1f95260fc70490b16774074225da52ea165a58e95eb7a72a59d1700029'
const ABI = [
{
constant: false,
inputs: [{ name: '_value', type: 'uint256' }],
name: 'set',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'get',
outputs: [{ name: '', type: 'uint256' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{ inputs: [], payable: false, stateMutability: 'nonpayable', type: 'constructor' },
{
anonymous: false,
inputs: [{ indexed: true, name: '_value', type: 'uint256' }],
name: 'NewValueSet',
type: 'event'
}
]
const result = await deployContract(loomProvider, contractData)
const contract = new web3.eth.Contract(ABI as AbiItem[], result.contractAddress, { from })
return { contract, client, web3, from, privKey }
}
async function testWeb3MismatchedTopic(t: test.Test, useEthEndpoint: boolean) {
let contract: Contract, client, from
// Time to wait until assuming unrleated event has effectively not been emitted
const waitMs = 10000
const newValue = 1
try {
({ contract, client, from } = await newContractAndClient(useEthEndpoint))
const wrongTopicPromise = new Promise((resolve) =>
contract.events.NewValueSet({ filter: { _value: [4, 5] } }, resolve)
)
contract.methods.set(newValue).send({ from })
await Promise.all([
rejectOnTimeOut(wrongTopicPromise, waitMs)
.then(() => t.fail("Wrong Topic listener should not be triggered"))
.catch(() => t.pass("Wrong topic listener not triggered within ms" + waitMs)),
])
} catch (err) {
t.error(err)
} finally {
if (client) {
client.disconnect()
}
t.end()
}
}
async function testWeb3MultipleTopics(t: test.Test, useEthEndpoint: boolean) {
t.timeoutAfter(20000)
const newValue = 1
const { contract, client, from } = await newContractAndClient(useEthEndpoint)
// contract.transactionConfirmationBlocks = 3
// contract.transactionBlockTimeout = 3
const assertions = new Promise((resolve, reject) => {
contract.events.NewValueSet(
{ filter: { _value: [1, 2, 3] } },
async (err: Error, event: any) => {
t.error(err, "contract.events.NewValueSet should not fail")
t.equal(+event.returnValues._value, newValue, `Return value should be ${newValue}`)
const resultOfGet: any = await contract.methods.get().call()
t.equal(+resultOfGet, newValue, `SimpleStore.get should return correct value`)
resolve(true)
})
})
const txHash = new Promise(async (resolve, rej) => {
const set: ContractSendMethod = contract.methods.set(newValue)
set.send({ from })
.on("transactionHash", (hash: string) => {
t.pass("contract.methods.set emits transactionHash")
resolve(hash)
})
// // for some reason this is never called
// // https://github.com/ChainSafe/web3.js/issues/2837#issuecomment-498838831
// .on("receipt", (hash: TransactionReceipt) => {
// t.pass("receipt")
// })
})
try {
await Promise.all([txHash, assertions])
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3Sign(t: any, useEthEndpoint: boolean) {
const { client, web3, from, privKey } = await newContractAndClient(useEthEndpoint)
try {
const msg = '0xff'
const result = await web3.eth.sign(msg, from)
// Checking the ecrecover
const hash = soliditySha3('\x19Ethereum Signed Message:\n32', msg).slice(2)
const { r, s, v } = fromRpcSig(result)
const pubKey = ecrecover(Buffer.from(hash, 'hex'), v, r, s)
const privateHash = soliditySha3(privKey).slice(2)
t.equal(
bytesToHexAddr(pubKey),
bytesToHexAddr(privateToPublic(Buffer.from(privateHash, 'hex'))),
'Should pubKey from ecrecover be valid'
)
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3NetId(t: any, useEthEndpoint: boolean) {
const { client, web3 } = await newContractAndClient(useEthEndpoint)
try {
const chainIdHash = soliditySha3(client.chainId)
.slice(2)
.slice(0, 13)
const netVersionFromChainId = new BN(chainIdHash).toNumber()
const result = await web3.eth.net.getId()
t.equal(`${netVersionFromChainId}`, `${result}`, 'Should version match')
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3BlockNumber(t: any, useEthEndpoint: boolean) {
const { client, web3 } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await web3.eth.getBlockNumber()
t.assert(typeof blockNumber === 'number', 'Block number should be a number')
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3BlockByNumber(t: any, useEthEndpoint: boolean) {
const { client, web3 } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await web3.eth.getBlockNumber()
const blockInfo = await web3.eth.getBlock(blockNumber, false)
t.equal(blockInfo.number, blockNumber, 'Block number should be equal')
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3BlockByHash(t: test.Test, useEthEndpoint: boolean) {
t.timeoutAfter(30000)
const { client, web3 } = await newContractAndClient(useEthEndpoint)
try {
const blockNumber = await web3.eth.getBlockNumber()
const blockInfo = await web3.eth.getBlock(blockNumber, false)
const blockInfoByHash = await web3.eth.getBlock(blockInfo.hash, false)
t.assert(blockInfoByHash, 'Should return block info by hash')
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3GasPrice(t: test.Test, useEthEndpoint: boolean) {
const { client, web3 } = await newContractAndClient(useEthEndpoint)
try {
const gasPrice = await web3.eth.getGasPrice()
t.equal(gasPrice, null, "Gas price isn't used on Loomchain")
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3Balance(t: any, useEthEndpoint: boolean) {
const { client, web3, from } = await newContractAndClient(useEthEndpoint)
try {
const balance = await web3.eth.getBalance(from)
t.equal(balance, '0', 'Default balance is 0')
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3TransactionReceipt(t: test.Test, useEthEndpoint: boolean) {
t.timeoutAfter(60 * 1000)
const { contract, client, from, web3 } = await newContractAndClient(useEthEndpoint)
let error
try {
const newValue = 1
const set = contract.methods.set(newValue) as ContractSendMethod
const txHash: string = await new Promise<string>((resolve, reject) => {
set.send({ from })
.on('transactionHash', resolve)
.on('error', reject)
});
waitForMillisecondsAsync(3000)
const receipt = await web3.eth.getTransactionReceipt(txHash);
// TODO: there is no blockTime property in tx.events.NewValueSet, it's a Loom extension that's
// not implemented on the /eth endpoint yet, re-enable this when we implement it again
if (!useEthEndpoint) {
// @ts-ignore
t.assert(receipt.logs[0].blockTime > 0, 'blockTime should be greater than 0')
}
t.ok(receipt.logs[0].blockHash, 'blockHash should be greater than 0')
t.equal(receipt.status, true, 'SimpleStore.set should return correct status')
} catch (err) {
t.error(error, "Unexpected errors")
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3PastEvents(t: test.Test, useEthEndpoint: boolean) {
const { contract, client, web3, from } = await newContractAndClient(useEthEndpoint)
t.timeoutAfter(20000)
try {
const newValue = 1
const blockNum = await web3.eth.getBlockNumber()
const txHash = await new Promise(async (resolve, reject) => {
contract.methods.set(newValue).send({ from })
.on("transactionHash", resolve)
.on("error", reject)
})
await waitForMillisecondsAsync(5000)
const events = await contract.getPastEvents('NewValueSet', {
fromBlock: blockNum
})
t.assert(events.length > 0, 'Should have more than 0 events')
// TODO: there is no blockTime property on Ethereum events, it's a Loom extension that's
// not implemented on the /eth endpoint yet, re-enable this when we implement it again
if (!useEthEndpoint) {
// @ts-ignore
t.assert(events[0].blockTime > 0, 'blockTime should be greater than 0')
}
} catch (err) {
t.error(err, "Unexpected error")
} finally {
client.disconnect()
t.end()
}
}
async function testWeb3GetStorageAt(t: any, useEthEndpoint: boolean) {
const { client, web3, contract } = await newContractAndClient(useEthEndpoint)
try {
const storageValue = await web3.eth.getStorageAt(contract.options.address, 0x0, 'latest')
t.equal(
storageValue,
'0x000000000000000000000000000000000000000000000000000000000000000a',
'Storage value at 0x0 for contract SimpleStore'
)
} catch (err) {
t.error(err)
} finally {
client.disconnect()
t.end()
}
}
test('LoomProvider + Web3 + Event with not matching topic (/query)', (t: test.Test) =>
testWeb3MismatchedTopic(t, false))
// test('LoomProvider + Web3 + Event with not matching topic (/eth)', (t: any) =>
// testWeb3MismatchedTopic(t, true))
test('LoomProvider + Web3 + Multiple event topics (/query)', (t: any) =>
testWeb3MultipleTopics(t, false))
// test('LoomProvider + Web3 + Multiple event topics (/eth)', (t: any) =>
// testWeb3MultipleTopics(t, true))
test('LoomProvider + Web3 + Eth Sign (/query)', (t: any) => testWeb3Sign(t, false))
test('LoomProvider + Web3 + Eth Sign (/eth)', (t: any) => testWeb3Sign(t, true))
test('LoomProvider + Web3 + Get version (/query)', (t: any) => testWeb3NetId(t, false))
test('LoomProvider + Web3 + Get version (/eth)', (t: any) => testWeb3NetId(t, true))
test('LoomProvider + Web3 + getBlockNumber (/query)', (t: any) => testWeb3BlockNumber(t, false))
test('LoomProvider + Web3 + getBlockNumber (/eth)', (t: any) => testWeb3BlockNumber(t, true))
test('LoomProvider + Web3 + getBlockByNumber (/query)', (t: any) =>
testWeb3BlockByNumber(t, false))
test('LoomProvider + Web3 + getBlockByNumber (/eth)', (t: any) => testWeb3BlockByNumber(t, true))
// test('LoomProvider + Web3 + getBlock by hash (/query)', (t: any) => testWeb3BlockByHash(t, false))
test('LoomProvider + Web3 + getBlock by hash (/eth)', (t: any) => testWeb3BlockByHash(t, true))
test('LoomProvider + Web3 + getGasPrice (/query)', (t: any) => testWeb3GasPrice(t, false))
test('LoomProvider + Web3 + getGasPrice (/eth)', (t: any) => testWeb3GasPrice(t, true))
test('LoomProvider + Web3 + getBalance (/query)', (t: any) => testWeb3Balance(t, false))
test('LoomProvider + Web3 + getBalance (/eth)', (t: any) => testWeb3Balance(t, true))
test('LoomProvider + Web3 + getTransactionReceipt (/query)', (t: any) =>
testWeb3TransactionReceipt(t, false))
test('LoomProvider + Web3 + getTransactionReceipt (/eth)', (t) =>
testWeb3TransactionReceipt(t, true))
test('LoomProvider + Web3 + Logs (/query)', (t: any) => testWeb3PastEvents(t, false))
// test('LoomProvider + Web3 + Logs (/eth)', (t: any) => testWeb3PastEvents(t, true))
test('LoomProvider + Web3 + getStorageAt (/eth)', (t: any) => testWeb3GetStorageAt(t, true)) | the_stack |
"use strict";
require("es6-promise").polyfill();
try {
// optional
require("source-map-support").install();
} catch (e) {
}
import * as updateNotifier from "update-notifier";
let pkg = require("../package.json");
let notifier = updateNotifier({
packageName: pkg.name,
packageVersion: pkg.version
});
if (notifier.update) {
notifier.notify();
}
import * as dtsm from "./";
import * as pmb from "packagemanager-backend";
import * as is from "./incrementalsearch";
import * as commandpost from "commandpost";
import * as archy from "archy";
interface RootOptions {
offline: boolean;
config: string[];
remote: string[];
insight: string[];
ref: string[];
}
let root = commandpost
.create<RootOptions, {}>("dtsm")
.version(pkg.version, "-v, --version")
.option("--insight <use>", "send usage opt in/out. in = `--insight true`, out = `--insight false`")
.option("--offline", "offline first")
.option("--remote <uri>", "uri of remote repository")
.option("--config <path>", "path to json file")
.option("--ref <ref>", "ref of repository")
.action(() => {
process.stdout.write(root.helpText() + '\n');
});
root
.subCommand("init")
.description("make new dtsm.json")
.action(() => {
setup(root.parsedOpts)
.then(manager => {
let jsonContent = manager.init();
console.log("write to " + manager.configPath);
console.log(jsonContent);
})
.catch(errorHandler);
});
interface SearchOptions {
raw: boolean;
interactive: boolean;
}
interface SearchArguments {
phrase: string;
}
root
.subCommand<SearchOptions, SearchArguments>("search [phrase]")
.description("search .d.ts files")
.option("--raw", "output search result by raw format")
.option("-i, --interactive", "do incremental searching. use `peco` default")
.action((opts, args) => {
setup(root.parsedOpts)
.then(manager => {
return manager.search(args.phrase || "");
})
.then(resultList => {
if (!opts.interactive) {
return Promise.resolve(resultList);
}
let candidates = resultList.map(result => result.fileInfo.path);
if (candidates.length === 0) {
return Promise.resolve(resultList);
}
return is
.exec(candidates, [args.phrase], "peco")
.then(selected => {
return selected
.map(path => {
return resultList.filter(result => result.fileInfo.path === path)[0];
})
.filter(result => !!result);
});
})
.then(resultList => {
if (opts.raw) {
resultList.forEach(result => {
console.log(result.fileInfo.path);
});
} else {
if (resultList.length === 0) {
console.log("No results.");
} else {
console.log("Search results.");
console.log("");
resultList.forEach(result => {
console.log("\t" + result.fileInfo.path);
});
}
}
})
.catch(errorHandler);
});
root
.subCommand("fetch")
.description("fetch all data from remote repos")
.action(() => {
setup(root.parsedOpts)
.then(manager => {
process.stdout.write("fetching...\n");
return manager.fetch();
})
.catch(errorHandler);
});
interface InstallOptions {
save: boolean;
dryRun: boolean;
interactive: boolean;
}
interface InstallArguments {
files: string[];
}
root
.subCommand<InstallOptions, InstallArguments>("install [files...]")
.description("install .d.ts files")
.option("-S, --save", "save .d.ts file path into dtsm.json")
.option("--dry-run", "save .d.ts file path into dtsm.json")
.option("-i, --interactive", "do incremental searching. use `peco` default")
.action((opts, args) => {
// .action((...targets:string[])=> {
setup(root.parsedOpts)
.then(manager => {
if (!opts.interactive && args.files.length === 0) {
return manager.installFromFile({ dryRun: opts.dryRun })
.then(result => printResult(result))
.then(() => manager.link({ dryRun: opts.dryRun }))
.then(result => printLinkResult(result));
} else if (opts.interactive || args.files.length === 0) {
return manager.search("")
.then(resultList => {
let candidates = resultList.map(result => result.fileInfo.path);
if (candidates.length === 0) {
return Promise.resolve(resultList);
}
return is
.exec(candidates, args.files, "peco")
.then(selected => {
return selected
.map(path => {
return resultList.filter(result => result.fileInfo.path === path)[0];
})
.filter(result => !!result);
});
})
.then(resultList => {
let files = resultList.map(result => result.fileInfo.path);
return manager.install({ save: opts.save, dryRun: opts.dryRun }, files)
.then(result => printResult(result));
});
} else {
return manager.install({ save: opts.save, dryRun: opts.dryRun }, args.files)
.then(result => printResult(result));
}
})
.catch(errorHandler);
});
interface UninstallOptions {
save: boolean;
dryRun: boolean;
}
interface UninstallArguments {
files: string[];
}
root
.subCommand<InstallOptions, InstallArguments>("uninstall [files...]")
.description("uninstall .d.ts files")
.option("-S, --save", "save .d.ts file path into dtsm.json")
.option("--dry-run", "save .d.ts file path into dtsm.json")
.action((opts, args) => {
// .action((...targets:string[])=> {
setup(root.parsedOpts)
.then(manager => {
return manager.uninstall({ save: opts.save, dryRun: opts.dryRun }, args.files);
})
.then(resultList => resultList.forEach(dep => console.log(dep.depName)))
.catch(errorHandler);
});
interface UpdateOptions {
save: boolean;
dryRun: boolean;
}
root
.subCommand<UpdateOptions, {}>("update")
.description("update definition files version")
.option("-S, --save", "save updated ref into dtsm.json")
.option("--dry-run", "save .d.ts file path into dtsm.json")
.action((opts, args) => {
setup(root.parsedOpts)
.then(manager => {
return manager.update({ save: opts.save, dryRun: opts.dryRun });
})
.then(result => printResult(result))
.catch(errorHandler);
});
interface LinkOptions {
save: boolean;
dryRun: boolean;
}
root
.subCommand<LinkOptions, {}>("link")
.description("link to npm or bower dependencies")
.option("-S, --save", "save updated ref into dtsm.json")
.option("--dry-run", "save .d.ts file path into dtsm.json")
.action((opts, args) => {
setup(root.parsedOpts)
.then(manager => {
return manager.link({ save: opts.save, dryRun: opts.dryRun });
})
.then(result => printLinkResult(result))
.catch(errorHandler);
});
root
.subCommand<{}, {}>("refs")
.description("show refs, it can use with --ref option")
.action((opts, args) => {
setup(root.parsedOpts)
.then(manager => manager.refs())
.then(refs => {
refs = refs.filter(ref => {
// ignore github pull refs
if (ref.name.indexOf("refs/pull/") === 0) {
return false;
}
return true;
});
let branches = refs.filter(ref => ref.name.indexOf("refs/heads/") === 0);
let tags = refs.filter(ref => ref.name.indexOf("refs/tags/") === 0);
if (branches.length !== 0) {
console.log("Branches:");
branches.forEach(ref => {
let branchName = ref.name.substr("refs/heads/".length);
console.log("\t", branchName);
});
console.log("");
}
if (tags.length !== 0) {
console.log("Tags:");
tags.forEach(ref => {
let tagName = ref.name.substr("refs/tags/".length);
console.log("\t", tagName);
});
console.log("");
}
})
.catch(errorHandler);
});
commandpost
.exec(root, process.argv)
.catch(errorHandler);
function setup(opts: RootOptions): Promise<dtsm.Manager> {
"use strict";
let offline = opts.offline;
let configPath: string = opts.config[0];
let remoteUri: string = opts.remote[0];
let specifiedRef: string = opts.ref[0];
let insightStr = opts.insight[0];
let insightOptout: boolean;
if (typeof insightStr === "string") {
if (insightStr !== "true" && insightStr !== "false") {
return Promise.reject<dtsm.Manager>("--insight options required \"true\" or \"false\"");
} else if (insightStr === "true") {
insightOptout = false; // inverse
} else {
insightOptout = true; // inverse
}
}
let repos: pmb.RepositorySpec[] = [];
if (remoteUri || specifiedRef) {
repos.push({
url: remoteUri,
ref: specifiedRef
});
}
let options: dtsm.Options = {
configPath: configPath || "dtsm.json",
repos: repos,
offline: offline,
insightOptout: insightOptout
};
return dtsm
.createManager(options)
.then(manager => {
return manager.tracker
.askPermissionIfNeeded()
.then(() => manager);
});
}
function printResolvedDependency(dep: pmb.ResolvedDependency, opts: { emitRepo: boolean; emitHost: boolean; }) {
"use strict";
let fileInfo = (dep: pmb.ResolvedDependency) => {
if (!!dep.parent && dep.parent.repo === dep.repo && dep.parent.ref === dep.ref) {
// emit only root node
return "";
}
let result = "";
if (opts.emitRepo && opts.emitHost) {
if (dep.repoInstance.urlInfo) {
result += dep.repoInstance.urlInfo.hostname;
} else if (dep.repoInstance.sshInfo) {
result += dep.repoInstance.sshInfo.hostname;
}
}
if (opts.emitRepo) {
let path: string;
if (dep.repoInstance.urlInfo) {
path = dep.repoInstance.urlInfo.pathname;
} else if (dep.repoInstance.sshInfo) {
path = dep.repoInstance.sshInfo.path;
}
let hasExt = /\.git$/.test(path);
if (!opts.emitHost) {
path = path.substr(1);
}
if (hasExt) {
path = path.substr(0, path.length - 4);
}
result += path;
}
result += "#" + dep.fileInfo.ref.substr(0, 6);
return " " + result;
};
let resultTree = (dep: pmb.ResolvedDependency, data?: archy.Data) => {
let d: archy.Data = {
label: dep.depName,
nodes: []
};
if (!!data) {
data.nodes.push(d);
}
d.label += fileInfo(dep);
Object.keys(dep.dependencies).forEach(depName => {
resultTree(dep.dependencies[depName], d);
});
if (!data) {
return archy(d);
}
return null;
};
let output = resultTree(dep);
console.log(output);
}
function printResult(result: pmb.Result) {
"use strict";
// short is justice.
let emitRepo = 1 < result.manager.repos.length;
let emitHost = result.manager.repos.filter(repo => {
if (!!repo.urlInfo) {
return repo.urlInfo.host !== "github.com";
} else if (!!repo.sshInfo) {
return repo.sshInfo.hostname !== "github.com";
} else {
return true;
}
}).length !== 0;
Object.keys(result.dependencies).forEach(depName => {
let dep = result.dependencies[depName];
printResolvedDependency(dep, { emitRepo: emitRepo, emitHost: emitHost });
});
}
function printLinkResult(resultList: dtsm.LinkResult[]) {
"use strict";
["npm", "bower"].forEach(managerName => {
let npmList = resultList.filter(result => result.managerName === managerName);
if (npmList.length !== 0) {
let d: archy.Data = {
label: `from ${managerName} dependencies`,
nodes: npmList.map(dep => {
return {
label: dep.depName,
nodes: dep.files
};
})
};
console.log(archy(d));
}
});
}
function errorHandler(err: any) {
"use strict";
if (err instanceof Error) {
console.error(err.stack);
} else {
console.error(err);
}
return Promise.resolve(null).then(() => {
process.exit(1);
});
} | the_stack |
import * as am5 from "@amcharts/amcharts5";
import * as am5map from "@amcharts/amcharts5/map";
import am5geodata_worldLow from "@amcharts/amcharts5/geodata/worldLow";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
const root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create the map chart
// https://www.amcharts.com/docs/v5/charts/map-chart/
const chart = root.container.children.push(am5map.MapChart.new(root, {
panX: "rotateX",
panY: "rotateY",
projection: am5map.geoOrthographic()
}));
// Create series for background fill
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/#Background_polygon
const backgroundSeries = chart.series.push(
am5map.MapPolygonSeries.new(root, {})
);
backgroundSeries.mapPolygons.template.setAll({
fill: root.interfaceColors.get("alternativeBackground"),
fillOpacity: 0.1,
strokeOpacity: 0
});
backgroundSeries.data.push({
geometry:
am5map.getGeoRectangle(90, 180, -90, -180)
});
// Create main polygon series for countries
// https://www.amcharts.com/docs/v5/charts/map-chart/map-polygon-series/
const polygonSeries = chart.series.push(am5map.MapPolygonSeries.new(root, {
geoJSON: am5geodata_worldLow as any
}));
polygonSeries.mapPolygons.template.setAll({
fill: root.interfaceColors.get("alternativeBackground"),
fillOpacity: 0.15,
strokeWidth: 0.5,
stroke: root.interfaceColors.get("background")
});
// Create polygon series for projected circles
const circleSeries = chart.series.push(am5map.MapPolygonSeries.new(root, {}));
circleSeries.mapPolygons.template.setAll({
templateField: "polygonTemplate",
tooltipText: "{name}: {value}"
});
// Define data
const colors = am5.ColorSet.new(root, {});
const data = [
{ "id": "AF", "name": "Afghanistan", "value": 32358260, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "AL", "name": "Albania", "value": 3215988, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "DZ", "name": "Algeria", "value": 35980193, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "AO", "name": "Angola", "value": 19618432, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "AR", "name": "Argentina", "value": 40764561, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "AM", "name": "Armenia", "value": 3100236, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "AU", "name": "Australia", "value": 22605732, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "AT", "name": "Austria", "value": 8413429, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "AZ", "name": "Azerbaijan", "value": 9306023, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "BH", "name": "Bahrain", "value": 1323535, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "BD", "name": "Bangladesh", "value": 150493658, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "BY", "name": "Belarus", "value": 9559441, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "BE", "name": "Belgium", "value": 10754056, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "BJ", "name": "Benin", "value": 9099922, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "BT", "name": "Bhutan", "value": 738267, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "BO", "name": "Bolivia", "value": 10088108, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "BA", "name": "Bosnia and Herzegovina", "value": 3752228, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "BW", "name": "Botswana", "value": 2030738, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "BR", "name": "Brazil", "value": 196655014, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "BN", "name": "Brunei", "value": 405938, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "BG", "name": "Bulgaria", "value": 7446135, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "BF", "name": "Burkina Faso", "value": 16967845, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "BI", "name": "Burundi", "value": 8575172, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "KH", "name": "Cambodia", "value": 14305183, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "CM", "name": "Cameroon", "value": 20030362, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CA", "name": "Canada", "value": 34349561, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "CV", "name": "Cape Verde", "value": 500585, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CF", "name": "Central African Rep.", "value": 4486837, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "TD", "name": "Chad", "value": 11525496, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CL", "name": "Chile", "value": 17269525, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "CN", "name": "China", "value": 1347565324, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "CO", "name": "Colombia", "value": 46927125, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "KM", "name": "Comoros", "value": 753943, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CD", "name": "Congo, Dem. Rep.", "value": 67757577, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CG", "name": "Congo, Rep.", "value": 4139748, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "CR", "name": "Costa Rica", "value": 4726575, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "CI", "name": "Cote d'Ivoire", "value": 20152894, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "HR", "name": "Croatia", "value": 4395560, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "CU", "name": "Cuba", "value": 11253665, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "CY", "name": "Cyprus", "value": 1116564, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "CZ", "name": "Czech Rep.", "value": 10534293, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "DK", "name": "Denmark", "value": 5572594, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "DJ", "name": "Djibouti", "value": 905564, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "DO", "name": "Dominican Rep.", "value": 10056181, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "EC", "name": "Ecuador", "value": 14666055, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "EG", "name": "Egypt", "value": 82536770, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "SV", "name": "El Salvador", "value": 6227491, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "GQ", "name": "Equatorial Guinea", "value": 720213, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "ER", "name": "Eritrea", "value": 5415280, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "EE", "name": "Estonia", "value": 1340537, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "ET", "name": "Ethiopia", "value": 84734262, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "FJ", "name": "Fiji", "value": 868406, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "FI", "name": "Finland", "value": 5384770, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "FR", "name": "France", "value": 63125894, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "GA", "name": "Gabon", "value": 1534262, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "GM", "name": "Gambia", "value": 1776103, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "GE", "name": "Georgia", "value": 4329026, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "DE", "name": "Germany", "value": 82162512, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "GH", "name": "Ghana", "value": 24965816, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "GR", "name": "Greece", "value": 11390031, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "GT", "name": "Guatemala", "value": 14757316, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "GN", "name": "Guinea", "value": 10221808, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "GW", "name": "Guinea-Bissau", "value": 1547061, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "GY", "name": "Guyana", "value": 756040, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "HT", "name": "Haiti", "value": 10123787, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "HN", "name": "Honduras", "value": 7754687, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "HK", "name": "Hong Kong, China", "value": 7122187, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "HU", "name": "Hungary", "value": 9966116, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "IS", "name": "Iceland", "value": 324366, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "IN", "name": "India", "value": 1241491960, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "ID", "name": "Indonesia", "value": 242325638, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "IR", "name": "Iran", "value": 74798599, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "IQ", "name": "Iraq", "value": 32664942, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "IE", "name": "Ireland", "value": 4525802, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "IL", "name": "Israel", "value": 7562194, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "IT", "name": "Italy", "value": 60788694, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "JM", "name": "Jamaica", "value": 2751273, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "JP", "name": "Japan", "value": 126497241, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "JO", "name": "Jordan", "value": 6330169, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "KZ", "name": "Kazakhstan", "value": 16206750, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "KE", "name": "Kenya", "value": 41609728, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "KP", "name": "Korea, Dem. Rep.", "value": 24451285, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "KR", "name": "Korea, Rep.", "value": 48391343, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "KW", "name": "Kuwait", "value": 2818042, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "KG", "name": "Kyrgyzstan", "value": 5392580, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "LA", "name": "Laos", "value": 6288037, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "LV", "name": "Latvia", "value": 2243142, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "LB", "name": "Lebanon", "value": 4259405, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "LS", "name": "Lesotho", "value": 2193843, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "LR", "name": "Liberia", "value": 4128572, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "LY", "name": "Libya", "value": 6422772, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "LT", "name": "Lithuania", "value": 3307481, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "LU", "name": "Luxembourg", "value": 515941, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "MK", "name": "Macedonia, FYR", "value": 2063893, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "MG", "name": "Madagascar", "value": 21315135, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MW", "name": "Malawi", "value": 15380888, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MY", "name": "Malaysia", "value": 28859154, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "ML", "name": "Mali", "value": 15839538, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MR", "name": "Mauritania", "value": 3541540, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MU", "name": "Mauritius", "value": 1306593, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MX", "name": "Mexico", "value": 114793341, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "MD", "name": "Moldova", "value": 3544864, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "MN", "name": "Mongolia", "value": 2800114, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "ME", "name": "Montenegro", "value": 632261, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "MA", "name": "Morocco", "value": 32272974, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MZ", "name": "Mozambique", "value": 23929708, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "MM", "name": "Myanmar", "value": 48336763, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "NA", "name": "Namibia", "value": 2324004, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "NP", "name": "Nepal", "value": 30485798, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "NL", "name": "Netherlands", "value": 16664746, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "NZ", "name": "New Zealand", "value": 4414509, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "NI", "name": "Nicaragua", "value": 5869859, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "NE", "name": "Niger", "value": 16068994, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "NG", "name": "Nigeria", "value": 162470737, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "NO", "name": "Norway", "value": 4924848, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "OM", "name": "Oman", "value": 2846145, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "PK", "name": "Pakistan", "value": 176745364, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "PA", "name": "Panama", "value": 3571185, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "PG", "name": "Papua New Guinea", "value": 7013829, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "PY", "name": "Paraguay", "value": 6568290, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "PE", "name": "Peru", "value": 29399817, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "PH", "name": "Philippines", "value": 94852030, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "PL", "name": "Poland", "value": 38298949, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "PT", "name": "Portugal", "value": 10689663, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "PR", "name": "Puerto Rico", "value": 3745526, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "QA", "name": "Qatar", "value": 1870041, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "RO", "name": "Romania", "value": 21436495, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "RU", "name": "Russia", "value": 142835555, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "RW", "name": "Rwanda", "value": 10942950, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "SA", "name": "Saudi Arabia", "value": 28082541, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "SN", "name": "Senegal", "value": 12767556, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "RS", "name": "Serbia", "value": 9853969, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "SL", "name": "Sierra Leone", "value": 5997486, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "SG", "name": "Singapore", "value": 5187933, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "SK", "name": "Slovak Republic", "value": 5471502, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "SI", "name": "Slovenia", "value": 2035012, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "SB", "name": "Solomon Islands", "value": 552267, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "SO", "name": "Somalia", "value": 9556873, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "ZA", "name": "South Africa", "value": 50459978, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "ES", "name": "Spain", "value": 46454895, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "LK", "name": "Sri Lanka", "value": 21045394, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "SD", "name": "Sudan", "value": 34735288, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "SR", "name": "Suriname", "value": 529419, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "SZ", "name": "Swaziland", "value": 1203330, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "SE", "name": "Sweden", "value": 9440747, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "CH", "name": "Switzerland", "value": 7701690, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "SY", "name": "Syria", "value": 20766037, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "TW", "name": "Taiwan", "value": 23072000, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "TJ", "name": "Tajikistan", "value": 6976958, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "TZ", "name": "Tanzania", "value": 46218486, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "TH", "name": "Thailand", "value": 69518555, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "TG", "name": "Togo", "value": 6154813, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "TT", "name": "Trinidad and Tobago", "value": 1346350, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "TN", "name": "Tunisia", "value": 10594057, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "TR", "name": "Turkey", "value": 73639596, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "TM", "name": "Turkmenistan", "value": 5105301, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "UG", "name": "Uganda", "value": 34509205, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "UA", "name": "Ukraine", "value": 45190180, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "AE", "name": "United Arab Emirates", "value": 7890924, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "GB", "name": "United Kingdom", "value": 62417431, polygonTemplate: { fill: colors.getIndex(8) } },
{ "id": "US", "name": "United States", "value": 313085380, polygonTemplate: { fill: colors.getIndex(4) } },
{ "id": "UY", "name": "Uruguay", "value": 3380008, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "UZ", "name": "Uzbekistan", "value": 27760267, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "VE", "name": "Venezuela", "value": 29436891, polygonTemplate: { fill: colors.getIndex(3) } },
{ "id": "PS", "name": "West Bank and Gaza", "value": 4152369, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "VN", "name": "Vietnam", "value": 88791996, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "YE", "name": "Yemen, Rep.", "value": 24799880, polygonTemplate: { fill: colors.getIndex(0) } },
{ "id": "ZM", "name": "Zambia", "value": 13474959, polygonTemplate: { fill: colors.getIndex(2) } },
{ "id": "ZW", "name": "Zimbabwe", "value": 12754378, polygonTemplate: { fill: colors.getIndex(2) } }
];
let valueLow = Infinity;
let valueHigh = -Infinity;
for (let i = 0; i < data.length; i++) {
let value = data[i].value;
if (value < valueLow) {
valueLow = value;
}
if (value > valueHigh) {
valueHigh = value;
}
}
// radius in degrees
const minRadius = 0.5;
const maxRadius = 5;
// Create circles when data for countries is fully loaded.
polygonSeries.events.on("datavalidated", () => {
circleSeries.data.clear();
for (let i = 0; i < data.length; i++) {
const dataContext = data[i];
const countryDataItem = polygonSeries.getDataItemById(dataContext.id);
const countryPolygon = countryDataItem.get("mapPolygon");
const value = dataContext.value;
const radius = minRadius + maxRadius * (value - valueLow) / (valueHigh - valueLow);
if (countryPolygon) {
const geometry = am5map.getGeoCircle(countryPolygon.visualCentroid(), radius);
circleSeries.data.push({
name: dataContext.name,
value: dataContext.value,
polygonTemplate: dataContext.polygonTemplate,
geometry: geometry
});
}
}
})
// Make stuff animate on load
chart.appear(1000, 100); | the_stack |
import { Subject, Observable, Subscription } from 'rxjs';
import { IPC, Subscription as IPCSubscription } from '../../../../services/service.electron.ipc';
import { ControllerSessionTabSearch } from '../search/controller.session.tab.search';
import {
FilterRequest,
IFilterUpdateEvent,
} from '../search/dependencies/filters/controller.session.tab.search.filters.storage';
import { ControllerSessionTabStream } from '../stream/controller.session.tab.stream';
import { IPositionData } from '../output/controller.session.tab.stream.output';
import { Lock } from '../../../helpers/lock';
import { Dependency, SessionGetter } from '../session.dependency';
import ServiceElectronIpc from '../../../../services/service.electron.ipc';
import * as Toolkit from 'chipmunk.client.toolkit';
export interface IMapPoint {
column: number;
position: number;
color: string;
description: string;
reg?: string;
regs?: string[];
}
export interface IMapState {
count: number;
position: number;
rowsInView: number;
}
export interface IControllerSessionTabMap {
guid: string;
search: ControllerSessionTabSearch;
stream: ControllerSessionTabStream;
}
export interface IColumn {
guid: string;
description: string;
search: boolean;
index: number;
}
export interface IMap {
points: IMapPoint[];
columns: number;
}
const CSettings = {
columnWideWidth: 16,
columnNarroweWidth: 8,
minMarkerHeight: 1,
};
export class ControllerSessionTabMap implements Dependency {
public static SearchResultMapRequestDelay: number = 250;
private _guid: string;
private _logger: Toolkit.Logger;
private _state: IMapState = {
count: 0,
position: 0,
rowsInView: 0,
};
private _subscriptions: { [key: string]: IPCSubscription | Subscription } = {};
private _expanded: boolean = false;
private _width: number = CSettings.columnNarroweWidth;
private _cached: {
src: IPC.ISearchResultMapData | undefined;
map: IMap;
pending: {
scale: number;
expanded: boolean;
timer: any;
requested: number;
progress: boolean;
};
} = {
src: undefined,
map: { points: [], columns: 0 },
pending: {
progress: false,
scale: -1,
expanded: false,
timer: -1,
requested: -1,
},
};
private _lock: Lock = new Lock();
private _subjects: {
onStateUpdate: Subject<IMapState>;
onPositionUpdate: Subject<IMapState>;
onRepaint: Subject<void>;
onRepainted: Subject<void>;
onRestyle: Subject<FilterRequest>;
onMapRecalculated: Subject<IMap>;
} = {
onStateUpdate: new Subject(),
onPositionUpdate: new Subject(),
onRepaint: new Subject(),
onRepainted: new Subject(),
onRestyle: new Subject(),
onMapRecalculated: new Subject(),
};
private _session: SessionGetter;
constructor(uuid: string, getter: SessionGetter) {
this._guid = uuid;
this._logger = new Toolkit.Logger(`ControllerSessionTabMap: ${this._guid}`);
this._session = getter;
}
public init(): Promise<void> {
return new Promise((resolve, reject) => {
this._subscriptions.SearchResultMapUpdated = ServiceElectronIpc.subscribe(
IPC.SearchResultMapUpdated,
this._ipc_SearchResultMapUpdated.bind(this),
);
this._subscriptions.StreamUpdated = ServiceElectronIpc.subscribe(
IPC.StreamUpdated,
this._ipc_onStreamUpdated.bind(this),
);
this._subscriptions.onSearchDropped = this._session()
.getSessionSearch()
.getFiltersAPI()
.getObservable()
.dropped.subscribe(this._onSearchDropped.bind(this));
this._subscriptions.onSearchStarted = this._session()
.getSessionSearch()
.getFiltersAPI()
.getObservable()
.searching.subscribe(this._onSearchStarted.bind(this));
this._subscriptions.onPositionChanged = this._session()
.getStreamOutput()
.getObservable()
.onPositionChanged.subscribe(this._onPositionChanged.bind(this));
this._subscriptions.onFiltersStyleUpdate = this._session()
.getSessionSearch()
.getFiltersAPI()
.getStorage()
.getObservable()
.changed.subscribe(this._onFiltersStyleUpdate.bind(this));
resolve();
});
}
public destroy(): Promise<void> {
return new Promise((resolve, reject) => {
clearTimeout(this._cached.pending.timer);
Object.keys(this._subscriptions).forEach((key: string) => {
this._subscriptions[key].unsubscribe();
});
resolve();
});
}
public getName(): string {
return 'ControllerSessionTabMap';
}
public getGuid(): string {
return this._guid;
}
public getState(): IMapState {
return this._state;
}
public getStreamLength(): number {
return this._session().getStreamOutput().getRowsCount();
}
public getObservable(): {
onStateUpdate: Observable<IMapState>;
onPositionUpdate: Observable<IMapState>;
onRepaint: Observable<void>;
onRepainted: Observable<void>;
onRestyle: Observable<FilterRequest>;
onMapRecalculated: Observable<IMap>;
} {
return {
onStateUpdate: this._subjects.onStateUpdate.asObservable(),
onPositionUpdate: this._subjects.onPositionUpdate.asObservable(),
onRepaint: this._subjects.onRepaint.asObservable(),
onRepainted: this._subjects.onRepainted.asObservable(),
onRestyle: this._subjects.onRestyle.asObservable(),
onMapRecalculated: this._subjects.onMapRecalculated.asObservable(),
};
}
public toggleColumnWidth() {
this._width = this.isColumnsWide()
? CSettings.columnNarroweWidth
: CSettings.columnWideWidth;
}
public repainted() {
this._subjects.onRepainted.next();
}
public isExpanded(): boolean {
return this._expanded;
}
public expanding() {
this._expanded = !this._expanded;
if (this._cached.src !== undefined) {
this._cached.map = this._extractMap(this._expanded, this._cached.src.map);
}
}
public getSettings(): {
columnWideWidth: number;
columnNarroweWidth: number;
minMarkerHeight: number;
} {
return CSettings;
}
public isColumnsWide(): boolean {
return this._width === CSettings.columnWideWidth;
}
public getColumnWidth(): number {
return this._width;
}
public requestMapCalculation(scale: number, force: boolean) {
const request = () => {
this._cached.pending.progress = true;
const expandedReq = this._cached.pending.expanded;
ServiceElectronIpc.request<IPC.SearchResultMapResponse>(
new IPC.SearchResultMapRequest({
streamId: this._guid,
scale: this._cached.pending.scale,
details: expandedReq,
}),
IPC.SearchResultMapResponse,
)
.then((response) => {
this._cached.src = response.getData();
this._cached.map = this._extractMap(expandedReq, this._cached.src.map);
this._subjects.onMapRecalculated.next({
points: this._cached.map.points,
columns: this._cached.map.columns,
});
this._cached.pending.progress = false;
if (this._cached.pending.scale !== -1) {
// While IPC message was in progress we get new request.
this.requestMapCalculation(this._cached.pending.scale, false);
}
})
.catch((err: Error) => {
this._logger.warn(`Fail delivery search result map due error: ${err.message}`);
});
this._cached.pending.requested = -1;
this._cached.pending.scale = -1;
};
if (this._cached.pending.requested === -1) {
this._cached.pending.requested = Date.now();
}
this._cached.pending.scale = scale;
this._cached.pending.expanded = this._expanded;
if (this._cached.pending.progress) {
return;
}
clearTimeout(this._cached.pending.timer);
const timeout: number = Date.now() - this._cached.pending.requested;
if (timeout > ControllerSessionTabMap.SearchResultMapRequestDelay || force) {
request();
} else {
this._cached.pending.timer = setTimeout(() => {
request();
}, timeout);
}
}
public getMatchesMap(
scale: number,
range: { begin: number; end: number },
): Promise<{
[key: number]: {
[key: string]: number;
};
}> {
return new Promise((resolve, reject) => {
ServiceElectronIpc.request<IPC.SearchResultMapResponse>(
new IPC.SearchResultMapRequest({
streamId: this._guid,
scale: scale,
range: range,
details: true,
}),
IPC.SearchResultMapResponse,
)
.then((response) => {
resolve(response.getData().map);
})
.catch((err: Error) => {
reject(
new Error(
this._logger.warn(
`Fail delivery search result map due error: ${err.message}`,
),
),
);
});
});
}
private _extractMap(
expanded: boolean,
scaled: { [key: number]: { [key: string]: number } },
): IMap {
function max(matches: { [match: string]: number }): string {
let v: number = 0;
let n: string = '';
Object.keys(matches).forEach((key: string) => {
if (v < matches[key]) {
v = matches[key];
n = key;
}
});
return n;
}
const results: IMap = {
points: [],
columns: 0,
};
const map: { [key: string]: FilterRequest } = {};
this._session()
.getSessionSearch()
.getFiltersAPI()
.getStorage()
.get()
.forEach((request: FilterRequest) => {
map[request.asDesc().request] = request;
});
let column: number = 0;
if (expanded) {
// Expanded
const columns: { [key: string]: number } = {};
Object.keys(scaled).forEach((position: number | string) => {
const matches: { [match: string]: number } = (scaled as any)[position];
Object.keys(matches).forEach((match: string) => {
if (columns[match] === undefined) {
columns[match] = column;
column += 1;
}
const point: IMapPoint = {
position: typeof position === 'number' ? position : parseInt(position, 10),
color:
map[match] === undefined
? ''
: map[match].getBackground() !== ''
? map[match].getBackground()
: map[match].getColor(),
column: columns[match],
description: match,
reg: match,
regs: [match],
};
results.points.push(point);
});
});
results.columns = column;
} else {
// Single
Object.keys(scaled).forEach((position: number | string) => {
const matches: { [match: string]: number } = (scaled as any)[position];
const hotest: string = max(matches);
if (hotest !== '') {
const all: string[] = Object.keys(matches);
const point: IMapPoint = {
position: typeof position === 'number' ? position : parseInt(position, 10),
color:
map[hotest] === undefined
? ''
: map[hotest].getBackground() !== ''
? map[hotest].getBackground()
: map[hotest].getColor(),
column: 0,
description: all.join(', '),
reg: hotest,
regs: all,
};
results.points.push(point);
}
});
results.columns = 1;
}
return results;
}
private _onFiltersStyleUpdate(event: IFilterUpdateEvent) {
if (!event.updated.colors) {
return;
}
this._subjects.onRestyle.next(event.filter);
}
private _onSearchDropped() {
// Lock update workflow
this._lock.lock();
// Trigger event
this._saveTriggerStateUpdate();
}
private _onSearchStarted() {
// Unlock update workflow
this._lock.unlock();
}
private _onPositionChanged(position: IPositionData) {
this._state.position = position.start;
this._state.rowsInView = position.count;
// Trigger event
this._subjects.onPositionUpdate.next(this._state);
}
private _saveTriggerStateUpdate() {
this._subjects.onStateUpdate.next({
count: this._state.count,
position: this._state.position,
rowsInView: this._state.rowsInView,
});
}
private _ipc_SearchResultMapUpdated(message: IPC.SearchResultMapUpdated) {
this._saveTriggerStateUpdate();
}
private _ipc_onStreamUpdated(message: IPC.StreamUpdated) {
if (message.guid !== this._guid) {
return;
}
this._state.count = message.rowsCount;
this._saveTriggerStateUpdate();
}
} | the_stack |
import * as server from 'vscode-languageserver';
import * as im from 'immutable';
import * as lexical from '../lexical';
import * as tree from './tree';
export interface Visitor {
visit(): void
}
export abstract class VisitorBase implements Visitor {
protected rootObject: tree.Node | null = null;
constructor(
protected rootNode: tree.Node,
private parent: tree.Node | null = null,
private env: tree.Environment = tree.emptyEnvironment,
) {}
public visit = () => {
this.visitHelper(this.rootNode, this.parent, this.env);
}
protected visitHelper = (
node: tree.Node, parent: tree.Node | null, currEnv: tree.Environment
): void => {
if (node == null) {
throw Error("INTERNAL ERROR: Can't visit a null node");
}
this.previsit(node, parent, currEnv);
switch(node.type) {
case "CommentNode": {
this.visitComment(<tree.Comment>node);
return;
}
case "CompSpecNode": {
const castedNode = <tree.CompSpec>node;
this.visitCompSpec(castedNode);
castedNode.varName && this.visitHelper(castedNode.varName, castedNode, currEnv);
this.visitHelper(castedNode.expr, castedNode, currEnv);
return;
}
case "ApplyNode": {
const castedNode = <tree.Apply>node;
this.visitApply(castedNode);
this.visitHelper(castedNode.target, castedNode, currEnv);
castedNode.args.forEach((arg: tree.Node) => {
this.visitHelper(arg, castedNode, currEnv);
});
return;
}
case "ApplyBraceNode": {
const castedNode = <tree.ApplyBrace>node;
this.visitApplyBrace(castedNode);
this.visitHelper(castedNode.left, castedNode, currEnv);
this.visitHelper(castedNode.right, castedNode, currEnv);
return;
}
case "ApplyParamAssignmentNode": {
const castedNode = <tree.ApplyParamAssignment>node;
this.visitApplyParamAssignmentNode(castedNode);
this.visitHelper(castedNode.right, castedNode, currEnv);
return;
}
case "ArrayNode": {
const castedNode = <tree.Array>node;
this.visitArray(castedNode);
castedNode.headingComment && this.visitHelper(
castedNode.headingComment, castedNode, currEnv);
castedNode.elements.forEach((e: tree.Node) => {
this.visitHelper(e, castedNode, currEnv);
});
castedNode.trailingComment && this.visitHelper(
castedNode.trailingComment, castedNode, currEnv);
return;
}
case "ArrayCompNode": {
const castedNode = <tree.ArrayComp>node;
this.visitArrayComp(castedNode);
this.visitHelper(castedNode.body, castedNode, currEnv);
castedNode.specs.forEach((spec: tree.CompSpec) =>
this.visitHelper(spec, castedNode, currEnv));
return;
}
case "AssertNode": {
const castedNode = <tree.Assert>node;
this.visitAssert(castedNode);
this.visitHelper(castedNode.cond, castedNode, currEnv);
castedNode.message && this.visitHelper(
castedNode.message, castedNode, currEnv);
this.visitHelper(castedNode.rest, castedNode, currEnv);
return;
}
case "BinaryNode": {
const castedNode = <tree.Binary>node;
this.visitBinary(castedNode);
this.visitHelper(castedNode.left, castedNode, currEnv);
this.visitHelper(castedNode.right, castedNode, currEnv);
return;
}
case "BuiltinNode": {
const castedNode = <tree.Builtin>node;
this.visitBuiltin(castedNode);
return;
}
case "ConditionalNode": {
const castedNode = <tree.Conditional>node;
this.visitConditional(castedNode);
this.visitHelper(castedNode.cond, castedNode, currEnv);
this.visitHelper(castedNode.branchTrue, castedNode, currEnv);
castedNode.branchFalse && this.visitHelper(
castedNode.branchFalse, castedNode, currEnv);
return;
}
case "DollarNode": {
const castedNode = <tree.Dollar>node;
this.visitDollar(castedNode);
return;
}
case "ErrorNode": {
const castedNode = <tree.ErrorNode>node;
this.visitError(castedNode);
this.visitHelper(castedNode.expr, castedNode, currEnv);
return;
}
case "FunctionNode": {
const castedNode = <tree.Function>node;
this.visitFunction(castedNode);
if (castedNode.headingComment != null) {
this.visitHelper(castedNode.headingComment, castedNode, currEnv);
}
// Add params to environment before visiting body.
const envWithParams = currEnv.merge(
tree.envFromParams(castedNode.parameters));
castedNode.parameters.forEach((param: tree.FunctionParam) => {
this.visitHelper(param, castedNode, envWithParams);
});
// Visit body.
this.visitHelper(castedNode.body, castedNode, envWithParams);
castedNode.trailingComment.forEach((comment: tree.Comment) => {
// NOTE: Using `currEnv` instead of `envWithparams`.
this.visitHelper(comment, castedNode, currEnv);
});
return;
}
case "FunctionParamNode": {
const castedNode = <tree.FunctionParam>node;
castedNode.defaultValue && this.visitHelper(
castedNode.defaultValue, castedNode, currEnv);
return;
}
case "IdentifierNode": {
this.visitIdentifier(<tree.Identifier>node);
return;
}
case "ImportNode": {
this.visitImport(<tree.Import>node);
return;
}
case "ImportStrNode": {
this.visitImportStr(<tree.ImportStr>node);
return;
}
case "IndexNode": {
const castedNode = <tree.Index>node;
this.visitIndex(castedNode);
castedNode.id != null && this.visitHelper(castedNode.id, castedNode, currEnv);
castedNode.target != null && this.visitHelper(
castedNode.target, castedNode, currEnv);
castedNode.index != null && this.visitHelper(
castedNode.index, castedNode, currEnv);
return;
}
case "LocalBindNode": {
const castedNode = <tree.LocalBind>node;
this.visitLocalBind(<tree.LocalBind>node);
// NOTE: If `functionSugar` is false, the params will be
// empty.
const envWithParams = currEnv.merge(
tree.envFromParams(castedNode.params));
castedNode.params.forEach((param: tree.FunctionParam) => {
this.visitHelper(param, castedNode, envWithParams)
});
this.visitHelper(castedNode.body, castedNode, envWithParams);
return;
}
case "LocalNode": {
const castedNode = <tree.Local>node;
this.visitLocal(castedNode);
// NOTE: The binds of a `local` are in scope for both the
// binds themselves, as well as the body of the `local`.
const envWithBinds = currEnv.merge(tree.envFromLocalBinds(castedNode));
castedNode.env = envWithBinds;
castedNode.binds.forEach((bind: tree.LocalBind) => {
this.visitHelper(bind, castedNode, envWithBinds);
});
this.visitHelper(castedNode.body, castedNode, envWithBinds);
return;
}
case "LiteralBooleanNode": {
const castedNode = <tree.LiteralBoolean>node;
this.visitLiteralBoolean(castedNode);
return;
}
case "LiteralNullNode": {
const castedNode = <tree.LiteralNull>node;
this.visitLiteralNull(castedNode);
return;
}
case "LiteralNumberNode": { return this.visitLiteralNumber(<tree.LiteralNumber>node); }
case "LiteralStringNode": {
const castedNode = <tree.LiteralString>node;
this.visitLiteralString(castedNode);
return;
}
case "ObjectFieldNode": {
const castedNode = <tree.ObjectField>node;
this.visitObjectField(castedNode);
// NOTE: If `methodSugar` is false, the params will be empty.
let envWithParams = currEnv.merge(tree.envFromParams(castedNode.ids));
castedNode.id != null && this.visitHelper(
castedNode.id, castedNode, envWithParams);
castedNode.expr1 != null && this.visitHelper(
castedNode.expr1, castedNode, envWithParams);
castedNode.ids.forEach((param: tree.FunctionParam) => {
this.visitHelper(param, castedNode, envWithParams);
});
castedNode.expr2 != null && this.visitHelper(
castedNode.expr2, castedNode, envWithParams);
castedNode.expr3 != null && this.visitHelper(
castedNode.expr3, castedNode, envWithParams);
if (castedNode.headingComments != null) {
this.visitHelper(castedNode.headingComments, castedNode, currEnv);
}
return;
}
case "ObjectNode": {
const castedNode = <tree.ObjectNode>node;
if (this.rootObject == null) {
this.rootObject = castedNode;
castedNode.rootObject = castedNode;
}
this.visitObject(castedNode);
// `local` object fields are scoped with order-independence,
// so something like this is legal:
//
// {
// bar: {baz: foo},
// local foo = 3,
// }
//
// Since this case requires `foo` to be in the environment of
// `bar`'s body, we here collect up the `local` fields first,
// create a new environment that includes them, and pass that
// on to each field we visit.
const envWithLocals = currEnv.merge(
tree.envFromFields(castedNode.fields));
castedNode.fields.forEach((field: tree.ObjectField) => {
// NOTE: If this is a `local` field, there is no need to
// remove current field from environment. It is perfectly
// legal to do something like `local foo = foo; foo` (though
// it will cause a stack overflow).
this.visitHelper(field, castedNode, envWithLocals);
});
return;
}
case "DesugaredObjectFieldNode": {
const castedNode = <tree.DesugaredObjectField>node;
this.visitDesugaredObjectField(castedNode);
this.visitHelper(castedNode.name, castedNode, currEnv);
this.visitHelper(castedNode.body, castedNode, currEnv);
return;
}
case "DesugaredObjectNode": {
const castedNode = <tree.DesugaredObject>node;
this.visitDesugaredObject(castedNode);
castedNode.asserts.forEach((a: tree.Assert) => {
this.visitHelper(a, castedNode, currEnv);
});
castedNode.fields.forEach((field: tree.DesugaredObjectField) => {
this.visitHelper(field, castedNode, currEnv);
});
return;
}
case "ObjectCompNode": {
const castedNode = <tree.ObjectComp>node;
this.visitObjectComp(castedNode);
castedNode.specs.forEach((spec: tree.CompSpec) => {
this.visitHelper(spec, castedNode, currEnv);
});
castedNode.fields.forEach((field: tree.ObjectField) => {
this.visitHelper(field, castedNode, currEnv);
});
return;
}
case "ObjectComprehensionSimpleNode": {
const castedNode = <tree.ObjectComprehensionSimple>node;
this.visitObjectComprehensionSimple(castedNode);
this.visitHelper(castedNode.id, castedNode, currEnv);
this.visitHelper(castedNode.field, castedNode, currEnv);
this.visitHelper(castedNode.value, castedNode, currEnv);
this.visitHelper(castedNode.array, castedNode, currEnv);
return;
}
case "SelfNode": {
const castedNode = <tree.Self>node;
this.visitSelf(castedNode);
return;
}
case "SuperIndexNode": {
const castedNode = <tree.SuperIndex>node;
this.visitSuperIndex(castedNode);
castedNode.index && this.visitHelper(castedNode.index, castedNode, currEnv);
castedNode.id && this.visitHelper(castedNode.id, castedNode, currEnv);
return;
}
case "UnaryNode": {
const castedNode = <tree.Unary>node;
this.visitUnary(castedNode);
this.visitHelper(castedNode.expr, castedNode, currEnv);
return;
}
case "VarNode": {
const castedNode = <tree.Var>node;
this.visitVar(castedNode);
castedNode.id != null && this.visitHelper(castedNode.id, castedNode, currEnv);
return
}
default: throw new Error(
`Visitor could not traverse tree; unknown node type '${node.type}'`);
}
}
protected previsit = (
node: tree.Node, parent: tree.Node | null, currEnv: tree.Environment
): void => {}
protected visitComment = (node: tree.Comment): void => {}
protected visitCompSpec = (node: tree.CompSpec): void => {}
protected visitApply = (node: tree.Apply): void => {}
protected visitApplyBrace = (node: tree.ApplyBrace): void => {}
protected visitApplyParamAssignmentNode = (node: tree.ApplyParamAssignment): void => {}
protected visitArray = (node: tree.Array): void => {}
protected visitArrayComp = (node: tree.ArrayComp): void => {}
protected visitAssert = (node: tree.Assert): void => {}
protected visitBinary = (node: tree.Binary): void => {}
protected visitBuiltin = (node: tree.Builtin): void => {}
protected visitConditional = (node: tree.Conditional): void => {}
protected visitDollar = (node: tree.Dollar): void => {}
protected visitError = (node: tree.ErrorNode): void => {}
protected visitFunction = (node: tree.Function): void => {}
protected visitIdentifier = (node: tree.Identifier): void => {}
protected visitImport = (node: tree.Import): void => {}
protected visitImportStr = (node: tree.ImportStr): void => {}
protected visitIndex = (node: tree.Index): void => {}
protected visitLocalBind = (node: tree.LocalBind): void => {}
protected visitLocal = (node: tree.Local): void => {}
protected visitLiteralBoolean = (node: tree.LiteralBoolean): void => {}
protected visitLiteralNull = (node: tree.LiteralNull): void => {}
protected visitLiteralNumber = (node: tree.LiteralNumber): void => {}
protected visitLiteralString = (node: tree.LiteralString): void => {}
protected visitObjectField = (node: tree.ObjectField): void => {}
protected visitObject = (node: tree.ObjectNode): void => {}
protected visitDesugaredObjectField = (node: tree.DesugaredObjectField): void => {}
protected visitDesugaredObject = (node: tree.DesugaredObject): void => {}
protected visitObjectComp = (node: tree.ObjectComp): void => {}
protected visitObjectComprehensionSimple = (node: tree.ObjectComprehensionSimple): void => {}
protected visitSelf = (node: tree.Self): void => {}
protected visitSuperIndex = (node: tree.SuperIndex): void => {}
protected visitUnary = (node: tree.Unary): void => {}
protected visitVar = (node: tree.Var): void => {}
}
// ----------------------------------------------------------------------------
// Initializing visitor.
// ----------------------------------------------------------------------------
// InitializingVisitor initializes an AST by populating the `parent`
// and `env` values in every node.
export class InitializingVisitor extends VisitorBase {
protected previsit = (
node: tree.Node, parent: tree.Node | null, currEnv: tree.Environment
): void => {
node.parent = parent;
node.env = currEnv;
node.rootObject = this.rootObject;
}
}
// ----------------------------------------------------------------------------
// Cursor visitor.
// ----------------------------------------------------------------------------
// FindFailure represents a failure find a node whose range wraps a
// cursor location.
export type FindFailure = AnalyzableFindFailure | UnanalyzableFindFailure;
export const isFindFailure = (thing): thing is FindFailure => {
return thing instanceof UnanalyzableFindFailure ||
thing instanceof AnalyzableFindFailure;
}
export type FindFailureKind =
"BeforeDocStart" | "AfterDocEnd" | "AfterLineEnd" | "NotIdentifier";
// AnalyzableFindFailure represents a failure to find a node whose
// range wraps a cursor location, but which is amenable to static
// analysis.
//
// In particular, this means that the cursor lies in the range of the
// document's AST, and it is therefore possible to inspect the AST
// surrounding the cursor.
export class AnalyzableFindFailure {
// IMPLEMENTATION NOTES: Currently we consider the kind
// `"AfterDocEnd"` to be unanalyzable, but as our static analysis
// features become more featureful, we can probably revisit this
// corner case and get better results in the general case.
constructor(
public readonly kind: "AfterLineEnd" | "NotIdentifier",
public readonly tightestEnclosingNode: tree.Node,
public readonly terminalNodeOnCursorLine: tree.Node | null,
) {}
}
export const isAnalyzableFindFailure = (
thing
): thing is AnalyzableFindFailure => {
return thing instanceof AnalyzableFindFailure;
}
// UnanalyzableFindFailrue represents a failure to find a node whose
// range wraps a cursor location, and is not amenable to static
// analysis.
//
// In particular, this means that the cursor lies outside of the range
// of a document's AST, which means we cannot inspect the context of
// where the cursor lies in an AST.
export class UnanalyzableFindFailure {
constructor(public readonly kind: "BeforeDocStart" | "AfterDocEnd") {}
}
export const isUnanalyzableFindFailure = (
thing
): thing is UnanalyzableFindFailure => {
return thing instanceof UnanalyzableFindFailure;
}
// CursorVisitor finds a node whose range some cursor lies in, or the
// closest node to it.
export class CursorVisitor extends VisitorBase {
// IMPLEMENTATION NOTES: The goal of this class is to map the corner
// cases into `ast.Node | FindFailure`. Broadly, this mapping falls
// into a few cases:
//
// * Cursor in the range of an identifier.
// * Return the identifier.
// * Cursor in the range of a node that is not an identifier (e.g.,
// number literal, multi-line object with no members, and so on).
// * Return a find failure with kind `"NotIdentifier"`.
// * Cursor lies inside document range, the last node on the line
// of the cursor ends before the cursor's position.
// * Return find failure with kind `"AfterLineEnd"`.
// * Cursor lies outside document range.
// * Return find failure with kind `"BeforeDocStart"` or
// `"AfterDocEnd"`.
constructor(
private cursor: lexical.Location,
root: tree.Node,
) {
super(root);
this.terminalNode = root;
}
// Identifier whose range encloses the cursor, if there is one. This
// can be a multi-line node (e.g., perhaps an empty object), or a
// single line node (e.g., a number literal).
private enclosingNode: tree.Node | null = null;
// Last node in the tree.
private terminalNode: tree.Node;
// Last node in the line our cursor lies on, if there is one.
private terminalNodeOnCursorLine: tree.Node | null = null;
get nodeAtPosition(): tree.Identifier | FindFailure {
if (this.enclosingNode == null) {
if (this.cursor.strictlyBeforeRange(this.rootNode.loc)) {
return new UnanalyzableFindFailure("BeforeDocStart");
} else if (this.cursor.strictlyAfterRange(this.terminalNode.loc)) {
return new UnanalyzableFindFailure("AfterDocEnd");
}
throw new Error(
"INTERNAL ERROR: No wrapping identifier was found, but node didn't lie outside of document range");
} else if (!tree.isIdentifier(this.enclosingNode)) {
if (
this.terminalNodeOnCursorLine != null &&
this.cursor.strictlyAfterRange(this.terminalNodeOnCursorLine.loc)
) {
return new AnalyzableFindFailure(
"AfterLineEnd", this.enclosingNode, this.terminalNodeOnCursorLine);
}
return new AnalyzableFindFailure(
"NotIdentifier", this.enclosingNode, this.terminalNodeOnCursorLine);
}
return this.enclosingNode;
}
protected previsit = (
node: tree.Node, parent: tree.Node | null, currEnv: tree.Environment,
): void => {
const nodeEnd = node.loc.end;
if (this.cursor.inRange(node.loc)) {
if (
this.enclosingNode == null ||
node.loc.rangeIsTighter(this.enclosingNode.loc)
) {
this.enclosingNode = node;
}
}
if (nodeEnd.afterRangeOrEqual(this.terminalNode.loc)) {
this.terminalNode = node;
}
if (nodeEnd.line === this.cursor.line) {
if (this.terminalNodeOnCursorLine == null) {
this.terminalNodeOnCursorLine = node;
} else if (nodeEnd.afterRangeOrEqual(this.terminalNodeOnCursorLine.loc)) {
this.terminalNodeOnCursorLine = node;
}
}
}
}
// nodeRangeIsCloser checks whether `thisNode` is closer to `pos` than
// `thatNode`.
//
// NOTE: Function currently works for expressions that are on one
// line.
const nodeRangeIsCloser = (
pos: lexical.Location, thisNode: tree.Node, thatNode: tree.Node
): boolean => {
const thisLoc = thisNode.loc;
const thatLoc = thatNode.loc;
if (thisLoc.begin.line == pos.line && thisLoc.end.line == pos.line) {
if (thatLoc.begin.line == pos.line && thatLoc.end.line == pos.line) {
// `thisNode` and `thatNode` lie on the same line, and
// `thisNode` begins closer to the position.
//
// NOTE: We use <= here so that we always choose the last node
// that begins at a point. For example, a `Var` and `Identifier`
// might begin in the same place, but we'd like to choose the
// `Identifier`, as it would be a child of the `Var`.
return Math.abs(thisLoc.begin.column - pos.column) <=
Math.abs(thatLoc.begin.column - pos.column)
} else {
return true;
}
}
return false;
} | the_stack |
import { Camera } from "@itwin/core-common";
import { IModelConnection, Viewport } from "@itwin/core-frontend";
import { Angle, AngleProps, Point3d, Vector3d, XYZProps } from "@itwin/core-geometry";
import { createButton, createTextBox } from "@itwin/frontend-devtools";
import { DtaRpcInterface } from "../common/DtaRpcInterface";
import { ToolBarDropDown } from "./ToolBar";
interface KeyframeProps {
time: number;
location: XYZProps;
target: XYZProps;
up: XYZProps;
lensAngle: AngleProps | undefined;
extents: XYZProps | undefined;
}
class Keyframe {
/// Position in time (ms) of the keyframe
public time: number;
/// Location of the camera
public location: Point3d;
/// Point to look at
public target: Point3d;
/// Up vector
public up: Vector3d;
/// Lens angle, undefined for ortho camera
public lensAngle: Angle | undefined;
/// View extent, undefined for perspective camera
public extents: Vector3d | undefined;
constructor(time: number, location: Point3d, target: Point3d, up: Vector3d, lensAngle: Angle | undefined, extents: Vector3d | undefined) {
this.time = time;
this.location = location;
this.target = target;
this.up = up;
this.lensAngle = lensAngle;
this.extents = extents;
}
public clone(): Keyframe {
return new Keyframe(
this.time,
this.location.clone(),
this.target.clone(),
this.up.clone(),
this.lensAngle?.clone(),
this.extents?.clone()
);
}
public static createZero(): Keyframe {
return new Keyframe(0, Point3d.createZero(), Point3d.createZero(), Vector3d.createZero(), undefined, undefined);
}
/**
* Perform linear interpolation of the keyframe with another keyframe.
*/
public interpolate(fraction: number, other: Keyframe): Keyframe {
let lensAngle;
if (this.lensAngle === undefined) {
lensAngle = other.lensAngle;
} else {
lensAngle = other.lensAngle !== undefined ? Angle.createInterpolate(this.lensAngle, fraction, other.lensAngle) : this.lensAngle;
}
let extent;
if (this.extents === undefined) {
extent = other.extents;
} else {
extent = other.extents !== undefined ? this.extents.interpolate(fraction, other.extents) : other.extents;
}
return new Keyframe(
this.time + fraction * (other.time - this.time),
this.location.interpolate(fraction, other.location),
this.target.interpolate(fraction, other.target),
this.up.interpolate(fraction, other.up),
lensAngle,
extent,
);
}
public static fromJSON(json?: KeyframeProps): Keyframe {
if (!json)
return Keyframe.createZero();
return new Keyframe(
json.time,
Point3d.fromJSON(json.location),
Point3d.fromJSON(json.target),
Vector3d.fromJSON(json.up),
json.lensAngle !== undefined ? Angle.fromJSON(json.lensAngle) : undefined,
json.extents !== undefined ? Vector3d.fromJSON(json.extents) : undefined);
}
public toJSON(): KeyframeProps {
return {
time: this.time,
location: this.location.toJSON(),
target: this.target.toJSON(),
up: this.up.toJSON(),
lensAngle: this.lensAngle?.toJSON(),
extents: this.extents?.toJSON(),
};
}
}
interface CameraPathProps {
name: string;
duration: number;
keyframes: Array<KeyframeProps>;
}
class CameraPath {
public name: string;
public duration: number;
private _keyframes = new Array<Keyframe>();
public get keyframes() {
return this._keyframes;
}
constructor(name: string, duration: number, keyframes?: Array<Keyframe>) {
this.name = name;
this.duration = duration;
if (!!keyframes) {
this._keyframes = keyframes;
this.sortKeyframes();
}
}
public clone(): CameraPath {
return new CameraPath(this.name, this.duration, this.keyframes.map((keyframe) => keyframe.clone()));
}
public static createEmpty(): CameraPath {
return new CameraPath("", 0, []);
}
/**
* Ensure that keyframes are sorted by time
*/
public sortKeyframes() {
this.keyframes.sort((a, b) => a.time - b.time);
}
/**
* Remove keyframes that can be reconstructed with interpolation within the given error range.
*/
public simplifies(distanceThreshold: number, lensAngleThreshold: Angle, extentThreshold: number): void {
let i = 1;
while (i < this.keyframes.length - 1) {
const [before, current, after] = this.keyframes.slice(i - 1, i + 2);
const fraction = (current.time - before.time) / (after.time - before.time);
const interpolated = before.interpolate(fraction, after);
// Check if the distances between the reconstructed keyframe and the original is acceptable
const sameCameraType = (interpolated.lensAngle === undefined) === (current.lensAngle === undefined);
const locationDistance = interpolated.location.distance(current.location);
const targetDistance = interpolated.target.distance(current.target);
const lensAngleDistance = (interpolated.lensAngle === undefined || !sameCameraType) ? 0 : Math.abs(interpolated.lensAngle.degrees - current.lensAngle!.degrees);
const extentDistance = (interpolated.extents !== undefined && current.extents !== undefined) ? interpolated.extents.distance(current.extents) : 0;
if (sameCameraType
&& locationDistance < distanceThreshold
&& targetDistance < distanceThreshold
&& lensAngleDistance < lensAngleThreshold.degrees
&& extentDistance < extentThreshold) {
this.keyframes.splice(i, 1);
} else {
i++;
}
}
}
/**
* Get the interpolated keyframe at a given time in the path.
* @param time In ms, the location in the timeline to get the keyframe at.
* @returns the interpolated keyframe.
*/
public getKeyframeAtTime(time: number): Keyframe {
const {before, after} = this.getKeyframeRangeAtTime(time);
// Only one keyframe, use it directly
if (after === undefined)
return before;
// Two keyframes: interpolate between them
const timeDifference = after.time - before.time;
const fraction = timeDifference !== 0 ? (time - before.time) / timeDifference : 0.0;
return before.interpolate(fraction, after);
}
/**
* Get the two closest keyframes to a given time in the path. One before, one after.
* @param time In ms, the location in the timeline to get the keyframe at.
* @returns an object with the keyframes. ``before`` will always be set, but ``after`` can be missing.
*/
private getKeyframeRangeAtTime(time: number): {before: Keyframe, after?: Keyframe} {
if (this.keyframes.length <= 0)
throw new Error("Selected path has no keyframes.");
// Only one keyframe or before first keyframe
if (this.keyframes.length === 1 || time < this.keyframes[0].time) {
return {before: this.keyframes[0]};
}
// Between two keyframes
for (let i = 1; i < this.keyframes.length; i++) {
if (time < this.keyframes[i].time)
return {before: this.keyframes[i - 1], after: this.keyframes[i]};
}
// After the last keyframe
return {before: this.keyframes[this.keyframes.length - 1]};
}
public static fromJSON(json?: CameraPathProps): CameraPath {
if (!json)
return CameraPath.createEmpty();
return new CameraPath(
json.name,
json.duration,
json.keyframes.map((keyframeProps) => Keyframe.fromJSON(keyframeProps))
);
}
public toJSON(): CameraPathProps {
return {
name: this.name,
duration: this.duration,
keyframes: this.keyframes.map((frame) => frame.toJSON()),
};
}
}
export class CameraPathsMenu extends ToolBarDropDown {
private readonly _element: HTMLElement;
private readonly _viewport: Viewport;
private _imodel: IModelConnection;
private _paths: Array<CameraPath>;
private _selectedPath?: CameraPath | undefined;
private _onStateChanged = () => {};
private _newPathName: string;
private _isPlaying: boolean;
private _isRecording: boolean;
private _animID: number;
private _previousAnimationFrame: number | undefined;
private _currentAnimationTime: number;
public get selectedPath(): CameraPath | undefined {
return this._selectedPath;
}
public set selectedPath(value: CameraPath | undefined) {
this._selectedPath = value;
this._onStateChanged();
}
public constructor(viewport: Viewport, parent: HTMLElement) {
super();
this._viewport = viewport;
this._imodel = viewport.iModel;
this._newPathName = "";
this._paths = [];
this._isPlaying = false;
this._isRecording = false;
this._animID = 0;
this._previousAnimationFrame = undefined;
this._currentAnimationTime = 0;
this._element = document.createElement("div");
this._element.className = "toolMenu";
this._element.style.display = "block";
this._element.style.width = "300px";
this._element.style.overflowX = "none";
parent.appendChild(this._element);
}
public get isOpen() { return "none" !== this._element.style.display; }
protected _open() { this._element.style.display = "block"; }
protected _close() { this._element.style.display = "none"; }
public override get onViewChanged(): Promise<void> | undefined {
if (this._imodel !== this._viewport.iModel) {
this._imodel = this._viewport.iModel;
return this.populate();
} else {
return undefined;
}
}
public async populate(): Promise<void> {
if (!this._viewport.iModel.isOpen)
return;
await this.loadPathsFromExternalFile();
await this.populateFromPathList();
}
private async populateFromPathList(): Promise<void> {
this.clearContent();
const pathNameTextBox = createTextBox({
id: "txt_pathName",
parent: this._element,
tooltip: "Name of new camera path to create",
keypresshandler: async (_tb, ev): Promise<void> => {
ev.stopPropagation();
if ("Enter" === ev.key) {
if (await this.appendNewPathToPathList())
await this.savePathsToExternalFile();
}
},
});
pathNameTextBox.div.style.marginLeft = pathNameTextBox.div.style.marginRight = "3px";
pathNameTextBox.textbox.size = 36;
pathNameTextBox.textbox.value = this._newPathName;
this._element.appendChild(document.createElement("hr"));
const pathsList = document.createElement("select");
// If only 1 entry in list, input becomes a combo box and can't select the view...
pathsList.size = 1 === this._paths.length ? 2 : Math.min(15, this._paths.length);
pathsList.style.width = "100%";
pathsList.style.display = 0 < this._paths.length ? "" : "none";
this._element.appendChild(pathsList);
this._element.onchange = () => this.selectedPath = pathsList.value ? this.findPath(pathsList.value) : undefined;
pathsList.addEventListener("keyup", async (ev) => {
if (ev.key === "Delete")
await this.deletePath();
});
for (const path of this._paths) {
const option = document.createElement("option");
option.value = option.innerText = path.name;
if (path.duration === 0 || path.keyframes.length === 0) {
option.style.color = "grey";
option.title = "This path is empty. Please use the record button to record it.";
}
pathsList.appendChild(option);
}
const buttonDiv = document.createElement("div");
buttonDiv.style.textAlign = "center";
const createPathButton = createButton({
parent: buttonDiv,
id: "btn_createCameraPath",
value: "Create",
handler: async () => {
if (await this.appendNewPathToPathList())
await this.savePathsToExternalFile();
},
tooltip: "Create a new camera path",
inline: true,
}).button;
const deletePathButton = createButton({
parent: buttonDiv,
id: "btn_deleteCameraPath",
value: "Delete",
handler: async () => {
if (await this.deletePath())
await this.savePathsToExternalFile();
},
tooltip: "Delete selected camera path",
inline: true,
}).button;
buttonDiv.appendChild(document.createElement("hr"));
const recordButton = createButton({
parent: buttonDiv,
id: "btn_recordCameraPath",
value: "Record",
handler: async () => this.play(true),
tooltip: "Record a camera path",
inline: true,
}).button;
const playButton = createButton({
parent: buttonDiv,
id: "btn_playCameraPath",
value: "Play",
handler: async () => this.play(false),
tooltip: "Play selected camera path",
inline: true,
}).button;
const stopButton = createButton({
parent: buttonDiv,
id: "btn_stopCameraPath",
value: "Stop",
handler: async () => this.stop(),
tooltip: "Stop running camera path",
inline: true,
}).button;
const setCreatePathButtonDisabled = () => {
const pathExist = this._paths.findIndex((path) => path.name === this._newPathName) !== -1;
const isPathNameValid = this._newPathName.length > 0 && !pathExist;
pathNameTextBox.textbox.style.color = isPathNameValid ? "" : "red";
createPathButton.disabled = !isPathNameValid;
};
pathNameTextBox.textbox.onkeyup = () => {
this._newPathName = pathNameTextBox.textbox.value;
setCreatePathButtonDisabled();
};
this._onStateChanged = () => {
if (this.selectedPath === undefined) {
playButton.disabled = recordButton.disabled = stopButton.disabled = deletePathButton.disabled = true;
pathsList.disabled = false;
} else {
const canRecord = this.selectedPath.duration === 0 || this.selectedPath.keyframes.length === 0;
playButton.disabled = this._isPlaying || canRecord;
recordButton.disabled = this._isPlaying || !canRecord;
stopButton.disabled = !this._isPlaying;
pathsList.disabled = this._isPlaying;
deletePathButton.disabled = false;
}
setCreatePathButtonDisabled();
};
this._onStateChanged();
this._element.appendChild(buttonDiv);
}
private clearContent(): void {
while (this._element.hasChildNodes())
this._element.removeChild(this._element.firstChild!);
this._onStateChanged = () => {};
}
private async deletePath(): Promise<boolean> {
if (this.selectedPath === undefined)
return false;
const index = this._paths.indexOf(this.selectedPath);
if (index > -1) {
this._paths.splice(index, 1);
this.selectedPath = undefined;
await this.populateFromPathList();
return true;
}
return false;
}
private async appendNewPathToPathList(): Promise<boolean> {
const pathExist = this._paths.findIndex((path) => path.name === this._newPathName) !== -1;
if (this._newPathName.length > 0 && !pathExist) {
this._paths.push(CameraPath.createEmpty());
this.selectedPath = this._paths[this._paths.length - 1];
this.selectedPath.name = this._newPathName;
this._newPathName = "";
await this.populateFromPathList();
return true;
}
return false;
}
private async loadPathsFromExternalFile() {
const filename = this._viewport.view.iModel.key;
const externalCameraPathsString = await DtaRpcInterface.getClient().readExternalCameraPaths(filename);
try {
this._paths = JSON.parse(externalCameraPathsString).map((path: CameraPathProps) => CameraPath.fromJSON(path));
} catch (_e) {
this._paths = [];
}
}
private async savePathsToExternalFile(): Promise<void> {
const filename = this._viewport.view.iModel.key;
if (undefined === filename)
return;
const namedViews = JSON.stringify(this._paths.map((path) => path.toJSON()));
await DtaRpcInterface.getClient().writeExternalCameraPaths(filename, namedViews);
}
private findPath(name: string): CameraPath | undefined {
const index = this._paths.findIndex((path) => name === path.name);
return -1 !== index ? this._paths[index]! : undefined;
}
public prepareView(record = false): void {
if (!this.selectedPath)
throw new Error("No valid camera path loaded");
this._viewport.setAnimator(undefined);
if (!record) {
// This line prevents a bug that occurs in orthographic views if no camera has been set before.
// If not using a perspective camera, it will be turned off at the first frame.
this._viewport.turnCameraOn();
}
this._viewport.synchWithView();
}
public play(record = false): void {
if (this._isPlaying)
this.stop();
this._previousAnimationFrame = undefined;
this._currentAnimationTime = 0;
if (this.selectedPath === undefined)
return;
this.selectedPath.sortKeyframes();
const animate = (timestamp: number) => {
const elapsed = this._previousAnimationFrame ? timestamp - this._previousAnimationFrame : 0;
this._currentAnimationTime += elapsed;
this.computeAnimationFrame();
this._previousAnimationFrame = timestamp;
if (this._isPlaying)
this._animID = requestAnimationFrame(animate);
};
this.prepareView(record);
this._animID = requestAnimationFrame(animate);
this._isPlaying = true;
this._isRecording = record;
this._onStateChanged();
}
public stop(): void {
if (this._animID) {
cancelAnimationFrame(this._animID);
}
// End of recording
if (this._isPlaying && this._isRecording) {
if (!this.selectedPath)
throw new Error("No valid camera path loaded");
this.selectedPath.duration = this._currentAnimationTime;
// Remove keyframes that we can easily interpolate with a decent error range
this.selectedPath.simplifies(0.005, Angle.createDegrees(1.0), 0.01);
void this.savePathsToExternalFile();
void this.populateFromPathList();
}
this._animID = 0;
this._isPlaying = false;
this._isRecording = false;
this._currentAnimationTime = 0;
this._previousAnimationFrame = undefined;
this._onStateChanged();
}
private computeAnimationFrame(): void {
if (!this.selectedPath) {
this.endAnimation();
return;
}
if (this._isRecording) {
this.recordAnimationFrame();
} else {
this.playAnimationFrame();
if (this._currentAnimationTime > this.selectedPath.duration)
this.endAnimation();
}
}
private playAnimationFrame(): void {
if (!this.selectedPath)
throw new Error("No valid camera path loaded");
this._viewport.setAnimator(undefined);
const keyframe = this.selectedPath.getKeyframeAtTime(this._currentAnimationTime);
this.setCameraPosition(keyframe);
}
private recordAnimationFrame(): void {
if (!this.selectedPath)
throw new Error("No valid camera path loaded");
const view = this._viewport.view;
if (!view.is3d() || !view.supportsCamera())
throw new Error("Invalid view for camera path");
// TODO: Handle global coordinates
const location = this._viewport.npcToWorld(new Point3d(0.5, 0.5, 1.0));
const target = this._viewport.npcToWorld(new Point3d(0.5, 0.5, 0.0));
// Location and target are the same, the keyframe will be invalid
if (target.distance(location) <= Number.EPSILON)
return;
const topScreen = this._viewport.npcToWorld(new Point3d(0.5, 1.0, 0.0));
const up = location.unitVectorTo(topScreen);
if (up === undefined)
return;
const lensAngle = view.isCameraOn ? view.camera.getLensAngle().clone() : undefined;
const extents = view.isCameraOn ? undefined : view.getExtents().clone();
this.selectedPath.keyframes.push(new Keyframe(this._currentAnimationTime, location, target, up, lensAngle, extents));
}
private endAnimation(): void {
this.stop();
}
private setCameraPosition(keyframe: Keyframe) {
const view = this._viewport.view;
if (!view.is3d() || !view.supportsCamera())
throw new Error("Invalid view for camera path");
// TODO: Handle global coordinates
if (keyframe.lensAngle !== undefined) {
const lensAngle = keyframe.lensAngle.clone();
Camera.validateLensAngle(lensAngle);
// Perspective
view.lookAt(
{
eyePoint: keyframe.location,
targetPoint: keyframe.target,
upVector: keyframe.up,
lensAngle,
}
);
} else {
if (keyframe.extents === undefined)
throw new Error("Invalid keyframe for camera: path should specifies either lensAngle or extents.");
// Orthographic camera
view.lookAt(
{
eyePoint: keyframe.location,
viewDirection: (keyframe.target.minus(keyframe.location)),
upVector: keyframe.up,
newExtents: keyframe.extents,
}
);
}
this._viewport.synchWithView({noSaveInUndo: true});
}
} | the_stack |
import { Events } from 'vue-iclient/src/common/_types/event/Events';
import { isXField, isYField, urlAppend } from 'vue-iclient/src/common/_utils/util';
import * as convert from 'xml-js';
const DEFAULT_WELLKNOWNSCALESET = [
'GoogleCRS84Quad',
'GoogleMapsCompatible',
'urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible',
'urn:ogc:def:wkss:OGC:1.0:GoogleCRS84Quad'
];
const MB_SCALEDENOMINATOR_3857 = [
'559082264.0287178',
'279541132.0143589',
'139770566.0071794',
'69885283.00358972',
'34942641.50179486',
'17471320.75089743',
'8735660.375448715',
'4367830.1877224357',
'2183915.093862179',
'1091957.546931089',
'545978.7734655447',
'272989.3867327723',
'136494.6933663862',
'68247.34668319309',
'34123.67334159654',
'17061.83667079827',
'8530.918335399136',
'4265.459167699568',
'2132.729583849784'
];
const MB_SCALEDENOMINATOR_4326 = [
'5.590822640287176E8',
'2.795411320143588E8',
'1.397705660071794E8',
'6.98852830035897E7',
'3.494264150179485E7',
'1.7471320750897426E7',
'8735660.375448713',
'4367830.187724357',
'2183915.0938621783',
'1091957.5469310891',
'545978.7734655446',
'272989.3867327723',
'136494.69336638614',
'68247.34668319307',
'34123.673341596535',
'17061.836670798268',
'8530.918335399134'
];
interface webMapOptions {
serverUrl?: string;
accessToken?: string;
accessKey?: string;
tiandituKey?: string;
withCredentials?: boolean;
excludePortalProxyUrl?: boolean;
proxy?: boolean | string;
iportalServiceProxyUrlPrefix?: string;
}
export default class WebMapService extends Events {
mapId: string | number;
mapInfo: any;
serverUrl: string;
accessToken: string;
accessKey: string;
tiandituKey: string;
withCredentials: boolean;
target: string;
excludePortalProxyUrl: boolean;
isSuperMapOnline: boolean;
proxy: boolean | string;
iportalServiceProxyUrl: string;
proxyOptions: Object = {
data: 'apps/viewer/getUrlResource.json?url=',
image: 'apps/viewer/getUrlResource.png?url='
};
constructor(mapId: string | number | Object, options: webMapOptions = {}) {
super();
if (typeof mapId === 'string' || typeof mapId === 'number') {
this.mapId = mapId;
} else if (mapId !== null && typeof mapId === 'object') {
this.mapInfo = mapId;
}
this.serverUrl = options.serverUrl || 'https://www.supermapol.com';
this.accessToken = options.accessToken;
this.accessKey = options.accessKey;
this.tiandituKey = options.tiandituKey || '';
this.withCredentials = options.withCredentials || false;
this.excludePortalProxyUrl = options.excludePortalProxyUrl;
this.iportalServiceProxyUrl = options.iportalServiceProxyUrlPrefix;
this.proxy = options.proxy;
}
public setMapId(mapId: string | number | Object): void {
if (typeof mapId === 'string' || typeof mapId === 'number') {
this.mapId = mapId;
this.mapInfo = null;
} else if (mapId !== null && typeof mapId === 'object') {
this.mapInfo = mapId;
this.mapId = '';
}
}
public setServerUrl(serverUrl: string): void {
this.serverUrl = serverUrl;
}
public setWithCredentials(withCredentials) {
this.withCredentials = withCredentials;
}
public setProxy(proxy) {
this.proxy = proxy;
}
public handleServerUrl(serverUrl) {
let urlArr: string[] = serverUrl.split('');
if (urlArr[urlArr.length - 1] !== '/') {
serverUrl += '/';
}
this.serverUrl = serverUrl;
return serverUrl;
}
public getMapInfo() {
if (!this.mapId && this.mapInfo) {
return new Promise(resolve => {
resolve(this.mapInfo);
});
}
let mapUrl = this._handleMapUrl();
return new Promise(async (resolve, reject) => {
try {
await this.getiPortalServiceProxy();
SuperMap.FetchRequest.get(mapUrl, null, {
withCredentials: this.withCredentials
})
.then(response => {
return response.json();
})
.then(mapInfo => {
if (mapInfo && mapInfo.succeed === false) {
let error = { message: mapInfo && mapInfo.error && mapInfo.error.errorMsg };
reject(error);
return;
}
mapInfo.mapParams = {
title: mapInfo.title,
description: mapInfo.description
};
resolve(mapInfo);
})
.catch(error => {
reject(error);
});
} catch (err) {
reject(err);
}
});
}
public getiPortalServiceProxy() {
return new Promise((resolve, reject) => {
SuperMap.FetchRequest.get(`${this.serverUrl}web/config/portal.json`, { scope: ['serviceProxy'] })
.then(response => {
return response.json();
})
.then(serviceProxyInfo => {
if (!serviceProxyInfo || !serviceProxyInfo.serviceProxy) {
reject('serviceProxyFailed');
return;
}
const serviceProxy = serviceProxyInfo.serviceProxy;
if (serviceProxy.enable) {
if (serviceProxy.proxyServerRootUrl) {
this.iportalServiceProxyUrl = serviceProxy.proxyServerRootUrl;
} else if (serviceProxy.port && serviceProxy.rootUrlPostfix) {
this.iportalServiceProxyUrl = `${serviceProxy.port}/${serviceProxy.rootUrlPostfix}`;
}
if (this.serverUrl.indexOf(this.iportalServiceProxyUrl) > -1) {
this.iportalServiceProxyUrl = '';
}
}
resolve(serviceProxy);
})
.catch(error => {
reject(error);
});
});
}
public getLayerFeatures(type, layer, baseProjection?) {
let pro;
switch (type) {
case 'hosted':
// 数据存储到iportal上了
pro = this._getFeaturesFromHosted(layer, baseProjection);
break;
case 'rest_data':
pro = this._getFeaturesFromRestData(layer, baseProjection);
break;
case 'rest_map':
pro = this._getFeaturesFromRestMap(layer);
break;
case 'dataflow':
pro = this._getFeaturesFromDataflow(layer);
break;
case 'user_data':
pro = this._getFeaturesFromUserData(layer);
break;
}
return pro;
}
public getWmsInfo(layerInfo) {
return new Promise(resolve => {
const proxy = this.handleProxy();
const serviceUrl = `${layerInfo.url.split('?')[0]}?REQUEST=GetCapabilities&SERVICE=WMS`;
SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, layerInfo.url, false),
withoutFormatSuffix: true,
proxy
})
.then(response => {
return response.text();
})
.then(capabilitiesText => {
let converts = convert || window.convert;
const capabilities = JSON.parse(
converts.xml2json(capabilitiesText, {
compact: true,
spaces: 4
})
);
const wmsCapabilities = capabilities.WMT_MS_Capabilities || capabilities.WMS_Capabilities;
resolve({ version: wmsCapabilities['_attributes']['version'] });
});
});
}
public getWmtsInfo(layerInfo, mapCRS) {
return new Promise((resolve, reject) => {
let isMatched = false;
let matchMaxZoom = 22;
let style = '';
let bounds;
let restResourceURL = '';
let kvpResourceUrl = '';
const proxy = this.handleProxy();
let serviceUrl = `${layerInfo.url.split('?')[0]}?REQUEST=GetCapabilities&SERVICE=WMTS&VERSION=1.0.0`;
serviceUrl = this.handleParentRes(serviceUrl);
SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, layerInfo.url, false),
withoutFormatSuffix: true,
proxy
})
.then(response => {
return response.text();
})
.then(capabilitiesText => {
let converts = convert || window.convert;
const capabilities = JSON.parse(
converts.xml2json(capabilitiesText, {
compact: true,
spaces: 4
})
).Capabilities;
const content = capabilities.Contents;
const metaData = capabilities['ows:OperationsMetadata'];
if (metaData) {
let operations = metaData['ows:Operation'];
if (!Array.isArray(operations)) {
operations = [operations];
}
const operation = operations.find(item => {
return item._attributes.name === 'GetTile';
});
if (operation) {
let getConstraints = operation['ows:DCP']['ows:HTTP']['ows:Get'];
if (!Array.isArray(getConstraints)) {
getConstraints = [getConstraints];
}
const getConstraint = getConstraints.find(item => {
return item['ows:Constraint']['ows:AllowedValues']['ows:Value']['_text'] === 'KVP';
});
if (getConstraint) {
kvpResourceUrl = getConstraint['_attributes']['xlink:href'];
}
}
}
let tileMatrixSet = content.TileMatrixSet;
for (let i = 0; i < tileMatrixSet.length; i++) {
if (
tileMatrixSet[i]['ows:Identifier'] &&
tileMatrixSet[i]['ows:Identifier']['_text'] === layerInfo.tileMatrixSet
) {
if (
tileMatrixSet[i]['WellKnownScaleSet'] &&
DEFAULT_WELLKNOWNSCALESET.includes(tileMatrixSet[i]['WellKnownScaleSet']['_text'])
) {
isMatched = true;
} else {
let matchedScaleDenominator = [];
// 坐标系判断
let defaultCRSScaleDenominators =
// @ts-ignore -------- crs 为 enhance 新加属性
mapCRS === 'EPSG:3857' ? MB_SCALEDENOMINATOR_3857 : MB_SCALEDENOMINATOR_4326;
for (let j = 0, len = defaultCRSScaleDenominators.length; j < len; j++) {
if (!tileMatrixSet[i].TileMatrix[j]) {
break;
}
if (
parseFloat(defaultCRSScaleDenominators[j]) !==
parseFloat(tileMatrixSet[i].TileMatrix[j]['ScaleDenominator']['_text'])
) {
break;
}
matchedScaleDenominator.push(defaultCRSScaleDenominators[j]);
}
matchMaxZoom = matchedScaleDenominator.length - 1;
if (matchedScaleDenominator.length !== 0) {
isMatched = true;
} else {
throw Error('TileMatrixSetNotSuppport');
}
}
break;
}
}
const layer = content.Layer.find(item => {
return item['ows:Identifier']['_text'] === layerInfo.layer;
});
if (layer) {
let styles = layer.Style;
if (Array.isArray(layer.Style)) {
style = styles[0]['ows:Identifier'] ? styles[0]['ows:Identifier']['_text'] : '';
} else {
style = styles['ows:Identifier'] ? styles['ows:Identifier']['_text'] : '';
}
if (layer['ows:WGS84BoundingBox']) {
const lowerCorner = layer['ows:WGS84BoundingBox']['ows:LowerCorner']['_text'].split(' ');
const upperCorner = layer['ows:WGS84BoundingBox']['ows:UpperCorner']['_text'].split(' ');
bounds = [
parseFloat(lowerCorner[0]),
parseFloat(lowerCorner[1]),
parseFloat(upperCorner[0]),
parseFloat(upperCorner[1])
];
}
let resourceUrls = layer.ResourceURL;
if (!Array.isArray(resourceUrls)) {
resourceUrls = [resourceUrls];
}
const resourceUrl = resourceUrls.find(item => {
return item._attributes.resourceType === 'tile';
});
if (resourceUrl) {
restResourceURL = resourceUrl._attributes.template;
}
}
resolve({ isMatched, matchMaxZoom, style, bounds, restResourceURL, kvpResourceUrl });
})
.catch(error => {
reject(error);
});
});
}
private _getFeaturesFromHosted(layer, baseProjection?) {
let { dataSource, layerType } = layer;
let serverId = dataSource ? dataSource.serverId : layer.serverId;
if (!serverId) {
return new Promise(resolve => {
resolve({ type: 'noServerId' });
});
}
let getDataFromIportal =
layerType === 'MARKER' || (dataSource && (!dataSource.accessType || dataSource.accessType === 'DIRECT'));
if (getDataFromIportal) {
return this._getDataFromIportal(serverId, layer);
} else {
return this._getDataFromHosted({ layer, serverId, baseProjection });
}
}
private _getFeaturesFromRestData(layer, baseProjection?) {
// 从restData获取数据
let features;
let dataSource = layer.dataSource;
return new Promise((resolve, reject) => {
this._getFeatureBySQL(
dataSource.url,
[dataSource.dataSourceName || layer.name],
result => {
features = this.parseGeoJsonData2Feature({
allDatas: {
features: result.result.features.features
}
});
resolve({ type: 'feature', features });
},
err => {
reject(err);
},
baseProjection
);
});
}
private _getFeaturesFromRestMap(layer) {
return new Promise((resolve, reject) => {
this._queryFeatureBySQL(
layer.dataSource.url,
layer.dataSource.layerName,
result => {
let recordsets = result && result.result.recordsets;
let recordset = recordsets && recordsets[0];
let attributes = recordset.fields;
if (recordset && attributes) {
let fileterAttrs: string[] = [];
for (let i in attributes) {
let value = attributes[i];
if (value.indexOf('Sm') !== 0 || value === 'SmID') {
fileterAttrs.push(value);
}
}
this._getFeatures(
fileterAttrs,
layer,
features => {
resolve({ type: 'feature', features });
},
err => {
reject(err);
}
);
}
},
err => {
reject(err);
},
'smid=1'
);
});
}
private _getFeaturesFromUserData(layer) {
let dataSource = layer.dataSource;
return new Promise((resolve, reject) => {
const proxy = this.handleProxy();
let serviceUrl = this.handleParentRes(dataSource.url);
SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, serviceUrl, this.withCredentials),
proxy
})
.then(response => {
return response.json();
})
.then(data => {
let features;
if (data && data instanceof Object && data.type === 'FeatureCollection') {
features = data.features;
} else {
features = data;
}
features = this.parseGeoJsonData2Feature({
allDatas: {
features
}
});
resolve({ type: 'feature', features });
})
.catch(err => {
reject(err);
});
});
}
private _queryFeatureBySQL(
url: string,
layerName: string,
processCompleted: Function,
processFaild: Function,
attributeFilter?: string,
fields?: Array<string>,
epsgCode?: string,
startRecord?,
recordLength?,
onlyAttribute?
): void {
let queryBySQLParams = this._getQueryFeaturesParam(
layerName,
attributeFilter,
fields,
epsgCode,
startRecord,
recordLength,
onlyAttribute
);
const proxy = this.handleProxy();
let serviceUrl = this.handleParentRes(url);
// @ts-ignore
let queryBySQLService = new SuperMap.QueryBySQLService(serviceUrl, {
proxy,
withCredentials: this.handleWithCredentials(proxy, url, false),
eventListeners: {
processCompleted: data => {
processCompleted && processCompleted(data);
},
processFailed: data => {
processFaild && processFaild(data);
}
}
});
queryBySQLService.processAsync(queryBySQLParams);
}
private _getFeatures(fields: string[], layerInfo: any, resolve: Function, reject: Function): void {
let source = layerInfo.dataSource;
// 示例数据
this._queryFeatureBySQL(
source.url,
source.layerName,
result => {
let recordsets = result.result.recordsets[0];
let features = recordsets.features.features;
let featuresObj = this.parseGeoJsonData2Feature({
allDatas: { features }
});
resolve(featuresObj);
},
err => {
reject(err);
},
null,
fields
);
}
private _getQueryFeaturesParam(
layerName: string,
attributeFilter?: string,
fields?: Array<string>,
epsgCode?: string,
startRecord?,
recordLength?,
onlyAttribute?
) {
let queryParam = new SuperMap.FilterParameter({
name: layerName,
attributeFilter: attributeFilter
});
if (fields) {
queryParam.fields = fields;
}
let params: any = {
queryParams: [queryParam]
};
if (onlyAttribute) {
params.queryOption = SuperMap.QueryOption.ATTRIBUTE;
}
startRecord && (params.startRecord = startRecord);
recordLength && (params.expectCount = recordLength);
if (epsgCode) {
params.prjCoordSys = {
epsgCode: epsgCode
};
}
let queryBySQLParams = new SuperMap.QueryBySQLParameters(params);
return queryBySQLParams;
}
private _getFeaturesFromDataflow(layer) {
return new Promise((resolve, reject) => {
this._getDataflowInfo(
layer,
() => {
resolve({ type: 'dataflow' });
},
e => {
reject(e);
}
);
});
}
private _getDataflowInfo(layerInfo, success, faild?) {
let url = layerInfo.url;
let token;
let requestUrl = `${url}.json`;
if (layerInfo.credential && layerInfo.credential.token) {
token = layerInfo.credential.token;
requestUrl += `?token=${token}`;
}
const proxy = this.handleProxy();
requestUrl = this.handleParentRes(requestUrl);
SuperMap.FetchRequest.get(requestUrl, null, {
proxy,
withCredentials: this.handleWithCredentials(proxy, requestUrl, false)
})
.then(function (response) {
return response.json();
})
.then(function (result) {
if (!result) {
faild();
return;
}
if (result.featureMetaData) {
layerInfo.featureType = result.featureMetaData.featureType.toUpperCase();
layerInfo.dataSource = { dataTypes: {} };
if (result.featureMetaData.fieldInfos && result.featureMetaData.fieldInfos.length > 0) {
result.featureMetaData.fieldInfos.forEach(function (data) {
let name = data.name.trim();
if (data.type === 'TEXT') {
layerInfo.dataSource.dataTypes[name] = 'STRING';
} else if (['DOUBLE', 'INT', 'FLOAT', 'LONG', 'SHORT'].includes(data.type)) {
layerInfo.dataSource.dataTypes[name] = 'NUMBER';
} else {
layerInfo.dataSource.dataTypes[name] = 'UNKNOWN';
}
});
}
}
layerInfo.wsUrl = result.urls[0].url;
layerInfo.name = result.urls[0].url.split('iserver/services/')[1].split('/dataflow')[0];
success();
})
.catch(function () {
faild();
});
}
public getDatasourceType(layer) {
let { dataSource, layerType } = layer;
if (dataSource && dataSource.type === 'SAMPLE_DATA') {
return dataSource.type;
}
let type;
let isHosted = (dataSource && dataSource.serverId) || layerType === 'MARKER' || layerType === 'HOSTED_TILE';
let isTile =
layerType === 'SUPERMAP_REST' ||
layerType === 'TILE' ||
layerType === 'WMS' ||
layerType === 'WMTS' ||
layerType === 'MAPBOXSTYLE';
if (isHosted) {
type = 'hosted';
} else if (isTile) {
type = 'tile';
} else if (dataSource && dataSource.type === 'REST_DATA') {
type = 'rest_data';
} else if (dataSource && dataSource.type === 'REST_MAP' && dataSource.url) {
type = 'rest_map';
} else if (layerType === 'DATAFLOW_POINT_TRACK' || layerType === 'DATAFLOW_HEAT') {
type = 'dataflow';
} else if (dataSource && dataSource.type === 'USER_DATA') {
type = 'user_data';
}
return type;
}
public getFeatureProperties(features) {
let properties = [];
if (features && features.length) {
features.forEach(feature => {
let property = feature.properties;
property && properties.push(property);
});
}
return properties;
}
public parseGeoJsonData2Feature(metaData: any) {
let allFeatures = metaData.allDatas.features;
let features = [];
for (let i = 0, len = allFeatures.length; i < len; i++) {
let feature = allFeatures[i];
let coordinate = feature.geometry.coordinates;
if (allFeatures[i].geometry.type === 'Point') {
// 标注图层 还没有属性值时候不加
if (allFeatures[i].properties) {
allFeatures[i].properties.lon = coordinate[0];
allFeatures[i].properties.lat = coordinate[1];
}
}
feature.properties['index'] = i + '';
features.push(feature);
}
return features;
}
private _getDataFromIportal(serverId, layerInfo) {
let features;
// 原来二进制文件
let url = `${this.serverUrl}web/datas/${serverId}/content.json?pageSize=9999999¤tPage=1`;
if (this.accessToken) {
url = `${url}&${this.accessKey}=${this.accessToken}`;
}
return new Promise((resolve, reject) => {
url = this.handleParentRes(url);
const proxy = this.handleProxy();
SuperMap.FetchRequest.get(url, null, {
withCredentials: this.handleWithCredentials(proxy, url, this.withCredentials),
proxy
})
.then(response => {
return response.json();
})
.then(async data => {
if (data.succeed === false) {
reject(data.error);
}
if (data && data.type) {
if (data.type === 'JSON' || data.type === 'GEOJSON') {
data.content = JSON.parse(data.content.trim());
features = this._formatGeoJSON(data.content);
} else if (data.type === 'EXCEL' || data.type === 'CSV') {
if (layerInfo.dataSource && layerInfo.dataSource.administrativeInfo) {
// 行政规划信息
data.content.rows.unshift(data.content.colTitles);
const { divisionType, divisionField } = layerInfo.dataSource.administrativeInfo;
const geojson = await this._excelData2FeatureByDivision(data.content, divisionType, divisionField);
features = this._formatGeoJSON(geojson);
} else {
features = this._excelData2Feature(data.content, (layerInfo && layerInfo.xyField) || {});
}
} else if (data.type === 'SHP') {
data.content = JSON.parse(data.content.trim());
features = this._formatGeoJSON(data.content.layers[0]);
}
resolve({ type: 'feature', features });
}
})
.catch(error => {
reject(error);
});
});
}
private _getDataFromHosted({ layer, serverId, baseProjection }) {
// 关系型文件
let isMapService = layer.layerType === 'HOSTED_TILE';
return new Promise((resolve, reject) => {
this._checkUploadToRelationship(serverId)
.then(result => {
if (result && result.length > 0) {
let datasetName = result[0].name;
let featureType = result[0].type.toUpperCase();
this._getDataService(serverId, datasetName).then(data => {
let dataItemServices = data.dataItemServices;
if (dataItemServices.length === 0) {
reject('noDataServices');
}
let param = { layer, dataItemServices, datasetName, featureType, resolve, reject, baseProjection };
if (isMapService) {
let dataService = dataItemServices.filter(info => {
return info && info.serviceType === 'RESTDATA';
})[0];
this._isMvt(dataService.address, datasetName, baseProjection)
.then(info => {
this._getServiceInfoFromLayer(param, info);
})
.catch(() => {
// 判断失败就走之前逻辑,>数据量用tile
this._getServiceInfoFromLayer(param);
});
} else {
this._getServiceInfoFromLayer(param);
}
});
} else {
reject('resultIsEmpty');
}
})
.catch(error => {
reject(error);
});
});
}
private _isMvt(serviceUrl, datasetName, baseProjection) {
return this._getDatasetsInfo(serviceUrl, datasetName).then(info => {
// 判断是否和底图坐标系一直
/* eslint-disable */
if (info.epsgCode == baseProjection.split('EPSG:')[1]) {
return SuperMap.FetchRequest.get(`${info.url}/tilefeature.mvt`)
.then(function (response) {
return response.json();
})
.then(function (result) {
info.isMvt = result.error && result.error.code === 400;
return info;
})
.catch(() => {
return info;
});
}
return info;
});
}
private _getServiceInfoFromLayer(
{ layer, dataItemServices, datasetName, featureType, resolve, reject, baseProjection },
info?: any
) {
let isMapService = info ? !info.isMvt : layer.layerType === 'HOSTED_TILE';
let isAdded = false;
dataItemServices.forEach(service => {
if (isAdded) {
return;
}
// TODO 对接 MVT
// 有服务了,就不需要循环
if (service && isMapService && service.serviceType === 'RESTMAP') {
isAdded = true;
// 地图服务,判断使用mvt还是tile
this._getTileLayerInfo(service.address, baseProjection).then(restMaps => {
resolve({ type: 'restMap', restMaps });
});
} else if (service && !isMapService && service.serviceType === 'RESTDATA') {
if (info && info.isMvt) {
// this._addVectorLayer(info, layer, featureType);
resolve({ type: 'mvt', info, featureType });
} else {
// 数据服务
isAdded = true;
// 关系型文件发布的数据服务
this._getDatasources(service.address).then(
datasourceName => {
layer.dataSource.dataSourceName = datasourceName + ':' + datasetName;
layer.dataSource.url = `${service.address}/data`;
this._getFeatureBySQL(
layer.dataSource.url,
[layer.dataSource.dataSourceName || layer.name],
result => {
let features = this.parseGeoJsonData2Feature({
allDatas: {
features: result.result.features.features
}
});
resolve({ type: 'feature', features });
},
err => {
reject(err);
}
);
},
err => {
reject(err);
}
);
}
}
}, this);
if (!isAdded) {
// 循环完成了,也没有找到合适的服务。有可能服务被删除
reject('noService');
}
}
private _getDatasetsInfo(serviceUrl, datasetName) {
return this._getDatasources(serviceUrl).then(datasourceName => {
// 判断mvt服务是否可用
let url = `${serviceUrl}/data/datasources/${datasourceName}/datasets/${datasetName}`;
const proxy = this.handleProxy();
url = this.handleParentRes(url);
return SuperMap.FetchRequest.get(url, null, {
withCredentials: this.handleWithCredentials(proxy, url, false),
proxy
})
.then(response => {
return response.json();
})
.then(datasetsInfo => {
return {
epsgCode: datasetsInfo.datasetInfo.prjCoordSys.epsgCode,
bounds: datasetsInfo.datasetInfo.bounds,
datasourceName,
datasetName,
url // 返回的是原始url,没有代理。因为用于请求mvt
};
});
});
}
private _getDatasources(url) {
const proxy = this.handleProxy();
let serviceUrl = `${url}/data/datasources.json`;
serviceUrl = this.handleParentRes(serviceUrl);
return SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, serviceUrl, false),
proxy
})
.then(response => {
return response.json();
})
.then(datasource => {
if (datasource.code === 401) {
throw Error(datasource.errorMsg);
}
let datasourceNames = datasource.datasourceNames;
return datasourceNames[0];
});
}
private _getDataService(fileId, datasetName) {
const proxy = this.handleProxy();
let serviceUrl = `${this.serverUrl}web/datas/${fileId}.json`;
serviceUrl = this.handleParentRes(serviceUrl);
return SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, serviceUrl, this.withCredentials),
proxy
})
.then(response => {
return response.json();
})
.then(result => {
result.fileId = fileId;
result.datasetName = datasetName;
return result;
});
}
private _checkUploadToRelationship(fileId) {
const proxy = this.handleProxy();
let serviceUrl = `${this.serverUrl}web/datas/${fileId}/datasets.json`;
serviceUrl = this.handleParentRes(serviceUrl);
return SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, serviceUrl, this.withCredentials),
proxy
})
.then(response => {
return response.json();
})
.then(result => {
return result;
});
}
private _handleMapUrl() {
let mapUrl = this.serverUrl + 'web/maps/' + this.mapId + '/map';
if (this.accessToken || this.accessKey) {
mapUrl += '?' + (this.accessToken && !this.accessKey) ? 'token=' + this.accessToken : 'key=' + this.accessKey;
}
let filter = 'getUrlResource.json?url=';
if (this.excludePortalProxyUrl && this.serverUrl.indexOf(filter) > -1) {
// 大屏需求,或者有加上代理的
let urlArray = this.serverUrl.split(filter);
if (urlArray.length > 1) {
mapUrl = urlArray[0] + filter + this.serverUrl + 'web/maps/' + this.mapId + '/map.json';
}
}
mapUrl = mapUrl.indexOf('.json') === -1 ? `${mapUrl}.json` : mapUrl;
return mapUrl;
}
public handleProxy(type?: string): string {
if (!this.proxy) {
return null;
}
const proxySuffix: string = this.proxyOptions[type || 'data'];
let proxy: string = this.serverUrl + proxySuffix;
if (typeof this.proxy === 'string') {
proxy = this.proxy;
}
return proxy;
}
public handleWithCredentials(proxyUrl?: string, serviceUrl?: string, defaultValue = this.withCredentials): boolean {
if (proxyUrl && proxyUrl.startsWith(this.serverUrl) && (!serviceUrl || serviceUrl.startsWith(proxyUrl))) {
return true;
}
if (serviceUrl && this.iportalServiceProxyUrl && serviceUrl.indexOf(this.iportalServiceProxyUrl) >= 0) {
return true;
}
return defaultValue;
}
public isIportalResourceUrl(serviceUrl) {
return (
serviceUrl.startsWith(this.serverUrl) ||
(this.iportalServiceProxyUrl && serviceUrl.indexOf(this.iportalServiceProxyUrl) >= 0)
);
}
public handleParentRes(url, parentResId = this.mapId, parentResType = 'MAP'): string {
if (!this.isIportalResourceUrl(url)) {
return url;
}
return urlAppend(url, `parentResType=${parentResType}&parentResId=${parentResId}`);
}
private _formatGeoJSON(data): any {
let features = data.features;
features.forEach((row, index) => {
row.properties['index'] = index;
});
return features;
}
private _excelData2Feature(dataContent: any, xyField: any = {}): any {
let fieldCaptions = dataContent.colTitles;
// 位置属性处理
let xfieldIndex = fieldCaptions.indexOf(xyField.xField);
let yfieldIndex = fieldCaptions.indexOf(xyField.yField);
if (yfieldIndex < 0 || xfieldIndex < 0) {
for (let i = 0, len = fieldCaptions.length; i < len; i++) {
if (isXField(fieldCaptions[i])) {
xfieldIndex = i;
}
if (isYField(fieldCaptions[i])) {
yfieldIndex = i;
}
}
}
// feature 构建后期支持坐标系 4326/3857
let features = [];
for (let i = 0, len = dataContent.rows.length; i < len; i++) {
let row = dataContent.rows[i];
let x = Number(row[xfieldIndex]);
let y = Number(row[yfieldIndex]);
// 属性信息
let attributes = {};
for (let index = 0; index < dataContent.colTitles.length; index++) {
const element = dataContent.colTitles[index].trim();
attributes[element] = dataContent.rows[i][index];
}
attributes['index'] = i + '';
// 目前csv 只支持处理点,所以先生成点类型的 geojson
let feature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [x, y]
},
properties: attributes
};
features.push(feature);
}
return features;
}
private _excelData2FeatureByDivision(content: any, divisionType: string, divisionField: string): Promise<Object> {
const dataName = ['城市', 'City'].includes(divisionType) ? 'MunicipalData' : 'ProvinceData';
if (window[dataName] && window[dataName].features) {
return new Promise(resolve => {
resolve(this._combineFeature(content, window[dataName], divisionField));
});
}
const dataFileName = ['城市', 'City'].includes(divisionType) ? 'MunicipalData.js' : 'ProvincialData.js';
const proxy = this.handleProxy();
const dataUrl = `${this.serverUrl}apps/dataviz/libs/administrative_data/${dataFileName}`;
return SuperMap.FetchRequest.get(dataUrl, null, {
withCredentials: false,
proxy,
withoutFormatSuffix: true
})
.then(response => {
return response.text();
})
.then(result => {
new Function(result)();
return this._combineFeature(content, window[dataName], divisionField);
});
}
private _combineFeature(
properties: any,
geoData: GeoJSON.FeatureCollection,
divisionField: string
): GeoJSON.FeatureCollection {
let geojson: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: []
};
if (properties.length < 2) {
return geojson;
} // 只有一行数据时为标题
let titles = properties.colTitles;
let rows = properties.rows;
let fieldIndex = titles.findIndex(title => title === divisionField);
rows.forEach(row => {
let feature = geoData.features.find(item => {
return this._isMatchAdministrativeName(item.properties.Name, row[fieldIndex]);
});
// todo 需提示忽略无效数据
if (feature) {
const province = feature.properties.Province;
const combineFeature: GeoJSON.Feature = { properties: {}, geometry: feature.geometry, type: 'Feature' };
row.forEach((item, idx) => {
combineFeature.properties[titles[idx]] = item;
});
if (province) {
combineFeature.properties.Province = province;
}
geojson.features.push(combineFeature);
}
});
return geojson;
}
/**
* @description 行政区划原始数据和当前数据是否匹配
*/
private _isMatchAdministrativeName(featureName: string, fieldName: string): boolean {
if (featureName && typeof fieldName === 'string' && fieldName.constructor === String) {
let shortName = featureName.trim().substr(0, 2);
// 张家口市和张家界市
if (shortName === '张家') {
shortName = featureName.trim().substr(0, 3);
}
// 阿拉善盟 阿拉尔市
if (shortName === '阿拉') {
shortName = featureName.trim().substr(0, 3);
}
return !!fieldName.match(new RegExp(shortName));
}
return false;
}
private _getTileLayerInfo(url, baseProjection) {
const proxy = this.handleProxy();
let epsgCode = baseProjection.split('EPSG:')[1];
let serviceUrl = `${url}/maps.json`;
serviceUrl = this.handleParentRes(serviceUrl);
return SuperMap.FetchRequest.get(serviceUrl, null, {
withCredentials: this.handleWithCredentials(proxy, serviceUrl, this.withCredentials),
proxy
})
.then(response => {
return response.json();
})
.then(mapInfo => {
let promises = [];
if (mapInfo) {
mapInfo.forEach(info => {
let promise = SuperMap.FetchRequest.get(
`${info.path}.json?prjCoordSys=${JSON.stringify({ epsgCode: epsgCode })}`,
null,
{
withCredentials: this.withCredentials,
proxy
}
)
.then(response => {
return response.json();
})
.then(restMapInfo => {
restMapInfo.url = info.path;
return restMapInfo;
});
promises.push(promise);
});
}
return Promise.all(promises).then(allRestMaps => {
return allRestMaps;
});
});
}
private _getFeatureBySQL(
url: string,
datasetNames: Array<string>,
processCompleted: Function,
processFaild: Function,
baseProjection?
): void {
let getFeatureParam, getFeatureBySQLService, getFeatureBySQLParams;
getFeatureParam = new SuperMap.FilterParameter({
name: datasetNames.join().replace(':', '@'),
attributeFilter: null
});
getFeatureBySQLParams = new SuperMap.GetFeaturesBySQLParameters({
queryParameter: getFeatureParam,
datasetNames: datasetNames,
fromIndex: 0,
toIndex: -1,
maxFeatures: -1,
returnContent: true
});
if (baseProjection) {
if (baseProjection === 'EPSG:3857' || baseProjection === 'EPSG:-1000') {
getFeatureBySQLParams.targetEpsgCode = 4326;
} else {
getFeatureBySQLParams.targetEpsgCode = +baseProjection.split(':')[1];
}
}
const proxy = this.handleProxy();
let options = {
proxy,
withCredentials: this.handleWithCredentials(proxy, url, false),
eventListeners: {
processCompleted: getFeaturesEventArgs => {
processCompleted && processCompleted(getFeaturesEventArgs);
},
processFailed: e => {
processFaild && processFaild(e);
}
}
};
const serviceUrl = this.handleParentRes(url);
getFeatureBySQLService = new SuperMap.GetFeaturesBySQLService(serviceUrl, options);
getFeatureBySQLService.processAsync(getFeatureBySQLParams);
}
public async getEpsgCodeInfo(epsgCode, iPortalUrl) {
const url = iPortalUrl.slice(-1) === '/' ? iPortalUrl : `${iPortalUrl}/`;
let codeUrl = `${url}epsgcodes/${epsgCode}.json`;
const wkt = await SuperMap.FetchRequest.get(codeUrl, null)
.then(response => {
return response.json();
})
.then(epsgcodeInfo => {
return epsgcodeInfo.wkt;
})
.catch(err => {
console.error(err);
return undefined;
});
return wkt;
}
} | the_stack |
import { CommentChar } from "./comment_char.ts";
import { escapeForWithinString, getStringFromStrOrFunc } from "./utils/string_utils.ts";
/**
* Options for the writer.
*/
export interface Options {
/**
* Newline character.
* @remarks Defaults to \n.
*/
newLine: "\n" | "\r\n";
/**
* Number of spaces to indent when `useTabs` is false.
* @remarks Defaults to 4.
*/
indentNumberOfSpaces: number;
/**
* Whether to use tabs (true) or spaces (false).
* @remarks Defaults to false.
*/
useTabs: boolean;
/**
* Whether to use a single quote (true) or double quote (false).
* @remarks Defaults to false.
*/
useSingleQuote: boolean;
}
// Using the char codes is a performance improvement (about 5.5% faster when writing because it eliminates additional string allocations).
const CHARS = {
BACK_SLASH: "\\".charCodeAt(0),
FORWARD_SLASH: "/".charCodeAt(0),
NEW_LINE: "\n".charCodeAt(0),
CARRIAGE_RETURN: "\r".charCodeAt(0),
ASTERISK: "*".charCodeAt(0),
DOUBLE_QUOTE: "\"".charCodeAt(0),
SINGLE_QUOTE: "'".charCodeAt(0),
BACK_TICK: "`".charCodeAt(0),
OPEN_BRACE: "{".charCodeAt(0),
CLOSE_BRACE: "}".charCodeAt(0),
DOLLAR_SIGN: "$".charCodeAt(0),
SPACE: " ".charCodeAt(0),
TAB: "\t".charCodeAt(0),
};
const isCharToHandle = new Set<number>([
CHARS.BACK_SLASH,
CHARS.FORWARD_SLASH,
CHARS.NEW_LINE,
CHARS.CARRIAGE_RETURN,
CHARS.ASTERISK,
CHARS.DOUBLE_QUOTE,
CHARS.SINGLE_QUOTE,
CHARS.BACK_TICK,
CHARS.OPEN_BRACE,
CHARS.CLOSE_BRACE,
]);
/**
* Code writer that assists with formatting and visualizing blocks of JavaScript or TypeScript code.
*/
export default class CodeBlockWriter {
/** @internal */
private readonly _indentationText: string;
/** @internal */
private readonly _newLine: "\n" | "\r\n";
/** @internal */
private readonly _useTabs: boolean;
/** @internal */
private readonly _quoteChar: string;
/** @internal */
private readonly _indentNumberOfSpaces: number;
/** @internal */
private _currentIndentation = 0;
/** @internal */
private _queuedIndentation: number | undefined;
/** @internal */
private _queuedOnlyIfNotBlock: true | undefined;
/** @internal */
private _length = 0;
/** @internal */
private _newLineOnNextWrite = false;
/** @internal */
private _currentCommentChar: CommentChar | undefined = undefined;
/** @internal */
private _stringCharStack: number[] = [];
/** @internal */
private _isInRegEx = false;
/** @internal */
private _isOnFirstLineOfBlock = true;
// An array of strings is used rather than a single string because it was
// found to be ~11x faster when printing a 10K line file (~11s to ~1s).
/** @internal */
private _texts: string[] = [];
/**
* Constructor.
* @param opts - Options for the writer.
*/
constructor(opts: Partial<Options> = {}) {
this._newLine = opts.newLine || "\n";
this._useTabs = opts.useTabs || false;
this._indentNumberOfSpaces = opts.indentNumberOfSpaces || 4;
this._indentationText = getIndentationText(this._useTabs, this._indentNumberOfSpaces);
this._quoteChar = opts.useSingleQuote ? "'" : `"`;
}
/**
* Gets the options.
*/
getOptions(): Options {
return {
indentNumberOfSpaces: this._indentNumberOfSpaces,
newLine: this._newLine,
useTabs: this._useTabs,
useSingleQuote: this._quoteChar === "'",
};
}
/**
* Queues the indentation level for the next lines written.
* @param indentationLevel - Indentation level to queue.
*/
queueIndentationLevel(indentationLevel: number): this;
/**
* Queues the indentation level for the next lines written using the provided indentation text.
* @param whitespaceText - Gets the indentation level from the indentation text.
*/
queueIndentationLevel(whitespaceText: string): this;
/** @internal */
queueIndentationLevel(countOrText: string | number): this;
queueIndentationLevel(countOrText: string | number) {
this._queuedIndentation = this._getIndentationLevelFromArg(countOrText);
this._queuedOnlyIfNotBlock = undefined;
return this;
}
/**
* Writes the text within the provided action with hanging indentation.
* @param action - Action to perform with hanging indentation.
*/
hangingIndent(action: () => void): this {
return this._withResetIndentation(() => this.queueIndentationLevel(this.getIndentationLevel() + 1), action);
}
/**
* Writes the text within the provided action with hanging indentation unless writing a block.
* @param action - Action to perform with hanging indentation unless a block is written.
*/
hangingIndentUnlessBlock(action: () => void): this {
return this._withResetIndentation(() => {
this.queueIndentationLevel(this.getIndentationLevel() + 1);
this._queuedOnlyIfNotBlock = true;
}, action);
}
/**
* Sets the current indentation level.
* @param indentationLevel - Indentation level to be at.
*/
setIndentationLevel(indentationLevel: number): this;
/**
* Sets the current indentation using the provided indentation text.
* @param whitespaceText - Gets the indentation level from the indentation text.
*/
setIndentationLevel(whitespaceText: string): this;
/** @internal */
setIndentationLevel(countOrText: string | number): this;
setIndentationLevel(countOrText: string | number) {
this._currentIndentation = this._getIndentationLevelFromArg(countOrText);
return this;
}
/**
* Sets the indentation level within the provided action and restores the writer's indentation
* state afterwards.
* @remarks Restores the writer's state after the action.
* @param indentationLevel - Indentation level to set.
* @param action - Action to perform with the indentation.
*/
withIndentationLevel(indentationLevel: number, action: () => void): this;
/**
* Sets the indentation level with the provided indentation text within the provided action
* and restores the writer's indentation state afterwards.
* @param whitespaceText - Gets the indentation level from the indentation text.
* @param action - Action to perform with the indentation.
*/
withIndentationLevel(whitespaceText: string, action: () => void): this;
withIndentationLevel(countOrText: string | number, action: () => void) {
return this._withResetIndentation(() => this.setIndentationLevel(countOrText), action);
}
/** @internal */
private _withResetIndentation(setStateAction: () => void, writeAction: () => void) {
const previousState = this._getIndentationState();
setStateAction();
try {
writeAction();
} finally {
this._setIndentationState(previousState);
}
return this;
}
/**
* Gets the current indentation level.
*/
getIndentationLevel(): number {
return this._currentIndentation;
}
/**
* Writes a block using braces.
* @param block - Write using the writer within this block.
*/
block(block?: () => void): this {
this._newLineIfNewLineOnNextWrite();
if (this.getLength() > 0 && !this.isLastNewLine()) {
this.spaceIfLastNot();
}
this.inlineBlock(block);
this._newLineOnNextWrite = true;
return this;
}
/**
* Writes an inline block with braces.
* @param block - Write using the writer within this block.
*/
inlineBlock(block?: () => void): this {
this._newLineIfNewLineOnNextWrite();
this.write("{");
this._indentBlockInternal(block);
this.newLineIfLastNot().write("}");
return this;
}
/**
* Indents the code one level for the current line.
*/
indent(times?: number): this;
/**
* Indents a block of code.
* @param block - Block to indent.
*/
indent(block: () => void): this;
indent(timesOrBlock: number | (() => void) = 1) {
if (typeof timesOrBlock === "number") {
this._newLineIfNewLineOnNextWrite();
return this.write(this._indentationText.repeat(timesOrBlock));
} else {
this._indentBlockInternal(timesOrBlock);
if (!this.isLastNewLine()) {
this._newLineOnNextWrite = true;
}
return this;
}
}
/** @internal */
private _indentBlockInternal(block?: () => void) {
if (this.getLastChar() != null) {
this.newLineIfLastNot();
}
this._currentIndentation++;
this._isOnFirstLineOfBlock = true;
if (block != null) {
block();
}
this._isOnFirstLineOfBlock = false;
this._currentIndentation = Math.max(0, this._currentIndentation - 1);
}
/**
* Conditionally writes a line of text.
* @param condition - Condition to evaluate.
* @param textFunc - A function that returns a string to write if the condition is true.
*/
conditionalWriteLine(condition: boolean | undefined, textFunc: () => string): this;
/**
* Conditionally writes a line of text.
* @param condition - Condition to evaluate.
* @param text - Text to write if the condition is true.
*/
conditionalWriteLine(condition: boolean | undefined, text: string): this;
conditionalWriteLine(condition: boolean | undefined, strOrFunc: string | (() => string)) {
if (condition) {
this.writeLine(getStringFromStrOrFunc(strOrFunc));
}
return this;
}
/**
* Writes a line of text.
* @param text - String to write.
*/
writeLine(text: string): this {
this._newLineIfNewLineOnNextWrite();
if (this.getLastChar() != null) {
this.newLineIfLastNot();
}
this._writeIndentingNewLines(text);
this.newLine();
return this;
}
/**
* Writes a newline if the last line was not a newline.
*/
newLineIfLastNot(): this {
this._newLineIfNewLineOnNextWrite();
if (!this.isLastNewLine()) {
this.newLine();
}
return this;
}
/**
* Writes a blank line if the last written text was not a blank line.
*/
blankLineIfLastNot(): this {
if (!this.isLastBlankLine()) {
this.blankLine();
}
return this;
}
/**
* Writes a blank line if the condition is true.
* @param condition - Condition to evaluate.
*/
conditionalBlankLine(condition: boolean | undefined): this {
if (condition) {
this.blankLine();
}
return this;
}
/**
* Writes a blank line.
*/
blankLine(): this {
return this.newLineIfLastNot().newLine();
}
/**
* Writes a newline if the condition is true.
* @param condition - Condition to evaluate.
*/
conditionalNewLine(condition: boolean | undefined): this {
if (condition) {
this.newLine();
}
return this;
}
/**
* Writes a newline.
*/
newLine(): this {
this._newLineOnNextWrite = false;
this._baseWriteNewline();
return this;
}
/**
* Writes a quote character.
*/
quote(): this;
/**
* Writes text surrounded in quotes.
* @param text - Text to write.
*/
quote(text: string): this;
quote(text?: string) {
this._newLineIfNewLineOnNextWrite();
this._writeIndentingNewLines(text == null ? this._quoteChar : this._quoteChar + escapeForWithinString(text, this._quoteChar) + this._quoteChar);
return this;
}
/**
* Writes a space if the last character was not a space.
*/
spaceIfLastNot(): this {
this._newLineIfNewLineOnNextWrite();
if (!this.isLastSpace()) {
this._writeIndentingNewLines(" ");
}
return this;
}
/**
* Writes a space.
* @param times - Number of times to write a space.
*/
space(times = 1): this {
this._newLineIfNewLineOnNextWrite();
this._writeIndentingNewLines(" ".repeat(times));
return this;
}
/**
* Writes a tab if the last character was not a tab.
*/
tabIfLastNot(): this {
this._newLineIfNewLineOnNextWrite();
if (!this.isLastTab()) {
this._writeIndentingNewLines("\t");
}
return this;
}
/**
* Writes a tab.
* @param times - Number of times to write a tab.
*/
tab(times = 1): this {
this._newLineIfNewLineOnNextWrite();
this._writeIndentingNewLines("\t".repeat(times));
return this;
}
/**
* Conditionally writes text.
* @param condition - Condition to evaluate.
* @param textFunc - A function that returns a string to write if the condition is true.
*/
conditionalWrite(condition: boolean | undefined, textFunc: () => string): this;
/**
* Conditionally writes text.
* @param condition - Condition to evaluate.
* @param text - Text to write if the condition is true.
*/
conditionalWrite(condition: boolean | undefined, text: string): this;
conditionalWrite(condition: boolean | undefined, textOrFunc: string | (() => string)) {
if (condition) {
this.write(getStringFromStrOrFunc(textOrFunc));
}
return this;
}
/**
* Writes the provided text.
* @param text - Text to write.
*/
write(text: string): this {
this._newLineIfNewLineOnNextWrite();
this._writeIndentingNewLines(text);
return this;
}
/**
* Writes text to exit a comment if in a comment.
*/
closeComment(): this {
const commentChar = this._currentCommentChar;
switch (commentChar) {
case CommentChar.Line:
this.newLine();
break;
case CommentChar.Star:
if (!this.isLastNewLine()) {
this.spaceIfLastNot();
}
this.write("*/");
break;
default: {
const _assertUndefined: undefined = commentChar;
break;
}
}
return this;
}
/**
* Inserts text at the provided position.
*
* This method is "unsafe" because it won't update the state of the writer unless
* inserting at the end position. It is biased towards being fast at inserting closer
* to the start or end, but slower to insert in the middle. Only use this if
* absolutely necessary.
* @param pos - Position to insert at.
* @param text - Text to insert.
*/
unsafeInsert(pos: number, text: string): this {
const textLength = this._length;
const texts = this._texts;
verifyInput();
if (pos === textLength) {
return this.write(text);
}
updateInternalArray();
this._length += text.length;
return this;
function verifyInput() {
if (pos < 0) {
throw new Error(`Provided position of '${pos}' was less than zero.`);
}
if (pos > textLength) {
throw new Error(`Provided position of '${pos}' was greater than the text length of '${textLength}'.`);
}
}
function updateInternalArray() {
const { index, localIndex } = getArrayIndexAndLocalIndex();
if (localIndex === 0) {
texts.splice(index, 0, text);
} else if (localIndex === texts[index].length) {
texts.splice(index + 1, 0, text);
} else {
const textItem = texts[index];
const startText = textItem.substring(0, localIndex);
const endText = textItem.substring(localIndex);
texts.splice(index, 1, startText, text, endText);
}
}
function getArrayIndexAndLocalIndex() {
if (pos < textLength / 2) {
// start searching from the front
let endPos = 0;
for (let i = 0; i < texts.length; i++) {
const textItem = texts[i];
const startPos = endPos;
endPos += textItem.length;
if (endPos >= pos) {
return { index: i, localIndex: pos - startPos };
}
}
} else {
// start searching from the back
let startPos = textLength;
for (let i = texts.length - 1; i >= 0; i--) {
const textItem = texts[i];
startPos -= textItem.length;
if (startPos <= pos) {
return { index: i, localIndex: pos - startPos };
}
}
}
throw new Error("Unhandled situation inserting. This should never happen.");
}
}
/**
* Gets the length of the string in the writer.
*/
getLength(): number {
return this._length;
}
/**
* Gets if the writer is currently in a comment.
*/
isInComment(): boolean {
return this._currentCommentChar !== undefined;
}
/**
* Gets if the writer is currently at the start of the first line of the text, block, or indentation block.
*/
isAtStartOfFirstLineOfBlock(): boolean {
return this.isOnFirstLineOfBlock() && (this.isLastNewLine() || this.getLastChar() == null);
}
/**
* Gets if the writer is currently on the first line of the text, block, or indentation block.
*/
isOnFirstLineOfBlock(): boolean {
return this._isOnFirstLineOfBlock;
}
/**
* Gets if the writer is currently in a string.
*/
isInString(): boolean {
return this._stringCharStack.length > 0 && this._stringCharStack[this._stringCharStack.length - 1] !== CHARS.OPEN_BRACE;
}
/**
* Gets if the last chars written were for a newline.
*/
isLastNewLine(): boolean {
const lastChar = this.getLastChar();
return lastChar === "\n" || lastChar === "\r";
}
/**
* Gets if the last chars written were for a blank line.
*/
isLastBlankLine(): boolean {
let foundCount = 0;
// todo: consider extracting out iterating over past characters, but don't use
// an iterator because it will be slow.
for (let i = this._texts.length - 1; i >= 0; i--) {
const currentText = this._texts[i];
for (let j = currentText.length - 1; j >= 0; j--) {
const currentChar = currentText.charCodeAt(j);
if (currentChar === CHARS.NEW_LINE) {
foundCount++;
if (foundCount === 2) {
return true;
}
} else if (currentChar !== CHARS.CARRIAGE_RETURN) {
return false;
}
}
}
return false;
}
/**
* Gets if the last char written was a space.
*/
isLastSpace(): boolean {
return this.getLastChar() === " ";
}
/**
* Gets if the last char written was a tab.
*/
isLastTab(): boolean {
return this.getLastChar() === "\t";
}
/**
* Gets the last char written.
*/
getLastChar(): string | undefined {
const charCode = this._getLastCharCodeWithOffset(0);
return charCode == null ? undefined : String.fromCharCode(charCode);
}
/**
* Gets if the writer ends with the provided text.
* @param text - Text to check if the writer ends with the provided text.
*/
endsWith(text: string): boolean {
const length = this._length;
return this.iterateLastCharCodes((charCode, index) => {
const offset = length - index;
const textIndex = text.length - offset;
if (text.charCodeAt(textIndex) !== charCode) {
return false;
}
return textIndex === 0 ? true : undefined;
}) || false;
}
/**
* Iterates over the writer characters in reverse order. The iteration stops when a non-null or
* undefined value is returned from the action. The returned value is then returned by the method.
*
* @remarks It is much more efficient to use this method rather than `#toString()` since `#toString()`
* will combine the internal array into a string.
*/
iterateLastChars<T>(action: (char: string, index: number) => T | undefined): T | undefined {
return this.iterateLastCharCodes((charCode, index) => action(String.fromCharCode(charCode), index));
}
/**
* Iterates over the writer character char codes in reverse order. The iteration stops when a non-null or
* undefined value is returned from the action. The returned value is then returned by the method.
*
* @remarks It is much more efficient to use this method rather than `#toString()` since `#toString()`
* will combine the internal array into a string. Additionally, this is slightly more efficient that
* `iterateLastChars` as this won't allocate a string per character.
*/
iterateLastCharCodes<T>(action: (charCode: number, index: number) => T | undefined): T | undefined {
let index = this._length;
for (let i = this._texts.length - 1; i >= 0; i--) {
const currentText = this._texts[i];
for (let j = currentText.length - 1; j >= 0; j--) {
index--;
const result = action(currentText.charCodeAt(j), index);
if (result != null) {
return result;
}
}
}
return undefined;
}
/**
* Gets the writer's text.
*/
toString(): string {
if (this._texts.length > 1) {
const text = this._texts.join("");
this._texts.length = 0;
this._texts.push(text);
}
return this._texts[0] || "";
}
/** @internal */
private static readonly _newLineRegEx = /\r?\n/;
/** @internal */
private _writeIndentingNewLines(text: string) {
text = text || "";
if (text.length === 0) {
writeIndividual(this, "");
return;
}
const items = text.split(CodeBlockWriter._newLineRegEx);
items.forEach((s, i) => {
if (i > 0) {
this._baseWriteNewline();
}
if (s.length === 0) {
return;
}
writeIndividual(this, s);
});
function writeIndividual(writer: CodeBlockWriter, s: string) {
if (!writer.isInString()) {
const isAtStartOfLine = writer.isLastNewLine() || writer.getLastChar() == null;
if (isAtStartOfLine) {
writer._writeIndentation();
}
}
writer._updateInternalState(s);
writer._internalWrite(s);
}
}
/** @internal */
private _baseWriteNewline() {
if (this._currentCommentChar === CommentChar.Line) {
this._currentCommentChar = undefined;
}
const lastStringCharOnStack = this._stringCharStack[this._stringCharStack.length - 1];
if ((lastStringCharOnStack === CHARS.DOUBLE_QUOTE || lastStringCharOnStack === CHARS.SINGLE_QUOTE) && this._getLastCharCodeWithOffset(0) !== CHARS.BACK_SLASH) {
this._stringCharStack.pop();
}
this._internalWrite(this._newLine);
this._isOnFirstLineOfBlock = false;
this._dequeueQueuedIndentation();
}
/** @internal */
private _dequeueQueuedIndentation() {
if (this._queuedIndentation == null) {
return;
}
if (this._queuedOnlyIfNotBlock && wasLastBlock(this)) {
this._queuedIndentation = undefined;
this._queuedOnlyIfNotBlock = undefined;
} else {
this._currentIndentation = this._queuedIndentation;
this._queuedIndentation = undefined;
}
function wasLastBlock(writer: CodeBlockWriter) {
let foundNewLine = false;
return writer.iterateLastCharCodes(charCode => {
switch (charCode) {
case CHARS.NEW_LINE:
if (foundNewLine) {
return false;
} else {
foundNewLine = true;
}
break;
case CHARS.CARRIAGE_RETURN:
return undefined;
case CHARS.OPEN_BRACE:
return true;
default:
return false;
}
});
}
}
/** @internal */
private _updateInternalState(str: string) {
for (let i = 0; i < str.length; i++) {
const currentChar = str.charCodeAt(i);
// This is a performance optimization to short circuit all the checks below. If the current char
// is not in this set then it won't change any internal state so no need to continue and do
// so many other checks (this made it 3x faster in one scenario I tested).
if (!isCharToHandle.has(currentChar)) {
continue;
}
const pastChar = i === 0 ? this._getLastCharCodeWithOffset(0) : str.charCodeAt(i - 1);
const pastPastChar = i === 0 ? this._getLastCharCodeWithOffset(1) : i === 1 ? this._getLastCharCodeWithOffset(0) : str.charCodeAt(i - 2);
// handle regex
if (this._isInRegEx) {
if (pastChar === CHARS.FORWARD_SLASH && pastPastChar !== CHARS.BACK_SLASH || pastChar === CHARS.NEW_LINE) {
this._isInRegEx = false;
} else {
continue;
}
} else if (!this.isInString() && !this.isInComment() && isRegExStart(currentChar, pastChar, pastPastChar)) {
this._isInRegEx = true;
continue;
}
// handle comments
if (this._currentCommentChar == null && pastChar === CHARS.FORWARD_SLASH && currentChar === CHARS.FORWARD_SLASH) {
this._currentCommentChar = CommentChar.Line;
} else if (this._currentCommentChar == null && pastChar === CHARS.FORWARD_SLASH && currentChar === CHARS.ASTERISK) {
this._currentCommentChar = CommentChar.Star;
} else if (this._currentCommentChar === CommentChar.Star && pastChar === CHARS.ASTERISK && currentChar === CHARS.FORWARD_SLASH) {
this._currentCommentChar = undefined;
}
if (this.isInComment()) {
continue;
}
// handle strings
const lastStringCharOnStack = this._stringCharStack.length === 0 ? undefined : this._stringCharStack[this._stringCharStack.length - 1];
if (pastChar !== CHARS.BACK_SLASH && (currentChar === CHARS.DOUBLE_QUOTE || currentChar === CHARS.SINGLE_QUOTE || currentChar === CHARS.BACK_TICK)) {
if (lastStringCharOnStack === currentChar) {
this._stringCharStack.pop();
} else if (lastStringCharOnStack === CHARS.OPEN_BRACE || lastStringCharOnStack === undefined) {
this._stringCharStack.push(currentChar);
}
} else if (pastPastChar !== CHARS.BACK_SLASH && pastChar === CHARS.DOLLAR_SIGN && currentChar === CHARS.OPEN_BRACE && lastStringCharOnStack === CHARS.BACK_TICK) {
this._stringCharStack.push(currentChar);
} else if (currentChar === CHARS.CLOSE_BRACE && lastStringCharOnStack === CHARS.OPEN_BRACE) {
this._stringCharStack.pop();
}
}
}
/** @internal - This is private, but exposed for testing. */
_getLastCharCodeWithOffset(offset: number) {
if (offset >= this._length || offset < 0) {
return undefined;
}
for (let i = this._texts.length - 1; i >= 0; i--) {
const currentText = this._texts[i];
if (offset >= currentText.length) {
offset -= currentText.length;
} else {
return currentText.charCodeAt(currentText.length - 1 - offset);
}
}
return undefined;
}
/** @internal */
private _writeIndentation() {
const flooredIndentation = Math.floor(this._currentIndentation);
this._internalWrite(this._indentationText.repeat(flooredIndentation));
const overflow = this._currentIndentation - flooredIndentation;
if (this._useTabs) {
if (overflow > 0.5) {
this._internalWrite(this._indentationText);
}
} else {
const portion = Math.round(this._indentationText.length * overflow);
// build up the string first, then append it for performance reasons
let text = "";
for (let i = 0; i < portion; i++) {
text += this._indentationText[i];
}
this._internalWrite(text);
}
}
/** @internal */
private _newLineIfNewLineOnNextWrite() {
if (!this._newLineOnNextWrite) {
return;
}
this._newLineOnNextWrite = false;
this.newLine();
}
/** @internal */
private _internalWrite(text: string) {
if (text.length === 0) {
return;
}
this._texts.push(text);
this._length += text.length;
}
/** @internal */
private static readonly _spacesOrTabsRegEx = /^[ \t]*$/;
/** @internal */
private _getIndentationLevelFromArg(countOrText: string | number) {
if (typeof countOrText === "number") {
if (countOrText < 0) {
throw new Error("Passed in indentation level should be greater than or equal to 0.");
}
return countOrText;
} else if (typeof countOrText === "string") {
if (!CodeBlockWriter._spacesOrTabsRegEx.test(countOrText)) {
throw new Error("Provided string must be empty or only contain spaces or tabs.");
}
const { spacesCount, tabsCount } = getSpacesAndTabsCount(countOrText);
return tabsCount + spacesCount / this._indentNumberOfSpaces;
} else {
throw new Error("Argument provided must be a string or number.");
}
}
/** @internal */
private _setIndentationState(state: IndentationLevelState) {
this._currentIndentation = state.current;
this._queuedIndentation = state.queued;
this._queuedOnlyIfNotBlock = state.queuedOnlyIfNotBlock;
}
/** @internal */
private _getIndentationState(): IndentationLevelState {
return {
current: this._currentIndentation,
queued: this._queuedIndentation,
queuedOnlyIfNotBlock: this._queuedOnlyIfNotBlock,
};
}
}
interface IndentationLevelState {
current: number;
queued: number | undefined;
queuedOnlyIfNotBlock: true | undefined;
}
function isRegExStart(currentChar: number, pastChar: number | undefined, pastPastChar: number | undefined) {
return pastChar === CHARS.FORWARD_SLASH
&& currentChar !== CHARS.FORWARD_SLASH
&& currentChar !== CHARS.ASTERISK
&& pastPastChar !== CHARS.ASTERISK
&& pastPastChar !== CHARS.FORWARD_SLASH;
}
function getIndentationText(useTabs: boolean, numberSpaces: number) {
if (useTabs) {
return "\t";
}
return Array(numberSpaces + 1).join(" ");
}
function getSpacesAndTabsCount(str: string) {
let spacesCount = 0;
let tabsCount = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode === CHARS.SPACE) {
spacesCount++;
} else if (charCode === CHARS.TAB) {
tabsCount++;
}
}
return { spacesCount, tabsCount };
} | the_stack |
import * as CapabilitiesUtil from "../../../../main/js/joynr/util/CapabilitiesUtil";
import DiscoveryEntry from "../../../../main/js/generated/joynr/types/DiscoveryEntry";
import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo";
import GlobalDiscoveryEntry from "../../../../main/js/generated/joynr/types/GlobalDiscoveryEntry";
import Version from "../../../../main/js/generated/joynr/types/Version";
import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos";
import MqttAddress from "../../../../main/js/generated/joynr/system/RoutingTypes/MqttAddress";
describe("libjoynr-js.joynr.CapabilitiesUtil", () => {
it("is of correct type and has all members", () => {
expect(CapabilitiesUtil).toBeDefined();
expect(CapabilitiesUtil).not.toBeNull();
expect(typeof CapabilitiesUtil === "object").toBeTruthy();
expect(CapabilitiesUtil.toDiscoveryEntry).toBeDefined();
expect(typeof CapabilitiesUtil.toDiscoveryEntry === "function").toBeTruthy();
expect(CapabilitiesUtil.toDiscoveryEntries).toBeDefined();
expect(typeof CapabilitiesUtil.toDiscoveryEntries === "function").toBeTruthy();
expect(CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry).toBeDefined();
expect(typeof CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry === "function").toBeTruthy();
expect(CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo).toBeDefined();
expect(typeof CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo === "function").toBeTruthy();
expect(CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray).toBeDefined();
expect(typeof CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray === "function").toBeTruthy();
});
});
describe("libjoynr-js.joynr.CapabilitiesUtil.discoveryEntryConversions", () => {
let providerVersion: any;
let providerDomain: any;
let interfaceName: string;
let providerParticipantId: any;
let providerQos: ProviderQos;
let now: any;
let lastSeenDateMs: number;
let expiryDateMs: number;
let publicKeyId: any;
let address: any;
let serializedAddress: any;
let discoveryEntry: DiscoveryEntry;
let globalDiscoveryEntry: GlobalDiscoveryEntry;
let localDiscoveryEntryWithMetaInfo: any;
let globalDiscoveryEntryWithMetaInfo: any;
beforeEach(() => {
providerVersion = new Version({
majorVersion: 47,
minorVersion: 11
});
providerDomain = "providerDomain";
interfaceName = "interfaceName";
providerParticipantId = "providerParticipantId";
providerQos = new ProviderQos(undefined as any);
now = Date.now();
lastSeenDateMs = now;
expiryDateMs = now + 60000;
publicKeyId = "testPublicKeyId";
address = new MqttAddress(undefined as any);
serializedAddress = JSON.stringify(address);
discoveryEntry = new DiscoveryEntry({
providerVersion,
domain: providerDomain,
interfaceName,
participantId: providerParticipantId,
qos: providerQos,
lastSeenDateMs,
expiryDateMs,
publicKeyId
});
globalDiscoveryEntry = new GlobalDiscoveryEntry({
providerVersion,
domain: providerDomain,
interfaceName,
participantId: providerParticipantId,
qos: providerQos,
lastSeenDateMs,
expiryDateMs,
publicKeyId,
address: serializedAddress
});
localDiscoveryEntryWithMetaInfo = new DiscoveryEntryWithMetaInfo({
providerVersion,
domain: providerDomain,
interfaceName,
participantId: providerParticipantId,
qos: providerQos,
lastSeenDateMs,
expiryDateMs,
publicKeyId,
isLocal: true
});
globalDiscoveryEntryWithMetaInfo = new DiscoveryEntryWithMetaInfo({
providerVersion,
domain: providerDomain,
interfaceName,
participantId: providerParticipantId,
qos: providerQos,
lastSeenDateMs,
expiryDateMs,
publicKeyId,
isLocal: false
});
});
function compareDiscoveryEntries(expected: any, actual: any) {
expect(actual._typeName).toEqual(expected._typeName);
expect(actual.providerVersion).toEqual(expected.providerVersion);
expect(actual.domain).toEqual(expected.domain);
expect(actual.interfaceName).toEqual(expected.interfaceName);
expect(actual.participantId).toEqual(expected.participantId);
expect(actual.qos).toEqual(expected.qos);
expect(actual.lastSeenDateMs).toEqual(expected.lastSeenDateMs);
expect(actual.expiryDateMs).toEqual(expected.expiryDateMs);
expect(actual.publicKeyId).toEqual(expected.publicKeyId);
}
function compareDiscoveryEntriesWithMetaInfo(isLocal: any, expected: any, actual: any) {
compareDiscoveryEntries(expected, actual);
expect(actual.isLocal).toEqual(isLocal);
}
function compareGlobalDiscoveryEntries(address: any, expected: any, actual: any) {
compareDiscoveryEntries(expected, actual);
expect(actual.address).toEqual(address);
}
it("convert to GlobalDiscoveryEntry", () => {
let convertedDiscoveryEntry = CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry(discoveryEntry, address);
compareGlobalDiscoveryEntries(serializedAddress, globalDiscoveryEntry, convertedDiscoveryEntry);
convertedDiscoveryEntry = CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry(
localDiscoveryEntryWithMetaInfo,
address
);
compareGlobalDiscoveryEntries(serializedAddress, globalDiscoveryEntry, convertedDiscoveryEntry);
convertedDiscoveryEntry = CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry(
globalDiscoveryEntryWithMetaInfo,
address
);
compareGlobalDiscoveryEntries(serializedAddress, globalDiscoveryEntry, convertedDiscoveryEntry);
});
it("convert to local DiscoveryEntryWithMetaInfo", () => {
let convertedDiscoveryEntry = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(true, discoveryEntry);
compareDiscoveryEntriesWithMetaInfo(true, localDiscoveryEntryWithMetaInfo, convertedDiscoveryEntry);
convertedDiscoveryEntry = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(true, globalDiscoveryEntry);
compareDiscoveryEntriesWithMetaInfo(true, localDiscoveryEntryWithMetaInfo, convertedDiscoveryEntry);
});
it("convert to global DiscoveryEntryWithMetaInfo", () => {
let convertedDiscoveryEntry = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, discoveryEntry);
compareDiscoveryEntriesWithMetaInfo(false, localDiscoveryEntryWithMetaInfo, convertedDiscoveryEntry);
convertedDiscoveryEntry = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, globalDiscoveryEntry);
compareDiscoveryEntriesWithMetaInfo(false, localDiscoveryEntryWithMetaInfo, convertedDiscoveryEntry);
});
function createArrayOfDiscoveryEntries() {
const discoveryEntries = [];
discoveryEntries.push(discoveryEntry);
discoveryEntries.push(
new DiscoveryEntry({
providerVersion,
domain: "providerDomain2",
interfaceName,
participantId: "providerParticipantId2",
qos: providerQos,
lastSeenDateMs: 4711,
expiryDateMs: 4712,
publicKeyId: "testPublicKeyId2"
})
);
return discoveryEntries;
}
function createArrayOfDiscoveryEntriesWithMetaInfo(isLocal: any) {
const discoveryEntries = [];
const discoveryEntry2 = new DiscoveryEntryWithMetaInfo({
providerVersion,
domain: "providerDomain2",
interfaceName,
participantId: "providerParticipantId2",
qos: providerQos,
lastSeenDateMs: 4711,
expiryDateMs: 4712,
publicKeyId: "testPublicKeyId2",
isLocal: false
});
if (isLocal === true) {
discoveryEntries.push(localDiscoveryEntryWithMetaInfo);
discoveryEntry2.isLocal = true;
} else {
discoveryEntries.push(globalDiscoveryEntryWithMetaInfo);
}
discoveryEntries.push(discoveryEntry2);
return discoveryEntries;
}
function compareArrayOfDiscoveryEntriesWithMetaInfo(isLocal: any, expected: any, actual: any) {
let i: any;
expect(actual.length).toEqual(expected.length);
for (i = 0; i < expected.length; i++) {
compareDiscoveryEntriesWithMetaInfo(isLocal, expected[i], actual[i]);
}
}
it("convert to array of local DiscoveryEntryWithMetaInfo", () => {
const discoveryEntryArray = createArrayOfDiscoveryEntries();
const convertedDiscoveryEntryArray = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(
true,
discoveryEntryArray
);
const expected = createArrayOfDiscoveryEntriesWithMetaInfo(true);
compareArrayOfDiscoveryEntriesWithMetaInfo(true, expected, convertedDiscoveryEntryArray);
});
it("convert to array of global DiscoveryEntryWithMetaInfo", () => {
const discoveryEntryArray = createArrayOfDiscoveryEntries();
const convertedDiscoveryEntryArray = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(
false,
discoveryEntryArray
);
const expected = createArrayOfDiscoveryEntriesWithMetaInfo(false);
compareArrayOfDiscoveryEntriesWithMetaInfo(false, expected, convertedDiscoveryEntryArray);
});
}); | the_stack |
import { RelatedContentRepresentation } from '../model/relatedContentRepresentation';
import { ResultListDataRepresentationRelatedContentRepresentation } from '../model/resultListDataRepresentationRelatedContentRepresentation';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
/**
* Content service.
* @module ContentApi
*/
export class ContentApi extends BaseApi {
/**
* Attach existing content to a process instance
*
*
*
* @param processInstanceId processInstanceId
* @param relatedContent relatedContent
* @param opts Optional parameters
* @param opts.isRelatedContent isRelatedContent
* @return Promise<RelatedContentRepresentation>
*/
createRelatedContentOnProcessInstance(processInstanceId: string, relatedContent: RelatedContentRepresentation | any, opts?: any): Promise<RelatedContentRepresentation> {
throwIfNotDefined(processInstanceId, 'processInstanceId');
throwIfNotDefined(relatedContent, 'relatedContent');
opts = opts || {};
let pathParams = {
'processInstanceId': processInstanceId
};
let queryParams = {
'isRelatedContent': opts['isRelatedContent']
};
let headerParams = {};
let formParams = {};
let accepts = ['application/json'];
if (relatedContent instanceof RelatedContentRepresentation) {
let postBody = relatedContent;
let contentTypes = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/process-instances/{processInstanceId}/content', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
} else {
let postBody = null;
formParams = {
'file': relatedContent
};
let contentTypes = ['multipart/form-data'];
return this.apiClient.callApi(
'/api/enterprise/process-instances/{processInstanceId}/raw-content', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
}
}
/**
* Attach existing content to a task
*
*
*
* @param taskId taskId
* @param relatedContent relatedContent
* @param opts Optional parameters
* @param opts.isRelatedContent isRelatedContent
* @return Promise<RelatedContentRepresentation>
*/
createRelatedContentOnTask(taskId: string, relatedContent: RelatedContentRepresentation | any, opts?: any): Promise<RelatedContentRepresentation> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(relatedContent, 'relatedContent');
opts = opts || {};
let pathParams = {
'taskId': taskId
};
let queryParams = {
'isRelatedContent': opts['isRelatedContent']
};
let headerParams = {};
let formParams = {};
let accepts = ['application/json'];
if (relatedContent instanceof RelatedContentRepresentation) {
let postBody = relatedContent;
let contentTypes = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/content', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
} else {
let postBody = null;
formParams = {
'file': relatedContent
};
let contentTypes = ['multipart/form-data'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/raw-content', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
}
}
/**
* Upload content and create a local representation
*
*
*
* @param file file
* @return Promise<RelatedContentRepresentation>
*/
createTemporaryRawRelatedContent(file: any): Promise<RelatedContentRepresentation> {
throwIfNotDefined(file, 'file');
let postBody = null;
let pathParams = {};
let queryParams = {};
let headerParams = {};
let formParams = {
'file': file
};
let contentTypes = ['multipart/form-data'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/content/raw', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
}
/**
* Create a local representation of content from a remote repository
*
*
*
* @param relatedContent relatedContent
* @return Promise<RelatedContentRepresentation>
*/
createTemporaryRelatedContent(relatedContent: RelatedContentRepresentation): Promise<RelatedContentRepresentation> {
throwIfNotDefined(relatedContent, 'relatedContent');
let postBody = relatedContent;
let pathParams = {};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/content', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
}
/**
* Remove a local content representation
*
*
*
* @param contentId contentId
* @return Promise<{}>
*/
deleteContent(contentId: number): Promise<any> {
throwIfNotDefined(contentId, 'contentId');
let postBody = null;
let pathParams = {
'contentId': contentId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/content/{contentId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Get a local content representation
*
*
*
* @param contentId contentId
* @return Promise<RelatedContentRepresentation>
*/
getContent(contentId: number): Promise<RelatedContentRepresentation> {
throwIfNotDefined(contentId, 'contentId');
let postBody = null;
let pathParams = {
'contentId': contentId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/content/{contentId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RelatedContentRepresentation);
}
/**
* Get content Raw URL for the given contentId
* @param contentId contentId
*/
getRawContentUrl(contentId: number) {
return `${this.apiClient.basePath}/api/enterprise/content/${contentId}/raw`;
}
/**
* Stream content rendition
*
*
*
* @param contentId contentId
* @param renditionType renditionType
* @return Promise<{}>
*/
getRawContent(contentId: number, renditionType?: string): Promise<any> {
throwIfNotDefined(contentId, 'contentId');
let postBody = null;
let queryParams = {};
let headerParams = {};
let formParams = {};
if (renditionType) {
const contentTypes = ['application/json'];
const accepts = ['application/json'];
let pathParams = {
'contentId': contentId,
'renditionType': renditionType
};
return this.apiClient.callApi(
'/api/enterprise/content/{contentId}/rendition/{renditionType}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, 'blob');
} else {
const contentTypes = ['application/json'];
const accepts = ['application/json'];
let pathParams = {
'contentId': contentId
};
return this.apiClient.callApi(
'/api/enterprise/content/{contentId}/raw', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, 'blob', undefined, 'blob');
}
}
/**
* List content attached to a process instance
*
*
*
* @param processInstanceId processInstanceId
* @param opts Optional parameters
* @param opts.isRelatedContent isRelatedContent
* @return Promise<ResultListDataRepresentationRelatedContentRepresentation>
*/
getRelatedContentForProcessInstance(processInstanceId: string, opts?: any): Promise<ResultListDataRepresentationRelatedContentRepresentation> {
throwIfNotDefined(processInstanceId, 'processInstanceId');
opts = opts || {};
let postBody = null;
let pathParams = {
'processInstanceId': processInstanceId
};
let queryParams = {
'isRelatedContent': opts['isRelatedContent']
};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/process-instances/{processInstanceId}/content', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ResultListDataRepresentationRelatedContentRepresentation);
}
/**
* List content attached to a task
*
*
*
* @param taskId taskId
* @param opts Optional parameters
* @param opts.isRelatedContent isRelatedContent
* @return Promise<ResultListDataRepresentationRelatedContentRepresentation>
*/
getRelatedContentForTask(taskId: string, opts?: any): Promise<ResultListDataRepresentationRelatedContentRepresentation> {
throwIfNotDefined(taskId, 'taskId');
opts = opts || {};
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {
'isRelatedContent': opts['isRelatedContent']
};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/content', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ResultListDataRepresentationRelatedContentRepresentation);
}
} | the_stack |
import * as pl from "@akashic/playlog";
import {
Asset,
AssetConfiguration,
Camera2D,
E,
GameConfiguration,
LoadingScene,
LoadingSceneParameterObject,
LocalTickModeString,
MessageEvent,
PlatformPointType,
Scene,
XorshiftRandomGenerator
} from "..";
import { customMatchers, EntityStateFlags, Game, Renderer, ImageAsset, ScriptAsset } from "./helpers";
expect.extend(customMatchers);
describe("test Game", () => {
it("初期化", () => {
const game = new Game({ width: 320, height: 270, main: "", assets: {} }, undefined, "foo");
expect(game._idx).toBe(0);
expect(game.db).toEqual({});
expect(game.renderers.length).toBe(0);
expect(game.scenes.length).toBe(0);
expect(game.random).toBeUndefined();
expect(game.localRandom).toBeDefined();
expect(game._modified).toBe(true);
expect(game.external).toEqual({});
expect(game.age).toBe(0);
expect(game.fps).toBe(30);
expect(game.width).toBe(320);
expect(game.height).toBe(270);
expect(game.selfId).toBe("foo");
expect(game.joinedPlayerIds).toEqual([]);
expect(game.playId).toBeUndefined();
expect(game.onSkipChange).not.toBeUndefined();
expect(game.onSceneChange).not.toBeUndefined();
expect(game._onSceneChange).not.toBeUndefined();
expect(game).toHaveProperty("_assetManager");
expect(game).toHaveProperty("_initialScene");
expect(game._moduleManager).toBeDefined();
});
it("_destroy()", () => {
const game = new Game({ width: 320, height: 270, main: "", assets: {} }, undefined, "foo");
game._destroy();
expect(game.db).toBeUndefined();
expect(game.renderers).toBeUndefined();
expect(game.scenes).toBeUndefined();
expect(game.random).toBeUndefined();
expect(game.localRandom).toBeUndefined();
expect(game._modified).toBe(false);
expect(game.external).toEqual({}); // external は触らない
expect(game.vars).toEqual({}); // vars も触らない
expect(game.playId).toBeUndefined();
expect(game.onSkipChange).toBeUndefined();
expect(game.onSceneChange).toBeUndefined();
expect(game._onSceneChange).toBeUndefined();
expect(game._moduleManager).toBeUndefined();
});
it("global assets", done => {
const game = new Game({
width: 320,
height: 270,
main: "",
assets: {
foo: {
type: "image",
path: "/dummypath.png",
virtualPath: "dummypath.png",
global: true,
width: 1,
height: 1
},
bar: {
type: "text",
path: "/dummypath.txt",
virtualPath: "dummypath.txt"
}
}
});
game._onLoad.add(() => {
expect(game.assets.foo).not.toBe(undefined);
expect(game.assets.foo instanceof ImageAsset).toBe(true);
expect(game.assets).not.toHaveProperty("bar");
done();
});
game._startLoadingGlobalAssets();
});
it("_loadAndStart", done => {
const assets: { [id: string]: AssetConfiguration } = {
mainScene: {
// _loadAndStart() には mainScene が必要
type: "script",
path: "/dummy/dummy.js", // パスはダミーであり使用されてはいない。tsのScriptAssetを参照のこと
virtualPath: "dummy/dummy.js",
global: true
}
};
const game = new Game({ width: 320, height: 320, assets: assets, main: "./dummy/dummy.js" });
let loadedFired = false;
game._onLoad.add(() => {
loadedFired = true;
});
game._onStart.add(() => {
expect(loadedFired).toBe(true);
expect(game.assets.mainScene).not.toBe(undefined);
expect(game.assets.mainScene instanceof ScriptAsset).toBe(true);
expect(game.assets).not.toHaveProperty("foo");
done();
});
game._loadAndStart();
});
it("must fire 'loaded' of mainScene at age 0", done => {
const assets: { [id: string]: AssetConfiguration } = {
mainScene: {
// _loadAndStart() には mainScene が必要
type: "script",
path: "./script/mainScene.js",
virtualPath: "script/mainScene.js",
global: true
}
};
const game = new Game({ width: 320, height: 320, assets: assets, main: "./script/mainScene.js" });
game.resourceFactory.scriptContents["./script/mainScene.js"] = "module.exports = () => g.game.__test__();";
let testPass = false;
function requestTick(): void {
if (!testPass) {
game.classicTick();
setTimeout(requestTick, 1);
return;
}
done();
}
(game as any).__test__ = () => {
const scene = new Scene({ game: game });
expect(game.age).toBe(0);
scene.onLoad.add(() => {
expect(game.age).toBe(0);
testPass = true;
});
game.pushScene(scene);
requestTick();
return scene;
};
game._loadAndStart();
});
it("_loadAndStart - with entry point", done => {
const assets: { [id: string]: AssetConfiguration } = {
dummy: {
type: "script",
path: "/dummy/dummy.js", // パスはダミー
virtualPath: "dummy/dummy.js",
global: true
}
};
const game = new Game({ width: 320, height: 320, assets: assets, main: "./dummy/dummy.js" }, "/");
let loadedFired = false;
game._onLoad.add(() => {
loadedFired = true;
});
game._onStart.add(() => {
expect(loadedFired).toBe(true);
expect(game.assets.dummy).not.toBe(undefined);
expect(game.assets.dummy instanceof ScriptAsset).toBe(true);
done();
});
game._loadAndStart({ args: "arg-value" });
});
it("_loadAndStart - with mainFunc", done => {
const mainFunc = (g: any, args: any): void => {
expect(g).toBeDefined();
expect(g.Game).toBeDefined();
expect(g.Scene).toBeDefined();
expect(args).toEqual({ args: "arg-value" });
done();
};
const game = new Game({ width: 320, height: 320, main: "dummy", assets: {} }, "/", undefined, undefined, mainFunc);
game._loadAndStart({ args: "arg-value" });
});
it("_loadAndStart - after loaded", done => {
const assets: { [id: string]: AssetConfiguration } = {
mainScene: {
type: "script",
path: "/script/mainScene.js",
virtualPath: "script/mainScene.js",
global: true
}
};
const game = new Game({ width: 320, height: 320, assets: assets, main: "./script/mainScene.js" }, "/");
game.resourceFactory.scriptContents["/script/mainScene.js"] = "module.exports = () => { return g.game.__test__(); };";
(game as any).__test__ = () => {
delete game.resourceFactory.scriptContents["/script/mainScene.js"];
done();
return new Scene({ game: game });
};
game._onLoad.add(() => {
const scene = new Scene({ game: game });
scene.onLoad.add(() => {
game._loadAndStart();
});
game.pushScene(scene);
game._flushPostTickTasks();
expect(() => {
game._startLoadingGlobalAssets();
}).toThrowError("AssertionError");
});
game._startLoadingGlobalAssets();
});
it("pushScene", done => {
const game = new Game({
width: 320,
height: 320,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
}
}
});
game._onLoad.add(() => {
// game.scenes テストのため _loaded を待つ必要がある
const scene1 = new Scene({ game, assetIds: ["foo"] });
const scene2 = new Scene({ game, assetIds: ["foo"] });
game.pushScene(scene1);
let scene1foo: Asset;
scene1.onLoad.addOnce(() => {
expect(game.scenes).toEqual([game._initialScene, scene1]);
scene1foo = scene1.assets.foo;
game.pushScene(scene2);
});
scene2.onLoad.addOnce(() => {
expect(game.scenes).toEqual([game._initialScene, scene1, scene2]);
// 同一IDのアセットを前のシーンで読み込んでいた場合はアセットの再読み込みが発生しない (= 同一インスタンスである) ことを確認
expect(scene1foo).toBe(scene2.assets.foo);
done();
});
});
game._startLoadingGlobalAssets();
});
it("popScene", done => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
game._onLoad.add(() => {
// game.scenes テストのため _loaded を待つ必要がある
const scene = new Scene({ game: game, name: "SCENE1" });
const scene2 = new Scene({ game: game, name: "SCENE2" });
game.pushScene(scene);
game.pushScene(scene2);
game.popScene();
game._flushPostTickTasks();
expect(game.scenes).toEqual([game._initialScene, scene]);
game.popScene();
game._flushPostTickTasks();
expect(game.scenes).toEqual([game._initialScene]);
done();
});
game._startLoadingGlobalAssets();
});
it("popScene - specified step", done => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
game._onLoad.add(() => {
// game.scenes テストのため _loaded を待つ必要がある
// popSceneで指定したシーンまで戻る際に経過したシーンは全て削除
const scene = new Scene({ game: game, name: "SCENE1" });
const scene2 = new Scene({ game: game, name: "SCENE2" });
const scene3 = new Scene({ game: game, name: "SCENE3" });
game.pushScene(scene);
game.pushScene(scene2);
game.pushScene(scene3);
game.popScene(false, 2);
game._flushPostTickTasks();
expect(game.scenes).toEqual([game._initialScene, scene]);
expect(scene.destroyed()).toBe(false);
expect(scene2.destroyed()).toBe(true);
expect(scene3.destroyed()).toBe(true);
// popSceneで指定したシーンまで戻る際に経過したシーンは全て残す
const scene2Alpha = new Scene({ game: game, name: "SCENE2_Alpha" });
const scene3Beta = new Scene({ game: game, name: "SCENE3_Beta" });
game.pushScene(scene2Alpha);
game.pushScene(scene3Beta);
game.popScene(true, 3);
game._flushPostTickTasks();
expect(game.scenes).toEqual([game._initialScene]);
expect(scene.destroyed()).toBe(false);
expect(scene2Alpha.destroyed()).toBe(false);
expect(scene3Beta.destroyed()).toBe(false);
done();
});
game._startLoadingGlobalAssets();
});
it("replaceScene", done => {
const game = new Game({
width: 320,
height: 320,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
}
}
});
game._onLoad.add(() => {
// game.scenes テストのため _loaded を待つ必要がある
const scene1 = new Scene({ game, assetIds: ["foo"] });
const scene2 = new Scene({ game, assetIds: ["foo"] });
game.pushScene(scene1);
let scene1foo: Asset;
scene1.onLoad.addOnce(() => {
scene1foo = scene1.assets.foo;
game.replaceScene(scene2);
});
scene2.onLoad.addOnce(() => {
expect(game.scenes).toEqual([game._initialScene, scene2]);
// 同一IDのアセットを前のシーンで読み込んでいた場合はアセットの再読み込みが発生しない (= 同一インスタンスである) ことを確認
expect(scene1foo).toBe(scene2.assets.foo);
done();
});
});
game._startLoadingGlobalAssets();
});
it("tick", done => {
const assets: { [id: string]: AssetConfiguration } = {
mainScene: {
// _loadAndStart() には mainScene が必要
type: "script",
path: "./dummy/dummy.js", // パスはダミーであり使用されてはいない。tsのScriptAssetを参照のこと
virtualPath: "dummy/dummy.js",
global: true
}
};
const game = new Game({ width: 320, height: 320, assets: assets, main: "./dummy/dummy.js" });
game._onLoad.add(() => {
const scene = new Scene({ game: game });
game.pushScene(scene);
expect(game.age).toBe(0);
expect(game.classicTick()).toBe(true);
expect(game.scene()!.local).toBe("non-local");
expect(game.classicTick()).toBe(false);
expect(game.age).toBe(1);
expect(game.tick(false, 3)).toBe(false);
expect(game.age).toBe(1);
expect(game.isLastTickLocal).toBe(true);
expect(game.lastOmittedLocalTickCount).toBe(3);
expect(game.tick(true)).toBe(false);
expect(game.age).toBe(2);
expect(game.isLastTickLocal).toBe(false);
expect(game.lastOmittedLocalTickCount).toBe(0);
done();
});
game._loadAndStart();
});
it("loadingScene - without assets", done => {
const game = new Game({
width: 320,
height: 320,
fps: 30,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
}
}
});
let logs: string[] = [];
class TestLoadingScene extends LoadingScene {
constructor(param: LoadingSceneParameterObject) {
super(param);
this.onLoad.add(() => {
logs.push("LoadingSceneLoaded");
});
this.onTargetReady.add(() => {
logs.push("TargetLoaded");
}, this);
}
}
const loadingScene = new TestLoadingScene({
game: game,
name: "testLoadingScene"
});
game._onLoad.add(() => {
game.loadingScene = loadingScene;
class MockScene1 extends Scene {
_load(): void {
logs.push("SceneLoad");
super._load();
}
}
const scene = new MockScene1({
game: game,
assetIds: ["foo"],
name: "scene1"
});
scene.onAssetLoad.add(() => {
logs.push("SceneAssetLoaded");
});
scene.onLoad.add(() => {
expect(logs).toEqual([
"LoadingSceneLoaded", // これ(LoagingSceneの読み込み完了)の後に
"SceneLoad", // 遷移先シーンの読み込みが開始されることが重要
"SceneAssetLoaded",
"TargetLoaded"
]);
// LoadingScene の読み込みが終わっている状態でのシーン遷移をテスト
logs = [];
class MockScene2 extends Scene {
_load(): void {
logs.push("Scene2Load");
super._load();
}
}
const scene2 = new MockScene2({ game: game, assetIds: ["foo"] });
scene2.onAssetLoad.add(() => {
logs.push("Scene2AssetLoaded");
});
scene2.onLoad.add(() => {
expect(logs).toEqual(["Scene2Load", "Scene2AssetLoaded", "TargetLoaded"]);
setTimeout(() => {
expect(game.loadingScene.onLoad.length).toBe(1); // loadingSceneのonLoadハンドラが増えていかないことを確認
done();
}, 1);
});
game.pushScene(scene2);
game._flushPostTickTasks();
});
game.pushScene(scene);
game._flushPostTickTasks();
});
game._startLoadingGlobalAssets();
});
it("loadingScene - with assets", done => {
const game = new Game({
width: 320,
height: 320,
fps: 30,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
},
zoo: {
type: "audio",
path: "/path/to/a/file",
virtualPath: "path/to/a/file",
systemId: "sound",
duration: 1984
}
}
});
let logs: string[] = [];
class TestLoadingScene extends LoadingScene {
constructor(param: LoadingSceneParameterObject) {
super(param);
this.onAssetLoad.add(() => {
logs.push("LoadingSceneAssetLoaded");
});
this.onLoad.add(() => {
logs.push("LoadingSceneLoaded");
});
this.onTargetReady.add(() => {
logs.push("TargetLoaded");
}, this);
}
}
const loadingScene = new TestLoadingScene({
game: game,
assetIds: ["foo", "zoo"]
});
game._onLoad.add(() => {
game.loadingScene = loadingScene;
class MockScene1 extends Scene {
_load(): void {
logs.push("SceneLoad");
super._load();
}
}
const scene = new MockScene1({ game: game, assetIds: ["zoo"] });
scene.onAssetLoad.add(() => {
logs.push("SceneAssetLoaded");
});
scene.onLoad.add(() => {
expect(logs).toEqual([
"LoadingSceneAssetLoaded",
"LoadingSceneAssetLoaded",
"LoadingSceneLoaded", // これ(LoagingSceneの読み込み完了)の後に
"SceneLoad", // 遷移先シーンの読み込みが開始されることが重要
"SceneAssetLoaded",
"TargetLoaded"
]);
// LoadingScene の読み込みが終わっている状態でのシーン遷移をテスト
logs = [];
class MockScene2 extends Scene {
_load(): void {
logs.push("Scene2Load");
super._load();
}
}
const scene2 = new MockScene2({ game: game, assetIds: ["zoo"] });
scene2.onAssetLoad.add(() => {
logs.push("Scene2AssetLoaded");
});
scene2.onLoad.add(() => {
expect(logs).toEqual(["Scene2Load", "Scene2AssetLoaded", "TargetLoaded"]);
setTimeout(() => {
expect(game.loadingScene.onLoad.length).toBe(1); // loadingSceneのloadedハンドラが増えていかないことを確認
done();
}, 1);
});
game.pushScene(scene2);
game._flushPostTickTasks();
});
game.pushScene(scene);
game._flushPostTickTasks();
});
game._startLoadingGlobalAssets();
});
it("loadingScene - with assets, manual end", done => {
const game = new Game({
width: 320,
height: 320,
fps: 30,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
},
zoo: {
type: "audio",
path: "/path/to/a/file",
virtualPath: "path/to/a/file",
systemId: "sound",
duration: 1984
}
}
});
let asyncEndCalled = false;
let resetCount = 0;
let invalidEndTrialCount = 0;
const loadingScene = new LoadingScene({
game: game,
assetIds: ["foo", "zoo"],
explicitEnd: true
});
loadingScene.onTargetReset.add(() => {
resetCount++;
expect(loadingScene.getTargetWaitingAssetsCount()).toBe(1); // 下記 const scene の assetIds: ["zoo"] しかこないので
}, loadingScene);
loadingScene.onTargetAssetLoad.add(() => {
invalidEndTrialCount++;
expect(() => {
loadingScene.end();
}).toThrow();
}, loadingScene);
loadingScene.onTargetReady.add(() => {
setTimeout(() => {
asyncEndCalled = true;
loadingScene.end();
}, 10);
}, loadingScene);
game._onLoad.add(() => {
game.loadingScene = loadingScene;
const scene = new Scene({ game: game, assetIds: ["zoo"] });
scene.onLoad.add(() => {
expect(asyncEndCalled).toBe(true);
expect(invalidEndTrialCount).toBe(1);
expect(resetCount).toBe(1);
done();
});
game.pushScene(scene);
game._flushPostTickTasks();
});
game._startLoadingGlobalAssets();
});
it("_sceneChanged", done => {
const gameConfiguration: GameConfiguration = {
width: 320,
height: 320,
fps: 30,
main: "",
assets: {
foo: {
type: "image",
path: "/path1.png",
virtualPath: "path1.png",
width: 1,
height: 1
},
zoo: {
type: "audio",
path: "/path/to/a/file",
virtualPath: "path/to/a/file",
systemId: "sound",
duration: 1984
}
}
};
const game = new Game(gameConfiguration);
let topIsLocal: LocalTickModeString | undefined = undefined;
let sceneChangedCount = 0;
let _sceneChangedCount = 0;
game.onSceneChange.add(() => {
sceneChangedCount++;
});
game._onSceneChange.add(scene => {
_sceneChangedCount++;
topIsLocal = scene!.local;
});
game._onLoad.add(() => {
// game.scenes テストのため _loaded を待つ必要がある
const scene = new Scene({ game: game });
const scene2 = new Scene({ game: game, assetIds: ["foo"] });
const scene3 = new Scene({
game: game,
assetIds: ["foo", "zoo"],
local: true
});
scene.onLoad.add(() => {
expect(sceneChangedCount).toBe(2); // _initialScene と scene (いずれも loadingSceneなし) で 2
expect(_sceneChangedCount).toBe(2);
expect(topIsLocal).toBe("non-local");
expect(game.scenes).toEqual([game._initialScene, scene]);
expect(game._eventTriggerMap["point-down"]).toBe(scene.onPointDownCapture);
scene2.onLoad.add(() => {
expect(sceneChangedCount).toBe(4); // loadingScene が pop されて 1 増えたので 4
expect(_sceneChangedCount).toBe(4);
expect(topIsLocal).toBe("non-local");
expect(game.scenes).toEqual([game._initialScene, scene2]);
expect(game._eventTriggerMap["point-down"]).toBe(scene2.onPointDownCapture);
scene3.onLoad.add(() => {
expect(sceneChangedCount).toBe(6);
expect(_sceneChangedCount).toBe(6);
expect(topIsLocal).toBe("full-local");
expect(game.scenes).toEqual([game._initialScene, scene2, scene3]);
expect(game._eventTriggerMap["point-down"]).toBe(scene3.onPointDownCapture);
game.popScene();
game._flushPostTickTasks();
expect(sceneChangedCount).toBe(7);
expect(_sceneChangedCount).toBe(7);
expect(topIsLocal).toBe("non-local");
expect(game.scenes).toEqual([game._initialScene, scene2]);
expect(game._eventTriggerMap["point-down"]).toBe(scene2.onPointDownCapture);
game.popScene();
game._flushPostTickTasks();
expect(sceneChangedCount).toBe(8);
expect(_sceneChangedCount).toBe(8);
expect(topIsLocal).toBe("full-local");
expect(game.scenes).toEqual([game._initialScene]);
expect(game._eventTriggerMap["point-down"]).toBe(game._initialScene.onPointDownCapture);
done();
});
game.pushScene(scene3);
game._flushPostTickTasks();
expect(sceneChangedCount).toBe(5);
expect(_sceneChangedCount).toBe(5);
expect(topIsLocal).toBe("full-local");
expect(game.scenes).toEqual([game._initialScene, scene2, scene3, game._defaultLoadingScene]);
expect(game._eventTriggerMap["point-down"]).toBe(game._defaultLoadingScene.onPointDownCapture);
});
game.replaceScene(scene2);
game._flushPostTickTasks();
expect(sceneChangedCount).toBe(3); // scene2とloadingSceneが乗るが、scene2はまだ_sceneStackTopChangeCountをfireしてない
expect(_sceneChangedCount).toBe(3);
expect(topIsLocal).toBe("full-local"); // loadingScene がトップなので local
expect(game.scenes).toEqual([game._initialScene, scene2, game._defaultLoadingScene]);
expect(game._eventTriggerMap["point-down"]).toBe(game._defaultLoadingScene.onPointDownCapture);
});
expect(sceneChangedCount).toBe(1); // _initialScene (loadingSceneなし) が push された分で 1
expect(_sceneChangedCount).toBe(1);
expect(topIsLocal).toBe("full-local");
expect(game.scenes).toEqual([game._initialScene]);
expect(game._eventTriggerMap["point-down"]).toBe(game._initialScene.onPointDownCapture);
game.pushScene(scene);
game._flushPostTickTasks();
});
game._startLoadingGlobalAssets();
});
it("scene", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const scene = new Scene({ game: game });
const scene2 = new Scene({ game: game });
game.pushScene(scene);
game._flushPostTickTasks();
expect(game.scene()).toBe(scene);
game.replaceScene(scene2);
game._flushPostTickTasks();
expect(game.scene()).toBe(scene2);
});
it("register", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const scene = new Scene({ game: game });
const e = new E({ scene: scene });
expect(e.id).toBe(1);
expect(game.db).toEqual({ 1: e });
const e2 = new E({ scene: scene });
expect(e2.id).toBe(2);
expect(game.db).toEqual({ 1: e, 2: e2 });
const n = { id: undefined as any, age: 100 };
game.register(n as any);
expect(game.db[n.id]).toEqual(n);
const e3 = new E({ scene: scene, local: true });
expect(game._localDb[e3.id].id).toBe(e3.id);
});
it("unregister", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const scene = new Scene({ game: game });
const e = new E({ scene: scene });
expect(game.db).toEqual({ 1: e });
game.unregister(e);
expect(game.db).toEqual({});
const e2 = new E({ scene: scene, local: true });
expect(game.db).toEqual({});
expect(game._localDb[e2.id]).toBe(e2);
game.unregister(e2);
expect(game._localDb[e2.id]).toBeUndefined();
});
it("terminateGame", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const scene = new Scene({ game: game });
let count = 0;
scene.onUpdate.add(() => {
++count;
});
game.pushScene(scene);
game._flushPostTickTasks();
game.classicTick();
expect(count).toBe(1);
game.classicTick();
expect(count).toBe(2);
game.terminateGame();
expect(game.terminatedGame).toBe(true);
game.classicTick();
expect(count).toBe(2);
game.classicTick();
expect(count).toBe(2);
});
it("no crash on Scene#destroy()", done => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
game._onLoad.add(() => {
const scene = new Scene({ game: game });
let timerFired = false;
scene.onLoad.add(() => {
scene.onUpdate.add(() => {
game.popScene();
});
scene.setInterval(() => {
// 「update が popScene してシーンを破壊した後にこれを呼ぼうとしてクラッシュする」ことが問題だった
timerFired = true;
}, 1);
game._initialScene.onStateChange.add(state => {
if (state === "active") {
// ↑のpopScene()後、例外を投げずにシーン遷移してここに来れたらOK
expect(timerFired).toBe(true);
done();
}
});
});
game.pushScene(scene);
game._flushPostTickTasks();
game.classicTick();
});
game._startLoadingGlobalAssets();
});
it("raiseEvent", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const ev = new MessageEvent("data");
const ev2 = new MessageEvent("foo");
game.raiseEvent(ev);
game.raiseEvent(ev2);
expect(game.handlerSet.raisedEvents.length).toBe(2);
expect(game.handlerSet.raisedEvents[0]).toEqual([32, undefined, null, "data", false]);
expect(game.handlerSet.raisedEvents[1]).toEqual([32, undefined, null, "foo", false]);
});
it("vars", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
expect(game.vars).toEqual({});
game.vars.myState = "well";
expect(game.vars.myState).toBe("well");
});
it("_reset", done => {
const game = new Game({
width: 320,
height: 320,
main: "./script/mainScene.js",
assets: {
mainScene: {
type: "script",
global: true,
path: "./script/mainScene.js",
virtualPath: "script/mainScene.js"
}
}
});
game.onSceneChange.add(() => {
//
});
game._onSceneChange.add(() => {
//
});
game.resourceFactory.scriptContents["/script/mainScene.js"] =
"module.exports = () => { const s = new g.Scene({game: g.game}); g.game.pushScene(s);}";
expect(game.age).toBe(0);
expect(game.random).toBeUndefined();
game._onLoad.add(() => {
expect(game.isLoaded).toBe(true);
const scene = new Scene({
game,
local: "interpolate-local",
tickGenerationMode: "manual"
});
const scene2 = new Scene({
game,
local: "interpolate-local",
tickGenerationMode: "by-clock"
});
const scene3 = new Scene({
game,
local: "interpolate-local",
tickGenerationMode: "by-clock"
}); // same scene mode as scene2
game.pushScene(scene);
game.pushScene(scene2);
game.pushScene(scene3);
game._flushPostTickTasks();
expect(game.handlerSet.modeHistry.length).toBe(3);
expect(game.handlerSet.modeHistry[0]).toEqual({
local: "full-local",
tickGenerationMode: "by-clock"
}); // initial scene
expect(game.handlerSet.modeHistry[1]).toEqual({
local: "interpolate-local",
tickGenerationMode: "manual"
}); // scene1
expect(game.handlerSet.modeHistry[2]).toEqual({
local: "interpolate-local",
tickGenerationMode: "by-clock"
}); // scene2
const randGen1 = new XorshiftRandomGenerator(10);
game._pointEventResolver.pointDown({
type: PlatformPointType.Down,
identifier: 0,
offset: { x: 0, y: 0 }
});
const moduleManager = game._moduleManager;
game._reset({
age: 3,
randSeed: 10,
randGenSer: randGen1.serialize()
});
expect(game.scene()).toBe(game._initialScene);
expect(game.age).toBe(3);
const randGen2 = XorshiftRandomGenerator.deserialize(randGen1.serialize());
expect(game.random.generate()).toBe(randGen2.generate());
// reset 前の PointDownEvent の情報が破棄されていることを確認
expect(
game._pointEventResolver.pointUp({
type: PlatformPointType.Up,
identifier: 0,
offset: { x: 0, y: 0 }
})
).toBeNull();
// reset で Game#onSceneChange は removeAll() されるが、Game#_onSceneChange は removeAll() されないことを確認
expect(game.onSceneChange.length).toBe(0);
expect(game._onSceneChange.length).not.toBe(0);
// reset後、Game#_moduleManagerが作り直されていることを確認
expect(game._moduleManager).not.toBe(moduleManager);
done();
});
game._loadAndStart();
});
it("_reset - until loaded _initialScene", done => {
const game = new Game({
width: 320,
height: 320,
main: "./script/mainScene.js",
assets: {
mainScene: {
type: "script",
global: true,
path: "./script/mainScene.js",
virtualPath: "script/mainScene.js"
}
}
});
game.resourceFactory.scriptContents["./script/mainScene.js"] =
"module.exports = () => { const s = new g.Scene({game: g.game}); g.game.pushScene(s); };";
expect(game.age).toBe(0);
expect(game.random).toBeUndefined();
let testDone = false;
game._onLoad.add(() => {
expect(testDone).toBe(true);
done();
});
const loadScene = game._defaultLoadingScene;
expect(game._initialScene.onLoad.contains(game._handleInitialSceneLoad, game)).toBe(true);
expect(loadScene.onLoad.contains(loadScene._doReset, loadScene)).toBe(false);
game._loadAndStart();
expect(game.isLoaded).toBe(false); // _loadAndStartしたがまだ読み込みは終わっていない
expect(game._initialScene.onLoad.contains(game._handleInitialSceneLoad, game)).toBe(true);
expect(game.scenes.length).toBe(2);
expect(game.scenes[0]).toBe(game._initialScene);
expect(game.scenes[1]).toBe(loadScene);
game._reset({ age: 0 });
const loadScene2 = game._defaultLoadingScene;
expect(loadScene2).not.toBe(loadScene);
expect(loadScene.destroyed()).toBe(true);
expect(game.isLoaded).toBe(false);
expect(game._initialScene.onLoad.contains(game._handleInitialSceneLoad, game)).toBe(true);
expect(loadScene2.onLoad.contains(loadScene2._doReset, loadScene2)).toBe(false);
expect(game.scenes.length).toBe(0);
game._loadAndStart();
expect(game.scenes.length).toBe(2);
testDone = true;
});
it("controls audio volume", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
expect(game.audio._muted).toBe(false);
expect(() => {
game._setAudioPlaybackRate(-0.5);
}).toThrowError("AssertionError");
expect(game.audio.sound._muted).toBe(false);
expect(game.audio.music._muted).toBe(false);
game._setMuted(true);
game._setMuted(true); // 同じ値を設定するパスのカバレッジ稼ぎ
expect(game.audio._muted).toBe(true);
expect(game.audio.sound._muted).toBe(true);
expect(game.audio.music._muted).toBe(true);
game._setAudioPlaybackRate(1.7);
game._setAudioPlaybackRate(1.7); // 同じ値を設定するパスのカバレッジ稼ぎ
expect(game.audio.sound._muted).toBe(true);
expect(game.audio.music._muted).toBe(true);
game._setAudioPlaybackRate(1.0);
game._setMuted(false);
expect(game.audio._muted).toBe(false);
expect(game.audio.sound._muted).toBe(false);
expect(game.audio.music._muted).toBe(false);
});
it("focusingCamera", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const r = new Renderer();
game.renderers.push(r);
const scene = new Scene({ game: game });
game.pushScene(scene);
game._flushPostTickTasks();
const e = new E({ scene: scene });
scene.append(e);
expect(e.state).toBe(0);
expect(game._modified).toBe(true);
const camera = new Camera2D({});
game.focusingCamera = camera;
expect(game.focusingCamera).toEqual(camera);
expect(e.state).toBe(EntityStateFlags.None);
expect(game._modified).toBe(false);
e.modified();
expect(e.state).toBe(EntityStateFlags.Modified | EntityStateFlags.ContextLess);
expect(game._modified).toBe(true);
game.focusingCamera = camera;
expect(e.state).toBe(EntityStateFlags.Modified | EntityStateFlags.ContextLess);
expect(game._modified).toBe(true);
e.modified();
const camera2 = new Camera2D({});
game.focusingCamera = camera2;
expect(game.focusingCamera).toEqual(camera2);
expect(e.state).toBe(EntityStateFlags.ContextLess);
expect(game._modified).toBe(false);
game._modified = false;
game.focusingCamera = camera;
expect(game.focusingCamera).toEqual(camera);
});
it("joinedPlayerIds", () => {
const game = new Game({ width: 320, height: 320, main: "", assets: {} });
const scene = new Scene({ game: game });
scene.onLoad.add(() => {
const joinPlaylogEvent: pl.JoinEvent = [0, 2, "1234", "nicotaro"];
game.tick(true, 0, [joinPlaylogEvent]);
expect(game.joinedPlayerIds).toEqual(["1234"]);
const leavePlaylogEvent: pl.LeaveEvent = [1, 2, "1234"];
game.tick(true, 0, [leavePlaylogEvent]);
expect(game.joinedPlayerIds).toEqual([]);
game.tick(true, 0, [joinPlaylogEvent]);
(game as any)._reset({ age: 0 });
expect(game.joinedPlayerIds).toEqual([]);
});
game.pushScene(scene);
});
it("localRandom", () => {
const game1 = new Game({ width: 320, height: 320, main: "", assets: {} });
const game2 = new Game({ width: 320, height: 320, main: "", assets: {} });
// 異なるGameインスタンスのlocalRandomが生成する乱数が異なる値になる
const randoms1: number[] = [];
const randoms2: number[] = [];
for (let i = 0; i < 10; i++) {
randoms1[i] = game1.localRandom.generate();
randoms2[i] = game2.localRandom.generate();
}
expect(randoms1).not.toEqual(randoms2);
});
}); | the_stack |
import { observable, action } from 'mobx'
import { proxyGetters, promiseTry } from './utils'
/**
* Returns a type without the promise wrapper.
*/
export type WithoutPromise<T> = T extends Promise<infer P> ? P : T
/**
* Task status.
*/
export type TaskStatus = 'pending' | 'resolved' | 'rejected'
/**
* Task function signature.
*/
export type TaskFunc<A extends any[], R> = (...args: A) => Promise<R>
/**
* Task options.
*/
export interface TaskOptions<A extends any[], R> {
state?: TaskStatus
error?: unknown
result?: WithoutPromise<R>
args?: A
swallow?: boolean
}
/**
* Object type used for pattern matching.
*/
export interface TaskMatchProps<T1, T2, T3, A extends any[], R = any> {
pending?: (...args: A) => T1
rejected?: (error: unknown) => T2
resolved?: (result: WithoutPromise<R>) => T3
}
/**
* Task state.
*/
export interface TaskState<A extends any[], R> {
/**
* The status (resolved, rejected, pending)
*/
readonly state: TaskStatus
/**
* Convenience getter for `state === 'pending'`.
*/
readonly pending: boolean
/**
* Convenience getter for `state === 'resolved'`.
*/
readonly resolved: boolean
/**
* Convenience getter for `state === 'rejected'`.
*/
readonly rejected: boolean
/**
* The last arguments passed to the task.
*/
readonly args: A
/**
* The result of the last invocation.
*/
readonly result?: WithoutPromise<R>
/**
* The error of the last failed invocation.
*/
readonly error?: unknown
}
/**
* Task methods.
*/
export interface TaskMethods<A extends any[], R> {
/**
* Pattern-matches on the task status.
* @param props
*/
match<PT, ET, RT>(props: TaskMatchProps<PT, ET, RT, A, R>): PT | ET | RT
/**
* Wraps the task by invoking `func` with the inner task function, which returns the wrapped function
* and converts that to a task.
*
* @param func
*/
wrap<NA extends any[], NR>(
func: (inner: (...args: A) => R) => (...args: NA) => NR
): Task<NA, NR>
/**
* Sets the state.
*/
setState(props: TaskOptions<A, R>): void
/**
* Resets the state.
*/
reset(): void
}
/**
* Task function, state and methods.
*/
export type Task<A extends any[], R> = TaskFunc<A, WithoutPromise<R>> &
TaskState<A, R> &
TaskMethods<A, R>
/**
* Actual task factory.
*/
export interface TaskCreator<K extends keyof TaskOptions<any, any>>
extends MethodDecorator,
PropertyDecorator {
/**
* Calls the actual task function.
*/
<A extends any[], R>(
func: (...args: A) => R,
options?: Pick<TaskOptions<A, R>, K>
): Task<A, R>
(options: Pick<TaskOptions<any, any>, K>): PropertyDecorator
(options: Pick<TaskOptions<any, any>, K>): MethodDecorator
}
export interface TaskFactory extends TaskCreator<keyof TaskOptions<any, any>> {
/**
* Creates a task in the `resolved` state.
*/
resolved: TaskCreator<Exclude<keyof TaskOptions<any, any>, 'state'>>
/**
* Creates a task in the `rejected` state.
*/
rejected: TaskCreator<Exclude<keyof TaskOptions<any, any>, 'state'>>
}
/**
* Creates a task in the `pending` state.
*/
const task: TaskFactory = taskCreatorFactory() as any
task.resolved = taskCreatorFactory({ state: 'resolved' }) as any
task.rejected = taskCreatorFactory({ state: 'rejected' }) as any
export { task }
/**
* Wraps the given function in a task function.
*
* @param {Function} fn
* @return {Task}
*/
function createTask<A extends any[], R>(
fn: (...args: A) => R | Promise<R>,
opts: TaskOptions<A, R>
) {
opts = {
swallow: false,
state: 'pending',
args: ([] as unknown) as A,
...opts
}
// Track how many times this task was called.
// Used to prevent premature state changes when the
// task is called again before the first run completes.
let callCount = 0
/**
* The actual task function.
*/
function task(this: any, ...args: A) {
const callCountWhenStarted = ++callCount
return promiseTry(() => {
;(task as Task<A, R>).setState({
state: 'pending',
error: undefined,
result: undefined,
args: Array.from(arguments) as A
})
return Promise.resolve(fn.apply(this, args)).then(result => {
// If we called the task again before the first
// one completes, we don't want to set to resolved before the last call completes.
if (callCountWhenStarted === callCount) {
;(task as Task<A, R>).setState({
state: 'resolved',
error: undefined,
result: result as WithoutPromise<R>
})
}
return result
})
}).catch(err => {
if (callCountWhenStarted === callCount) {
;(task as Task<A, R>).setState({
state: 'rejected',
error: err,
result: undefined
})
}
if (!opts.swallow) {
throw err
}
// To avoid the case where `opts.swallow` is true.
// If you use this, you know the risks.
return (undefined as unknown) as R
})
}
const taskStateSchema: TaskState<A, R> = {
state: opts.state!,
error: opts.error,
result: opts.result,
args: opts.args!,
get pending() {
return taskState.state === 'pending'
},
get resolved() {
return taskState.state === 'resolved'
},
get rejected() {
return taskState.state === 'rejected'
}
}
const taskStateSchemaKeys = Object.keys(taskStateSchema)
const taskState = observable.object(
taskStateSchema,
{
error: observable.ref,
result: observable.ref,
args: observable.ref
},
{
deep: false
}
)
setupTask(task, taskState, taskStateSchemaKeys, opts)
return task
}
/**
* Assigns the task methods and state to the given function.
*/
function setupTask<A extends any[], R>(
fn: (...args: A) => Promise<R>,
taskState: TaskState<A, R>,
taskStateSchemaKeys: any,
opts: TaskOptions<A, R>
) {
const setup = (func: any) =>
setupTask(func, taskState, taskStateSchemaKeys, opts)
proxyGetters(fn, taskState, taskStateSchemaKeys)
Object.assign(fn, {
/**
* Patch `bind` so we always return
* the task function (with the additional properties)
*/
bind: (...args: any[]) => {
const bound = Function.prototype.bind.apply(fn, args as any)
return setup(bound)
},
/**
* Wraps the task and returns the new function with the task stuff attached.
*
* @param {Function} wrapper
* Invoked with the inner function as the only parameter.
*
* @return {Task}
* Wrapped function as a task.
*/
wrap: (wrapper: any) => {
return setup(
wrapper(function wrapped(this: any, ...args: A) {
return fn.apply(this, args)
})
)
},
/**
* Assigns the given properties to the task.
* E.g. task.setState({ state: 'resolved', result: 1337 })
*/
setState: action('setState', (opts: TaskOptions<A, R>) => {
Object.assign(taskState, opts)
return fn
}),
/**
* Given an object, returns the value for the key which equals the
* current state, or undefined if not specified.
*/
match: (obj: any) => {
const state = taskState.state
const match = obj[state]
if (!match) {
return undefined
}
switch (state) {
case 'pending':
return match.apply(null, taskState.args)
case 'resolved':
return match(taskState.result)
case 'rejected':
return match(taskState.error)
}
/* istanbul ignore next */
return match()
},
/**
* Resets the state to what it was when initialized.
*/
reset: () => {
;(fn as Task<A, R>).setState({
state: opts.state,
result: opts.result,
error: opts.error
})
return fn
}
})
return fn
}
/**
* Returns a function, which returns either a decorator, a task, or a decorator factory.
*/
function taskCreatorFactory<A extends any[], R>(opts?: TaskOptions<A, R>) {
/**
* Decorator to make async functions "so fucking graceful", by maintaining observables for errors
* and running state.
*/
return function task(arg1: any, arg2: any, arg3: any) {
if (typeof arg1 === 'function') {
// regular invocation
return createTask(arg1, { ...opts, ...arg2 })
}
const makeDecorator = (innerOpts?: any) => {
return function decorator(
_target: any,
name: string,
descriptor: any = {}
) {
let get = descriptor.get
if (descriptor.value || descriptor.initializer) {
const fn = descriptor.value
delete descriptor.writable
delete descriptor.value
get = fn
? () => fn
: /* istanbul ignore next: babel */ descriptor.initializer
}
// In IE11 calling Object.defineProperty has a side-effect of evaluating the
// getter for the property which is being replaced. This causes infinite
// recursion and an "Out of stack space" error.
// Credit: autobind-decorator source
let definingProperty = false
return {
get: function getter() {
/* istanbul ignore next */
if (definingProperty) {
return get.apply(this)
}
const fn = get.apply(this, arguments)
const wrapped = createTask(fn, { ...opts, ...innerOpts })
definingProperty = true
Object.defineProperty(this, name, {
value: wrapped,
configurable: true,
writable: true
})
definingProperty = false
return wrapped
},
set: function setter(newValue: any) {
Object.defineProperty(this, name, {
configurable: true,
writable: true,
// IS enumerable when reassigned by the outside word
enumerable: true,
value: newValue
})
return newValue
}
}
}
}
// decorator invocation
if (typeof arg2 === 'string') {
// parameterless - @task method()
return makeDecorator()(arg1, arg2, arg3)
}
// parameters - @task({ state: 'resolved' }) method()
return makeDecorator({ ...opts, ...arg1 })
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Common fields that are returned in the response for all Azure Resource Manager resources
* @summary Resource
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource ID for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
* "Microsoft.Storage/storageAccounts"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The resource model definition for a Azure Resource Manager proxy resource. It will not have tags
* and a location
* @summary Proxy Resource
*/
export interface ProxyResource extends Resource {
}
/**
* Represents a Database.
*/
export interface Database extends ProxyResource {
/**
* The charset of the database.
*/
charset?: string;
/**
* The collation of the database.
*/
collation?: string;
}
/**
* The resource management error additional info.
*/
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly info?: any;
}
/**
* Common error response for all Azure Resource Manager APIs to return error details for failed
* operations. (This also follows the OData error response format.)
* @summary Error Response
*/
export interface ErrorResponse {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The error target.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly target?: string;
/**
* The error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ErrorResponse[];
/**
* The error additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/**
* The resource model definition for an Azure Resource Manager tracked top level resource which has
* 'tags' and a 'location'
* @summary Tracked Resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* The resource model definition for an Azure Resource Manager resource with an etag.
* @summary Entity Resource
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* Sku information related properties of a server.
*/
export interface Sku {
/**
* The name of the sku, typically, tier + family + cores, e.g. Standard_D4s_v3.
*/
name: string;
/**
* The tier of the particular SKU, e.g. Burstable. Possible values include: 'Burstable',
* 'GeneralPurpose', 'MemoryOptimized'
*/
tier: SkuTier;
}
/**
* Represents a recoverable server resource.
*/
export interface RecoverableServerResource extends ProxyResource {
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* The location the resource resides in.
*/
location?: string;
/**
* Availability zone of the server
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly availabilityZone?: string;
/**
* Edition of the performance tier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serverEdition?: string;
/**
* The PostgreSQL version
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly version?: string;
}
/**
* Virtual network subnet usage parameter
*/
export interface VirtualNetworkSubnetUsageParameter {
/**
* Virtual network resource id.
*/
virtualNetworkArmResourceId?: string;
}
/**
* Delegated subnet usage data.
*/
export interface DelegatedSubnetUsage {
/**
* name of the subnet
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subnetName?: string;
/**
* Number of used delegated subnets
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly usage?: number;
}
/**
* Virtual network subnet usage data.
*/
export interface VirtualNetworkSubnetUsageResult {
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly delegatedSubnetsUsage?: DelegatedSubnetUsage[];
}
/**
* storage size in MB capability
*/
export interface StorageMBCapability {
/**
* storage MB name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* supported IOPS
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedIops?: number;
/**
* storage size in MB
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly storageSizeMB?: number;
}
/**
* Vcores capability
*/
export interface VcoreCapability {
/**
* vCore name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* supported vCores
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly vCores?: number;
/**
* supported IOPS
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedIops?: number;
/**
* supported memory per vCore in MB
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedMemoryPerVcoreMB?: number;
}
/**
* Server version capabilities.
*/
export interface ServerVersionCapability {
/**
* server version
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedVcores?: VcoreCapability[];
}
/**
* storage edition capability
*/
export interface StorageEditionCapability {
/**
* storage edition name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedStorageMB?: StorageMBCapability[];
}
/**
* Server edition capabilities.
*/
export interface ServerEditionCapability {
/**
* Server edition name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedStorageEditions?: StorageEditionCapability[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedServerVersions?: ServerVersionCapability[];
}
/**
* Location capabilities.
*/
export interface CapabilityProperties {
/**
* zone name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly zone?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedFlexibleServerEditions?: ServerEditionCapability[];
}
/**
* Storage Profile properties of a server
*/
export interface StorageProfile {
/**
* Backup retention days for the server.
*/
backupRetentionDays?: number;
/**
* Max storage allowed for a server.
*/
storageMB?: number;
/**
* Geo Backup redundancy option. Possible values include: 'Enabled', 'Disabled'
*/
geoRedundantBackup?: GeoRedundantBackupOption;
}
/**
* Maintenance window of a server.
*/
export interface MaintenanceWindow {
/**
* indicates whether custom window is enabled or disabled
*/
customWindow?: string;
/**
* start hour for maintenance window
*/
startHour?: number;
/**
* start minute for maintenance window
*/
startMinute?: number;
/**
* day of week for maintenance window
*/
dayOfWeek?: number;
}
/**
* An interface representing ServerPropertiesDelegatedSubnetArguments.
*/
export interface ServerPropertiesDelegatedSubnetArguments {
/**
* delegated subnet arm resource id.
*/
subnetArmResourceId?: string;
}
/**
* An interface representing ServerPropertiesPrivateDnsZoneArguments.
*/
export interface ServerPropertiesPrivateDnsZoneArguments {
/**
* private dns zone arm resource id.
*/
privateDnsZoneArmResourceId?: string;
}
/**
* Identity for the resource.
*/
export interface Identity {
/**
* The principal ID of resource identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly principalId?: string;
/**
* The tenant ID of resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tenantId?: string;
/**
* The identity type. Possible values include: 'SystemAssigned'
*/
type?: ResourceIdentityType;
}
/**
* Represents a server.
*/
export interface Server extends TrackedResource {
/**
* The Azure Active Directory identity of the server.
*/
identity?: Identity;
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* The administrator's login name of a server. Can only be specified when the server is being
* created (and is required for creation).
*/
administratorLogin?: string;
/**
* The administrator login password (required for server creation).
*/
administratorLoginPassword?: string;
/**
* PostgreSQL Server version. Possible values include: '12', '11'
*/
version?: ServerVersion;
/**
* A state of a server that is visible to user. Possible values include: 'Ready', 'Dropping',
* 'Disabled', 'Starting', 'Stopping', 'Stopped', 'Updating'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly state?: ServerState;
/**
* A state of a HA server that is visible to user. Possible values include: 'NotEnabled',
* 'CreatingStandby', 'ReplicatingData', 'FailingOver', 'Healthy', 'RemovingStandby'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly haState?: ServerHAState;
/**
* The fully qualified domain name of a server.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly fullyQualifiedDomainName?: string;
/**
* The display name of a server.
*/
displayName?: string;
/**
* Storage profile of a server.
*/
storageProfile?: StorageProfile;
/**
* public network access is enabled or not. Possible values include: 'Enabled', 'Disabled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly publicNetworkAccess?: ServerPublicNetworkAccessState;
/**
* Maintenance window of a server.
*/
maintenanceWindow?: MaintenanceWindow;
/**
* stand by count value can be either enabled or disabled. Possible values include: 'Enabled',
* 'Disabled'
*/
haEnabled?: HAEnabledEnum;
/**
* The source PostgreSQL server name to restore from.
*/
sourceServerName?: string;
/**
* The subscription id of source PostgreSQL server name to restore from.
*/
sourceSubscriptionId?: string;
/**
* The resource group name of source PostgreSQL server name to restore from.
*/
sourceResourceGroupName?: string;
/**
* Restore point creation time (ISO8601 format), specifying the time to restore from.
*/
pointInTimeUTC?: Date;
/**
* availability Zone information of the server.
*/
availabilityZone?: string;
/**
* availability Zone information of the server.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly standbyAvailabilityZone?: string;
/**
* Status showing whether the data encryption is enabled with customer-managed keys.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly byokEnforcement?: string;
delegatedSubnetArguments?: ServerPropertiesDelegatedSubnetArguments;
privateDnsZoneArguments?: ServerPropertiesPrivateDnsZoneArguments;
/**
* The mode to create a new PostgreSQL server. Possible values include: 'Default',
* 'PointInTimeRestore', 'GeoRestore'
*/
createMode?: CreateMode;
/**
* Application-specific metadata in the form of key-value pairs.
*/
serverTags?: { [propertyName: string]: string };
}
/**
* Represents a server to be updated.
*/
export interface ServerForUpdate {
/**
* The location the resource resides in.
*/
location?: string;
/**
* The SKU (pricing tier) of the server.
*/
sku?: Sku;
/**
* The password of the administrator login.
*/
administratorLoginPassword?: string;
/**
* Storage profile of a server.
*/
storageProfile?: StorageProfile;
/**
* stand by count value can be either enabled or disabled. Possible values include: 'Enabled',
* 'Disabled'
*/
haEnabled?: HAEnabledEnum;
/**
* Maintenance window of a server.
*/
maintenanceWindow?: MaintenanceWindow;
/**
* Application-specific metadata in the form of key-value pairs.
*/
tags?: { [propertyName: string]: string };
}
/**
* Represents a server firewall rule.
*/
export interface FirewallRule extends ProxyResource {
/**
* The start IP address of the server firewall rule. Must be IPv4 format.
*/
startIpAddress: string;
/**
* The end IP address of the server firewall rule. Must be IPv4 format.
*/
endIpAddress: string;
}
/**
* Represents a Configuration.
*/
export interface Configuration extends ProxyResource {
/**
* Value of the configuration.
*/
value?: string;
/**
* Description of the configuration.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
/**
* Default value of the configuration.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly defaultValue?: string;
/**
* Data type of the configuration. Possible values include: 'Boolean', 'Numeric', 'Integer',
* 'Enumeration'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dataType?: ConfigurationDataType;
/**
* Allowed values of the configuration.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly allowedValues?: string;
/**
* Source of the configuration.
*/
source?: string;
}
/**
* Display metadata associated with the operation.
*/
export interface OperationDisplay {
/**
* Operation resource provider name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* Resource on which the operation is performed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
/**
* Localized friendly name for the operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
/**
* Operation description.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
}
/**
* REST API operation definition.
*/
export interface Operation {
/**
* The name of the operation being performed on this particular object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The localized display information for this particular operation or action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly display?: OperationDisplay;
/**
* Indicates whether the operation is a data action
*/
isDataAction?: boolean;
/**
* The intended executor of the operation. Possible values include: 'NotSpecified', 'user',
* 'system'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly origin?: OperationOrigin;
/**
* Additional descriptions for the operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly properties?: { [propertyName: string]: any };
}
/**
* A list of resource provider operations.
*/
export interface OperationListResult {
/**
* Collection of available operation details
*/
value?: Operation[];
/**
* URL client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/**
* Request from client to check resource name availability.
*/
export interface NameAvailabilityRequest {
/**
* Resource name to verify.
*/
name: string;
/**
* Resource type used for verification.
*/
type?: string;
}
/**
* Represents a resource name availability.
*/
export interface NameAvailability {
/**
* Error Message.
*/
message?: string;
/**
* Indicates whether the resource name is available.
*/
nameAvailable?: boolean;
/**
* name of the PostgreSQL server.
*/
name?: string;
/**
* type of the server
*/
type?: string;
}
/**
* An interface representing ResourceModelWithAllowedPropertySetIdentity.
*/
export interface ResourceModelWithAllowedPropertySetIdentity extends Identity {
}
/**
* An interface representing ResourceModelWithAllowedPropertySetSku.
*/
export interface ResourceModelWithAllowedPropertySetSku extends Sku {
}
/**
* Plan for the resource.
*/
export interface Plan {
/**
* A user defined name of the 3rd Party Artifact that is being procured.
*/
name: string;
/**
* The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic
*/
publisher: string;
/**
* The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID
* specified for the artifact at the time of Data Market onboarding.
*/
product: string;
/**
* A publisher provided promotion code as provisioned in Data Market for the said
* product/artifact.
*/
promotionCode?: string;
/**
* The version of the desired product/artifact.
*/
version?: string;
}
/**
* An interface representing ResourceModelWithAllowedPropertySetPlan.
*/
export interface ResourceModelWithAllowedPropertySetPlan extends Plan {
}
/**
* The resource model definition containing the full set of allowed properties for a resource.
* Except properties bag, there cannot be a top level property outside of this set.
*/
export interface ResourceModelWithAllowedPropertySet extends BaseResource {
/**
* Fully qualified resource ID for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
* "Microsoft.Storage/storageAccounts"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The geo-location where the resource lives
*/
location?: string;
/**
* The fully qualified resource ID of the resource that manages this resource. Indicates if this
* resource is managed by another Azure resource. If this is present, complete mode deployment
* will not delete the resource if it is removed from the template since it is managed by another
* resource.
*/
managedBy?: string;
/**
* Metadata used by portal/tooling/etc to render different UX experiences for resources of the
* same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. If supported, the resource
* provider must validate and persist this value.
*/
kind?: string;
/**
* The etag field is *not* required. If it is provided in the response body, it must also be
* provided as a header per the normal etag convention. Entity tags are used for comparing two
* or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag
* (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range
* (section 14.27) header fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
identity?: ResourceModelWithAllowedPropertySetIdentity;
sku?: ResourceModelWithAllowedPropertySetSku;
plan?: ResourceModelWithAllowedPropertySetPlan;
}
/**
* An interface representing PostgreSQLFlexibleManagementClientOptions.
*/
export interface PostgreSQLFlexibleManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* A List of databases.
* @extends Array<Database>
*/
export interface DatabaseListResult extends Array<Database> {
/**
* The link used to get the next page of databases.
*/
nextLink?: string;
}
/**
* @interface
* A list of servers.
* @extends Array<Server>
*/
export interface ServerListResult extends Array<Server> {
/**
* The link used to get the next page of operations.
*/
nextLink?: string;
}
/**
* @interface
* A list of firewall rules.
* @extends Array<FirewallRule>
*/
export interface FirewallRuleListResult extends Array<FirewallRule> {
/**
* The link used to get the next page of operations.
*/
nextLink?: string;
}
/**
* @interface
* A list of server configurations.
* @extends Array<Configuration>
*/
export interface ConfigurationListResult extends Array<Configuration> {
/**
* The link used to get the next page of operations.
*/
nextLink?: string;
}
/**
* @interface
* location capability
* @extends Array<CapabilityProperties>
*/
export interface CapabilitiesListResult extends Array<CapabilityProperties> {
/**
* Link to retrieve next page of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* Defines values for SkuTier.
* Possible values include: 'Burstable', 'GeneralPurpose', 'MemoryOptimized'
* @readonly
* @enum {string}
*/
export type SkuTier = 'Burstable' | 'GeneralPurpose' | 'MemoryOptimized';
/**
* Defines values for ServerVersion.
* Possible values include: '12', '11'
* @readonly
* @enum {string}
*/
export type ServerVersion = '12' | '11';
/**
* Defines values for ServerState.
* Possible values include: 'Ready', 'Dropping', 'Disabled', 'Starting', 'Stopping', 'Stopped',
* 'Updating'
* @readonly
* @enum {string}
*/
export type ServerState = 'Ready' | 'Dropping' | 'Disabled' | 'Starting' | 'Stopping' | 'Stopped' | 'Updating';
/**
* Defines values for ServerHAState.
* Possible values include: 'NotEnabled', 'CreatingStandby', 'ReplicatingData', 'FailingOver',
* 'Healthy', 'RemovingStandby'
* @readonly
* @enum {string}
*/
export type ServerHAState = 'NotEnabled' | 'CreatingStandby' | 'ReplicatingData' | 'FailingOver' | 'Healthy' | 'RemovingStandby';
/**
* Defines values for GeoRedundantBackupOption.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type GeoRedundantBackupOption = 'Enabled' | 'Disabled';
/**
* Defines values for ServerPublicNetworkAccessState.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type ServerPublicNetworkAccessState = 'Enabled' | 'Disabled';
/**
* Defines values for HAEnabledEnum.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type HAEnabledEnum = 'Enabled' | 'Disabled';
/**
* Defines values for CreateMode.
* Possible values include: 'Default', 'PointInTimeRestore', 'GeoRestore'
* @readonly
* @enum {string}
*/
export type CreateMode = 'Default' | 'PointInTimeRestore' | 'GeoRestore';
/**
* Defines values for ResourceIdentityType.
* Possible values include: 'SystemAssigned'
* @readonly
* @enum {string}
*/
export type ResourceIdentityType = 'SystemAssigned';
/**
* Defines values for ConfigurationDataType.
* Possible values include: 'Boolean', 'Numeric', 'Integer', 'Enumeration'
* @readonly
* @enum {string}
*/
export type ConfigurationDataType = 'Boolean' | 'Numeric' | 'Integer' | 'Enumeration';
/**
* Defines values for OperationOrigin.
* Possible values include: 'NotSpecified', 'user', 'system'
* @readonly
* @enum {string}
*/
export type OperationOrigin = 'NotSpecified' | 'user' | 'system';
/**
* Defines values for Body.
* Possible values include: 'PostgreSQL', 'PostgreSQLCitus', 'MySQL', 'MariaDb', 'Oracle'
* @readonly
* @enum {string}
*/
export type Body = 'PostgreSQL' | 'PostgreSQLCitus' | 'MySQL' | 'MariaDb' | 'Oracle';
/**
* Contains response data for the create operation.
*/
export type DatabasesCreateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the get operation.
*/
export type DatabasesGetResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the listByServer operation.
*/
export type DatabasesListByServerResponse = DatabaseListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DatabaseListResult;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type DatabasesBeginCreateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the listByServerNext operation.
*/
export type DatabasesListByServerNextResponse = DatabaseListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DatabaseListResult;
};
};
/**
* Contains response data for the execute operation.
*/
export type GetPrivateDnsZoneSuffixExecuteResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the create operation.
*/
export type ServersCreateResponse = Server & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Server;
};
};
/**
* Contains response data for the update operation.
*/
export type ServersUpdateResponse = Server & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Server;
};
};
/**
* Contains response data for the get operation.
*/
export type ServersGetResponse = Server & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Server;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type ServersListByResourceGroupResponse = ServerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ServerListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type ServersListResponse = ServerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ServerListResult;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type ServersBeginCreateResponse = Server & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Server;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type ServersBeginUpdateResponse = Server & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Server;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type ServersListByResourceGroupNextResponse = ServerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ServerListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type ServersListNextResponse = ServerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ServerListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type FirewallRulesCreateOrUpdateResponse = FirewallRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FirewallRule;
};
};
/**
* Contains response data for the get operation.
*/
export type FirewallRulesGetResponse = FirewallRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FirewallRule;
};
};
/**
* Contains response data for the listByServer operation.
*/
export type FirewallRulesListByServerResponse = FirewallRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FirewallRuleListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type FirewallRulesBeginCreateOrUpdateResponse = FirewallRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FirewallRule;
};
};
/**
* Contains response data for the listByServerNext operation.
*/
export type FirewallRulesListByServerNextResponse = FirewallRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FirewallRuleListResult;
};
};
/**
* Contains response data for the listByServer operation.
*/
export type ConfigurationsListByServerResponse = ConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigurationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ConfigurationsGetResponse = Configuration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Configuration;
};
};
/**
* Contains response data for the update operation.
*/
export type ConfigurationsUpdateResponse = Configuration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Configuration;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type ConfigurationsBeginUpdateResponse = Configuration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Configuration;
};
};
/**
* Contains response data for the listByServerNext operation.
*/
export type ConfigurationsListByServerNextResponse = ConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigurationListResult;
};
};
/**
* Contains response data for the execute operation.
*/
export type CheckNameAvailabilityExecuteResponse = NameAvailability & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NameAvailability;
};
};
/**
* Contains response data for the execute operation.
*/
export type LocationBasedCapabilitiesExecuteResponse = CapabilitiesListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CapabilitiesListResult;
};
};
/**
* Contains response data for the executeNext operation.
*/
export type LocationBasedCapabilitiesExecuteNextResponse = CapabilitiesListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CapabilitiesListResult;
};
};
/**
* Contains response data for the execute operation.
*/
export type VirtualNetworkSubnetUsageExecuteResponse = VirtualNetworkSubnetUsageResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkSubnetUsageResult;
};
};
/**
* Contains response data for the get operation.
*/
export type RecoverableServersGetResponse = RecoverableServerResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RecoverableServerResource;
};
};
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
}; | the_stack |
import { abortAble } from 'lineupengine';
import {
getNumberOfBins,
IAdvancedBoxPlotData,
ICategoricalStatistics,
IDateStatistics,
ISequence,
ISortMessageResponse,
IStatistics,
lazySeq,
toIndexArray,
WorkerTaskScheduler,
createWorkerBlob,
IStringStatistics,
} from '../internal';
import TaskScheduler, { ABORTED, oneShotIterator } from '../internal/scheduler';
import Column, {
ICategoricalLikeColumn,
ICompareValue,
IDataRow,
IDateColumn,
IGroup,
IndicesArray,
INumberColumn,
IOrderedGroup,
isCategoricalLikeColumn,
isDateColumn,
isNumberColumn,
Ranking,
StringColumn,
UIntTypedArray,
} from '../model';
import type { IRenderTask } from '../renderer';
import { sortDirect } from './DirectRenderTasks';
import type { CompareLookup } from './sort';
import { ARenderTasks, IRenderTaskExecutor, MultiIndices, taskLater, TaskLater, taskNow, TaskNow } from './tasks';
export class ScheduleRenderTasks extends ARenderTasks implements IRenderTaskExecutor {
private readonly cache = new Map<string, IRenderTask<any>>();
private readonly tasks = new TaskScheduler();
private readonly workers = new WorkerTaskScheduler(createWorkerBlob());
setData(data: IDataRow[]) {
this.data = data;
this.cache.clear();
this.tasks.clear();
this.valueCacheData.clear();
this.workers.deleteRefs();
}
dirtyColumn(col: Column, type: 'data' | 'group' | 'summary') {
super.dirtyColumn(col, type);
// order designed such that first groups, then summaries, then data is deleted
for (const key of Array.from(this.cache.keys()).sort()) {
// data = all
// summary = summary + group
// group = group only
if (
(type === 'data' && key.startsWith(`${col.id}:`)) ||
(type === 'summary' && key.startsWith(`${col.id}:b:summary:`)) ||
key.startsWith(`${col.id}:a:group`)
) {
this.cache.delete(key);
this.tasks.abort(key);
}
}
if (type !== 'data') {
return;
}
this.valueCacheData.delete(col.id);
this.workers.deleteRef(col.id);
}
dirtyRanking(ranking: Ranking, type: 'data' | 'group' | 'summary') {
const cols = ranking.flatColumns;
let checker: ((key: string) => boolean)[];
switch (type) {
case 'group':
checker = cols.map((col) => (key: string) => key.startsWith(`${col.id}:a:group`));
break;
case 'summary':
checker = cols.map(
(col) => (key: string) => key.startsWith(`${col.id}:b:summary`) || key.startsWith(`${col.id}:a:group`)
);
break;
case 'data':
default:
checker = cols.map((col) => (key: string) => key.startsWith(`${col.id}:`));
break;
}
for (const key of Array.from(this.cache.keys()).sort()) {
if (checker.some((f) => f(key))) {
this.cache.delete(key);
this.tasks.abort(key);
}
}
// group compare tasks
this.tasks.abortAll((t) => t.id.startsWith(`r${ranking.id}:`));
// delete remote caches
this.workers.deleteRef(ranking.id, true);
if (type !== 'data') {
return;
}
for (const col of cols) {
super.dirtyColumn(col, type);
this.workers.deleteRef(col.id);
}
}
preCompute(ranking: Ranking, groups: { rows: IndicesArray; group: IGroup }[], maxDataIndex: number) {
if (groups.length === 0) {
return;
}
const cols = ranking.flatColumns;
if (groups.length === 1) {
const { group, rows } = groups[0];
const multi = new MultiIndices([rows], maxDataIndex);
for (const col of cols) {
if (isCategoricalLikeColumn(col)) {
this.summaryCategoricalStats(col, multi);
} else if (isNumberColumn(col)) {
this.summaryNumberStats(col, false, multi);
this.summaryNumberStats(col, true, multi);
} else if (isDateColumn(col)) {
this.summaryDateStats(col, multi);
} else if (col instanceof StringColumn) {
this.summaryStringStats(col, multi);
} else {
continue;
}
// copy from summary to group and create proper structure
this.chainCopy(
`${col.id}:a:group:${group.name}`,
this.cache.get(`${col.id}:b:summary`)!,
(v: { summary: any; data: any }) => ({ group: v.summary, summary: v.summary, data: v.data })
);
if (isNumberColumn(col)) {
this.chainCopy(
`${col.id}:a:group:${group.name}:raw`,
this.cache.get(`${col.id}:b:summary:raw`)!,
(v: { summary: any; data: any }) => ({ group: v.summary, summary: v.summary, data: v.data })
);
}
}
return;
}
const orderedGroups = groups.map(({ rows, group }) => Object.assign({ order: rows }, group));
const full = new MultiIndices(
groups.map((d) => d.rows),
maxDataIndex
);
for (const col of cols) {
if (isCategoricalLikeColumn(col)) {
this.summaryCategoricalStats(col, full);
for (const g of orderedGroups) {
this.groupCategoricalStats(col, g);
}
} else if (isDateColumn(col)) {
this.summaryDateStats(col, full);
for (const g of orderedGroups) {
this.groupDateStats(col, g);
}
} else if (isNumberColumn(col)) {
this.summaryNumberStats(col, false, full);
this.summaryNumberStats(col, true, full);
for (const g of orderedGroups) {
this.groupNumberStats(col, g, false);
this.groupNumberStats(col, g, true);
}
} else if (col instanceof StringColumn) {
this.summaryStringStats(col, full);
for (const g of orderedGroups) {
this.groupStringStats(col, g);
}
}
}
}
preComputeData(ranking: Ranking) {
for (const col of ranking.flatColumns) {
if (isCategoricalLikeColumn(col)) {
this.dataCategoricalStats(col);
} else if (isNumberColumn(col)) {
this.dataNumberStats(col, false);
this.dataNumberStats(col, true);
} else if (isDateColumn(col)) {
this.dataDateStats(col);
} else if (col instanceof StringColumn) {
this.dataStringStats(col);
}
}
}
preComputeCol(col: Column) {
const ranking = col.findMyRanker();
if (col instanceof StringColumn) {
this.dataStringStats(col);
if (!ranking) {
return;
}
this.summaryStringStats(col);
for (const group of ranking.getGroups()) {
this.groupStringStats(col, group);
}
return;
}
if (isCategoricalLikeColumn(col)) {
this.dataCategoricalStats(col);
if (!ranking) {
return;
}
this.summaryCategoricalStats(col);
for (const group of ranking.getGroups()) {
this.groupCategoricalStats(col, group);
}
return;
}
if (isNumberColumn(col)) {
this.dataNumberStats(col, false);
this.dataNumberStats(col, true);
if (!ranking) {
return;
}
this.summaryNumberStats(col, false);
this.summaryNumberStats(col, true);
for (const group of ranking.getGroups()) {
this.groupNumberStats(col, group, false);
this.groupNumberStats(col, group, true);
}
return;
}
if (!isDateColumn(col)) {
return;
}
this.dataDateStats(col);
if (!ranking) {
return;
}
this.summaryDateStats(col);
for (const group of ranking.getGroups()) {
this.groupDateStats(col, group);
}
}
copyData2Summary(ranking: Ranking) {
for (const col of ranking.flatColumns) {
if (isCategoricalLikeColumn(col)) {
this.dataCategoricalStats(col);
} else if (isNumberColumn(col)) {
this.dataNumberStats(col, false);
this.dataNumberStats(col, true);
} else if (isDateColumn(col)) {
this.dataDateStats(col);
} else if (col instanceof StringColumn) {
this.dataStringStats(col);
} else {
continue;
}
// copy from data to summary and create proper structure
this.chainCopy(`${col.id}:b:summary`, this.cache.get(`${col.id}:c:data`)!, (data: any) => ({
summary: data,
data,
}));
if (isNumberColumn(col)) {
this.chainCopy(`${col.id}:b:summary:raw`, this.cache.get(`${col.id}:c:data:raw`)!, (data: any) => ({
summary: data,
data,
}));
}
}
}
copyCache(col: Column, from: Column) {
const fromPrefix = `${from.id}:`;
for (const key of Array.from(this.cache.keys()).sort()) {
if (!key.startsWith(fromPrefix)) {
continue;
}
const chainKey = `${col.id}:${key.slice(fromPrefix.length)}`;
this.chainCopy(chainKey, this.cache.get(key)!, (data: any) => data);
}
}
groupCompare(ranking: Ranking, group: IGroup, rows: IndicesArray) {
return taskLater(
this.tasks.push(`r${ranking.id}:${group.name}`, () => {
const rg = ranking.getGroupSortCriteria();
if (rg.length === 0) {
return [group.name.toLowerCase()];
}
const o = this.byOrder(rows);
const vs: ICompareValue[] = [];
for (const s of rg) {
const cache = this.valueCache(s.col);
const r = s.col.toCompareGroupValue(o, group, cache ? lazySeq(rows).map((d) => cache(d)) : undefined);
if (Array.isArray(r)) {
vs.push(...r);
} else {
vs.push(r);
}
}
vs.push(group.name.toLowerCase());
return vs;
})
);
}
groupRows<T>(col: Column, group: IOrderedGroup, key: string, compute: (rows: ISequence<IDataRow>) => T) {
return this.cached(
`${col.id}:a:group:${group.name}:${key}`,
true,
oneShotIterator(() => compute(this.byOrder(group.order)))
);
}
groupExampleRows<T>(_col: Column, group: IOrderedGroup, _key: string, compute: (rows: ISequence<IDataRow>) => T) {
return taskNow(compute(this.byOrder(group.order.slice(0, 5))));
}
groupBoxPlotStats(col: Column & INumberColumn, group: IOrderedGroup, raw?: boolean) {
return this.chain(
`${col.id}:a:group:${group.name}${raw ? ':braw' : ':b'}`,
this.summaryBoxPlotStats(col, raw),
({ summary, data }) => {
const ranking = col.findMyRanker()!;
const key = raw ? `${col.id}:r` : col.id;
if (this.valueCacheData.has(key) && group.order.length > 0) {
// web worker version
return () =>
this.workers
.pushStats(
'boxplotStats',
{},
key,
this.valueCacheData.get(key) as Float32Array,
`${ranking.id}:${group.name}`,
group.order
)
.then((group) => ({ group, summary, data }));
}
return this.boxplotBuilder(group.order, col, raw, (group) => ({ group, summary, data }));
}
);
}
groupNumberStats(col: Column & INumberColumn, group: IOrderedGroup, raw?: boolean) {
return this.chain(
`${col.id}:a:group:${group.name}${raw ? ':raw' : ''}`,
this.summaryNumberStats(col, raw),
({ summary, data }) => {
const ranking = col.findMyRanker()!;
const key = raw ? `${col.id}:r` : col.id;
if (this.valueCacheData.has(key) && group.order.length > 0) {
// web worker version
return () =>
this.workers
.pushStats(
'numberStats',
{ numberOfBins: summary.hist.length, domain: this.resolveDomain(col, raw) },
key,
this.valueCacheData.get(key) as Float32Array,
`${ranking.id}:${group.name}`,
group.order
)
.then((group) => ({ group, summary, data }));
}
return this.statsBuilder(group.order, col, summary.hist.length, raw, (group) => ({
group,
summary,
data,
}));
}
);
}
groupCategoricalStats(col: Column & ICategoricalLikeColumn, group: IOrderedGroup) {
return this.chain(`${col.id}:a:group:${group.name}`, this.summaryCategoricalStats(col), ({ summary, data }) => {
const ranking = col.findMyRanker()!;
if (this.valueCacheData.has(col.id) && group.order.length > 0) {
// web worker version
return () =>
this.workers
.pushStats(
'categoricalStats',
{ categories: col.categories.map((d) => d.name) },
col.id,
this.valueCacheData.get(col.id) as UIntTypedArray,
`${ranking.id}:${group.name}`,
group.order
)
.then((group) => ({ group, summary, data }));
}
return this.categoricalStatsBuilder(group.order, col, (group) => ({ group, summary, data }));
});
}
groupDateStats(col: Column & IDateColumn, group: IOrderedGroup) {
const key = `${col.id}:a:group:${group.name}`;
return this.chain(key, this.summaryDateStats(col), ({ summary, data }) => {
const ranking = col.findMyRanker()!;
if (this.valueCacheData.has(col.id) && group.order.length > 0) {
// web worker version
return () =>
this.workers
.pushStats(
'dateStats',
{ template: summary },
col.id,
this.valueCacheData.get(col.id) as Float64Array,
`${ranking.id}:${group.name}`,
group.order
)
.then((group) => ({ group, summary, data }));
}
return this.dateStatsBuilder(group.order, col, summary, (group) => ({ group, summary, data }));
});
}
groupStringStats(col: StringColumn, group: IOrderedGroup) {
const key = `${col.id}:a:group:${group.name}`;
return this.chain(key, this.summaryStringStats(col), ({ summary, data }) => {
const ranking = col.findMyRanker()!;
const topN = summary.topN.map((d) => d.value);
if (this.valueCacheData.has(col.id) && group.order.length > 0) {
// web worker version
return () =>
this.workers
.pushStats(
'stringStats',
{ topN: this.options.stringTopNCount },
col.id,
this.valueCacheData.get(col.id) as readonly string[],
`${ranking.id}:${group.name}`,
group.order
)
.then((group) => ({ group, summary, data }));
}
return this.stringStatsBuilder(group.order, col, topN, (group) => ({ group, summary, data }));
});
}
summaryBoxPlotStats(col: Column & INumberColumn, raw?: boolean, order?: MultiIndices) {
return this.chain(`${col.id}:b:summary${raw ? ':braw' : ':b'}`, this.dataBoxPlotStats(col, raw), (data) => {
const ranking = col.findMyRanker()!;
const key = raw ? `${col.id}:r` : col.id;
if (this.valueCacheData.has(key)) {
// web worker version
return () =>
this.workers
.pushStats(
'boxplotStats',
{},
key,
this.valueCacheData.get(key) as Float32Array,
ranking.id,
order ? order.joined : ranking.getOrder()
)
.then((summary) => ({ summary, data }));
}
return this.boxplotBuilder(order ? order : ranking.getOrder(), col, raw, (summary) => ({ summary, data }));
});
}
summaryNumberStats(col: Column & INumberColumn, raw?: boolean, order?: MultiIndices) {
return this.chain(`${col.id}:b:summary${raw ? ':raw' : ''}`, this.dataNumberStats(col, raw), (data) => {
const ranking = col.findMyRanker()!;
const key = raw ? `${col.id}:r` : col.id;
if (this.valueCacheData.has(key)) {
// web worker version
return () =>
this.workers
.pushStats(
'numberStats',
{ numberOfBins: data.hist.length, domain: this.resolveDomain(col, raw) },
key,
this.valueCacheData.get(key) as Float32Array,
ranking.id,
order ? order.joined : ranking.getOrder()
)
.then((summary) => ({ summary, data }));
}
return this.statsBuilder(order ? order : ranking.getOrder(), col, data.hist.length, raw, (summary) => ({
summary,
data,
}));
});
}
summaryCategoricalStats(col: Column & ICategoricalLikeColumn, order?: MultiIndices) {
return this.chain(`${col.id}:b:summary`, this.dataCategoricalStats(col), (data) => {
const ranking = col.findMyRanker()!;
if (this.valueCacheData.has(col.id)) {
// web worker version
return () =>
this.workers
.pushStats(
'categoricalStats',
{ categories: col.categories.map((d) => d.name) },
col.id,
this.valueCacheData.get(col.id) as UIntTypedArray,
ranking.id,
order ? order.joined : ranking.getOrder()
)
.then((summary) => ({ summary, data }));
}
return this.categoricalStatsBuilder(order ? order : ranking.getOrder(), col, (summary) => ({ summary, data }));
});
}
summaryDateStats(col: Column & IDateColumn, order?: MultiIndices) {
return this.chain(`${col.id}:b:summary`, this.dataDateStats(col), (data) => {
const ranking = col.findMyRanker()!;
if (this.valueCacheData.has(col.id)) {
// web worker version
return () =>
this.workers
.pushStats(
'dateStats',
{ template: data },
col.id,
this.valueCacheData.get(col.id) as Float64Array,
ranking.id,
order ? order.joined : ranking.getOrder()
)
.then((summary) => ({ summary, data }));
}
return this.dateStatsBuilder(order ? order : ranking.getOrder(), col, data, (summary) => ({ summary, data }));
});
}
summaryStringStats(col: StringColumn, order?: MultiIndices) {
return this.chain(`${col.id}:b:summary`, this.dataStringStats(col), (data) => {
const ranking = col.findMyRanker()!;
if (this.valueCacheData.has(col.id)) {
// web worker version
return () =>
this.workers
.pushStats(
'stringStats',
{ topN: this.options.stringTopNCount },
col.id,
this.valueCacheData.get(col.id) as readonly string[],
ranking.id,
order ? order.joined : ranking.getOrder()
)
.then((summary) => ({ summary, data }));
}
return this.stringStatsBuilder(order ? order : ranking.getOrder(), col, undefined, (summary) => ({
summary,
data,
}));
});
}
private cached<T>(key: string, canAbort: boolean, it: Iterator<T | null> | (() => Promise<T>)): IRenderTask<T> {
const dontCache = this.data.length === 0;
if (this.isValidCacheEntry(key) && !dontCache) {
return this.cache.get(key)!;
}
const task = typeof it === 'function' ? abortAble(it()) : this.tasks.pushMulti(key, it, canAbort);
const s = taskLater(task);
if (!dontCache) {
this.cache.set(key, s);
}
task.then((r) => {
if (this.cache.get(key) !== s) {
return;
}
if (typeof r === 'symbol') {
this.cache.delete(key);
} else {
this.cache.set(key, taskNow(r));
}
});
return s;
}
private chain<T, U>(
key: string,
task: IRenderTask<T>,
creator: (data: T) => Iterator<U | null> | (() => Promise<U>)
): IRenderTask<U> {
if (this.isValidCacheEntry(key)) {
return this.cache.get(key)!;
}
if (task instanceof TaskNow) {
if (typeof task.v === 'symbol') {
// aborted
return taskNow(ABORTED);
}
return this.cached(key, true, creator(task.v));
}
const v = (task as TaskLater<T>).v;
const subTask = v.then((data) => {
if (typeof data === 'symbol') {
return ABORTED;
}
const created = creator(data);
if (typeof created === 'function') {
// promise
return created();
}
return this.tasks.pushMulti(key, created);
});
const s = taskLater(subTask);
this.cache.set(key, s);
subTask.then((r) => {
if (this.cache.get(key) !== s) {
return;
}
if (typeof r === 'symbol') {
this.cache.delete(key);
} else {
this.cache.set(key, taskNow(r));
}
});
return s;
}
private isValidCacheEntry(key: string) {
if (!this.cache.has(key)) {
return false;
}
const v = this.cache.get(key);
// not an aborted task
return !(v instanceof TaskNow && typeof v.v === 'symbol') && !(v instanceof TaskLater && v.v.isAborted());
}
private chainCopy<T, U>(key: string, task: IRenderTask<T>, creator: (data: T) => U): IRenderTask<U> {
if (this.isValidCacheEntry(key)) {
return this.cache.get(key)!;
}
if (task instanceof TaskNow) {
if (typeof task.v === 'symbol') {
// aborted
return taskNow(ABORTED);
}
const subTask = taskNow(creator(task.v));
this.cache.set(key, subTask);
return subTask;
}
const v = (task as TaskLater<T>).v;
const subTask = v.then((data) => {
if (typeof data === 'symbol') {
return ABORTED;
}
return creator(data);
});
const s = taskLater(subTask);
this.cache.set(key, s);
subTask.then((r) => {
if (this.cache.get(key) !== s) {
return;
}
if (typeof r === 'symbol') {
this.cache.delete(key);
} else {
this.cache.set(key, taskNow(r));
}
});
return s;
}
dataBoxPlotStats(col: Column & INumberColumn, raw?: boolean) {
const key = `${col.id}:c:data${raw ? ':braw' : ':b'}`;
const valueCacheKey = raw ? `${col.id}:r` : col.id;
if (this.valueCacheData.has(valueCacheKey) && this.data.length > 0) {
// use webworker
return this.cached(key, false, () =>
this.workers.pushStats(
'boxplotStats',
{},
valueCacheKey,
this.valueCacheData.get(valueCacheKey)! as Float32Array
)
);
}
return this.cached(key, false, this.boxplotBuilder<IAdvancedBoxPlotData>(null, col, raw));
}
dataNumberStats(col: Column & INumberColumn, raw?: boolean) {
return this.cached(
`${col.id}:c:data${raw ? ':raw' : ''}`,
false,
this.statsBuilder<IStatistics>(null, col, getNumberOfBins(this.data.length), raw)
);
}
dataCategoricalStats(col: Column & ICategoricalLikeColumn) {
return this.cached(`${col.id}:c:data`, false, this.categoricalStatsBuilder<ICategoricalStatistics>(null, col));
}
dataStringStats(col: StringColumn) {
return this.cached(`${col.id}:c:data`, false, this.stringStatsBuilder<IStringStatistics>(null, col));
}
dataDateStats(col: Column & IDateColumn) {
return this.cached(`${col.id}:c:data`, false, this.dateStatsBuilder<IDateStatistics>(null, col));
}
sort(
ranking: Ranking,
group: IGroup,
indices: IndicesArray,
singleCall: boolean,
maxDataIndex: number,
lookups?: CompareLookup
) {
if (!lookups || indices.length < 1000) {
// no thread needed
const order = sortDirect(indices, maxDataIndex, lookups);
return Promise.resolve(order);
}
const indexArray = toIndexArray(indices, maxDataIndex);
const toTransfer = [indexArray.buffer];
if (singleCall) {
// can transfer otherwise need to copy
toTransfer.push(...lookups.transferAbles);
}
return this.workers.push(
'sort',
{
ref: `${ranking.id}:${group.name}`,
indices: indexArray,
sortOrders: lookups.sortOrders,
},
toTransfer,
(r: ISortMessageResponse) => r.order
);
}
terminate() {
this.workers.terminate();
this.cache.clear();
this.valueCacheData.clear();
}
} | the_stack |
import supertest from "supertest";
import express, { Application, NextFunction, Request, Response } from "express";
import nock from "nock";
import { Installation, Subscription } from "../../../src/models";
import { mocked } from "ts-jest/utils";
import { mockModels } from "../../utils/models";
import api from "../../../src/api";
import { EnvironmentEnum } from "../../../src/interfaces/common";
import { getLogger } from "../../../src/config/logger";
import getAxiosInstance from "../../../src/jira/client/axios";
jest.mock("../../../src/models");
jest.mock("../../../src/jira/client/axios");
describe("API", () => {
let app: Application;
let locals;
const invalidId = 99999999;
const installationId = 1234;
const successfulAuthResponseWrite = {
data: {
viewer: {
login: "gimenete",
organization: {
viewerCanAdminister: true
}
}
}
};
const successfulAuthResponseAdmin = {
data: {
viewer: {
login: "monalisa",
organization: {
viewerCanAdminister: true
}
}
}
};
const createApp = async () => {
const app = express();
app.use((req: Request, res: Response, next: NextFunction) => {
res.locals = locals || {};
req.log = getLogger("test");
req.session = { jiraHost: process.env.ATLASSIAN_URL };
next();
});
app.use("/api", api);
return app;
};
beforeEach(async () => {
locals = {
client: {
apps: {
getInstallation: jest.fn().mockResolvedValue({ data: {} })
}
}
};
app = await createApp();
});
describe("Authentication", () => {
it("should return 404 if no token is provided", () => {
return supertest(app)
.get("/api")
.expect(404)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return 200 if a valid token is provided", () => {
githubNock
.post("/graphql")
.reply(200, successfulAuthResponseWrite);
return supertest(app)
.get("/api")
.set("Authorization", "Bearer xxx")
.expect(200)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return 200 if token belongs to an admin", () => {
githubNock
.post("/graphql")
.reply(200, successfulAuthResponseAdmin);
return supertest(app)
.get("/api")
.set("Authorization", "Bearer xxx")
.expect(200)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return 401 if the GraphQL query returns errors", () => {
githubNock
.post("/graphql")
.reply(200, {
errors: [
{
path: ["query", "viewer", "foo"],
extensions: {
code: "undefinedField",
typeName: "User",
fieldName: "foo"
},
locations: [
{
line: 4,
column: 5
}
],
message: "Field 'foo' doesn't exist on type 'User'"
}
]
});
return supertest(app)
.get("/api")
.set("Authorization", "Bearer xxx")
.then((response) => {
expect(response.body).toMatchSnapshot();
expect(response.status).toEqual(401);
});
});
it("should return 401 if the returned organization is null", () => {
githubNock
.post("/graphql")
.reply(200, {
data: {
viewer: {
login: "gimenete",
organization: null
}
}
});
return supertest(app)
.get("/api")
.set("Authorization", "Bearer xxx")
.expect(401)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return 401 if the token is invalid", () => {
githubNock
.post("/graphql")
.reply(401, {
HttpError: {
message: "Bad credentials",
documentation_url: "https://developer.github.com/v4"
}
});
return supertest(app)
.get("/api")
.set("Authorization", "Bearer bad token")
.expect(401)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
});
describe('Endpoints', () => {
function mockJiraResponse(status: number) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mocked(getAxiosInstance).mockReturnValue({
"get": () => Promise.resolve<any>({
status
})
});
}
describe("verify", () => {
beforeEach(() => {
mockJiraResponse(200);
mocked(Installation.findByPk).mockResolvedValue(
mockModels.Installation.findByPk
);
});
it("should return 'Installation already enabled'", () => {
githubNock
.post("/graphql")
.reply(200, successfulAuthResponseAdmin);
return supertest(app)
.post(`/api/jira/${installationId}/verify`)
.set("Authorization", "Bearer xxx")
.expect(200)
.expect("Content-Type", /json/)
.then((response) => {
expect(response.body.message).toMatchSnapshot();
expect(response.body.installation.enabled).toBeTruthy();
});
});
});
});
describe.skip("Endpoints (skipped, wtf?!)", () => {
beforeEach(() => {
githubNock
.post("/graphql")
.reply(200, successfulAuthResponseWrite);
});
describe("installation", () => {
it("should return 404 if no installation is found", async () => {
mocked(Subscription.getAllForInstallation).mockResolvedValue([]);
return supertest(app)
.get(`/api/${invalidId}`)
.set("Authorization", "Bearer xxx")
.expect(404)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return information for an existing installation", async () => {
mocked(Subscription.getAllForInstallation).mockResolvedValue([
{
jiraHost: process.env.ATLASSIAN_URL,
gitHubInstallationId: installationId
}
] as any);
return supertest(app)
.get(`/api/${installationId}`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send("jiraHost=https://test-atlassian-instance.net")
.expect(200)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
});
describe("repoSyncState", () => {
it("should return 404 if no installation is found", async () => {
mocked(Subscription.getSingleInstallation).mockResolvedValue(null);
return supertest(app)
.get(`/api/${invalidId}/repoSyncState.json`)
.set("Authorization", "Bearer xxx")
.expect(404)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it("should return the repoSyncState information for an existing installation", async () => {
mocked(Subscription.getSingleInstallation).mockResolvedValue(
mockModels.Subscription.getSingleInstallation
);
return supertest(app)
.get(
`/api/${installationId}/repoSyncState.json?jiraHost=https://test-atlassian-instance.net`
)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.expect(200)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
});
describe("sync", () => {
it("should return 404 if no installation is found", async () => {
return supertest(app)
.post(`/api/${invalidId}/sync`)
.set("Authorization", "Bearer xxx")
.send("jiraHost=https://unknownhost.atlassian.net")
.expect(404)
.then((response) => {
expect(response.text).toMatchSnapshot();
});
});
it("should trigger the sync or start function", async () => {
mocked(Subscription.getSingleInstallation).mockResolvedValue(
mockModels.Subscription.getSingleInstallation
);
return supertest(app)
.post(`/api/${installationId}/sync`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.expect(202)
.then((response) => {
expect(response.text).toMatchSnapshot();
// td.verify(Subscription.findOrStartSync(subscription, null));
});
});
it("should reset repoSyncState if asked to", async () => {
mocked(Subscription.getSingleInstallation).mockResolvedValue(
mockModels.Subscription.getSingleInstallation
);
return supertest(app)
.post(`/api/${installationId}/sync`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.send("resetType=full")
.expect(202)
.then((response) => {
expect(response.text).toMatchSnapshot();
// td.verify(Subscription.findOrStartSync(subscription, "full"));
});
});
});
describe.skip("undo and complete - prod", () => {
beforeEach(() => {
process.env.NODE_ENV = EnvironmentEnum.production;
});
afterEach(() => {
process.env.NODE_ENV = EnvironmentEnum.test;
});
it("should return 404 if no installation is found", async () => {
return supertest(app)
.post(`/api/${invalidId}/migrate/undo`)
.set("Authorization", "Bearer xxx")
.send("jiraHost=https://unknownhost.atlassian.net")
.expect(404)
.then((response) => {
expect(response.text).toMatchSnapshot();
});
});
/**
* We should be testing that instance.post (by mocking axios) has been called.
* However, current implementation of tests causes state to override test internals.
* TODO: after ticket #ARC-200 is completed, update this test.
*/
it("should migrate an installation", () => {
const update = jest.fn();
mocked(Subscription.getSingleInstallation).mockResolvedValue({ update } as any);
jiraNock
.post("/rest/devinfo/0.10/github/migrationComplete")
.reply(200);
return supertest(app)
.post(`/api/${installationId}/migrate`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.expect(200)
.then((response) => {
expect(response.text).toMatchSnapshot();
expect(update).toMatchSnapshot();
});
});
/**
* We should be testing that instance.post (by mocking axios) has been called.
* However, current implementation of tests causes state to override test internals.
* TODO: after ticket #ARC-200 is completed, update this test.
*/
it("should undo a migration", async () => {
const update = jest.fn();
mocked(Subscription.getSingleInstallation).mockResolvedValue({ update } as any);
jiraNock
.post("/rest/devinfo/0.10/github/undoMigration")
.reply(200);
return supertest(app)
.post(`/api/${installationId}/migrate/undo`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.expect(200)
.then((response) => {
expect(response.text).toMatchSnapshot();
expect(update).toMatchSnapshot();
});
});
});
describe("undo and complete - nonprod", () => {
/**
* We should be testing that instance.post (by mocking axios) has not been called.
* However, current implementation of tests causes state to override test internals.
* TODO: after ticket #ARC-200 is completed, update this test.
*/
it("should not migrate an installation", async () => {
const update = jest.fn();
mocked(Subscription.getSingleInstallation).mockResolvedValue({ update } as any);
const interceptor = jiraNock.post("/rest/devinfo/0.10/github/migrationComplete");
const scope = interceptor.reply(200);
return supertest(app)
.post(`/api/${installationId}/migrate`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.expect(200)
.then((response) => {
expect(response.text).toMatchSnapshot();
expect(update).toMatchSnapshot();
expect(scope).not.toBeDone();
nock.removeInterceptor(interceptor);
});
});
/**
* We should be testing that instance.post (by mocking axios) has not been called.
* However, current implementation of tests causes state to override test internals.
* TODO: after ticket #ARC-200 is completed, update this test.
*/
it("should not undo a migration", async () => {
const update = jest.fn();
mocked(Subscription.getSingleInstallation).mockResolvedValue({ update } as any);
const interceptor = githubNock.post("/rest/devinfo/0.10/github/undoMigration");
const scope = interceptor.reply(200);
return supertest(app)
.post(`/api/${installationId}/migrate/undo`)
.set("Authorization", "Bearer xxx")
.set("host", "127.0.0.1")
.send(`jiraHost=${process.env.ATLASSIAN_URL}`)
.expect(200)
.then((response) => {
expect(response.text).toMatchSnapshot();
expect(update).toMatchSnapshot();
expect(scope).not.toBeDone();
nock.removeInterceptor(interceptor);
});
});
});
});
}); | the_stack |
import { APP_BASE_HREF } from '@angular/common';
import {
ApplicationRef,
Component,
ComponentRef,
Injectable,
NgModule,
NgZone,
ɵivyEnabled,
ɵglobal
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { RouterModule, Router } from '@angular/router';
import { Action, NgxsModule, Select, Selector, State, StateContext, Store } from '@ngxs/store';
import { freshPlatform } from '@ngxs/store/internals/testing';
import { Observable, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
describe('Select decorator returning state from the wrong store during SSR (https://github.com/ngxs/store/issues/1646)', () => {
if (!ɵivyEnabled) {
throw new Error('This test requires Ivy to be enabled.');
}
class AddCountry {
static type = '[Countries] Add country';
constructor(public country: string) {}
}
@State({
name: 'countries',
defaults: ['Mexico', 'USA', 'Canada']
})
@Injectable()
class CountriesState {
@Selector()
static getLastCountry(countries: string[]): string {
return countries[countries.length - 1];
}
@Action(AddCountry)
addCountry(ctx: StateContext<string[]>, action: AddCountry) {
ctx.setState(state => [...state, action.country]);
}
}
describe('Declarations (directives, components and pipes)', () => {
it(
'different apps should use its own Store instances',
freshPlatform(async () => {
// Arrange
@Component({ selector: 'app-root', template: '' })
class TestComponent {
@Select(CountriesState) countries$!: Observable<string[]>;
@Select(CountriesState.getLastCountry) lastCountry$!: Observable<string>;
}
@NgModule({
imports: [
BrowserModule,
NgxsModule.forRoot([CountriesState], { developmentMode: true })
],
declarations: [TestComponent],
bootstrap: [TestComponent]
})
class TestModule {}
// Act
const platform = platformBrowserDynamic();
const firstAppCountries: string[][] = [];
const secondAppCountries: string[][] = [];
const subscriptions: Subscription[] = [];
// Now let's bootstrap 2 different apps in parallel, this is basically the same what
// Angular Universal does internally for concurrent HTTP requests.
const [firstNgModuleRef, secondNgModuleRef] = await Promise.all([
platform.bootstrapModule(TestModule),
platform.bootstrapModule(TestModule)
]);
// `TestComponent` that belongs to the first application.
const firstTestComponent: ComponentRef<TestComponent> = firstNgModuleRef.injector.get(
ApplicationRef
).components[0];
// `TestComponent` that belongs to the second application.
const secondTestComponent: ComponentRef<TestComponent> = secondNgModuleRef.injector.get(
ApplicationRef
).components[0];
subscriptions.push(
firstTestComponent.instance.countries$.subscribe(countries => {
firstAppCountries.push(countries);
})
);
subscriptions.push(
secondTestComponent.instance.countries$.subscribe(countries => {
secondAppCountries.push(countries);
})
);
const firstStore = firstTestComponent.injector.get(Store);
const secondStore = secondTestComponent.injector.get(Store);
firstStore.dispatch(new AddCountry('Spain'));
secondStore.dispatch(new AddCountry('Portugal'));
// Let's ensure that different states are updated independently.
expect(firstAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Spain']
]);
expect(secondAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Portugal']
]);
// Let's destroy the first app and ensure that the second app will use its own `Store` instance.
firstNgModuleRef.destroy();
secondStore.dispatch(new AddCountry('France'));
// Let's ensure that the first state hasn't been updated since the first app was destroyed.
expect(firstAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Spain']
]);
expect(secondAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Portugal'],
['Mexico', 'USA', 'Canada', 'Portugal', 'France']
]);
// Let's subscribe to the `lastCountry$` thus it will call `createSelectObservable()`.
// Previously it would've thrown an error that `store` is `null` on the `SelectFactory`,
// since `store` is set to `null` in `SelectFactory.ngOnDestroy`.
const lastCountry = await secondTestComponent.instance.lastCountry$
.pipe(take(1))
.toPromise();
expect(lastCountry).toEqual('France');
disposeSubscriptions(subscriptions);
})
);
});
describe('Injectables', () => {
it(
'should use independent states inside root providers',
freshPlatform(async () => {
// Arrange
@Injectable({ providedIn: 'root' })
class TestService {
@Select(CountriesState) countries$!: Observable<string[]>;
@Select(CountriesState.getLastCountry) lastCountry$!: Observable<string>;
}
@Component({ selector: 'app-root', template: '' })
class TestComponent {}
@NgModule({
imports: [
BrowserModule,
NgxsModule.forRoot([CountriesState], { developmentMode: true })
],
declarations: [TestComponent],
bootstrap: [TestComponent]
})
class TestModule {}
// Act
const platform = platformBrowserDynamic();
const firstAppCountries: string[][] = [];
const secondAppCountries: string[][] = [];
const subscriptions: Subscription[] = [];
const [firstNgModuleRef, secondNgModuleRef] = await Promise.all([
platform.bootstrapModule(TestModule),
platform.bootstrapModule(TestModule)
]);
const firstTestService = firstNgModuleRef.injector.get(TestService);
const secondTestService = secondNgModuleRef.injector.get(TestService);
subscriptions.push(
firstTestService.countries$.subscribe(countries => {
firstAppCountries.push(countries);
})
);
subscriptions.push(
secondTestService.countries$.subscribe(countries => {
secondAppCountries.push(countries);
})
);
const firstStore = firstNgModuleRef.injector.get(Store);
const secondStore = secondNgModuleRef.injector.get(Store);
firstStore.dispatch(new AddCountry('Spain'));
secondStore.dispatch(new AddCountry('Portugal'));
// Let's ensure that different states are updated independently.
expect(firstAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Spain']
]);
expect(secondAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Portugal']
]);
// Let's destroy the first app and ensure that the second app will use its own `Store` instance.
firstNgModuleRef.destroy();
secondStore.dispatch(new AddCountry('France'));
// Let's ensure that the first state hasn't been updated since the first app was destroyed.
expect(firstAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Spain']
]);
expect(secondAppCountries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Portugal'],
['Mexico', 'USA', 'Canada', 'Portugal', 'France']
]);
// Let's subscribe to the `lastCountry$` thus it will call `createSelectObservable()`.
// Previously it would've thrown an error that `store` is `null` on the `SelectFactory`,
// since `store` is set to `null` in `SelectFactory.ngOnDestroy`.
const lastCountry = await secondTestService.lastCountry$.pipe(take(1)).toPromise();
expect(lastCountry).toEqual('France');
disposeSubscriptions(subscriptions);
})
);
it(
'should work inside providers declared in lazy module',
freshPlatform(async () => {
// Arrange
@Injectable()
class TestService {
@Select(CountriesState) countries$!: Observable<string[]>;
@Select(CountriesState.getLastCountry) lastCountry$!: Observable<string>;
}
@Component({ selector: 'app-root', template: '<router-outlet></router-outlet>' })
class TestComponent {}
@Component({ selector: 'app-child', template: '<h1>child</h1>' })
class ChildComponent {
countries$ = this.testService.countries$;
lastCountry$ = this.testService.lastCountry$;
constructor(private testService: TestService) {}
}
@NgModule({
imports: [
RouterModule.forChild([
{
path: '',
component: ChildComponent
}
])
],
declarations: [ChildComponent],
providers: [TestService]
})
class ChildModule {}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'child',
loadChildren: async () => ChildModule
}
]),
NgxsModule.forRoot([CountriesState], { developmentMode: true })
],
declarations: [TestComponent],
bootstrap: [TestComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }]
})
class TestModule {}
// Act
const countries: string[][] = [];
const { injector } = await platformBrowserDynamic().bootstrapModule(TestModule);
const ngZone = injector.get(NgZone);
const router = injector.get(Router);
const store = injector.get(Store);
await ngZone.run(() => router.navigateByUrl('/child'));
expect(document.body.innerHTML).toContain('<h1>child</h1>');
const childComponent: ChildComponent = ɵglobal.ng.getComponent(
document.querySelector('app-child')
);
const subscription = childComponent.countries$.subscribe(
countries.push.bind(countries)
);
store.dispatch(new AddCountry('Spain'));
expect(countries).toEqual([
['Mexico', 'USA', 'Canada'],
['Mexico', 'USA', 'Canada', 'Spain']
]);
subscription.unsubscribe();
})
);
});
});
function disposeSubscriptions(subscriptions: Subscription[]): void {
while (subscriptions.length) {
subscriptions.pop()!.unsubscribe();
}
} | the_stack |
import {
Msg,
EvalRequestMsg,
EvalCancellationMsg,
EvalResponseMsg,
ClosePluginMsg,
SaveScriptMsg,
LoadScriptMsg,
ScriptMsg,
WindowConfigMsg,
WindowSize,
UpdateSavedScriptsIndexMsg,
} from "../common/messages"
import * as windowSize from "../common/windowsize"
import * as rpc from "./rpc"
import * as scriptLibImpl from "./script-lib"
import * as worker from "./script-lib-worker"
import { SavedScriptIndex } from "./saved-scripts"
import * as consts from "./constants"
import { createScriptNode, updateScriptNode } from "./scriptnode"
// scriptLib is a global declared in scripter-env.js
declare var scriptLib :{[k:string]:any}
scriptLib = scriptLibImpl
const initialWindowSize = WindowSize.MEDIUM
function main() {
figma.showUI(__html__, {
width: windowSize.width(initialWindowSize),
height: windowSize.height(initialWindowSize),
visible: false,
})
// load window size from figma.clientStorage
restoreWindowConfig().then(ok => {
if (ok) {
figma.ui.show()
}
})
// message dispatch
figma.ui.onmessage = msg => {
// dlog("plugin recv", JSON.stringify(msg, null, 2))
switch (msg.type) {
case "ui-init":
// UI is ready. Send info about our figma plugin API version
figma.ui.show()
break
case "eval":
evalCode(msg as EvalRequestMsg)
break
case "eval-cancel":
cancelEval(msg as EvalCancellationMsg)
break
case "close-plugin":
figma.closePlugin((msg as ClosePluginMsg).message)
break
case "window-config":
windowConfig(msg as WindowConfigMsg)
saveWindowConfig(msg as WindowConfigMsg)
break
case "save-script":
saveScript(msg as SaveScriptMsg).catch(err => console.error(err.stack))
break
case "worker-message":
case "worker-error":
case "worker-ctrl":
worker.handleIncomingMessage(msg)
break
default:
if (
typeof msg.type != "string" ||
typeof msg.id != "string" ||
!rpc.handleTransactionResponse(msg)
) {
dlog(`plugin received unexpected message`, msg)
}
}
}
// // check launch command (e.g. from clicking "Open Script")
// dlog("figma.command", figma.command)
// Note: There's currently a bug in Figma where figma.command is set even when the user
// opened the plugin normally, so we can't rely on its value for knowing if the user clicked
// the "relaunch" button.
// update "saved script index"
SavedScriptIndex.init()
// attempt to load a script from selection
loadScriptFromSelection()
}
const windowConfigStorageKey = "windowConfig"
async function restoreWindowConfig() :Promise<boolean> {
let ok = false
await figma.clientStorage.getAsync(windowConfigStorageKey)
.then((data :WindowConfigMsg|undefined|null) => {
if (data) {
try {
windowConfig(data)
ok = true
} catch (err) {
console.error(`windowConfig in restoreWindowConfig: ${err.stack||err}`)
}
}
})
.catch(err => {
console.error(`getAsync("${windowConfigStorageKey}") => ${err.stack||err}`)
})
return ok
}
function saveWindowConfig(config :WindowConfigMsg) {
figma.clientStorage.setAsync(windowConfigStorageKey, config)
// .then(() => dlog(`setAsync("${windowConfigStorageKey}") => OK`))
.catch(err => {
console.error(`setAsync("${windowConfigStorageKey}") => ${err.stack||err}`)
})
}
function loadScriptFromSelection() {
// Note: There's a bug-like (but intentional) behaviro in Figma where the figma.command
// "gets stuck"; is set even for normal plugin launches, so it's very likely that the user
// just launched the plugin normally in this case.
//
// However, the resulting behavior is acceptable:
// a) When the user clicks the "Open script" relaunch button, the selected script is opened.
// This is good.
// b) When the user selects a script node and just runs Scripter normally, the selected script
// is opened. This is not ideal, but it's acceptable. When/if Figma changes the API so that
// relaunch data doesn't "get stcuck" this behavior will change to the better.
// c) When the user selects something that is not a script node and runs Scripter, whatever the
// last script they were working on is opened. This is good.
//
let limit = 20
for (let n of figma.currentPage.selection) {
let script = loadScriptDataFromNode(n)
if (script) {
loadScript(script)
break
}
if (--limit == 0) {
break
}
}
}
function loadScriptDataFromNode(n :SceneNode) :ScriptMsg|null {
if (n.type == "GROUP") {
// Select the first child of groups.
// Note that groups are never empty so this always succeeeds.
n = n.children[0]
}
let guid = n.getSharedPluginData(consts.dataNamespace, consts.dataScriptGUID)
if (!guid) {
return null
}
let name = n.getSharedPluginData(consts.dataNamespace, consts.dataScriptName) || "Untitled"
let body = n.getSharedPluginData(consts.dataNamespace, consts.dataScriptBody) || ""
return { guid, name, body }
}
function loadScript(script :ScriptMsg) {
if (!script.guid) { throw new Error(`script missing guid`) }
if (typeof script.body != "string") { throw new Error(`script missing body`) }
rpc.sendMsg<LoadScriptMsg>({ type: "load-script", script })
}
const scriptNodeFont :FontName = { family: "IBM Plex Mono", style: "Regular" }
async function saveScript(msg :SaveScriptMsg) {
// setSharedPluginData(namespace: string, key: string, value: string): void
// setRelaunchData(data: { [command: string]: /* description */ string }): void
// attempt to lookup existing node for guid, and load font
let [node,] = await Promise.all([
SavedScriptIndex.getNodeByGUID(msg.script.guid) as Promise<SceneNode|null>,
figma.loadFontAsync(scriptNodeFont),
])
// update or create node
if (node) {
await updateScriptNode(node, msg.script)
} else if (msg.create) {
node = await createScriptNode(msg.script)
}
if (node) {
if (msg.create) {
// select node on canvas when "create if missing" was requested
let n = node
if (n.type == "FRAME" && n.parent && n.parent.type == "GROUP") {
n = n.parent
}
figma.currentPage.selection = [ n ]
}
// update index
SavedScriptIndex.patchIndex([{
type: "update",
guid: msg.script.guid,
entry: { nodeId: node.id, name: msg.script.name }
}])
}
}
function fmtErrorResponse(err :Error, response :EvalResponseMsg) {
response.error = err.message || String(err)
response.srcLineOffset = evalScript.lineOffset
let stack :string = (err as any).scripterStack || err.stack
if (typeof stack == "string") {
let frames = stack.split(/[\r\n]+/)
let framePos :{line:number,column:number}[] = []
for (let i = 1; i < frames.length; i++) {
// Note: fig-js does not provide source column info
let m = frames[i].match(/:(\d+)(:?:(\d+)|)\)$/)
if (m) {
let line = parseInt(m[1])
let column = parseInt(m[2])
framePos.push({
line: isNaN(line) ? 0 : line,
column: isNaN(column) ? 0 : column,
})
}
}
response.srcPos = framePos
}
}
class EvalTransaction {
id :string
code :string
response :EvalResponseMsg
canceled :bool = false
cancelFun :EvalCancelFun|null = null // set by tryEval
constructor(id :string, code :string) {
this.id = id
this.code = code
this.response = { type: "eval-response", id }
}
setError(err :Error) {
console.error("[script]", (err as any).scripterStack || err.stack || String(err))
fmtErrorResponse(err, this.response)
}
cancel(reason? :Error) {
if (this.canceled || !this.cancelFun) {
return
}
this.canceled = true
this.cancelFun(reason)
}
// returns time spent evaluating the script (in milliseconds)
async eval(maxRetries :number = 10) :Promise<number> { // never throws
let triedToFixSnippets = new Set<string>()
let timeStarted = 0
while (true) {
try {
timeStarted = Date.now()
await this.tryEval()
} catch (err) {
if (maxRetries-- && await this.retry(err, triedToFixSnippets)) {
continue
}
this.setError(err)
}
return Date.now() - timeStarted
}
}
async tryEval() {
let [p, c] = evalScript(this.id, this.code)
this.cancelFun = c
let result :any = p
while (result instanceof Promise) {
dlog("plugin awaiting promise from script...")
result = await result
}
dlog("plugin resolved result from script:", result)
this.response.result = result
this.cancelFun = null
}
async retry(err :Error, triedToFixSnippets :Set<string>) :Promise<bool> {
// try loading fonts automatically. This is such a common issue that it's worth doing this.
// e.g. `Please call figma.loadFontAsync({ family: "Roboto", style: "Regular" })`
let m = /Please call figma.loadFontAsync\((\{.+\})\)/.exec(err.message)
if (!m || triedToFixSnippets.has(m[1])) {
return false
}
triedToFixSnippets.add(m[1])
dlog("script failed -- trying to rescue by loading fonts " + m[1])
// @ts-ignore eval
await figma.loadFontAsync(eval(`(function(){return ${m[1]} })()`) as FontName)
return true
}
finalize() {
try {
figma.ui.postMessage(this.response)
} catch (_) {
// failed to encode result -- set to undefined
this.response.result = undefined
figma.ui.postMessage(this.response)
}
}
}
let activeRequests = new Map<string,EvalTransaction>()
async function evalCode(req :EvalRequestMsg) {
dlog(`evaluating code for request ${req.id}`)
let tx = new EvalTransaction(req.id, req.js)
if (activeRequests.has(tx.id)) {
console.error(`[scripter plugin] duplicate eval request ${tx.id}`)
tx.finalize()
return
}
activeRequests.set(tx.id, tx)
let timeTaken = await tx.eval()
activeRequests.delete(tx.id)
tx.finalize()
console.log(`script took ${timeTaken}ms`)
}
function cancelEval(msg :EvalCancellationMsg) {
let tx = activeRequests.get(msg.id)
if (!tx) {
dlog(`[plugin/cancelEval] no active request ${msg.id}; ignoring`)
return
}
tx.cancel()
}
function windowConfig(c :WindowConfigMsg) {
figma.ui.resize(windowSize.width(c.width), windowSize.height(c.height))
}
main() | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.