text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Utils } from "./Utils"; export class Cursor { constructor(public offset: number, public line: number, public column: number, public lineStart: number, public lineEnd: number) { } } export class ParseError { constructor(public message: string, public cursor: Cursor = null, public reader: Reader = null) { } } export interface IReaderHooks { errorCallback(error: ParseError): void; } export class Reader { wsOffset = 0; offset = 0; cursorSearch: CursorPositionSearch; lineComment = "//"; supportsBlockComment = true; blockCommentStart = "/*"; blockCommentEnd = "*/"; commentDisabled = false; identifierRegex = "[A-Za-z_][A-Za-z0-9_]*"; numberRegex = "[+-]?(\\d*\\.\\d+|\\d+\\.\\d+|0x[0-9a-fA-F_]+|0b[01_]+|[0-9_]+)"; errors: ParseError[] = []; hooks: IReaderHooks = null; wsLineCounter = 0; moveWsOffset = true; prevTokenOffset = -1; constructor(public input: string) { this.cursorSearch = new CursorPositionSearch(input); } get eof() { return this.offset >= this.input.length; } get cursor() { return this.cursorSearch.getCursorForOffset(this.offset); } linePreview(cursor: Cursor): string { const line = this.input.substring(cursor.lineStart, cursor.lineEnd - 1); return `${line}\n${" ".repeat(cursor.column - 1)}^^^`; } get preview() { let preview = this.input.substr(this.offset, 30).replace(/\n/g, "\\n"); if (preview.length === 30) preview += "..."; return preview; } fail(message: string, offset = -1): void { const error = new ParseError(message, this.cursorSearch.getCursorForOffset(offset === -1 ? this.offset : offset), this); this.errors.push(error); if (this.hooks !== null) this.hooks.errorCallback(error); else throw new Error(`${message} at ${error.cursor.line}:${error.cursor.column}\n${this.linePreview(error.cursor)}`); } skipWhitespace(includeInTrivia = false): void { for (; this.offset < this.input.length; this.offset++) { const c = this.input[this.offset]; if (c === '\n') this.wsLineCounter++; if (!(c === '\n' || c === '\r' || c === '\t' || c === ' ')) break; } if (!includeInTrivia) this.wsOffset = this.offset; } skipUntil(token: string): boolean { const index = this.input.indexOf(token, this.offset); if (index === -1) return false; this.offset = index + token.length; if (this.moveWsOffset) this.wsOffset = this.offset; return true; } readUntil(token: string, orToEnd: boolean = false): string { const index = this.input.indexOf(token, this.offset); if (index === -1) { if (!orToEnd) return null; const result = this.input.substr(this.offset); this.wsOffset = this.offset = this.input.length; return result; } else { const result = this.input.substring(this.offset, index); this.wsOffset = this.offset = index; return result; } } skipLine() { if(!this.skipUntil("\n")) this.offset = this.input.length; } isAlphaNum(c: string) { const n = c.charCodeAt(0); return (97 <= n && n <= 122) || (65 <= n && n <= 90) || (48 <= n && n <= 57) || n === 95; //return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c === '_'; } readExactly(what: string): boolean { if (this.input.startsWith(what, this.offset)) { this.wsOffset = this.offset = this.offset + what.length; return true; } return false; } peekExactly(what: string): boolean { return this.input.startsWith(what, this.offset); } readChar(): string { // TODO: should we move wsOffset? this.offset++; return this.input[this.offset - 1]; } peekToken(token: string): boolean { this.skipWhitespaceAndComment(); if (this.input.startsWith(token, this.offset)) { // TODO: hackish way to make sure space comes after word tokens if (this.isAlphaNum(token[token.length - 1]) && this.isAlphaNum(this.input[this.offset + token.length])) return false; return true; } else { return false; } } readToken(token: string): boolean { if (this.peekToken(token)) { this.prevTokenOffset = this.offset; this.wsOffset = this.offset = this.offset + token.length; return true; } return false; } readAnyOf(tokens: string[]): string { for (const token of tokens) if (this.readToken(token)) return token; return null; } expectToken(token: string, errorMsg: string = null): void { if (!this.readToken(token)) this.fail(errorMsg || `expected token '${token}'`); } expectString(errorMsg: string = null): string { const result = this.readString(); if (result === null) this.fail(errorMsg || `expected string`); return result; } expectOneOf(tokens: string[]) { const result = this.readAnyOf(tokens); if (result === null) this.fail(`expected one of the following tokens: ${tokens.join(", ")}`); return result; } static matchFromIndex(pattern: string, input: string, offset: number) { const regex = new RegExp(pattern, "gy"); regex.lastIndex = offset; const matches = regex.exec(input); if (matches === null) { return null; } else { const result: string[] = []; for (let i = 0; i < matches.length; i++) result.push(matches[i]); return result; } } peekRegex(pattern: string): string[] { const matches = Reader.matchFromIndex(pattern, this.input, this.offset); return matches; } readRegex(pattern: string): string[] { const matches = Reader.matchFromIndex(pattern, this.input, this.offset); if (matches !== null) { this.prevTokenOffset = this.offset; this.wsOffset = this.offset = this.offset + matches[0].length; } return matches; } skipWhitespaceAndComment(): void { if (this.commentDisabled) return; this.moveWsOffset = false; while (true) { this.skipWhitespace(true); if (this.input.startsWith(this.lineComment, this.offset)) { this.skipLine(); } else if (this.supportsBlockComment && this.input.startsWith(this.blockCommentStart, this.offset)) { if (!this.skipUntil(this.blockCommentEnd)) this.fail(`block comment end ("${this.blockCommentEnd}") was not found`); } else { break; } } this.moveWsOffset = true; } readLeadingTrivia(): string { this.skipWhitespaceAndComment(); const thisLineStart = this.input.lastIndexOf("\n", this.offset); if (thisLineStart <= this.wsOffset) return ""; let result = this.input.substring(this.wsOffset, thisLineStart + 1); result = Utils.deindent(result); this.wsOffset = thisLineStart; return result; } readIdentifier(): string { this.skipWhitespace(); const idMatch = this.readRegex(this.identifierRegex); if (idMatch === null) return null; return idMatch[0]; } readNumber(): string { this.skipWhitespace(); const numMatch = this.readRegex(this.numberRegex); if (numMatch === null) return null; if (this.readRegex("[0-9a-zA-Z]") !== null) this.fail("invalid character in number"); return numMatch[0]; } readString(): string { this.skipWhitespace(); const sepChar = this.input[this.offset]; if (sepChar !== "'" && sepChar !== '"') return null; let str = ""; this.readExactly(sepChar); while (!this.readExactly(sepChar)) { const chr = this.readChar(); if (chr == "\\") { const esc = this.readChar(); if (esc === "n") str += "\n"; else if (esc === "r") str += "\r"; else if (esc === "t") str += "\t"; else if (esc === "\\") str += "\\"; else if (esc === sepChar) str += sepChar; else this.fail("invalid escape", this.offset - 1); } else { const chrCode = chr.charCodeAt(0); if (!(32 <= chrCode && chrCode <= 126) || chr === "\\" || chr === sepChar) this.fail(`not allowed character (code=${chrCode})`, this.offset - 1); str += chr; } } return str; } expectIdentifier(errorMsg: string = null): string { const id = this.readIdentifier(); if (id === null) this.fail(errorMsg || "expected identifier"); return id; } readModifiers(modifiers: string[]): string[] { const result: string[] = []; while (true) { let success = false; for (const modifier of modifiers) { if (this.readToken(modifier)) { result.push(modifier); success = true; } } if (!success) break; } return result; } } class CursorPositionSearch { lineOffsets = [0]; constructor(public input: string) { for (let i = 0; i < input.length; i++) if (input[i] === '\n') this.lineOffsets.push(i + 1); this.lineOffsets.push(input.length); } getLineIdxForOffset(offset: number) { let low = 0; let high = this.lineOffsets.length - 1; while (low <= high) { // @java var middle = (int)Math.floor((low + high) / 2); const middle = Math.floor((low + high) / 2); const middleOffset = this.lineOffsets[middle]; if (offset == middleOffset) return middle; else if (offset <= middleOffset) high = middle - 1; else low = middle + 1; } return low - 1; } getCursorForOffset(offset: number): Cursor { const lineIdx = this.getLineIdxForOffset(offset); const lineStart = this.lineOffsets[lineIdx]; const lineEnd = this.lineOffsets[lineIdx + 1]; const column = offset - lineStart + 1; if (column < 1) throw new Error("Column should not be < 1"); return new Cursor(offset, lineIdx + 1, offset - lineStart + 1, lineStart, lineEnd); } }
the_stack
import MockWebSocket from "jest-websocket-mock"; import { Headers, Request } from "undici"; import { mockAccountId, mockApiToken } from "./helpers/mock-account-id"; import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch"; import { mockConsoleMethods } from "./helpers/mock-console"; import { useMockIsTTY } from "./helpers/mock-istty"; import { runInTempDir } from "./helpers/run-in-tmp"; import { runWrangler } from "./helpers/run-wrangler"; import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail"; import type WebSocket from "ws"; describe("tail", () => { runInTempDir(); mockAccountId(); mockApiToken(); const std = mockConsoleMethods(); afterEach(() => { mockWebSockets.forEach((ws) => ws.close()); mockWebSockets.splice(0); unsetAllMocks(); }); /** * Interaction with the tailing API, including tail creation, * deletion, and connection. */ describe("API interaction", () => { it("creates and then delete tails", async () => { const api = mockWebsocketAPIs(); expect(api.requests.creation.count).toStrictEqual(0); await runWrangler("tail test-worker"); await expect(api.ws.connected).resolves.toBeTruthy(); expect(api.requests.creation.count).toStrictEqual(1); expect(api.requests.deletion.count).toStrictEqual(0); api.ws.close(); expect(api.requests.deletion.count).toStrictEqual(1); }); it("creates and then delete tails: legacy envs", async () => { const api = mockWebsocketAPIs("some-env", true); expect(api.requests.creation.count).toStrictEqual(0); await runWrangler("tail test-worker --env some-env --legacy-env true"); await expect(api.ws.connected).resolves.toBeTruthy(); expect(api.requests.creation.count).toStrictEqual(1); expect(api.requests.deletion.count).toStrictEqual(0); api.ws.close(); expect(api.requests.deletion.count).toStrictEqual(1); }); it("creates and then delete tails: service envs", async () => { const api = mockWebsocketAPIs("some-env"); expect(api.requests.creation.count).toStrictEqual(0); await runWrangler("tail test-worker --env some-env --legacy-env false"); await expect(api.ws.connected).resolves.toBeTruthy(); expect(api.requests.creation.count).toStrictEqual(1); expect(api.requests.deletion.count).toStrictEqual(0); api.ws.close(); expect(api.requests.deletion.count).toStrictEqual(1); }); it("errors when the websocket closes unexpectedly", async () => { const api = mockWebsocketAPIs(); api.ws.close(); await expect(runWrangler("tail test-worker")).rejects.toThrow(); }); it("activates debug mode when the cli arg is passed in", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --debug"); await expect(api.nextMessageJson()).resolves.toHaveProperty( "debug", true ); }); }); describe("filtering", () => { it("sends sampling rate filters", async () => { const api = mockWebsocketAPIs(); const tooHigh = runWrangler("tail test-worker --sampling-rate 10"); await expect(tooHigh).rejects.toThrow(); const tooLow = runWrangler("tail test-worker --sampling-rate -5"); await expect(tooLow).rejects.toThrow(); await runWrangler("tail test-worker --sampling-rate 0.25"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { sampling_rate: 0.25 }, ]); }); it("sends single status filters", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --status error"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { outcome: ["exception", "exceededCpu", "unknown"] }, ]); }); it("sends multiple status filters", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --status error --status canceled"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { outcome: ["exception", "exceededCpu", "unknown", "canceled"] }, ]); }); it("sends single HTTP method filters", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --method POST"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { method: ["POST"] }, ]); }); it("sends multiple HTTP method filters", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --method POST --method GET"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { method: ["POST", "GET"] }, ]); }); it("sends header filters without a query", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --header X-CUSTOM-HEADER"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { header: { key: "X-CUSTOM-HEADER" } }, ]); }); it("sends header filters with a query", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value"); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { header: { key: "X-CUSTOM-HEADER", query: "some-value" } }, ]); }); it("sends single IP filters", async () => { const api = mockWebsocketAPIs(); const fakeIp = "192.0.2.1"; await runWrangler(`tail test-worker --ip ${fakeIp}`); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { client_ip: [fakeIp] }, ]); }); it("sends multiple IP filters", async () => { const api = mockWebsocketAPIs(); const fakeIp = "192.0.2.1"; await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { client_ip: [fakeIp, "self"] }, ]); }); it("sends search filters", async () => { const api = mockWebsocketAPIs(); const search = "filterMe"; await runWrangler(`tail test-worker --search ${search}`); await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [ { query: search }, ]); }); it("sends everything but the kitchen sink", async () => { const api = mockWebsocketAPIs(); const sampling_rate = 0.69; const status = ["ok", "error"]; const method = ["GET", "POST", "PUT"]; const header = "X-HELLO:world"; const client_ip = ["192.0.2.1", "self"]; const query = "onlyTheseMessagesPlease"; const cliFilters = `--sampling-rate ${sampling_rate} ` + status.map((s) => `--status ${s} `).join("") + method.map((m) => `--method ${m} `).join("") + `--header ${header} ` + client_ip.map((c) => `--ip ${c} `).join("") + `--search ${query} ` + `--debug`; const expectedWebsocketMessage = { filters: [ { sampling_rate }, { outcome: ["ok", "exception", "exceededCpu", "unknown"] }, { method }, { header: { key: "X-HELLO", query: "world" } }, { client_ip }, { query }, ], debug: true, }; await runWrangler(`tail test-worker ${cliFilters}`); await expect(api.nextMessageJson()).resolves.toEqual( expectedWebsocketMessage ); }); }); describe("printing", () => { const { setIsTTY } = useMockIsTTY(); it("logs request messages in JSON format", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --format json"); const event = generateMockRequestEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect(std.out).toMatch(deserializeToJson(serializedMessage)); }); it("logs scheduled messages in JSON format", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --format json"); const event = generateMockScheduledEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect(std.out).toMatch(deserializeToJson(serializedMessage)); }); it("logs request messages in pretty format", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --format pretty"); const event = generateMockRequestEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect( std.out .replace( new Date(mockEventTimestamp).toLocaleString(), "[mock event timestamp]" ) .replace( mockTailExpiration.toLocaleString(), "[mock expiration date]" ) ).toMatchInlineSnapshot(` "Successfully created tail, expires at [mock expiration date] Connected to test-worker, waiting for logs... GET https://example.org/ - Ok @ [mock event timestamp]" `); }); it("logs scheduled messages in pretty format", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --format pretty"); const event = generateMockScheduledEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect( std.out .replace( new Date(mockEventTimestamp).toLocaleString(), "[mock timestamp string]" ) .replace( mockTailExpiration.toLocaleString(), "[mock expiration date]" ) ).toMatchInlineSnapshot(` "Successfully created tail, expires at [mock expiration date] Connected to test-worker, waiting for logs... \\"* * * * *\\" @ [mock timestamp string] - Ok" `); }); it("should not crash when the tail message has a void event", async () => { const api = mockWebsocketAPIs(); await runWrangler("tail test-worker --format pretty"); const message = generateMockEventMessage({ event: null }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect( std.out .replace( new Date(mockEventTimestamp).toLocaleString(), "[mock timestamp string]" ) .replace( mockTailExpiration.toLocaleString(), "[mock expiration date]" ) ).toMatchInlineSnapshot(` "Successfully created tail, expires at [mock expiration date] Connected to test-worker, waiting for logs... [missing request] - Ok @ [mock timestamp string]" `); }); it("defaults to logging in pretty format when the output is a TTY", async () => { setIsTTY(true); const api = mockWebsocketAPIs(); await runWrangler("tail test-worker"); const event = generateMockRequestEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect( std.out .replace( new Date(mockEventTimestamp).toLocaleString(), "[mock event timestamp]" ) .replace( mockTailExpiration.toLocaleString(), "[mock expiration date]" ) ).toMatchInlineSnapshot(` "Successfully created tail, expires at [mock expiration date] Connected to test-worker, waiting for logs... GET https://example.org/ - Ok @ [mock event timestamp]" `); }); it("defaults to logging in json format when the output is not a TTY", async () => { setIsTTY(false); const api = mockWebsocketAPIs(); await runWrangler("tail test-worker"); const event = generateMockRequestEvent(); const message = generateMockEventMessage({ event }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect(std.out).toMatch(deserializeToJson(serializedMessage)); }); it("logs console messages and exceptions", async () => { setIsTTY(true); const api = mockWebsocketAPIs(); await runWrangler("tail test-worker"); const event = generateMockRequestEvent(); const message = generateMockEventMessage({ event, logs: [ { message: ["some string"], level: "log", timestamp: 1234561 }, { message: [{ complex: "object" }], level: "log", timestamp: 1234562, }, { message: [1234], level: "error", timestamp: 1234563 }, ], exceptions: [ { name: "Error", message: "some error", timestamp: 1234564 }, { name: "Error", message: { complex: "error" }, timestamp: 1234564 }, ], }); const serializedMessage = serialize(message); api.ws.send(serializedMessage); expect( std.out .replace( new Date(mockEventTimestamp).toLocaleString(), "[mock event timestamp]" ) .replace( mockTailExpiration.toLocaleString(), "[mock expiration date]" ) ).toMatchInlineSnapshot(` "Successfully created tail, expires at [mock expiration date] Connected to test-worker, waiting for logs... GET https://example.org/ - Ok @ [mock event timestamp] (log) some string (log) { complex: 'object' } (error) 1234" `); expect(std.err).toMatchInlineSnapshot(` "X [ERROR]  Error: some error X [ERROR]  Error: { complex: 'error' } " `); expect(std.warn).toMatchInlineSnapshot(`""`); }); }); }); /* helpers */ /** * The built in serialize-to-JSON feature of our mock websocket doesn't work * for our use-case since we actually expect a raw buffer, * not a Javascript string. Additionally, we have to do some fiddling * with `RequestEvent`s to get them to serialize properly. * * @param message a message to serialize to JSON * @returns the same type we expect when deserializing in wrangler */ function serialize(message: TailEventMessage): WebSocket.RawData { if (isScheduled(message.event)) { // `ScheduledEvent`s work just fine const stringified = JSON.stringify(message); return Buffer.from(stringified, "utf-8"); } else { // Since the "properties" of an `undici.Request` are actually getters, // which don't serialize properly, we need to hydrate them manually. // This isn't a problem outside of testing since deserialization // works just fine and wrangler never _sends_ any event messages, // it only receives them. const request = ((message.event as RequestEvent | undefined | null) || {}) .request; const stringified = JSON.stringify(message, (key, value) => { if (key !== "request") { return value; } return { ...request, url: request?.url, headers: request?.headers, method: request?.method, }; }); return Buffer.from(stringified, "utf-8"); } } /** * Small helper to disambiguate the event types possible in a `TailEventMessage` * * @param event A TailEvent * @returns whether event is a ScheduledEvent (true) or a RequestEvent */ function isScheduled( event: ScheduledEvent | RequestEvent | undefined | null ): event is ScheduledEvent { return Boolean(event && "cron" in event); } /** * Similarly, we need to deserialize from a raw buffer instead * of just JSON.parsing a raw string. This deserializer also then * re-stringifies with some spacing, the same way wrangler tail does. * * @param message a buffer of data received from the websocket * @returns a string ready to be printed to the terminal or compared against */ function deserializeToJson(message: WebSocket.RawData): string { return JSON.stringify(JSON.parse(message.toString()), null, 2); } /** * A mock for all the different API resources wrangler accesses * when running `wrangler tail` */ type MockAPI = { requests: { creation: RequestCounter; deletion: RequestCounter; }; ws: MockWebSocket; nextMessageJson(): Promise<unknown>; }; /** * A counter used to check how many times a mock API has been hit. * Useful as a helper in our testing to check if wrangler is making * the correct API calls without actually sending any web traffic */ type RequestCounter = { count: number; }; /** * Mock out the API hit during Tail creation * * @param websocketURL a fake URL for wrangler to connect a websocket to * @returns a `RequestCounter` for counting how many times the API is hit */ function mockCreateTailRequest( websocketURL: string, env?: string, legacyEnv = false ): RequestCounter { const requests = { count: 0 }; const servicesOrScripts = env && !legacyEnv ? "services" : "scripts"; const environment = env && !legacyEnv ? "/environments/:envName" : ""; setMockResponse( `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`, "POST", ([_url, accountId, scriptName, envName]) => { requests.count++; expect(accountId).toEqual("some-account-id"); expect(scriptName).toEqual( legacyEnv && env ? `test-worker-${env}` : "test-worker" ); if (!legacyEnv) { expect(envName).toEqual(env); } return { id: "tail-id", url: websocketURL, expires_at: mockTailExpiration, }; } ); return requests; } /** * Mock expiration datetime for tails created during testing */ const mockTailExpiration = new Date(3005, 1); /** * Default value for event timestamps */ const mockEventTimestamp = 1645454470467; /** * Mock out the API hit during Tail deletion * * @returns a `RequestCounter` for counting how many times the API is hit */ function mockDeleteTailRequest( env?: string, legacyEnv = false ): RequestCounter { const requests = { count: 0 }; const servicesOrScripts = env && !legacyEnv ? "services" : "scripts"; const environment = env && !legacyEnv ? "/environments/:envName" : ""; setMockResponse( // "/accounts/:accountId/workers/scripts/:worker/tails", `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`, "DELETE", ([_url, accountId, scriptName, envNameOrTailId, tailId]) => { requests.count++; expect(accountId).toEqual("some-account-id"); expect(scriptName).toEqual( legacyEnv && env ? `test-worker-${env}` : "test-worker" ); if (!legacyEnv) { if (env) { expect(envNameOrTailId).toEqual(env); expect(tailId).toEqual("tail-id"); } else { expect(envNameOrTailId).toEqual("tail-id"); } } else { expect(envNameOrTailId).toEqual("tail-id"); } return null; } ); return requests; } const mockWebSockets: MockWebSocket[] = []; /** * All-in-one convenience method to mock the appropriate API calls before * each test, and clean up afterwards. * * @param websocketURL a fake websocket URL for wrangler to connect to * @returns a mocked-out version of the API */ function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI { const websocketURL = "ws://localhost:1234"; const api: MockAPI = { requests: { deletion: { count: 0 }, creation: { count: 0 }, }, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion ws: null!, // will be set in the `beforeEach()` below. /** * Parse the next message received by the mock websocket as JSON * @returns JSON.parse of the next message received by the websocket */ async nextMessageJson() { const message = await api.ws.nextMessage; return JSON.parse(message as string); }, }; api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv); api.requests.deletion = mockDeleteTailRequest(env, legacyEnv); api.ws = new MockWebSocket(websocketURL); mockWebSockets.push(api.ws); return api; } /** * Generate a mock `TailEventMessage` of the same shape sent back by the * tail worker. * * @param opts Any specific parts of the message to use instead of defaults * @returns a `TailEventMessage` that wrangler can process and display */ function generateMockEventMessage({ outcome = "ok", exceptions = [], logs = [], eventTimestamp = mockEventTimestamp, event = generateMockRequestEvent(), }: Partial<TailEventMessage>): TailEventMessage { return { outcome, exceptions, logs, eventTimestamp, event, }; } /** * Generate a mock `RequestEvent` that, in an alternate timeline, was used * to trigger a worker. You can't disprove this! * * @param opts Any specific parts of the event to use instead of defaults * @returns a `RequestEvent` that can be used within an `EventMessage` */ function generateMockRequestEvent( opts?: Partial<RequestEvent["request"]> ): RequestEvent { return { request: Object.assign( new Request(opts?.url || "https://example.org/", { method: opts?.method || "GET", headers: opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }), }), { cf: opts?.cf || { tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA", tlsVersion: "TLSv2.0", asn: 42069, colo: "ATL", httpProtocol: "HTTP/4", asOrganization: "Cloudflare", }, } ), }; } function generateMockScheduledEvent( opts?: Partial<ScheduledEvent> ): ScheduledEvent { return { cron: opts?.cron || "* * * * *", scheduledTime: opts?.scheduledTime || mockEventTimestamp, }; }
the_stack
const container = require('@google-cloud/container'); // quickstart takes in the GCP credientials object and a timezone, defaults to central1-a if not specified async function quickstart(GOOGLE_APPLICATION_CREDENTIALS:object, zone:string='us-central1-a') { const client = new container.v1.ClusterManagerClient(GOOGLE_APPLICATION_CREDENTIALS); const projectId:string = GOOGLE_APPLICATION_CREDENTIALS['project_id']; const request:object = { projectId, zone }; //response returns an object that has all the info we need const [response] = await client.listClusters(request); const clusters:any = response.clusters; const clusterArray = []; clusters.forEach(cluster=>{ let gcpDat:object = {}; gcpDat["endpoint"] = cluster.endpoint gcpDat["clusterName"] = cluster.name; gcpDat["clusterDescription"] = cluster.description; gcpDat["creationTime"] = cluster.createTime; gcpDat["clusterStatus"] = cluster.status; gcpDat["nodeCount"] = cluster.currentNodeCount; gcpDat["location"] = cluster.location; cluster.nodePools.forEach((node, i)=>{ gcpDat[`NodePool_${i}`] = [node.name , `diskSize[Gb]: ${node.config.diskSizeGb}`, `MachineType: ${node.config.machineType}`] }) clusterArray.push(gcpDat) }) return clusterArray; } async function create(GOOGLE_APPLICATION_CREDENTIALS:any, zone:string ='us-central1-a', input:object = {'clusterType':'affordable', 'name':'deployCluster', 'zone':'us-central1-a'}){ const client:any = new container.v1.ClusterManagerClient(GOOGLE_APPLICATION_CREDENTIALS); GOOGLE_APPLICATION_CREDENTIALS = JSON.parse(GOOGLE_APPLICATION_CREDENTIALS); const projectId:string = GOOGLE_APPLICATION_CREDENTIALS["project_id"]; let cluster:object ={}; if(input['clusterType'] == 'affordable'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "none", "monitoringService": "none", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "pool-1", "config": { "machineType": "g1-small", "diskSizeGb": 30, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard" }, "initialNodeCount": 1, "autoscaling": {}, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.13.7-gke.24" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.13.7-gke.24", "location": input['zone'] } } if(input['clusterType'] == 'standard'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "logging.googleapis.com", "monitoringService": "monitoring.googleapis.com", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "default-pool", "config": { "machineType": "n1-standard-1", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 3, "autoscaling": {}, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.12.8-gke.10", "location": input['zone'] } } if(input['clusterType'] == 'cpuIntensive'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "logging.googleapis.com", "monitoringService": "monitoring.googleapis.com", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "high-cpu-pool-1", "config": { "machineType": "n1-highcpu-4", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 3, "autoscaling": { "enabled": true, "minNodeCount": 1, "maxNodeCount": 5 }, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.12.8-gke.10", "location": input['zone'] } } if(input['clusterType'] == 'memoryIntensive'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "logging.googleapis.com", "monitoringService": "monitoring.googleapis.com", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "high-mem-pool-1", "config": { "machineType": "n1-highmem-2", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 3, "autoscaling": { "enabled": true, "minNodeCount": 1, "maxNodeCount": 5 }, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.12.8-gke.10", "location": input['zone'] } } if(input['clusterType'] == 'gpuAcceleratedComputing'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "logging.googleapis.com", "monitoringService": "monitoring.googleapis.com", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "standard-pool-1", "config": { "machineType": "n1-standard-1", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 3, "autoscaling": {}, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" }, { "name": "gpu-pool-1", "config": { "machineType": "n1-highmem-2", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "accelerators": [ { "acceleratorCount": "1", "acceleratorType": "nvidia-tesla-k80" } ], "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 1, "autoscaling": {}, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.12.8-gke.10", "location": input['zone'] } } if(input['clusterType'] == 'highly_available'){ cluster = { "name": input['name'], "masterAuth": { "clientCertificateConfig": {} }, "loggingService": "logging.googleapis.com", "monitoringService": "monitoring.googleapis.com", "network": `projects/${projectId}/global/networks/default`, "addonsConfig": { "httpLoadBalancing": {}, "horizontalPodAutoscaling": {}, "kubernetesDashboard": { "disabled": true }, "istioConfig": { "disabled": true } }, "subnetwork": `projects/${projectId}/regions/${input['zone'].slice(0,-2)}/subnetworks/default`, "nodePools": [ { "name": "standard-pool-1", "config": { "machineType": "n1-standard-2", "diskSizeGb": 100, "oauthScopes": [ "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append" ], "imageType": "COS", "diskType": "pd-standard", "shieldedInstanceConfig": {} }, "initialNodeCount": 3, "autoscaling": { "enabled": true, "minNodeCount": 1, "maxNodeCount": 5 }, "management": { "autoUpgrade": true, "autoRepair": true }, "version": "1.12.8-gke.10" } ], "networkPolicy": {}, "ipAllocationPolicy": { "useIpAliases": true }, "masterAuthorizedNetworksConfig": {}, "maintenancePolicy": { "window": { "dailyMaintenanceWindow": { "startTime": "10:00" } } }, "defaultMaxPodsConstraint": { "maxPodsPerNode": "110" }, "authenticatorGroupsConfig": {}, "privateClusterConfig": {}, "databaseEncryption": { "state": "DECRYPTED" }, "initialClusterVersion": "1.12.8-gke.10", "location": input['zone'] } } //--------------After knowing input configuration----------\\ const request:object = { projectId, zone, cluster } client.createCluster(request) .then(responses => { var response = responses[0]; }) .catch(err => { console.error(err); }); } export default [quickstart,create];
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; import { ErrorResponse } from '../model/models'; import { PortalNotificationsResponse } from '../model/models'; import { User } from '../model/models'; import { UserInput } from '../model/models'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; export interface DeleteCurrentUserNotificationByNotificationIdRequestParams { /** Id of a notification. */ notificationId: string; } export interface GetCurrentUserNotificationsRequestParams { /** The page number for pagination. */ page?: number; /** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */ size?: number; } export interface UpdateCurrentUserRequestParams { /** Use to update a user. */ userInput?: UserInput; } @Injectable({ providedIn: 'root' }) export class UserService { protected basePath = 'http://localhost:8083/portal/environments/DEFAULT'; public defaultHeaders = new HttpHeaders(); public configuration = new Configuration(); public encoder: HttpParameterCodec; constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { if (typeof basePath !== 'string') { basePath = this.basePath; } this.configuration.basePath = basePath; } this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); } private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { if (typeof value === "object" && value instanceof Date === false) { httpParams = this.addToHttpParamsRecursive(httpParams, value); } else { httpParams = this.addToHttpParamsRecursive(httpParams, value, key); } return httpParams; } private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { if (value == null) { return httpParams; } if (typeof value === "object") { if (Array.isArray(value)) { (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); } else if (value instanceof Date) { if (key != null) { httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); } else { throw Error("key may not be null if value is Date"); } } else { Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( httpParams, value[k], key != null ? `${key}.${k}` : k)); } } else if (key != null) { httpParams = httpParams.append(key, value); } else { throw Error("key may not be null if value is not object or array"); } return httpParams; } /** * Delete all notifications of the current user * Delete all notifications of the current user. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public deleteAllCurrentUserNotifications(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>; public deleteAllCurrentUserNotifications(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>; public deleteAllCurrentUserNotifications(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>; public deleteAllCurrentUserNotifications(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.delete<any>(`${this.configuration.basePath}/user/notifications`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * Delete a specific notification of the current user * Delete a specific notification of the current user. * @param requestParameters * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public deleteCurrentUserNotificationByNotificationId(requestParameters: DeleteCurrentUserNotificationByNotificationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>; public deleteCurrentUserNotificationByNotificationId(requestParameters: DeleteCurrentUserNotificationByNotificationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>; public deleteCurrentUserNotificationByNotificationId(requestParameters: DeleteCurrentUserNotificationByNotificationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>; public deleteCurrentUserNotificationByNotificationId(requestParameters: DeleteCurrentUserNotificationByNotificationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { const notificationId = requestParameters.notificationId; if (notificationId === null || notificationId === undefined) { throw new Error('Required parameter notificationId was null or undefined when calling deleteCurrentUserNotificationByNotificationId.'); } let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.delete<any>(`${this.configuration.basePath}/user/notifications/${encodeURIComponent(String(notificationId))}`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * Get the authenticated user * Get information about the authenticated user. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public getCurrentUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>; public getCurrentUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>; public getCurrentUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>; public getCurrentUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<User>(`${this.configuration.basePath}/user`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * Retrieve user\&#39;s avatar * Retrieve user\&#39;s avatar. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public getCurrentUserAvatar(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<Blob>; public getCurrentUserAvatar(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpResponse<Blob>>; public getCurrentUserAvatar(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpEvent<Blob>>; public getCurrentUserAvatar(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<any> { let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'image/_*', 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } return this.httpClient.get(`${this.configuration.basePath}/user/avatar`, { responseType: "blob", withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * Retrieve user\&#39;s notifications * Retrieve current user\&#39;s notifications. * @param requestParameters * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public getCurrentUserNotifications(requestParameters: GetCurrentUserNotificationsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<PortalNotificationsResponse>; public getCurrentUserNotifications(requestParameters: GetCurrentUserNotificationsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<PortalNotificationsResponse>>; public getCurrentUserNotifications(requestParameters: GetCurrentUserNotificationsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<PortalNotificationsResponse>>; public getCurrentUserNotifications(requestParameters: GetCurrentUserNotificationsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { const page = requestParameters.page; const size = requestParameters.size; let queryParameters = new HttpParams({encoder: this.encoder}); if (page !== undefined && page !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>page, 'page'); } if (size !== undefined && size !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>size, 'size'); } let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<PortalNotificationsResponse>(`${this.configuration.basePath}/user/notifications`, { params: queryParameters, responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * Modify current user information. * Modify current user information. Only the current user can modify his/her information. * @param requestParameters * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public updateCurrentUser(requestParameters: UpdateCurrentUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>; public updateCurrentUser(requestParameters: UpdateCurrentUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>; public updateCurrentUser(requestParameters: UpdateCurrentUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>; public updateCurrentUser(requestParameters: UpdateCurrentUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { const userInput = requestParameters.userInput; let headers = this.defaultHeaders; // authentication (BasicAuth) required if (this.configuration.username || this.configuration.password) { headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } // authentication (CookieAuth) required if (this.configuration.apiKeys) { const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"]; if (key) { } } let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.put<User>(`${this.configuration.basePath}/user`, userInput, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } }
the_stack
import { Readable, Writable } from 'stream' import { JdbcStream } from './jdbcstream' import { ifs as createIfs } from './ifs' import { toInsertSql } from './sqlutil' import { createJdbcWriteStream } from './jdbcwritestream' import jvm = require('java') import JSONStream = require('JSONStream') import { defaults } from './defaults' import Q = require('q') import { deprecate } from 'util' import { Oops } from 'oops-error' const defaultConfig = { host: process.env.AS400_HOST, user: process.env.AS400_USERNAME, password: process.env.AS400_PASSWORD, naming: 'system', } const { promisify } = require('util') jvm.asyncOptions = { asyncSuffix: '', syncSuffix: 'Sync', promiseSuffix: 'Promise', // Generate methods returning promises, using the suffix Promise. promisify: promisify, } jvm.options.push('-Xrs') // fixing the signal handling issues (for exmaple ctrl-c) jvm.options.push('-Dcom.ibm.as400.access.AS400.guiAvailable=false') // Removes gui prompts jvm.classpath.push(__dirname + '/../../java/lib/jt400.jar') jvm.classpath.push(__dirname + '/../../java/lib/jt400wrap.jar') jvm.classpath.push(__dirname + '/../../java/lib/json-simple-1.1.1.jar') jvm.classpath.push(__dirname + '/../../java/lib/hsqldb.jar') /** * Creates a new simplified javascript object from the imported (Java Class) javascript object. * @param con The imported Java Connection Class */ function createConFrom(con) { return { connection: con, query: con.query.bind(con), queryAsStream: con.queryAsStream.bind(con), update: con.update.bind(con), batchUpdate: con.batchUpdate.bind(con), execute: con.execute.bind(con), insertAndGetId: con.insertAndGetId.bind(con), getColumns: con.getColumns.bind(con), getPrimaryKeys: con.getPrimaryKeys.bind(con), openMessageQ: con.openMessageQSync.bind(con), createKeyedDataQ: con.createKeyedDataQSync.bind(con), openMessageFile: con.openMessageFileSync.bind(con), } } function values(list) { return Object.keys(list).map((k) => list[k]) } function insertListInOneStatment(jt400, tableName, idColumn, list) { if (!list || list.length === 0) { return new Q([]) } const sql = 'SELECT ' + idColumn + ' FROM NEW TABLE(' + toInsertSql(tableName, list) + ')' const params = list.map(values).reduce((arr, valueArr) => { return arr.concat(valueArr) }, []) return jt400.query(sql, params).then((idList) => { return idList.map((idObj) => idObj[idColumn.toUpperCase()]) }) } function handleError(context) { return (err) => { const errMsg = (err.cause && err.cause.getMessageSync && err.cause.getMessageSync()) || err.message const category = errMsg.toLowerCase().includes('connection') ? 'OperationalError' : 'ProgrammerError' throw new Oops({ message: errMsg, context, category, cause: err, }) } } function standardInsertList(jt400, tableName, _, list) { const idList = [] const pushToIdList = idList.push.bind(idList) return list .map((record) => { return { sql: toInsertSql(tableName, [record]), values: values(record), } }) .reduce((soFar, sqlObj) => { return soFar .then(() => { return jt400.insertAndGetId(sqlObj.sql, sqlObj.values) }) .then(pushToIdList) }, new Q()) .then(() => { return idList }) } function convertDateValues(v) { return v instanceof Date ? v.toISOString().replace('T', ' ').replace('Z', '') : v } function paramsToJson(params) { return JSON.stringify((params || []).map(convertDateValues)) } function createInstance(connection, insertListFun, inMemory) { const mixinConnection = function (obj, newConn?) { const thisConn = newConn || connection obj.query = function (sql, params, options) { const jsonParams = paramsToJson(params || []) // Sending default options to java const trim = options && options.trim !== undefined ? options.trim : true return Q.nfcall(thisConn.query, sql, jsonParams, trim) .then(JSON.parse) .catch(handleError({ sql, params })) } obj.createReadStream = function (sql, params) { const jsonParams = paramsToJson(params || []) return new JdbcStream({ jdbcStreamPromise: Q.nfcall( thisConn.queryAsStream, sql, jsonParams, 100 ).catch(handleError({ sql, params })), }) } obj.queryAsStream = obj.createReadStream obj.execute = function (sql, params) { const jsonParams = paramsToJson(params || []) return Q.nfcall(thisConn.execute, sql, jsonParams) .then((statement) => { const isQuery = statement.isQuerySync() const metadata = statement.getMetaData.bind(statement) const updated = statement.updated.bind(statement) let stream const stWrap = { isQuery() { return isQuery }, metadata() { return Q.nfcall(metadata).then(JSON.parse) }, asArray() { return Q.nfcall(statement.asArray.bind(statement)).then( JSON.parse ) }, asStream(options) { options = options || {} stream = new JdbcStream({ jdbcStream: statement.asStreamSync(options.bufferSize || 100), }) return stream }, asIterable() { return { [Symbol.asyncIterator]() { return { async next() { return Q.nfcall(statement.next.bind(statement)) .then(JSON.parse) .then((value) => ({ done: !Boolean(value), value, })) }, } }, } }, updated() { return Q.nfcall(updated) }, close() { if (stream) { stream.close() } else { statement.close((err) => { if (err) { console.log('close error', err) } }) } }, } return stWrap }) .catch(handleError({ sql, params })) } obj.update = function (sql, params) { const jsonParams = paramsToJson(params || []) return Q.nfcall(thisConn.update, sql, jsonParams).catch( handleError({ sql, params }) ) } obj.createWriteStream = function (sql, options) { return createJdbcWriteStream( obj.batchUpdate, sql, options && options.bufferSize ) } obj.batchUpdate = function (sql, paramsList) { const params = (paramsList || []).map((row) => { return row.map(convertDateValues) }) const jsonParams = JSON.stringify(params) return Q.nfcall(thisConn.batchUpdate, sql, jsonParams) .then((res) => Array.from(res)) .catch(handleError({ sql, params })) } obj.insertAndGetId = function (sql, params) { const jsonParams = paramsToJson(params || []) return Q.nfcall(thisConn.insertAndGetId, sql, jsonParams).catch( handleError({ sql, params }) ) } obj.insertList = function (tableName, idColumn, list) { return insertListFun(obj, tableName, idColumn, list) } obj.isInMemory = function () { return inMemory } return obj } const jt400 = mixinConnection({ transaction(transactionFunction) { const t = connection.connection.createTransactionSync() const c = { update: t.update.bind(t), execute: t.execute.bind(t), insertAndGetId: t.insertAndGetId.bind(t), batchUpdate: t.batchUpdate.bind(t), query: t.query.bind(t), } const transaction = mixinConnection( { commit() { t.commitSync() }, rollback() { t.rollbackSync() }, }, c ) return transactionFunction(transaction) .then((res) => { t.commitSync() t.endSync() return res }) .catch((err) => { t.rollbackSync() t.endSync() throw err }) }, getTablesAsStream(opt) { return new JdbcStream({ jdbcStream: connection.connection.getTablesAsStreamSync( opt.catalog, opt.schema, opt.table || '%' ), }).pipe(JSONStream.parse([true])) }, getColumns(opt) { return Q.nfcall( connection.getColumns, opt.catalog, opt.schema, opt.table, opt.columns || '%' ).then(JSON.parse) }, getPrimaryKeys(opt) { return Q.nfcall( connection.getPrimaryKeys, opt.catalog, opt.schema, opt.table ).then(JSON.parse) }, openMessageQ(opt) { const hasPath = typeof opt.path === 'string' const name = hasPath ? opt.path : opt.name const dq = connection.openMessageQ(name, hasPath) const read = dq.read.bind(dq) const sendInformational = dq.sendInformational.bind(dq) return { // write (key, data) { // dq.writeSync(key, data); // }, read() { let wait = -1 if (arguments[0] === Object(arguments[0])) { wait = arguments[0].wait || wait } return Q.nfcall(read, wait) }, sendInformational(messageText) { return Q.nfcall(sendInformational, messageText) }, } }, createKeyedDataQ(opt) { const dq = connection.createKeyedDataQ(opt.name) const read = dq.read.bind(dq) const readRes = function (key, wait, writeKeyLength) { return Q.nfcall( dq.readResponse.bind(dq), key, wait, writeKeyLength ).then((res) => { return { data: res.getDataSync(), write: res.writeSync.bind(res), } }) } return { write(key, data) { dq.writeSync(key, data) }, read() { let wait = -1 let key let writeKeyLength if (arguments[0] === Object(arguments[0])) { key = arguments[0].key wait = arguments[0].wait || wait writeKeyLength = arguments[0].writeKeyLength } else { key = arguments[0] } return writeKeyLength ? readRes(key, wait, writeKeyLength) : Q.nfcall(read, key, wait) }, } }, openMessageFile(opt: MessageFileHandlerOptions) { const f: MessageFileHandler = connection.openMessageFile(opt.path) const read = f.read.bind(f) return { read() { const messageId = arguments[0].messageId return Q.nfcall(read, messageId) }, } }, ifs() { return createIfs(connection.connection) }, defineProgram(opt: ProgramDefinitionOptions) { const pgm = connection.connection.pgmSync( opt.programName, JSON.stringify(opt.paramsSchema), opt.libraryName || '*LIBL', opt.ccsid ) const pgmFunc = pgm.run.bind(pgm) return function run(params, timeout = 3) { return Q.nfcall(pgmFunc, JSON.stringify(params), timeout).then( JSON.parse ) } }, pgm: deprecate(function (programName, paramsSchema, libraryName) { return this.defineProgram({ programName, paramsSchema, libraryName, }) }, 'pgm function is deprecated and will be removed in version 5.0. Please use defineProgram.'), close() { const cl = connection.connection.close.bind(connection.connection) return Q.nfcall(cl) }, }) return jt400 } export interface ProgramDefinitionOptions { programName: string paramsSchema: PgmParamType[] libraryName?: string ccsid?: number } export interface WriteStreamOptions { bufferSize: number } export interface PgmParamType1 { name: string size: number type?: string decimals?: number } export interface PgmParamType2 { name: string precision: number typeName?: string scale?: number } export interface PgmParamStructType { [key: string]: PgmParamType[] } export type PgmParamType = PgmParamType1 | PgmParamType2 | PgmParamStructType export interface CLOB { type: 'CLOB' value: string } export interface BLOB { type: 'BLOB' value: string } export type Param = string | number | Date | null | CLOB | BLOB export interface JustNameMessageQ { name: string } export interface JustPathMessageQ { path: string } export type MessageQOptions = JustNameMessageQ | JustPathMessageQ export interface MessageQReadOptions { wait?: number } export interface DataQReadOptions { key: string wait?: number writeKeyLength?: number } export interface MessageFileHandlerOptions { /** Message File Location, e.g. /QSYS.LIB/YOURLIBRARY.LIB/YOURMSGFILE.MSGF */ path: string } export interface MessageFileReadOptions { /** Message Key */ messageId: string[7] } export interface MessageQ { sendInformational: (messageText: string) => Promise<void> read: (params?: MessageQReadOptions) => Promise<any> | Promise<null> } export interface DataQOptions { name: string } export interface KeyedDataQ { write: (key: string, data: string) => void read: (params: DataQReadOptions | string) => Promise<any> } export interface AS400Message { getText: (cb: (err: any, data: string) => void) => void getTextSync: () => string getTextPromise: () => Promise<string> } export interface MessageFileHandler { read: (params: MessageFileReadOptions) => Promise<AS400Message> } export interface IfsFileMetadata { exists: boolean length: number } export interface Ifs { createReadStream: (fileName: string | Promise<string>) => Readable createWriteStream: ( fileName: string | Promise<string>, options?: { append: boolean; ccsid?: number } ) => Writable deleteFile: (fileName: string) => Promise<boolean> fileMetadata: (fileName: string) => Promise<IfsFileMetadata> } export interface QueryOptions { trim: Boolean } export interface Metadata { name: string typeName: string precision: number scale: number } export interface Statement { isQuery: () => boolean metadata: () => Promise<Metadata[]> asArray: () => Promise<string[][]> asIterable: () => AsyncIterable<string[]> asStream: (options?: any) => Readable updated: () => Promise<number> close: Close } export type Execute = (sql: string, params?: Param[]) => Promise<Statement> export type Query = <T>( sql: string, params?: Param[], options?: QueryOptions ) => Promise<T[]> export type Update = (sql: string, params?: Param[]) => Promise<number> export type CreateReadStream = (sql: string, params?: Param[]) => Readable export type InsertAndGetId = (sql: string, params?: Param[]) => Promise<number> export type CreateWriteStream = ( sql: string, options?: WriteStreamOptions ) => Writable export type BatchUpdate = (sql: string, params?: Param[][]) => Promise<number[]> export type Close = () => void export type InsertList = ( tableName: string, idColumn: string, rows: any[] ) => Promise<number[]> export interface BaseConnection { query: Query update: Update isInMemory: () => boolean createReadStream: CreateReadStream insertAndGetId: InsertAndGetId insertList: InsertList createWriteStream: CreateWriteStream batchUpdate: (sql: string, params?: Param[][]) => Promise<number[]> execute: Execute close: Close } export type TransactionFun = (transaction: BaseConnection) => Promise<any> export interface Connection extends BaseConnection { pgm: ( programName: string, paramsSchema: PgmParamType[], libraryName?: string ) => any defineProgram: (options: ProgramDefinitionOptions) => any getTablesAsStream: (params: any) => Readable getColumns: (params: any) => any getPrimaryKeys: (params: any) => any transaction: (fn: TransactionFun) => Promise<any> openMessageQ: (params: MessageQOptions) => Promise<MessageQ> createKeyedDataQ: (params: DataQOptions) => KeyedDataQ openMessageFile: ( params: MessageFileHandlerOptions ) => Promise<MessageFileHandler> ifs: () => Ifs } export interface InMemoryConnection extends Connection { mockPgm: (programName: string, fn: (input: any) => any) => InMemoryConnection } export function pool(config?): Connection { const javaCon = jvm .import('nodejt400.JT400') .createPoolSync(JSON.stringify(defaults(config || {}, defaultConfig))) return createInstance(createConFrom(javaCon), insertListInOneStatment, false) } export function connect(config?) { const jt = jvm.import('nodejt400.JT400') const createConnection = jt.createConnection.bind(jt) return Q.nfcall( createConnection, JSON.stringify(defaults(config || {}, defaultConfig)) ).then((javaCon) => { return createInstance( createConFrom(javaCon), insertListInOneStatment, false ) }) } export function useInMemoryDb(): InMemoryConnection { const javaCon = jvm.newInstanceSync('nodejt400.HsqlClient') const instance = createInstance( createConFrom(javaCon), standardInsertList, true ) const pgmMockRegistry = {} instance.mockPgm = function (programName, func) { pgmMockRegistry[programName] = func return instance } const defaultPgm = instance.defineProgram instance.defineProgram = function (opt) { const defaultFunc = defaultPgm(opt.programName, opt.paramsSchema) return function (params, timeout = 3) { const mockFunc = pgmMockRegistry[opt.programName] if (mockFunc) { const res = mockFunc(params, timeout) return res.then ? res : Q.when(res) } return defaultFunc(params, timeout) } } return instance }
the_stack
* Javascript port of https://github.com/jgm/pandocfilters */ "use strict"; import getStdin from "get-stdin"; /** * type of the JSON file (new syntax, old syntax was just the array of blocks) */ export type PandocJson = { blocks: Block[]; "pandoc-api-version": number[]; meta: PandocMetaMap; }; type FAReturn = void | AnyElt | Array<AnyElt>; export type SingleFilterActionAsync = ( ele: AnyElt, format: string, meta: PandocMetaMap, ) => Promise<FAReturn> | FAReturn; export type ArrayFilterActionAsync = ( ele: AnyElt[], format: string, meta: PandocMetaMap, ) => Promise<Array<AnyElt>> | Array<AnyElt>; /** * allow both a function that filters single elements (compat with old version), as well as passing two filter functions: * one that will be called with every list of children and can return a new list of children to replace them, * and one that acts on single elements */ export type FilterActionAsync = | SingleFilterActionAsync | { array?: ArrayFilterActionAsync; single?: SingleFilterActionAsync }; /** list of key-value attributes */ export type AttrList = Array<[string, string]>; /** [id, classes, list of key-value attributes] */ export type Attr = [string, Array<string>, AttrList]; export type MathType = { t: "DisplayMath" | "InlineMath" }; export type QuoteType = { t: "SingleQuote" | "DoubleQuote" }; /** [url, title] */ export type Target = [string, string]; /** output file format */ export type Format = string; export type CitationMode = { t: "AuthorInText" | "SuppressAuthor" | "NormalCitation"; }; export type Citation = { citationId: string; citationPrefix: Array<Inline>; citationSuffix: Array<Inline>; citationMode: CitationMode; citationNoteNum: number; citationHash: number; }; export type ListNumberStyle = { t: | "DefaultStyle" | "Example" | "Decimal" | "LowerRoman" | "UpperRoman" | "LowerAlpha" | "UpperAlpha"; }; export type ListNumberDelim = { t: "DefaultDelim" | "Period" | "OneParen" | "TwoParens"; }; export type ListAttributes = [number, ListNumberStyle, ListNumberDelim]; export type Alignment = { t: "AlignLeft" | "AlignRight" | "AlignCenter" | "AlignDefault"; }; export type TableCell = Array<Block>; export type EltMap = { // Inline Str: string; Emph: Array<Inline>; Strong: Array<Inline>; Strikeout: Array<Inline>; Superscript: Array<Inline>; Subscript: Array<Inline>; SmallCaps: Array<Inline>; Quoted: [QuoteType, Array<Inline>]; Cite: [Array<Citation>, Array<Inline>]; Code: [Attr, string]; Space: undefined; SoftBreak: undefined; LineBreak: undefined; Math: [MathType, string]; RawInline: [Format, string]; Link: [Attr, Array<Inline>, Target]; Image: [Attr, Array<Inline>, Target]; Note: Array<Block>; Span: [Attr, Array<Inline>]; // Block Plain: Array<Inline>; Para: Array<Inline>; LineBlock: Array<Array<Inline>>; CodeBlock: [Attr, string]; RawBlock: [Format, string]; BlockQuote: Array<Block>; OrderedList: [ListAttributes, Array<Array<Block>>]; BulletList: Array<Array<Block>>; DefinitionList: Array<[Array<Inline>, Array<Array<Block>>]>; Header: [number, Attr, Array<Inline>]; HorizontalRule: undefined; Table: [ Array<Inline>, Array<Alignment>, Array<number>, Array<TableCell>, Array<Array<TableCell>>, ]; Div: [Attr, Array<Block>]; Null: undefined; }; export type EltType = keyof EltMap; export type Elt<A extends EltType> = { t: A; c: EltMap[A] }; export type AnyElt = Inline | Block; export type Inline = | Elt<"Str"> | Elt<"Emph"> | Elt<"Strong"> | Elt<"Strikeout"> | Elt<"Superscript"> | Elt<"Subscript"> | Elt<"SmallCaps"> | Elt<"Quoted"> | Elt<"Cite"> | Elt<"Code"> | Elt<"Space"> | Elt<"SoftBreak"> | Elt<"LineBreak"> | Elt<"Math"> | Elt<"RawInline"> | Elt<"Link"> | Elt<"Image"> | Elt<"Note"> | Elt<"Span">; export type Block = | Elt<"Plain"> | Elt<"Para"> | Elt<"LineBlock"> | Elt<"CodeBlock"> | Elt<"RawBlock"> | Elt<"BlockQuote"> | Elt<"OrderedList"> | Elt<"BulletList"> | Elt<"DefinitionList"> | Elt<"Header"> | Elt<"HorizontalRule"> | Elt<"Table"> | Elt<"Div"> | Elt<"Null">; export type Tree = Array<Block | Inline>; /** meta information about document, mostly from markdown frontmatter * https://hackage.haskell.org/package/pandoc-types-1.20/docs/Text-Pandoc-Definition.html#t:MetaValue */ export type PandocMetaValue = | { t: "MetaMap"; c: PandocMetaMap } | { t: "MetaList"; c: Array<PandocMetaValue> } | { t: "MetaBool"; c: boolean } | { t: "MetaInlines"; c: Inline[] } | { t: "MetaString"; c: string } | { t: "MetaBlocks"; c: Block[] }; export type PandocMetaMap = Record<string, PandocMetaValue>; /** * Converts an action into a filter that reads a JSON-formatted pandoc * document from stdin, transforms it by walking the tree with the action, and * returns a new JSON-formatted pandoc document to stdout. The argument is a * function action(key, value, format, meta), where key is the type of the * pandoc object (e.g. 'Str', 'Para'), value is the contents of the object * (e.g. a string for 'Str', a list of inline elements for 'Para'), format is * the target output format (which will be taken for the first command * line argument if present), and meta is the document's metadata. If the * function returns None, the object to which it applies will remain * unchanged. If it returns an object, the object will be replaced. If it * returns a list, the list will be spliced in to the list to which the target * object belongs. (So, returning an empty list deletes the object.) * * @param {Function} action Callback to apply to every object */ export async function toJSONFilter(action: FilterActionAsync) { const json = await getStdin(); var data = JSON.parse(json); var format = process.argv.length > 2 ? process.argv[2] : ""; filter(data, action, format).then((output) => process.stdout.write(JSON.stringify(output)), ); } function isElt(x: unknown): x is AnyElt { return (typeof x === "object" && x && "t" in x) || false; } function isEltArray(x: unknown[]): x is AnyElt[] { return x.every(isElt); } /** * Walk a tree, applying an action to every object. * @param {Object} x The object to traverse * @param {Function} action Callback to apply to each item * @param {String} format Output format * @param {Object} meta Pandoc metadata * @return {Object} The modified tree */ export async function walk( x: unknown, action: FilterActionAsync, format: Format, meta: PandocMetaMap, ): Promise<unknown> { if (typeof action === "function") action = { single: action }; if (Array.isArray(x)) { if (action.array && isEltArray(x)) { x = await action.array(x, format, meta); if (!Array.isArray(x)) throw "impossible (just for ts)"; } var array: unknown[] = []; for (const item of x) { if (isElt(item) && action.single) { var res = (await action.single(item, format, meta)) || item; if (Array.isArray(res)) { for (const z of res) { array.push(await walk(z, action, format, meta)); } } else { array.push(await walk(res, action, format, meta)); } } else { array.push(await walk(item, action, format, meta)); } } return array; } else if (typeof x === "object" && x !== null) { var obj: any = {}; for (const k of Object.keys(x)) { obj[k] = await walk((x as any)[k], action, format, meta); } return obj; } return x; } export function walkSync( x: unknown, action: (ele: AnyElt, format: string, meta: PandocMetaMap) => FAReturn, format: Format, meta: PandocMetaMap, ) { if (Array.isArray(x)) { var array: unknown[] = []; for (const item of x) { if (isElt(item)) { var res = action(item, format, meta) || item; if (Array.isArray(res)) { for (const z of res) { array.push(walkSync(z, action, format, meta)); } } else { array.push(walkSync(res, action, format, meta)); } } else { array.push(walkSync(item, action, format, meta)); } } return array; } else if (typeof x === "object" && x !== null) { var obj: any = {}; for (const k of Object.keys(x)) { obj[k] = walkSync((x as any)[k], action, format, meta); } return obj; } return x; } /** * Walks the tree x and returns concatenated string content, leaving out all * formatting. * @param {Object} x The object to walk * @return {String} JSON string */ export function stringify(x: Tree | AnyElt | { t: "MetaString"; c: string }) { if (!Array.isArray(x) && x.t === "MetaString") return x.c; var result: string[] = []; var go = function (e: AnyElt) { if (e.t === "Str") result.push(e.c); else if (e.t === "Code") result.push(e.c[1]); else if (e.t === "Math") result.push(e.c[1]); else if (e.t === "LineBreak") result.push(" "); else if (e.t === "Space") result.push(" "); else if (e.t === "SoftBreak") result.push(" "); else if (e.t === "Para") result.push("\n"); }; walkSync(x, go, "", {}); return result.join(""); } /** * Returns an attribute list, constructed from the dictionary attrs. * @param {Object} attrs Attribute dictionary * @return {Array} Attribute list */ export function attributes(attrs: { id?: string; classes?: string[]; [k: string]: any; }): Attr { attrs = attrs || {}; var ident = attrs.id || ""; var classes = attrs.classes || []; var keyvals: [string, string][] = []; Object.keys(attrs).forEach(function (k) { if (k !== "classes" && k !== "id") keyvals.push([k, attrs[k]]); }); return [ident, classes, keyvals]; } type IsTuple<T extends any[]> = number extends T["length"] ? false : true; type WrapArray<T> = T extends undefined ? [] : T extends any[] ? IsTuple<T> extends true ? T : [T] : [T]; // Utility for creating constructor functions function elt<T extends EltType>( eltType: T, numargs: number, ): (...args: WrapArray<EltMap[T]>) => Elt<T> { return function (...args: WrapArray<EltMap[T]>) { var len = args.length; if (len !== numargs) throw ( eltType + " expects " + numargs + " arguments, but given " + len ); return { t: eltType, c: len === 1 ? args[0] : args } as any; }; } /** * Filter the given object */ export async function filter( data: PandocJson, action: FilterActionAsync, format: Format, ) { return (await walk( data, action, format, data.meta || (data as any)[0].unMeta, )) as PandocJson; } type RawMetaRecord = { [name: string]: RawMeta }; type RawMeta = string | boolean | RawMetaRecord | Array<RawMeta>; /** `.meta` in the pandoc json format describes the markdown frontmatter yaml as an AST as described in * https://hackage.haskell.org/package/pandoc-types-1.20/docs/Text-Pandoc-Definition.html#t:MetaValue * * this function converts a raw object to a pandoc meta AST object **/ export function rawToMeta(e: RawMeta): PandocMetaValue { if (Array.isArray(e)) { return { t: "MetaList", c: e.map((x) => rawToMeta(x)) }; } // warning: information loss: can't tell if it was a number or string if (typeof e === "string" || typeof e === "number") return { t: "MetaString", c: String(e) }; if (typeof e === "object") { const c = fromEntries( Object.entries(e).map(([k, v]) => [k, rawToMeta(v)]), ); return { t: "MetaMap", c }; } if (typeof e === "boolean") return { t: "MetaBool", c: e }; throw Error(typeof e); } export function metaToRaw(m: PandocMetaValue): RawMeta { if (m.t === "MetaMap") { return fromEntries( Object.entries(m.c).map(([k, v]) => [k, metaToRaw(v)]), ); } else if (m.t === "MetaList") { return m.c.map(metaToRaw); } else if (m.t === "MetaBool" || m.t === "MetaString") { return m.c; } else if (m.t === "MetaInlines" || m.t === "MetaBlocks") { // warning: information loss: removes formatting return stringify(m.c); } throw Error(`Unknown meta type ${(m as any).t}`); } /** meta root object is a map */ export function metaMapToRaw(c: PandocMetaMap): RawMetaRecord { return metaToRaw({ t: "MetaMap", c }) as any; } /** Object.fromEntries ponyfill */ function fromEntries<V>(iterable: Iterable<[string, V]>): Record<string, V> { return [...iterable].reduce((obj, [key, val]) => { obj[key] = val; return obj; }, {} as Record<string, V>); } // Constructors for block elements export const Plain = elt("Plain", 1); export const Para = elt("Para", 1); export const CodeBlock = elt("CodeBlock", 2); export const RawBlock = elt("RawBlock", 2); export const BlockQuote = elt("BlockQuote", 1); export const OrderedList = elt("OrderedList", 2); export const BulletList = elt("BulletList", 1); export const DefinitionList = elt("DefinitionList", 1); export const Header = elt("Header", 3); export const HorizontalRule = elt("HorizontalRule", 0); export const Table = elt("Table", 5); export const Div = elt("Div", 2); export const Null = elt("Null", 0); // Constructors for inline elements export const Str = elt("Str", 1); export const Emph = elt("Emph", 1); export const Strong = elt("Strong", 1); export const Strikeout = elt("Strikeout", 1); export const Superscript = elt("Superscript", 1); export const Subscript = elt("Subscript", 1); export const SmallCaps = elt("SmallCaps", 1); export const Quoted = elt("Quoted", 2); export const Cite = elt("Cite", 2); export const Code = elt("Code", 2); export const Space = elt("Space", 0); export const LineBreak = elt("LineBreak", 0); export const Formula = elt("Math", 2); // don't conflict with js builtin Math; export const RawInline = elt("RawInline", 2); export const Link = elt("Link", 3); export const Image = elt("Image", 3); export const Note = elt("Note", 1); export const Span = elt("Span", 2); // a few aliases export const stdio = toJSONFilter;
the_stack
import { shell } from "electron"; import { join, extname, basename } from "path"; import { copy, readdir, remove } from "fs-extra"; import * as os from "os"; import * as React from "react"; import { ContextMenu, Menu, MenuItem, Classes, ButtonGroup, Button, Divider, MenuDivider, Tag, Intent } from "@blueprintjs/core"; import { SceneLoader, PickingInfo, Material, MultiMaterial, CubeTexture, Texture, Mesh, AbstractMesh, SubMesh, } from "babylonjs"; import "babylonjs-loaders"; import { Tools } from "../tools/tools"; import { GLTFTools } from "../tools/gltf"; import { undoRedo } from "../tools/undo-redo"; import { assetsHelper } from "../tools/offscreen-assets-helper/offscreen-asset-helper"; import { Overlay } from "../gui/overlay"; import { Icon } from "../gui/icon"; import { IFile, FilesStore } from "../project/files"; import { Project } from "../project/project"; import { SceneTools } from "../scene/tools"; import { Assets } from "../components/assets"; import { AbstractAssets, IAssetComponentItem } from "./abstract-assets"; export class MeshesAssets extends AbstractAssets { /** * Defines the size of assets to be drawn in the panel. Default is 100x100 pixels. * @override */ protected size: number = 75; /** * Defines the list of all supported extensions. */ public extensions: string[] = [".babylon", ".glb", ".gltf", ".obj", ".fbx", ".stl"]; /** * Defines the list of all avaiable meshes in the assets component. */ public static Meshes: IFile[] = []; /** * Registers the component. */ public static Register(): void { Assets.addAssetComponent({ title: "Meshes", identifier: "meshes", ctor: MeshesAssets, }); } /** * Renders the component. * @override */ public render(): React.ReactNode { return ( <> <div className={Classes.FILL} key="meshes-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px" }}> <ButtonGroup> <Button key="refresh-folder" icon="refresh" small={true} onClick={() => this.refresh()} /> <Divider /> <Button key="add-meshes" icon={<Icon src="plus.svg" />} small={true} text="Add..." onClick={() => this._addMeshes()} /> <Divider /> </ButtonGroup> </div> {super.render()} </> ); } /** * Refreshes the component. * @param object defines the optional reference to the object to refresh. * @override */ public async refresh(object?: string): Promise<void> { await assetsHelper.init(); for (const m of MeshesAssets.Meshes) { if (!object && this.items.find((i) => i.key === m.path)) { continue; } if (object && m.path !== object) { continue; } const rootUrl = join(Project.DirPath!, "files", "/"); const name = join("..", "assets/meshes", m.name); const importSuccess = await assetsHelper.importMesh(rootUrl, name); const base64 = (importSuccess ? await assetsHelper.getScreenshot() : "../css/svg/times.svg"); const style = (importSuccess ? {} : { background: "darkred" }); const item = this.items.find((i) => i.key === m.path); if (item) { item.style = style; item.base64 = base64; } else { this.items.push({ id: m.name, key: m.path, base64, style }); } this.updateAssetThumbnail(m.path, base64); await assetsHelper.reset(); this.updateAssetObservable.notifyObservers(); } return super.refresh(); } /** * Called once a project has been loaded, this function is used to clean up * unused assets files automatically. */ public async clean(): Promise<void> { if (!Project.DirPath) { return; } const existingFiles = await readdir(join(Project.DirPath, "assets/meshes")); for (const file of existingFiles) { const exists = MeshesAssets.Meshes.find((m) => m.name === file); if (!exists) { await remove(join(Project.DirPath, "assets/meshes", file)); } } } /** * Called on the user double clicks an item. * @param item the item being double clicked. * @param img the double-clicked image element. */ public async onDoubleClick(item: IAssetComponentItem, img: HTMLImageElement): Promise<void> { super.onDoubleClick(item, img); await this.editor.addWindowedPlugin("mesh-viewer", undefined, { rootUrl: join(Project.DirPath!, "files", "/"), name: join("..", "assets/meshes", item.id), }); } /** * Called on the user right-clicks on an item. * @param item the item being right-clicked. * @param event the original mouse event. */ public onContextMenu(item: IAssetComponentItem, e: React.MouseEvent<HTMLImageElement, MouseEvent>): void { super.onContextMenu(item, e); const platform = os.platform(); const explorer = platform === "darwin" ? "Finder" : "File Explorer"; ContextMenu.show( <Menu className={Classes.DARK}> <MenuItem text="Refresh..." icon={<Icon src="recycle.svg" />} onClick={() => this._refreshMeshPreview(item.id, item.key)} /> <MenuDivider /> <MenuItem text="Update Instantiated References..." onClick={() => this.addOrUpdateMeshesInScene(item, true, false)} /> <MenuItem text="Force Update Instantiated References..." onClick={() => this.addOrUpdateMeshesInScene(item, true, true)} /> <MenuDivider /> <MenuItem text={`Show in ${explorer}`} icon="document-open" onClick={() => shell.showItemInFolder(Tools.NormalizePathForCurrentPlatform(item.key))} /> <MenuItem text="Export To" icon="export"> <MenuItem text="To Babylon..." icon={<Icon src="logo-babylon.svg" style={{ filter: "none" }} />} onClick={() => SceneTools.ExportMeshAssetToBabylonJSFormat(this.editor, item.id)} /> <MenuItem text="To GLB..." icon={<Icon src="gltf.svg" style={{ filter: "none" }} />} onClick={() => SceneTools.ExportMeshAssetToGLTF(this.editor, item.id, "glb")} /> <MenuItem text="To GLTF..." icon={<Icon src="gltf.svg" style={{ filter: "none" }} />} onClick={() => SceneTools.ExportMeshAssetToGLTF(this.editor, item.id, "gltf")} /> </MenuItem> <MenuDivider /> <MenuItem text="Remove" icon={<Icon src="times.svg" />} onClick={() => this._handleRemoveMesh(item)} /> </Menu>, { left: e.clientX, top: e.clientY }, ); } /** * Called on the user drops an asset in editor. (typically the preview canvas). * @param item the item being dropped. * @param pickInfo the pick info generated on the drop event. * @override */ public onDropAsset(item: IAssetComponentItem, pickInfo: PickingInfo): Promise<void> { super.onDropAsset(item, pickInfo); return this.addOrUpdateMeshesInScene(item, false, false, pickInfo); } /** * Adds or updates the meshes/material in scehe scene. In case of an update, it will just add the newest meshes. * @param item defines the item being added or updated. * @param update defines wether or not the instantiated meshes in scene should be updated. * @param forceUpdate defines wether or not, in case of an update, the update should be forced. * @param pickInfo defines the pick info generated in case of a drop event. */ public async addOrUpdateMeshesInScene(item: IAssetComponentItem, update: boolean, forceUpdate: boolean, pickInfo?: PickingInfo): Promise<void> { require("babylonjs-loaders"); const extension = extname(item.id).toLowerCase(); const isGltf = extension === ".glb" || extension === ".gltf"; if (isGltf) { Overlay.Show("Configuring GLTF...", true); } const rootUrl = join(Project.DirPath!, "files", "/"); const sceneFilename = join("..", "assets/meshes", item.id); // Load and stop all animations const result = await SceneLoader.ImportMeshAsync("", rootUrl, sceneFilename, this.editor.scene!); this.editor.scene!.stopAllAnimations(); const onTextureDone = (n: string) => Overlay.SetMessage(`Configuring GLTF... ${n}`); await SceneTools.ImportAnimationGroupsFromFile(this.editor, item.key); for (const mesh of result.meshes) { if (!update || !this._updateImportedMeshGeometry(mesh, item.id, forceUpdate)) { // Store the pose matrix of the mesh. mesh.metadata ??= {}; mesh.metadata.basePoseMatrix = mesh.getPoseMatrix().asArray(); // Place mesh if (!mesh.parent && pickInfo?.pickedPoint) { mesh.position.addInPlace(pickInfo.pickedPoint); } if (mesh instanceof Mesh) { const meshMetadata = Tools.GetMeshMetadata(mesh); meshMetadata.originalSourceFile = { id: mesh.id, name: mesh.name, sceneFileName: item.id, }; if (mesh.geometry) { mesh.geometry.id = Tools.RandomId(); } } mesh.id = Tools.RandomId(); } // Materials if (mesh.material) { // Store original datas const materialMetadata = Tools.GetMaterialMetadata(mesh.material); materialMetadata.originalSourceFile = materialMetadata.originalSourceFile ?? { id: mesh.material.id, name: mesh.material.name, sceneFileName: item.id, }; mesh.material.id = Tools.RandomId(); if (mesh.material instanceof MultiMaterial) { for (const m of mesh.material.subMaterials) { if (!m) { return; } // Store original datas const subMaterialMetadata = Tools.GetMaterialMetadata(m); subMaterialMetadata.originalSourceFile = subMaterialMetadata.originalSourceFile ?? { id: m.id, name: m.name, sceneFileName: item.id, }; m.id = Tools.RandomId(); if (isGltf) { await this._configureGltfMaterial(m, onTextureDone); } this._configureMaterialTextures(m); }; } else { if (isGltf) { await this._configureGltfMaterial(mesh.material, onTextureDone); } this._configureMaterialTextures(mesh.material); } } } // Don't forget transform nodes for (const transformNode of this.editor.scene!.transformNodes) { if (!transformNode.metadata || !transformNode.metadata.gltf) { continue; } if (transformNode.metadata.gltf.editorDone) { continue; } if (update) { transformNode.dispose(true, false); } else { transformNode.id = Tools.RandomId(); transformNode.metadata.gltf.editorDone = true; } } result.skeletons.forEach((skeleton) => { // Skeleton Ids are not strings but numbers let id = 0; while (this.editor.scene!.getSkeletonById(id as any)) { id++; } skeleton.id = id as any; skeleton.bones.forEach((b) => { b.id = Tools.RandomId(); b.metadata ??= {}; b.metadata.originalId = b.id; }); }); result.particleSystems.forEach((ps) => ps.id = Tools.RandomId()); this.editor.assets.refresh(); this.editor.graph.refresh(); if (isGltf) { Overlay.Hide(); } } /** * Called on the user drops files in the assets component and returns true if the files have been computed. * @param files the list of files being dropped. */ public async onDropFiles(files: IFile[]): Promise<void> { for (const file of files) { const extension = extname(file.name).toLowerCase(); if (extension === ".bin") { // For GLTF files. await copy(file.path, join(Project.DirPath!, "files", file.name)); } if (this.extensions.indexOf(extension) === -1) { continue; } const existing = MeshesAssets.Meshes.find((m) => m.name === file.name); // Copy assets const dest = join(Project.DirPath!, "assets", "meshes", file.name); if (dest) { try { await copy(file.path, dest); } catch (e) { this.editor.console.logError(e.message); } } if (!existing) { MeshesAssets.Meshes.push({ name: file.name, path: dest }); } else { this.editor.assets.refresh(MeshesAssets, existing.path); } } } /** * Called on the user pressed the delete key on the asset. * @param item defines the item being deleted. */ public onDeleteAsset(item: IAssetComponentItem): void { super.onDeleteAsset(item); this._handleRemoveMesh(item); } /** * Returns the content of the item's tooltip on the pointer is over the given item. * @param item defines the reference to the item having the pointer over. */ protected getItemTooltipContent(item: IAssetComponentItem): JSX.Element { return ( <> <Tag fill={true} intent={Intent.PRIMARY}>{item.id}</Tag> <Divider /> <Tag fill={true} interactive={true} intent={Intent.PRIMARY} onClick={() => shell.showItemInFolder(Tools.NormalizePathForCurrentPlatform(item.key))}>{item.key}</Tag> <Divider /> <img src={item.base64} style={{ width: "256}px", height: "256px", objectFit: "contain", backgroundColor: "#222222", left: "50%", }} ></img> </> ); } /** * Called on the user wants to refresh preview of a mesh. */ private async _refreshMeshPreview(name: string, path: string): Promise<void> { const task = this.editor.addTaskFeedback(50, `Refresing "${name}"`); try { await this.editor.assets.refresh(MeshesAssets, path); this.editor.updateTaskFeedback(task, 100, "Done"); } catch (e) { this.editor.updateTaskFeedback(task, 0, "Failed"); } this.editor.closeTaskFeedback(task, 500); } /** * Called on the user wants to add textures. */ private async _addMeshes(): Promise<void> { const files = await Tools.ShowNativeOpenMultipleFileDialog(); // Meshes can be scenes. Textures, sounds, etc. should be selected as well. return this.editor.assets.addFilesToAssets(files); } /** * Updates the existing meshes in scene with the given mesh's geometry. */ private _updateImportedMeshGeometry(mesh: AbstractMesh, sceneFileName: string, force: boolean): boolean { if (!(mesh instanceof Mesh)) { return false; } // Check mesh already exists const updatedMeshes: Mesh[] = []; this.editor.scene!.meshes.forEach((m) => { if (!(m instanceof Mesh)) { return undefined; } const meshMetadata = Tools.GetMeshMetadata(m); if (!meshMetadata.originalSourceFile?.id || meshMetadata.originalSourceFile.sceneFileName !== sceneFileName) { return; } if (meshMetadata.originalSourceFile.id === mesh.id) { meshMetadata._waitingUpdatedReferences = {}; meshMetadata._waitingUpdatedReferences!.geometry = { geometry: mesh.geometry, skeleton: mesh.skeleton, subMeshes: mesh.subMeshes?.slice() ?? [], }; // Material if (mesh.material) { if (!m.material) { meshMetadata._waitingUpdatedReferences!.material = mesh.material; } else { meshMetadata._waitingUpdatedReferences!.material = mesh.material; } } else if (m.material) { meshMetadata._waitingUpdatedReferences!.material = null; } // Keep updated mesh metadata. updatedMeshes.push(m); } }); if (!updatedMeshes.length) { return false; } if (force) { updatedMeshes.forEach((um) => { const umMetadata = Tools.GetMeshMetadata(um); if (!umMetadata._waitingUpdatedReferences) { return; } umMetadata._waitingUpdatedReferences.geometry!.geometry?.applyToMesh(um); um.skeleton = umMetadata._waitingUpdatedReferences.geometry!.skeleton ?? null; if (umMetadata._waitingUpdatedReferences.geometry!.subMeshes) { um.subMeshes = []; umMetadata._waitingUpdatedReferences.geometry!.subMeshes?.forEach((sm) => { new SubMesh(sm.materialIndex, sm.verticesStart, sm.verticesCount, sm.indexStart, sm.indexCount, um, um, true, true); }); } um.material = umMetadata._waitingUpdatedReferences.material ?? null; delete umMetadata._waitingUpdatedReferences; }); } mesh._geometry = null; mesh.subMeshes = []; mesh.dispose(true, false); return true; } /** * Configures the given material's textures. */ private _configureMaterialTextures(material: Material): void { const textures = material.getActiveTextures(); textures?.forEach((t) => { if (!(t instanceof Texture) && !(t instanceof CubeTexture)) { return; } const path = join("files", basename(t.name)); t.name = path; if (t.url) { t.url = path; } }); } /** * Called on the user wants to remove a mesh from the library. */ private _handleRemoveMesh(item: IAssetComponentItem): void { undoRedo.push({ description: `Removed mesh asset "${item.id}" at path "${item.key}"`, common: () => this.refresh(), redo: () => { const meshIndex = MeshesAssets.Meshes.findIndex((m) => m.path === item.key); if (meshIndex !== -1) { MeshesAssets.Meshes.splice(meshIndex, 1); } const itemIndex = this.items.indexOf(item); if (itemIndex !== -1) { this.items.splice(itemIndex, 1); } }, undo: () => { MeshesAssets.Meshes.push({ name: item.id, path: item.key }); this.items.push(item); }, }); } /** * Configures the given material's textures. */ private async _configureGltfMaterial(material: Material, onTextureDone: (name: string) => void): Promise<void> { const textures = material.getActiveTextures(); for (const texture of textures) { if (texture.metadata?.gltf?.editorDone) { continue; } if (!(texture instanceof Texture) && !(texture instanceof CubeTexture)) { return; } if (texture.isRenderTarget) { return; } const mimeType = texture["_mimeType"]; if (mimeType) { const existingExtension = extname(texture.name); const targetExtension = Tools.GetExtensionFromMimeType(mimeType); if (existingExtension !== targetExtension) { texture.name = join("files", `${basename(texture.name)}${targetExtension}`); } else { texture.name = join("files", basename(texture.name)); } } else { texture.name = join("files", basename(texture.url!)); if (texture.url) { texture.url = texture.name; } } if (texture.url) { texture.url = texture.name; } FilesStore.AddFile(join(Project.DirPath!, texture.name)); } await GLTFTools.TexturesToFiles(join(Project.DirPath!, "files"), textures, onTextureDone); } }
the_stack
* @module Pouchy */ import { toUnderscorePrefix } from './to-underscore-prefix' import adapterFind from 'pouchdb-find' import adapterHttp from 'pouchdb-adapter-http' import adapterReplication from 'pouchdb-replication' import defaults from 'lodash/defaults' import get from 'lodash/get' import isNil from 'lodash/isNil' import path from 'path' import PouchDB from 'pouchdb-core' import unique from 'lodash/uniq' import url, { UrlObject } from 'url' PouchDB.plugin(adapterHttp) .plugin(adapterFind) .plugin(adapterReplication) export type MaybeSavedPouchDoc = { _id?: PouchDB.Core.DocumentId _rev?: PouchDB.Core.RevisionId } export type SavedPouchDoc = { _id: PouchDB.Core.DocumentId _rev: PouchDB.Core.RevisionId } /** * @private */ type FirstArgument<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : any export const couchUrlify = (url: string) => url.replace(/[^/a-z0-9_$()+-]/gi, '') export const POUCHY_API_DOCS_URI = 'https://cdaringe.github.io/pouchy' export type PouchyOptions = { conn?: UrlObject // creates `url` using the awesome and simple [url.format](https://www.npmjs.com/package/url#url-format-urlobj) couchdbSafe?: boolean // default: true. asserts that `name` provided or `url` provided will work with couchdb. tests by asserting str conforms to [couch specs](https://wiki.apache.org/couchdb/HTTP_database_API#Naming_and_Addressing), minus the `/`. This _may complain that some valid urls are invalid_. Please be aware and disable if necessary. name?: string // name of db. recommended for most dbs. calculated from derived url string if `conn` or `url` provided. otherwise, required path?: string // path to store db on filesystem, if using a filesystem adapter. defaults to _PouchDB_'s default of `cwd` if not specified pouchConfig?: PouchDB.Configuration.DatabaseConfiguration // PouchDB constructor input [options](http://pouchdb.com/api.html#create_database). be mindful of pouchy options you set, because they may comingle :) /** * in object form you can try `{ out/in/sync: ... }` where ... refers to the * [official PouchDB replication options](http://pouchdb.com/api.html#replication). in string form, simply provide * 'out/in/sync'. please note that the string shorthand applies default * heartbeat/retry options. */ replicate?: | string | { out?: PouchDB.Replication.ReplicateOptions in?: PouchDB.Replication.ReplicateOptions sync?: PouchDB.Replication.ReplicateOptions } replicateLive?: boolean // default: true. activates only if `replicate` is set url?: string // url to remote CouchDB. user may use the `conn` option instead as well } export class Pouchy<Content = {}> { static PouchDB = PouchDB static plugin = PouchDB.plugin static defaults = PouchDB.defaults static debug = PouchDB.debug // tap into your instance's replication `changes()` so you may listen to events. // calling `.destroy` will scrap this emitter. emitter only present when // `replicate` options intially provided public syncEmitter: | PouchDB.Replication.Replication<Content> | PouchDB.Replication.Sync<Content> | null = null public db: PouchDB.Database<Content> // internal PouchDB instance public hasLocalDb: boolean public isEnforcingCouchDbSafe: boolean public url: string | null public path: string | null private _replicationOpts: PouchDB.Replication.ReplicateOptions | null = null constructor (opts: PouchyOptions) { this._validatePouchyOpts(opts) this.isEnforcingCouchDbSafe = isNil(opts.couchdbSafe) ? true : opts.couchdbSafe this.url = this._getUrlFromOpts(opts) this.hasLocalDb = !!opts.name /* istanbul ignore next */ if (!this.url && !this.hasLocalDb) { throw new Error('remote database requires url') } this.name = this.hasLocalDb ? this._setDbNameFromOpts(opts) : this._setDbNameFromUri(this.url!) if (this.isEnforcingCouchDbSafe) this._validateDbName() this.path = this.hasLocalDb ? path.resolve(opts.path || '', this.name) : null this.db = new PouchDB<Content>( opts.name ? this.path! : this.url!, opts.pouchConfig ) if (opts.replicate) this._handleReplication(opts.replicate) } /** * @private */ _validatePouchyOpts (opts: PouchyOptions) { if (!opts || (!opts.name && (!opts.url && !opts.conn))) { throw new ReferenceError( [ 'missing pouchy database paramters. please see: ' + POUCHY_API_DOCS_URI + '\n', '\tif you are creating a local database (browser or node), provide a `name` key.\n', '\tif you are just using pouchy to access a remote database, provide a `url` or `conn` key\n', '\tif you are creating a database to replicate with a remote database, provide a', '`url` or `conn` key, plus a replicate key.\n' ].join('') ) } /* istanbul ignore next */ if (opts.url && opts.conn) { throw new ReferenceError('provide only a `url` or `conn` option') } /* istanbul ignore next */ if (!this) { throw new ReferenceError('no `this` context. did you forget `new`?') } } /** * @private */ _handleReplication (opts: PouchyOptions['replicate']) { var replOpts: PouchDB.Replication.ReplicateOptions var mode: string /* istanbul ignore next */ if (!this.url) { throw new ReferenceError('url or conn object required to replicate') } /* istanbul ignore else */ if (typeof opts === 'string') { mode = opts replOpts = { live: true, retry: true } } else if (opts) { mode = Object.keys(opts)[0] /* istanbul ignore else */ if (mode in opts) { replOpts = (opts as any)[mode] } else { throw new Error(`mode "${mode}" is not a valid replication option`) } } else { throw new Error('invalid replication options') } this._replicationOpts = replOpts switch (mode) { /* istanbul ignore next */ case 'out': this.syncEmitter = this.db.replicate.to(this.url, replOpts) break /* istanbul ignore next */ case 'in': this.syncEmitter = this.db.replicate.from(this.url, replOpts) break case 'sync': this.syncEmitter = this.db.sync(this.url, replOpts) break default: /* istanbul ignore next */ throw new Error( [ "in/out replication direction must be specified, got '", mode + "'" ].join(' ') ) } } /** * @private */ _getUrlFromOpts (opts: PouchyOptions) { if (!isNil(opts.url)) return opts.url if (!isNil(opts.conn)) return url.format(opts.conn) return null } /** * @private */ _setDbNameFromUri (uri: string) { const pathname = url.parse(uri).pathname // eslint-disable-line /* istanbul ignore next */ if (!pathname && !this.name) { throw new Error( [ 'unable to infer database name from uri. try adding a pathname', 'to the uri (e.g. host.org/my-db-name) or pass a `name` option' ].join(' ') ) } var pathParts = (pathname || '').split('/') this.name = this.name || pathParts[pathParts.length - 1] return this.name } /** * @private */ _setDbNameFromOpts (opts: PouchyOptions) { /* istanbul ignore next */ if (!opts.name) { throw new Error('local pouchy database requires a `name` field') } return opts.name } /** * @private */ _validateDbName () { var couchDbSafeName = couchUrlify(this.name.toLowerCase()) if (this.name === couchDbSafeName) return throw new Error( [ 'database name may not be couchdb safe.', '\tunsafe name: ' + this.name, '\tsafe name: ' + couchDbSafeName ].join('\n') ) } /** * add a document to the db. * @see save * @example * // with _id * const doc = await p.add({ _id: 'my-sauce', bbq: 'sauce' }) * console.log(doc._id, doc._rev, doc.bbq); // 'my-sauce', '1-a76...46c', 'sauce' * * // no _id * const doc = await p.add({ peanut: 'butter' }) * console.log(doc._id, doc._rev, doc.peanut); // '66188...00BF885E', '1-0d74...7ac', 'butter' */ add (doc: Content & MaybeSavedPouchDoc): Promise<Content & SavedPouchDoc> { return this.save.apply(this, arguments as any) } /** * get all documents from db * @example * const docs = await p.all() * console.log(`total # of docs: ${docs.length}!`)) * * @example * const docs = await p.all({ includeDesignDocs: true }) */ async all ( allOpts?: FirstArgument<PouchDB.Database<Content>['allDocs']> ): Promise<(Content & SavedPouchDoc)[]> { const opts = defaults(allOpts || {}, { include_docs: true }) const docs = await this.db.allDocs(opts) return docs.rows.reduce(function simplifyAllDocSet (r, v) { var doc: any = opts.include_docs ? v.doc : v // rework doc format to always have id ==> _id if (!opts.include_docs) { doc._id = doc.id doc._rev = doc.value.rev delete doc.id delete doc.value delete doc.key } ;(r as any).push(doc) return r }, []) } /** * The native bulkGet PouchDB API is not very user friendly. * In fact, it's down right wacky! * This method patches PouchDB's `bulkGet` and assumes that _all_ of your * requested docs exist. If they do not, it will error via the usual error * control flows. * * @example * // A good example of what you can expect is actually right out of the tests! * let dummyDocs = [ * { _id: 'a', data: 'a' }, * { _id: 'b', data: 'b' } * ] * Promise.resolve() * .then(() => p.save(dummyDocs[0])) // add our first doc to the db * .then((doc) => (dummyDocs[0] = doc)) // update our closure doc it knows the _rev * .then(() => p.save(dummyDocs[1])) * .then((doc) => (dummyDocs[1] = doc)) * .then(() => { * // prepare getMany query (set of { _id, _rev}'s are required) * const toFetch = dummyDocs.map(dummy => ({ * _id: dummy._id, * _rev: dummy._rev * // or you can provide .id, .rev * })) * p.getMany(toFetch) * .then((docs) => { * t.deepEqual(docs, dummyDocs, 'getMany returns sane results') * t.end() * }) * }) * @param {object|array} opts array of {_id, _rev}s, or { docs: [ ... } } where * ... is an array of {_id, _rev}s * @param {function} [cb] */ async getMany ( docMetas: { _id: string; _rev?: string | undefined }[] ): Promise<(Content & SavedPouchDoc)[]> { /* istanbul ignore else */ if (!docMetas || !Array.isArray(docMetas)) { throw new Error('getMany: missing doc metadatas') } const opts = { docs: docMetas.map(function remapIdRev (lastDoc: any) { const doc = { ...lastDoc } // we need to map back to id and rev here /* istanbul ignore else */ if (doc._id) doc.id = doc._id /* istanbul ignore else */ if (doc._rev) doc.rev = doc._rev delete doc._rev delete doc._id return doc }) } if (!opts.docs.length) return Promise.resolve([]) const r = await this.db.bulkGet(opts) return r.results.map(function tidyBulkGetDocs (docGroup) { var doc = get(docGroup, 'docs[0].ok') if (!doc) { throw new ReferenceError('doc ' + docGroup.id + 'not found') } return doc }) } /** * easy way to create a db index. * @see createIndicies * @example * await p.upsertIndex('myIndex') */ upsertIndex (indexName: string) { return this.createIndicies.apply(this, arguments as any) } /** * allow single or bulk creation of indicies. also, doesn't flip out if you've * already set an index. * @example * const indicies = await p.createIndicies('test') * console.dir(indicies) * // ==> * [{ * id: "_design/idx-28933dfe7bc072c94e2646126133dc0d" * name: "idx-28933dfe7bc072c94e2646126133dc0d" * result: "created" * }] */ createIndicies (indicies: string | string[]) { indicies = Array.isArray(indicies) ? indicies : [indicies] return ( this.db .createIndex({ index: { fields: unique(indicies) } }) /* istanbul ignore next */ .catch(function handleFailCreateIndicies (err) { /* istanbul ignore next */ if (err.status !== 409) throw err }) ) } /** * @see deleteAll * @returns {Promise} */ clear () { return this.deleteAll.apply(this, arguments as any) } /** * delete a document. * @example * // same as pouch.remove * const deleted = await p.delete(doc) * console.dir(deleted) * // ==> * { * id: "test-doc-1" * ok: true * rev: "2-5cf6a4725ed4b9398d609fc8d7af2553" * } */ delete (doc: PouchDB.Core.RemoveDocument, opts?: PouchDB.Core.Options) { return this.db.remove(doc, opts) } /** * clears the db of documents. under the hood, `_deleted` flags are added to docs */ async deleteAll () { var deleteSingleDoc = (doc: any) => this.delete(doc) const docs = await this.all() return Promise.all(docs.map(deleteSingleDoc)) } /** * Destroys the database. Proxies to pouchdb.destroy after completing * some internal cleanup first */ async destroy () { /* istanbul ignore next */ if (this.syncEmitter && !(<any>this.syncEmitter).canceled) { let isSyncCancelledP = Promise.resolve() if (this._replicationOpts && this._replicationOpts.live) { // early bind the `complete` event listener. careful not to bind it // inside the .then, otherwise binding happens at the end of the event // loop, which is too late! `.cancel` is a sync call! isSyncCancelledP = new Promise((resolve, reject) => { if (!this.syncEmitter) { return reject(new Error('syncEmitter not found')) } this.syncEmitter.on('complete' as any, () => { resolve() }) }) } this.syncEmitter.cancel() // will trigger a `complete` event await isSyncCancelledP } return this.db.destroy() } /** * Similar to standard pouchdb.find, but returns simple set of results */ async findMany ( opts: FirstArgument<PouchDB.Find.FindRequest<Content>> ): Promise<(Content & SavedPouchDoc)[]> { const rslt = await this.db.find(opts) return rslt.docs } /** * update a document, and get your sensibly updated doc in return. * * @example * const doc = await p.update({ _id: 'my-doc', _rev: '1-abc123' }) * console.log(doc) * // ==> * { * _id: 'my-doc', * _rev: '2-abc234' * } * @param {object} doc * @param {function} [cb] * @returns {Promise} */ async update ( doc: FirstArgument<PouchDB.Database<Content>['put']> ): Promise<Content & SavedPouchDoc> { // http://pouchdb.com/api.html#create_document // db.put(doc, [docId], [docRev], [options], [callback]) const meta = await this.db.put(doc) doc._id = meta.id doc._rev = meta.rev return doc as any } /** * Adds or updates a document. If `_id` is set, a `put` is performed (basic add operation). If no `_id` present, a `post` is performed, in which the doc is added, and large-random-string is assigned as `_id`. * @example * const doc = await p.save({ beep: 'bop' }) * console.log(doc) * // ==> * { * _id: 'AFEALJW-234LKJASDF-2A;LKFJDA', * _rev: '1-asdblkue242kjsa0f', * beep: 'bop' * } */ async save ( doc: Content & MaybeSavedPouchDoc ): Promise<Content & SavedPouchDoc> { // http://pouchdb.com/api.html#create_document // db.post(doc, [docId], [docRev], [options], [callback]) /* istanbul ignore next */ var method = Object.prototype.hasOwnProperty.call(doc, '_id') && (doc._id || (doc as any)._id === 0) ? 'put' : 'post' const meta = method === 'put' ? await this.db.put(doc as any) : await this.db.post(doc as any) delete (meta as any).status doc._id = meta.id doc._rev = meta.rev return doc as any } /** * START POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT * START POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT * START POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT */ /** * database name */ name: string /* istanbul ignore next */ /** Fetch all documents matching the given options. */ allDocs<Model> ( options?: | PouchDB.Core.AllDocsWithKeyOptions | PouchDB.Core.AllDocsWithKeysOptions | PouchDB.Core.AllDocsWithinRangeOptions | PouchDB.Core.AllDocsOptions ) { return {} as Promise<PouchDB.Core.AllDocsResponse<Content & Model>> } /* istanbul ignore next */ /** * Create, update or delete multiple documents. The docs argument is an array of documents. * If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you. * To update a document, you must include both an _id parameter and a _rev parameter, * which should match the ID and revision of the document on which to base your updates. * Finally, to delete a document, include a _deleted parameter with the value true. */ bulkDocs<Model> ( docs: Array<PouchDB.Core.PutDocument<Content & Model>>, options?: PouchDB.Core.BulkDocsOptions ) { return {} as Promise<Array<SavedPouchDoc>> } /* istanbul ignore next */ /** Compact the database */ compact (options?: PouchDB.Core.CompactOptions) { return {} as Promise<PouchDB.Core.Response> } /* istanbul ignore next */ /** Fetch a document */ get<Model> ( docId: PouchDB.Core.DocumentId, options?: PouchDB.Core.GetOptions ) { return {} as Promise< PouchDB.Core.Document<Content & Model> & PouchDB.Core.GetMeta > } /* istanbul ignore next */ /** * Create a new document without providing an id. * * You should prefer put() to post(), because when you post(), you are * missing an opportunity to use allDocs() to sort documents by _id * (because your _ids are random). * * @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips} */ post<Model> ( doc: PouchDB.Core.PostDocument<Content & Model>, options?: PouchDB.Core.Options ) { return {} as Promise<PouchDB.Core.Response> } /* istanbul ignore next */ /** * Create a new document or update an existing document. * * If the document already exists, you must specify its revision _rev, * otherwise a conflict will occur. * There are some restrictions on valid property names of the documents. * If you try to store non-JSON data (for instance Date objects) you may * see inconsistent results. */ put<Model> ( doc: PouchDB.Core.PutDocument<Content & Model>, options?: PouchDB.Core.PutOptions ) { return {} as Promise<PouchDB.Core.Response> } /* istanbul ignore next */ /** Remove a doc from the database */ remove (doc: PouchDB.Core.RemoveDocument, options?: PouchDB.Core.Options) { return {} as Promise<PouchDB.Core.Response> } /* istanbul ignore next */ /** Get database information */ info () { return {} as Promise<PouchDB.Core.DatabaseInfo> } /* istanbul ignore next */ /** * A list of changes made to documents in the database, in the order they were made. * It returns an object with the method cancel(), which you call if you don’t want to listen to new changes anymore. * * It is an event emitter and will emit a 'change' event on each document change, * a 'complete' event when all the changes have been processed, and an 'error' event when an error occurs. * Calling cancel() will unsubscribe all event listeners automatically. */ changes<Model> (options?: PouchDB.Core.ChangesOptions) { return {} as PouchDB.Core.Changes<Content & Model> } /* istanbul ignore next */ /** Close the database */ close () { return {} as Promise<void> } /* istanbul ignore next */ /** * Attaches a binary object to a document. * This method will update an existing document to add the attachment, so it requires a rev if the document already exists. * If the document doesn’t already exist, then this method will create an empty document containing the attachment. */ putAttachment ( docId: PouchDB.Core.DocumentId, attachmentId: PouchDB.Core.AttachmentId, attachment: PouchDB.Core.AttachmentData, type: string ) { return {} as Promise<PouchDB.Core.Response> } /* istanbul ignore next */ /** Get attachment data */ getAttachment ( docId: PouchDB.Core.DocumentId, attachmentId: PouchDB.Core.AttachmentId, options?: { rev?: PouchDB.Core.RevisionId } ) { return {} as Promise<Blob | Buffer> } /* istanbul ignore next */ /** Delete an attachment from a doc. You must supply the rev of the existing doc. */ removeAttachment ( docId: PouchDB.Core.DocumentId, attachmentId: PouchDB.Core.AttachmentId, rev: PouchDB.Core.RevisionId ) { return {} as Promise<PouchDB.Core.RemoveAttachmentResponse> } /* istanbul ignore next */ /** Given a set of document/revision IDs, returns the document bodies (and, optionally, attachment data) for each ID/revision pair specified. */ bulkGet<Model> (options: PouchDB.Core.BulkGetOptions) { return {} as Promise<PouchDB.Core.BulkGetResponse<Content & Model>> } /* istanbul ignore next */ /** Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database */ revsDiff (diff: PouchDB.Core.RevisionDiffOptions) { return {} as Promise<PouchDB.Core.RevisionDiffResponse> } /** * END POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT * END POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT * END POUCHDB IMPLEMENTATIONS FOR MIXIN SUPPORT */ } /** * @private * call Pouchy or native PouchDB methods and transform all repsonses to * unify ids & revs */ /* istanbul ignore next */ const nonTransformingPrototype: any = {} /* istanbul ignore next */ for (const key of Object.getOwnPropertyNames(Pouchy.prototype)) { const value = (Pouchy.prototype as any)[key] if ( typeof value !== 'function' || (value && value.name === 'Pouchy') || (value && value.name && value.name[0] === '_') ) { continue } nonTransformingPrototype[key] = value ;(Pouchy.prototype as any)[key] = async function transformResponse ( ...args: any[] ) { let res = nonTransformingPrototype[key].call(this, ...args) if (res && res.then && res.catch) res = await res if (typeof args[args.length - 1] === 'function') { throw new Error( [ 'the pouchy-pouchdb callback interface has been removed.', 'please use the promise interface.' ].join(' ') ) } return toUnderscorePrefix(res) } } export const pouchProxyMethods = [ 'bulkDocs', 'bulkGet', 'changes', 'close', 'compact', 'get', 'getAttachment', 'info', 'post', 'put', 'putAttachment', 'remove', 'removeAttachment', 'revsDiff' ] for (const key of pouchProxyMethods) { const value = PouchDB.prototype[key] /* istanbul ignore next */ if (!value) throw new Error(`pouchdb method "${key}" not found`) /* istanbul ignore next */ if (typeof value !== 'function') continue ;(Pouchy.prototype as any)[key] = async function proxyAndTransform ( ...args: any[] ) { const pouchMethod: Function = PouchDB.prototype[key] let res = pouchMethod.call(this.db, ...args) if (res && res.then && res.catch) res = await res /* istanbul ignore next */ if (typeof args[args.length - 1] === 'function') { throw new Error( [ 'the pouchy-pouchdb callback interface has been removed.', 'please use the promise interface.' ].join(' ') ) } return toUnderscorePrefix(res) } } export default Pouchy
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { NodeConstraints } from '../../../src/diagram/enum/enum'; import { MarginModel } from '../../../src/diagram/core/appearance-model'; import { NodeModel, BpmnSubProcessModel } from '../../../src/diagram/objects/node-model'; import { ShadowModel, RadialGradientModel, StopModel } from '../../../src/diagram/core/appearance-model'; import { Canvas } from '../../../src/diagram/core/containers/canvas'; import { BpmnDiagrams } from '../../../src/diagram/objects/bpmn'; import { BpmnShape } from "../../../src/index"; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; Diagram.Inject(BpmnDiagrams); /** * flow shapes */ describe('Diagram Control', () => { describe('BPMN Subprocess', () => { let diagram: Diagram; let shadow: ShadowModel = { distance: 10, opacity: 0.5 }; let stops: StopModel[] = [{ color: 'white', offset: 0 }, { color: 'red', offset: 50 }]; let gradient: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stops, type: 'Radial' }; let ele: HTMLElement; let sourceMargin: MarginModel = { left: 5, right: 5, bottom: 5, top: 5 }; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, style: { strokeDashArray: '2 2', opacity: 0.6 }, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { adhoc: true } }, }, }; let shadow1: ShadowModel = { angle: 135 }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 100, style: { strokeWidth: 5, }, shadow: shadow1, constraints: NodeConstraints.Default | NodeConstraints.Shadow, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { adhoc: false, collapsed: true } }, }, }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 100, shadow: shadow, constraints: NodeConstraints.Default | NodeConstraints.Shadow, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { adhoc: false, boundary: 'Default', collapsed: true } }, }, }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 700, offsetY: 100, style: { gradient: gradient, fill: 'red' }, shadow: shadow, constraints: NodeConstraints.Default & ~NodeConstraints.Shadow, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { adhoc: false, boundary: 'Event', collapsed: true } }, }, }; let node4: NodeModel = { id: 'node4', width: 100, height: 100, offsetX: 900, offsetY: 100, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { adhoc: false, boundary: 'Call', collapsed: true } }, }, }; let node5: NodeModel = { id: 'node5', width: 100, height: 100, offsetX: 100, offsetY: 300, style: { fill: 'red', strokeColor: 'blue', strokeWidth: 5 }, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { collapsed: true, compensation: true } }, } }; diagram = new Diagram({ width: '1500px', height: '1500px', nodes: [node, node1, node2, node3, node4, node5] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - adhoc true', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 100) && //collapsed node (wrapper.children[1].visible === true) && //loop node (wrapper.children[2].visible === false) && (wrapper.children[3].actualSize.width === 12 && wrapper.children[3].actualSize.height === 8 && wrapper.children[3].offsetX === 110 && wrapper.children[3].offsetY === 141) && //compensation node (wrapper.children[4].visible === false) ).toBe(true); done(); }); it('Checking diagram instance creation - adhoc false and collapsed - true', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 100) && //collapsed node (wrapper.children[1].visible === true && wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 302 || wrapper.children[1].offsetX === 300) && wrapper.children[1].offsetY === 139 ) && //loop node (wrapper.children[2].visible === false) && //adhoc node (wrapper.children[3].visible === false) && //compensation node (wrapper.children[4].visible === false) ).toBe(true); done(); }); it('Checking diagram instance creation - adhoc false, boundary-default and collapsed - true', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[2] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 100) && //collapsed node (wrapper.children[1].visible === true && wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 502 || wrapper.children[1].offsetX === 500) && wrapper.children[1].offsetY === 139 ) && //loop node (wrapper.children[2].visible === false) && //adhoc node (wrapper.children[3].visible === false) && //compensation node (wrapper.children[4].visible === false) ).toBe(true); done(); }); it('Checking diagram instance creation - adhoc false, boundary-event and collapsed - true', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[3] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 700 && wrapper.children[0].offsetY === 100 && wrapper.children[0].style.strokeDashArray === '2 2') && //second node (wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 702 || wrapper.children[1].offsetX === 700) && wrapper.children[1].offsetY === 139) && //loop node (wrapper.children[2].visible === false) && //adhoc node (wrapper.children[3].visible === false) && //compensation node (wrapper.children[4].visible === false) ).toBe(true); done(); }); it('Checking diagram instance creation - adhoc false, boundary-call and collapsed - true', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[4] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 900 && wrapper.children[0].offsetY === 100 && wrapper.children[0].style.strokeDashArray === '1 0' && wrapper.children[0].style.strokeWidth === 4 ) && //second node (wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 902 || wrapper.children[1].offsetX === 900) && wrapper.children[1].offsetY === 139) && //loop node (wrapper.children[2].visible === false) && //adhoc node (wrapper.children[3].visible === false) && //compensation node (wrapper.children[4].visible === false) ).toBe(true); done(); }); it('Checking subProcess with collapsed - true, compensation - true ', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[5] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 300) && //first node (wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 92 || wrapper.children[1].offsetX === 100) && wrapper.children[1].offsetY === 339) && //loop node (wrapper.children[2].visible === false) && //adhoc node (wrapper.children[3].visible === false) && //compensation node (wrapper.children[4].actualSize.width === 12 && wrapper.children[4].actualSize.height === 12 && wrapper.children[4].offsetX === 110 && wrapper.children[4].offsetY === 339) ).toBe(true); done(); }); }); describe('BPMN Sub Events', () => { let diagram: Diagram; let ele: HTMLElement; let sourceMargin: MarginModel = { left: 5, right: 5, bottom: 5, top: 5 }; let subeventMargin: MarginModel = { left: 10, top: 10 }; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node1: NodeModel = { id: 'node1', width: 190, height: 190, offsetX: 300, offsetY: 200, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 0, y: 0 }, margin: { left: 10, top: 10 }, horizontalAlignment: 'Left', verticalAlignment: 'Top', annotations: [{ id: 'label3', margin: { bottom: 10 }, horizontalAlignment: 'Center', verticalAlignment: 'Top', content: 'Event', offset: { x: 0.5, y: 1 }, style: { color: 'black', fontFamily: 'Fantasy', fontSize: 8 } }], ports: [{ shape: 'Square', id: 'port4', width: 6, height: 6, offset: { x: 0.5, y: 1 }, style: { strokeColor: 'black', strokeWidth: 2, opacity: 1 } }], event: 'Intermediate', trigger: 'Error' }] } } } }; let node2: NodeModel = { id: 'node2', width: 190, height: 190, offsetX: 500, offsetY: 200, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 1, y: 0.5 }, annotations: [{ id: 'label3', margin: { bottom: 10 }, horizontalAlignment: 'Center', verticalAlignment: 'Top', content: 'Event', offset: { x: 0.5, y: 1 }, style: { color: 'black', fontFamily: 'Fantasy', fontSize: 8, strokeColor: 'white' } }], ports: [{ shape: 'Square', id: 'port4', width: 6, height: 6, offset: { x: 0.5, y: 1 }, style: { fill: 'lightgrey', strokeColor: 'black', strokeWidth: 2, opacity: 1 } }], event: 'Intermediate', trigger: 'Error' }, { height: 20, width: 20, offset: { x: 0, y: 0 }, annotations: [{ id: 'label3', margin: sourceMargin, horizontalAlignment: 'Center', verticalAlignment: 'Center', content: 'Text', offset: { x: 0, y: 0 }, style: { color: 'black', fontFamily: 'Fantasy', fontSize: 4, strokeColor: 'white', } }], ports: [{ shape: 'Square', id: 'port4', margin: sourceMargin, horizontalAlignment: 'Right', verticalAlignment: 'Bottom', width: 6, height: 6, offset: { x: 1, y: 1 }, style: { fill: 'red', strokeColor: 'black', strokeWidth: 2, opacity: 1 } }], event: 'Intermediate', trigger: 'Error' }] } } } }; diagram = new Diagram({ width: '1500px', height: '500px', nodes: [node1, node2] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking single sub-event with ports-annotations', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 190 && wrapper.children[0].actualSize.height === 190 && wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 200) && //second node (wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (Math.round(wrapper.children[1].offsetX) === 284 || wrapper.children[1].offsetX === 300) && Math.round(wrapper.children[1].offsetY) === 284) && //third node (wrapper.children[2].actualSize.width === 20 && wrapper.children[2].actualSize.height === 20 && wrapper.children[2].offsetX === 225 && wrapper.children[2].offsetY === 125) && //fourth node (wrapper.children[3].actualSize.width === 12 && wrapper.children[3].actualSize.height === 12 && (wrapper.children[1].offsetX === 284 || wrapper.children[1].offsetX === 300) && wrapper.children[3].offsetY === 284) && //fith node (wrapper.children[5].actualSize.width === 12 && wrapper.children[5].actualSize.height === 12 && wrapper.children[5].offsetX === 318 && wrapper.children[5].offsetY === 284) ).toBe(true); done(); }); it('Checking mulitple sub events', (done: Function) => { let wrapper: Canvas = ((diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas).children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 190 && wrapper.children[0].actualSize.height === 190 && wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 200) && // second node (wrapper.children[1].actualSize.width === 12 && wrapper.children[1].actualSize.height === 12 && (wrapper.children[1].offsetX === 484 || wrapper.children[1].offsetX === 500) && wrapper.children[1].offsetY === 284) && // third node (wrapper.children[2].actualSize.width === 20 && wrapper.children[2].actualSize.height === 20 && wrapper.children[2].offsetX === 595 && wrapper.children[2].offsetY === 200) && // fourth node (wrapper.children[3].actualSize.width === 20 && wrapper.children[3].actualSize.height === 20 && wrapper.children[3].offsetX === 405 && wrapper.children[3].offsetY === 105) && // fith node (wrapper.children[6].actualSize.width === 12 && wrapper.children[6].actualSize.height === 12 && wrapper.children[6].offsetX === 518 && wrapper.children[6].offsetY === 284) ).toBe(true); done(); }); }); describe('BPMN Sub Events rotate handle', () => { let diagram: Diagram; let ele: HTMLElement; let sourceMargin: MarginModel = { left: 5, right: 5, bottom: 5, top: 5 }; let subeventMargin: MarginModel = { left: 10, top: 10 }; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let nodea: NodeModel = { id: 'nodea', maxHeight: 600, maxWidth: 600, minWidth: 300, minHeight: 300, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop, offsetX: 200, offsetY: 200, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { collapsed: false, type: 'Transaction', } as BpmnSubProcessModel }, }, }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [nodea] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking bpmn subprocess rotate handle', (done: Function) => { diagram.select([diagram.nodes[0]]); let rotateelem: HTMLCollection = document.getElementsByClassName('.e-diagram-rotate-handle'); expect(rotateelem && rotateelem.length === 0) done(); }); }); describe('BPMN transaction with its icon', () => { let diagram: Diagram; let ele: HTMLElement; let sourceMargin: MarginModel = { left: 5, right: 5, bottom: 5, top: 5 }; let subeventMargin: MarginModel = { left: 10, top: 10 }; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let nodea: NodeModel = { id: 'nodea', maxHeight: 600, maxWidth: 600, minWidth: 300, minHeight: 300, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop, offsetX: 200, offsetY: 200, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Transaction', collapsed: false } as BpmnSubProcessModel }, }, }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [nodea] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('update icon visibility', (done: Function) => { diagram.select([diagram.nodes[0]]); (diagram.selectedItems.nodes[0].shape as BpmnShape).activity.subProcess.collapsed = true; (diagram.selectedItems.nodes[0].shape as BpmnShape).activity.subProcess.compensation = true; (diagram.selectedItems.nodes[0].shape as BpmnShape).activity.subProcess.loop = 'Standard'; (diagram.selectedItems.nodes[0].shape as BpmnShape).activity.subProcess.adhoc = true; diagram.dataBind(); let task = (diagram.selectedItems.nodes[0].wrapper.children[0] as Canvas).children[0]; expect((task as Canvas).children[4].visible).toBe(true); expect((task as Canvas).children[5].visible).toBe(true); expect((task as Canvas).children[6].visible).toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); describe('BPMN transaction with its icon', () => { let diagram: Diagram; let ele: HTMLElement; let sourceMargin: MarginModel = { left: 5, right: 5, bottom: 5, top: 5 }; let subeventMargin: MarginModel = { left: 10, top: 10 }; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 100, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'Task', task: { type: 'Service' } } }, }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 100, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'Task', task: { type: 'BusinessRule' } }, }, }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node1, node2] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Update BPMN task Shape-Service', (done: Function) => { let node: NodeModel = diagram.nodes[1]; node.shape = { type: 'Bpmn', shape: 'Activity', activity: { activity: 'Task', task: { type: 'Service', }, }, }; diagram.dataBind(); let pathElement: HTMLElement = document.getElementById('node2_1_tasktType'); expect(pathElement.getAttribute('transform') === 'rotate(0,465.5,65.5)translate(455.5,55.5)').toBe(true); done(); }); it('Update BPMN task Shape-Bussiness', (done: Function) => { let node: NodeModel = diagram.nodes[0]; node.shape = { type: 'Bpmn', shape: 'Activity', activity: { activity: 'Task', task: { type: 'BusinessRule', }, }, }; diagram.dataBind(); let pathElement: HTMLElement = document.getElementById('node1_1_taskTypeService'); expect(pathElement === null).toBe(true); done(); }); }); });
the_stack
import basem = require('./ClientApiBases'); import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces'); import WorkItemTrackingProcessDefinitionsInterfaces = require("./interfaces/WorkItemTrackingProcessDefinitionsInterfaces"); export interface IWorkItemTrackingProcessDefinitionsApi extends basem.ClientApiBase { createBehavior(behavior: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; deleteBehavior(processId: string, behaviorId: string): Promise<void>; getBehavior(processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; getBehaviors(processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>; replaceBehavior(behaviorData: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel, processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; addControlToGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; editControl(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; removeControlFromGroup(processId: string, witRefName: string, groupId: string, controlId: string): Promise<void>; setControlInGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string, removeFromGroupId?: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; createField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; updateField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; addGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; editGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; removeGroup(processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<void>; setGroupInPage(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromPageId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; setGroupInSection(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; getFormLayout(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>; getListsMetadata(): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>; createList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; deleteList(listId: string): Promise<void>; getList(listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; updateList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel, listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; addPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; editPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; removePage(processId: string, witRefName: string, pageId: string): Promise<void>; createStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; deleteStateDefinition(processId: string, witRefName: string, stateId: string): Promise<void>; getStateDefinition(processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; getStateDefinitions(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>; hideStateDefinition(hideStateModel: WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; updateStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; addBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; getBehaviorForWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; getBehaviorsForWorkItemType(processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>; removeBehaviorFromWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<void>; updateBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; createWorkItemType(workItemType: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; deleteWorkItemType(processId: string, witRefName: string): Promise<void>; getWorkItemType(processId: string, witRefName: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; getWorkItemTypes(processId: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>; updateWorkItemType(workItemTypeUpdate: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; addFieldToWorkItemType(field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; getWorkItemTypeField(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; getWorkItemTypeFields(processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>; removeFieldFromWorkItemType(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<void>; } export declare class WorkItemTrackingProcessDefinitionsApi extends basem.ClientApiBase implements IWorkItemTrackingProcessDefinitionsApi { constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions); static readonly RESOURCE_AREA_ID: string; /** * Creates a single behavior in the given process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel} behavior * @param {string} processId - The ID of the process */ createBehavior(behavior: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; /** * Removes a behavior in the process. * * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ deleteBehavior(processId: string, behaviorId: string): Promise<void>; /** * Returns a single behavior in the process. * * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ getBehavior(processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; /** * Returns a list of all behaviors in the process. * * @param {string} processId - The ID of the process */ getBehaviors(processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>; /** * Replaces a behavior in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel} behaviorData * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ replaceBehavior(behaviorData: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel, processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; /** * Creates a control in a group * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group to add the control to */ addControlToGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; /** * Updates a control on the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The updated control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group * @param {string} controlId - The ID of the control */ editControl(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; /** * Removes a control from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group * @param {string} controlId - The ID of the control to remove */ removeControlFromGroup(processId: string, witRefName: string, groupId: string, controlId: string): Promise<void>; /** * Moves a control to a new group * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group to move the control to * @param {string} controlId - The id of the control * @param {string} removeFromGroupId - The group to remove the control from */ setControlInGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string, removeFromGroupId?: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; /** * Creates a single field in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.FieldModel} field * @param {string} processId - The ID of the process */ createField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; /** * Updates a given field in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate} field * @param {string} processId - The ID of the process */ updateField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; /** * Adds a group to the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page to add the group to * @param {string} sectionId - The ID of the section to add the group to */ addGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; /** * Updates a group in the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group */ editGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; /** * Removes a group from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section to the group is in * @param {string} groupId - The ID of the group */ removeGroup(processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<void>; /** * Moves a group to a different page and section * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group * @param {string} removeFromPageId - ID of the page to remove the group from * @param {string} removeFromSectionId - ID of the section to remove the group from */ setGroupInPage(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromPageId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; /** * Moves a group to a different section * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group * @param {string} removeFromSectionId - ID of the section to remove the group from */ setGroupInSection(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; /** * Gets the form layout * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ getFormLayout(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>; /** * Returns meta data of the picklist. * */ getListsMetadata(): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>; /** * Creates a picklist. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.PickListModel} picklist */ createList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; /** * Removes a picklist. * * @param {string} listId - The ID of the list */ deleteList(listId: string): Promise<void>; /** * Returns a picklist. * * @param {string} listId - The ID of the list */ getList(listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; /** * Updates a list. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.PickListModel} picklist * @param {string} listId - The ID of the list */ updateList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel, listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; /** * Adds a page to the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Page} page - The page * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ addPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; /** * Updates a page on the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Page} page - The page * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ editPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; /** * Removes a page from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page */ removePage(processId: string, witRefName: string, pageId: string): Promise<void>; /** * Creates a state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel} stateModel * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ createStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; /** * Removes a state definition in the work item type of the process. * * @param {string} processId - ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - ID of the state */ deleteStateDefinition(processId: string, witRefName: string, stateId: string): Promise<void>; /** * Returns a state definition in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - The ID of the state */ getStateDefinition(processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; /** * Returns a list of all state definitions in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ getStateDefinitions(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>; /** * Hides a state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel} hideStateModel * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - The ID of the state */ hideStateDefinition(hideStateModel: WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; /** * Updates a given state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel} stateModel * @param {string} processId - ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - ID of the state */ updateStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; /** * Adds a behavior to the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior} behavior * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ addBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; /** * Returns a behavior for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior * @param {string} behaviorRefName - The reference name of the behavior */ getBehaviorForWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; /** * Returns a list of all behaviors for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ getBehaviorsForWorkItemType(processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>; /** * Removes a behavior for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior * @param {string} behaviorRefName - The reference name of the behavior */ removeBehaviorFromWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<void>; /** * Updates default work item type for the behavior of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior} behavior * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ updateBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; /** * Creates a work item type in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel} workItemType * @param {string} processId - The ID of the process */ createWorkItemType(workItemType: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; /** * Removes a work itewm type in the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ deleteWorkItemType(processId: string, witRefName: string): Promise<void>; /** * Returns a work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand} expand */ getWorkItemType(processId: string, witRefName: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; /** * Returns a list of all work item types in the process. * * @param {string} processId - The ID of the process * @param {WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand} expand */ getWorkItemTypes(processId: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>; /** * Updates a work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel} workItemTypeUpdate * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ updateWorkItemType(workItemTypeUpdate: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; /** * Adds a field to the work item type in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2} field * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for the field */ addFieldToWorkItemType(field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; /** * Returns a single field in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields * @param {string} fieldRefName - The reference name of the field */ getWorkItemTypeField(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; /** * Returns a list of all fields in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields */ getWorkItemTypeFields(processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>; /** * Removes a field in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields * @param {string} fieldRefName - The reference name of the field */ removeFieldFromWorkItemType(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<void>; }
the_stack
import { FocusTrap } from "@a11y/focus-trap"; import "@a11y/focus-trap"; import { LitElement, property } from "lit-element"; import styles from "overlay-behavior.scss"; import { sharedStyles } from "../../style/shared"; import { pauseAnimations } from "../../util/animation"; import { CUBIC_BEZIER } from "../../util/constant/animation"; import { ESCAPE } from "../../util/constant/keycode"; import { cssResult } from "../../util/css"; import { renderAttributes, traverseActiveElements } from "../../util/dom"; import { addListener, EventListenerSubscription, removeListeners, stopEvent } from "../../util/event"; import { CAN_USE_RESIZE_OBSERVER, onSizeChanged } from "../../util/resize"; import { uniqueID } from "../../util/unique"; /** * Events the overlay behavior can dispatch. */ export enum OverlayBehaviorEvent { DID_SHOW = "didShow", DID_HIDE = "didHide" } /** * Base properties of the overlay behavior. */ export interface IOverlayBehaviorBaseProperties { open: boolean; persistent: boolean; blockScrolling: boolean; backdrop: boolean; duration: number; fixed: boolean; disableFocusTrap: boolean; scrollContainer: EventTarget; } /** * Properties of the overlay behavior. */ export interface IOverlayBehaviorProperties { open: boolean; } // Type of an overlay resolver. export declare type OverlayResolver<R> = (result: R | null | undefined) => void; /** * Default scroll container. */ export const DEFAULT_OVERLAY_SCROLL_CONTAINER = document.documentElement; // Prefix infront of the class indicating that an overlay is blocking the scrolling const OVERLAY_SCROLLING_BLOCKED_CLASS_PREFIX = `overlay`; // Generates a scroll blocking identifier css class name. const scrollingBlockedClass = (id: string) => `${OVERLAY_SCROLLING_BLOCKED_CLASS_PREFIX}-${id}`; /** * Provides overlay behavior. * @event didshow - Dispatches after the overlay has been shown. * @event didhide - Dispatches after the overlay has been hidden. */ export abstract class OverlayBehavior<R, C extends Partial<IOverlayBehaviorBaseProperties>> extends LitElement implements IOverlayBehaviorProperties { static styles = [sharedStyles, cssResult(styles)]; /** * Whether the overlay is open or not. * @attr */ @property({ type: Boolean, reflect: true }) open: boolean = false; /** * Whether the focus trap be disabled. * @attr */ @property({ type: Boolean, reflect: true }) disableFocusTrap: boolean = false; /** * Whether the backdrop is visible or not. * @attr */ @property({ type: Boolean, reflect: true }) backdrop: boolean = false; /** * Whether the overlay is fixed or not. * @attr */ @property({ type: Boolean, reflect: true }) fixed: boolean = false; /** * Whether the overlay is persistent or not. When the overlay is persistent, ESCAPE and backdrop clicks won't close it. * @attr */ @property({ type: Boolean }) persistent: boolean = false; /** * Whether the overlay blocks the scrolling on the scroll container. * @attr */ @property({ type: Boolean }) blockScrolling: boolean = false; /** * The duration of the animations. * @attr */ @property({ type: Number }) duration: number = 200; /** * The container the overlay lives in. * @attr */ @property({ type: Object }) scrollContainer: EventTarget = DEFAULT_OVERLAY_SCROLL_CONTAINER; /** * Returns the scroll container as an HTMLElement. Falls back to the documentElement if the scroll * container is not blockable since the style attribute is required to set the overflow hidden. */ get $blockableScrollContainer() { return this.scrollContainer instanceof HTMLElement ? this.scrollContainer : DEFAULT_OVERLAY_SCROLL_CONTAINER; } /** * Active in animation. */ protected activeInAnimations: Animation[] = []; /** * Active out animations. */ protected activeOutAnimations: Animation[] = []; /** * Resolvers that resolves when the overlay is closed. */ protected resolvers: OverlayResolver<R>[] = []; /** * Unique ID of the overlay. */ protected overlayId = uniqueID(); /** * Active event listeners. */ protected listeners: EventListenerSubscription[] = []; /** * Element that was active before the overlay was opened. */ protected activeElementBeforeOpen?: HTMLElement; /** * Trap where focus is going to be trapped within. */ protected abstract readonly $focusTrap?: FocusTrap; /** * Base configuration for the in and out animation. */ protected get animationConfig(): KeyframeAnimationOptions { return { duration: this.duration, easing: CUBIC_BEZIER, fill: "both" }; } /** * Focuses on the first element of the overlay. */ trapFocus() { if (this.$focusTrap != null) { this.storeCurrentActiveElement(); this.$focusTrap.focusFirstElement(); } } /** * Store the current active element so we can restore * the focus on that element when the overlay is closed. */ storeCurrentActiveElement() { this.activeElementBeforeOpen = <HTMLElement | undefined>traverseActiveElements(); } /** * Shows the overlayed component. * @param config */ show(config?: C): Promise<R | null> { // If an in animation is already playing return a new resolver. if (this.activeInAnimations.length > 0) { return this.createResolver(); } // Prepare the show animation with the configuration object this.prepareShowAnimation(config); // Animate the overlay in. this.animateIn(); // Show the overlay this.open = true; // Return a resolver return this.createResolver(); } /** * Hides the overlayed component. * @param result */ hide(result?: R) { // If there are out animations already being played, we simply return // knowing that the current out animation will finish soon. if (this.activeOutAnimations.length > 0) { return; } // Prepare the hide animation this.prepareHideAnimation(); // Animate the overlay out this.animateOut(result); } /** * Reacts on the properties changed. * @param props */ protected updated(props: Map<keyof IOverlayBehaviorProperties, unknown>) { super.updated(props); if (props.has("open")) { // When the overlay is closed it is removed from the tab order. this.open ? this.removeAttribute("tabindex") : this.setAttribute("tabindex", "-1"); } // Each time a property changes we need to update the aria information. this.updateAria(); } /** * Updates the aria information. */ protected updateAria() { renderAttributes(this, { "aria-hidden": !this.open }); } /** * Creates a new resolver. */ protected createResolver() { return new Promise((res: OverlayResolver<R>) => { this.resolvers.push(res); }); } /** * Resolves a result and clears the list of resolvers. * @param result */ protected resolve(result?: R | null) { for (const resolve of this.resolvers) { resolve(result); } this.resolvers.length = 0; } /** * Hides the overlay if it's not persistent. */ protected clickAway() { if (!this.persistent && this.open) { this.hide(); } } /** * Dispatches an overlay event. * @param e * @param detail */ protected dispatchOverlayEvent(e: OverlayBehaviorEvent, detail?: R | null) { this.dispatchEvent(new CustomEvent(e, { detail, composed: true, bubbles: true })); } /** * Sets the properties based on the configuration object. * @param config */ protected setConfig(config: C) { Object.assign(this, config); } /** * Pauses all ongoing animations. */ protected pauseAnimations() { this.pauseInAnimations(); this.pauseOutAnimations(); } /** * Pauses all ongoing in animations. */ protected pauseInAnimations() { pauseAnimations(this.activeInAnimations); } /** * Pauses all ongoing out animations. */ protected pauseOutAnimations() { pauseAnimations(this.activeOutAnimations); } /** * Prepares the show animation. * @param config */ protected prepareShowAnimation(config?: C) { // Listen for events on when to update the position of the overlay this.listeners.push( addListener(this.scrollContainer, "scroll", this.updatePosition.bind(this), { passive: true }), // Either attach a resize observer or fallback to listening to window resizes CAN_USE_RESIZE_OBSERVER ? onSizeChanged(this, this.updatePosition.bind(this), { debounceMs: 100 }) : addListener(window, "resize", this.updatePosition.bind(this), { passive: true }) ); this.pauseAnimations(); // Set the configuration object if necessary if (config != null) { this.setConfig(config); } // Block the scrolling on the body element if necessary. if (this.blockScrolling) { const $container = this.$blockableScrollContainer; $container.style.overflow = `hidden`; $container.classList.add(scrollingBlockedClass(this.overlayId)); } } /** * Prepares the hide animation. */ protected prepareHideAnimation() { removeListeners(this.listeners); this.pauseAnimations(); } /** * Animates the overlay in. */ protected abstract animateIn(): void; /** * Animates the overlay out. * @param result */ protected abstract animateOut(result?: R): void; /** * Hooks up listeners and traps the focus. */ protected didShow() { this.activeInAnimations.length = 0; this.listeners.push(addListener(this, "keydown", this.onKeyDown.bind(this))); // Focus the first element if element should be trap if (!this.disableFocusTrap) { this.trapFocus(); } this.dispatchOverlayEvent(OverlayBehaviorEvent.DID_SHOW); } /** * Removes listeners and restores the state before the overlay was opened. * @param result */ protected didHide(result?: R) { if (this.blockScrolling) { const $container = this.$blockableScrollContainer; // Check whether other overlays are blocking the same scroll container. // If that is the case, we do not have to release the scroll blocking yet. const currentBlockingOverlays = $container.className.match(new RegExp(OVERLAY_SCROLLING_BLOCKED_CLASS_PREFIX, "gm")); if (currentBlockingOverlays === null || (currentBlockingOverlays != null && currentBlockingOverlays.length === 1)) { $container.style.overflow = ``; } $container.classList.remove(scrollingBlockedClass(this.overlayId)); } // Focus on the element that was active before the overlay was opened if (this.activeElementBeforeOpen != null) { this.activeElementBeforeOpen.focus(); this.activeElementBeforeOpen = undefined; } this.activeOutAnimations.length = 0; this.open = false; this.dispatchOverlayEvent(OverlayBehaviorEvent.DID_HIDE, result); } /** * Updates the position of the overlay.. */ protected updatePosition() { // Implement if necessary } /** * Handles the key down event on focus. * @param {KeyboardEvent} e */ protected onKeyDown(e: KeyboardEvent) { switch (e.code) { case ESCAPE: if (this.open && !this.persistent) { this.hide(); stopEvent(e); } break; } } }
the_stack
import { ManagedTable, TableBodyColumn, TableRows, TableBodyRow, TableRowSortOrder, TableHighlightedRows, } from 'flipper'; import { DatabaseEntry, Page, plugin, Query, QueryResult, Structure, } from './index'; import {getStringFromErrorLike} from './utils'; import {Value, renderValue} from './TypeBasedValueRenderer'; import React, {KeyboardEvent, ChangeEvent, useState, useCallback} from 'react'; import ButtonNavigation from './ButtonNavigation'; import DatabaseDetailSidebar from './DatabaseDetailSidebar'; import DatabaseStructure from './DatabaseStructure'; import { convertStringToValue, constructUpdateQuery, isUpdatable, } from './UpdateQueryUtil'; import sqlFormatter from 'sql-formatter'; import { usePlugin, useValue, Layout, useMemoize, Toolbar, theme, styled, produce, } from 'flipper-plugin'; import { Select, Radio, RadioChangeEvent, Typography, Button, Menu, Dropdown, Input, } from 'antd'; import { ConsoleSqlOutlined, DatabaseOutlined, DownOutlined, HistoryOutlined, SettingOutlined, StarFilled, StarOutlined, TableOutlined, } from '@ant-design/icons'; const {TextArea} = Input; const {Option} = Select; const {Text} = Typography; const BoldSpan = styled.span({ fontSize: 12, color: '#90949c', fontWeight: 'bold', textTransform: 'uppercase', }); const ErrorBar = styled.div({ backgroundColor: theme.errorColor, color: theme.textColorPrimary, lineHeight: '26px', textAlign: 'center', }); const PageInfoContainer = styled(Layout.Horizontal)({alignItems: 'center'}); function transformRow( columns: Array<string>, row: Array<Value>, index: number, ): TableBodyRow { const transformedColumns: {[key: string]: TableBodyColumn} = {}; for (let i = 0; i < columns.length; i++) { transformedColumns[columns[i]] = {value: renderValue(row[i], true)}; } return {key: String(index), columns: transformedColumns}; } const QueryHistory = React.memo(({history}: {history: Array<Query>}) => { if (!history || typeof history === 'undefined') { return null; } const columns = { time: { value: 'Time', resizable: true, }, query: { value: 'Query', resizable: true, }, }; const rows: TableRows = []; if (history.length > 0) { for (let i = 0; i < history.length; i++) { const query = history[i]; const time = query.time; const value = query.value; rows.push({ key: `${i}`, columns: {time: {value: time}, query: {value: value}}, }); } } return ( <Layout.Horizontal grow> <ManagedTable floating={false} columns={columns} columnSizes={{time: 75}} zebra rows={rows} horizontallyScrollable /> </Layout.Horizontal> ); }); type PageInfoProps = { currentRow: number; count: number; totalRows: number; onChange: (currentRow: number, count: number) => void; }; const PageInfo = React.memo((props: PageInfoProps) => { const [state, setState] = useState({ isOpen: false, inputValue: String(props.currentRow), }); const onOpen = useCallback(() => { setState({...state, isOpen: true}); }, [state]); const onInputChanged = useCallback( (e: ChangeEvent<any>) => { setState({...state, inputValue: e.target.value}); }, [state], ); const onSubmit = useCallback( (e: KeyboardEvent) => { if (e.key === 'Enter') { const rowNumber = parseInt(state.inputValue, 10); props.onChange(rowNumber - 1, props.count); setState({...state, isOpen: false}); } }, [props, state], ); return ( <PageInfoContainer grow> <div style={{flex: 1}} /> <Text> {props.count === props.totalRows ? `${props.count} ` : `${props.currentRow + 1}-${props.currentRow + props.count} `} of {props.totalRows} rows </Text> <div style={{flex: 1}} /> {state.isOpen ? ( <Input tabIndex={-1} placeholder={(props.currentRow + 1).toString()} onChange={onInputChanged} onKeyDown={onSubmit} /> ) : ( <Button style={{textAlign: 'center'}} onClick={onOpen}> Go To Row </Button> )} </PageInfoContainer> ); }); const DataTable = React.memo( ({ page, highlightedRowsChanged, sortOrderChanged, currentSort, currentStructure, onRowEdited, }: { page: Page | null; highlightedRowsChanged: (highlightedRows: TableHighlightedRows) => void; sortOrderChanged: (sortOrder: TableRowSortOrder) => void; currentSort: TableRowSortOrder | null; currentStructure: Structure | null; onRowEdited: (changes: {[key: string]: string | null}) => void; }) => page ? ( <Layout.Horizontal grow> <ManagedTable tableKey={`databases-${page.databaseId}-${page.table}`} floating={false} columnOrder={page.columns.map((name) => ({ key: name, visible: true, }))} columns={page.columns.reduce( (acc, val) => Object.assign({}, acc, { [val]: {value: val, resizable: true, sortable: true}, }), {}, )} zebra rows={page.rows.map((row: Array<Value>, index: number) => transformRow(page.columns, row, index), )} horizontallyScrollable multiHighlight onRowHighlighted={highlightedRowsChanged} onSort={sortOrderChanged} initialSortOrder={currentSort ?? undefined} /> {page.highlightedRows.length === 1 && ( <DatabaseDetailSidebar columnLabels={page.columns} columnValues={page.rows[page.highlightedRows[0]]} onSave={ currentStructure && isUpdatable(currentStructure.columns, currentStructure.rows) ? onRowEdited : undefined } /> )} </Layout.Horizontal> ) : null, ); const QueryTable = React.memo( ({ query, highlightedRowsChanged, }: { query: QueryResult | null; highlightedRowsChanged: (highlightedRows: TableHighlightedRows) => void; }) => { if (!query || query === null) { return null; } if ( query.table && typeof query.table !== 'undefined' && query.table !== null ) { const table = query.table; const columns = table.columns; const rows = table.rows; return ( <Layout.Horizontal grow> <ManagedTable floating={false} multiline columnOrder={columns.map((name) => ({ key: name, visible: true, }))} columns={columns.reduce( (acc, val) => Object.assign({}, acc, {[val]: {value: val, resizable: true}}), {}, )} zebra rows={rows.map((row: Array<Value>, index: number) => transformRow(columns, row, index), )} horizontallyScrollable onRowHighlighted={highlightedRowsChanged} /> {table.highlightedRows.length === 1 && ( <DatabaseDetailSidebar columnLabels={table.columns} columnValues={table.rows[table.highlightedRows[0]]} /> )} </Layout.Horizontal> ); } else if (query.id && query.id !== null) { return ( <Layout.Horizontal grow pad> <Text>Row id: {query.id}</Text> </Layout.Horizontal> ); } else if (query.count && query.count !== null) { return ( <Layout.Horizontal grow pad> <Text>Rows affected: {query.count}</Text> </Layout.Horizontal> ); } else { return null; } }, ); const FavoritesMenu = React.memo( ({ favorites, onClick, }: { favorites: string[]; onClick: (value: string) => void; }) => { const onMenuClick = useCallback( (p: any) => onClick(p.key as string), [onClick], ); return ( <Menu> {favorites.map((q) => ( <Menu.Item key={q} onClick={onMenuClick}> {q} </Menu.Item> ))} </Menu> ); }, ); export function Component() { const instance = usePlugin(plugin); const state = useValue(instance.state); const favorites = useValue(instance.favoritesState); const onViewModeChanged = useCallback( (evt: RadioChangeEvent) => { instance.updateViewMode({viewMode: evt.target.value ?? 'data'}); }, [instance], ); const onDataClicked = useCallback(() => { instance.updateViewMode({viewMode: 'data'}); }, [instance]); const onStructureClicked = useCallback(() => { instance.updateViewMode({viewMode: 'structure'}); }, [instance]); const onSQLClicked = useCallback(() => { instance.updateViewMode({viewMode: 'SQL'}); }, [instance]); const onTableInfoClicked = useCallback(() => { instance.updateViewMode({viewMode: 'tableInfo'}); }, [instance]); const onQueryHistoryClicked = useCallback(() => { instance.updateViewMode({viewMode: 'queryHistory'}); }, [instance]); const onRefreshClicked = useCallback(() => { instance.state.update((state) => { state.error = null; }); instance.refresh(); }, [instance]); const onFavoriteButtonClicked = useCallback(() => { if (state.query) { instance.addOrRemoveQueryToFavorites(state.query.value); } }, [instance, state.query]); const onDatabaseSelected = useCallback( (selected: string) => { const dbId = instance.state.get().databases.find((x) => x.name === selected)?.id || 0; instance.updateSelectedDatabase({ database: dbId, }); }, [instance], ); const onDatabaseTableSelected = useCallback( (selected: string) => { instance.updateSelectedDatabaseTable({ table: selected, }); }, [instance], ); const onNextPageClicked = useCallback(() => { instance.nextPage(); }, [instance]); const onPreviousPageClicked = useCallback(() => { instance.previousPage(); }, [instance]); const onExecuteClicked = useCallback(() => { const query = instance.state.get().query; if (query) { instance.execute({query: query.value}); } }, [instance]); const onQueryTextareaKeyPress = useCallback( (event: KeyboardEvent) => { // Implement ctrl+enter as a shortcut for clicking 'Execute'. if (event.key === '\n' && event.ctrlKey) { event.preventDefault(); event.stopPropagation(); onExecuteClicked(); } }, [onExecuteClicked], ); const onGoToRow = useCallback( (row: number, _count: number) => { instance.goToRow({row: row}); }, [instance], ); const onQueryChanged = useCallback( (selected: any) => { instance.updateQuery({ value: selected.target.value, }); }, [instance], ); const onFavoriteQuerySelected = useCallback( (query: string) => { instance.updateQuery({ value: query, }); }, [instance], ); const pageHighlightedRowsChanged = useCallback( (rows: TableHighlightedRows) => { instance.pageHighlightedRowsChanged(rows); }, [instance], ); const queryHighlightedRowsChanged = useCallback( (rows: TableHighlightedRows) => { instance.queryHighlightedRowsChanged(rows); }, [instance], ); const sortOrderChanged = useCallback( (sortOrder: TableRowSortOrder) => { instance.sortByChanged({sortOrder}); }, [instance], ); const onRowEdited = useCallback( (change: {[key: string]: string | null}) => { const {selectedDatabaseTable, currentStructure, viewMode, currentPage} = instance.state.get(); const highlightedRowIdx = currentPage?.highlightedRows[0] ?? -1; const row = highlightedRowIdx >= 0 ? currentPage?.rows[currentPage?.highlightedRows[0]] : undefined; const columns = currentPage?.columns; // currently only allow to edit data shown in Data tab if ( viewMode !== 'data' || selectedDatabaseTable === null || currentStructure === null || currentPage === null || row === undefined || columns === undefined || // only trigger when there is change Object.keys(change).length <= 0 ) { return; } // check if the table has primary key to use for query // This is assumed data are in the same format as in SqliteDatabaseDriver.java const primaryKeyIdx = currentStructure.columns.indexOf('primary_key'); const nameKeyIdx = currentStructure.columns.indexOf('column_name'); const typeIdx = currentStructure.columns.indexOf('data_type'); const nullableIdx = currentStructure.columns.indexOf('nullable'); if (primaryKeyIdx < 0 && nameKeyIdx < 0 && typeIdx < 0) { console.error( 'primary_key, column_name, and/or data_type cannot be empty', ); return; } const primaryColumnIndexes = currentStructure.rows .reduce((acc, row) => { const primary = row[primaryKeyIdx]; if (primary.type === 'boolean' && primary.value) { const name = row[nameKeyIdx]; return name.type === 'string' ? acc.concat(name.value) : acc; } else { return acc; } }, [] as Array<string>) .map((name) => columns.indexOf(name)) .filter((idx) => idx >= 0); // stop if no primary key to distinguish unique query if (primaryColumnIndexes.length <= 0) { return; } const types = currentStructure.rows.reduce((acc, row) => { const nameValue = row[nameKeyIdx]; const name = nameValue.type === 'string' ? nameValue.value : null; const typeValue = row[typeIdx]; const type = typeValue.type === 'string' ? typeValue.value : null; const nullableValue = nullableIdx < 0 ? {type: 'null', value: null} : row[nullableIdx]; const nullable = nullableValue.value !== false; if (name !== null && type !== null) { acc[name] = {type, nullable}; } return acc; }, {} as {[key: string]: {type: string; nullable: boolean}}); const changeValue = Object.entries(change).reduce( (acc, [key, value]: [string, string | null]) => { acc[key] = convertStringToValue(types, key, value); return acc; }, {} as {[key: string]: Value}, ); instance.execute({ query: constructUpdateQuery( selectedDatabaseTable, primaryColumnIndexes.reduce((acc, idx) => { acc[columns[idx]] = row[idx]; return acc; }, {} as {[key: string]: Value}), changeValue, ), }); instance.updatePage({ ...produce(currentPage, (draft) => Object.entries(changeValue).forEach( ([key, value]: [string, Value]) => { const columnIdx = draft.columns.indexOf(key); if (columnIdx >= 0) { draft.rows[highlightedRowIdx][columnIdx] = value; } }, ), ), }); }, [instance], ); const databaseOptions = useMemoize( (databases) => databases.map((x) => ( <Option key={x.name} value={x.name} label={x.name}> {x.name} </Option> )), [state.databases], ); const selectedDatabaseName = useMemoize( (selectedDatabase: number, databases: DatabaseEntry[]) => selectedDatabase && databases[state.selectedDatabase - 1] ? databases[selectedDatabase - 1].name : undefined, [state.selectedDatabase, state.databases], ); const tableOptions = useMemoize( (selectedDatabase: number, databases: DatabaseEntry[]) => selectedDatabase && databases[state.selectedDatabase - 1] ? databases[selectedDatabase - 1].tables.map((tableName) => ( <Option key={tableName} value={tableName} label={tableName}> {tableName} </Option> )) : [], [state.selectedDatabase, state.databases], ); const selectedTableName = useMemoize( ( selectedDatabase: number, databases: DatabaseEntry[], selectedDatabaseTable: string | null, ) => selectedDatabase && databases[selectedDatabase - 1] ? databases[selectedDatabase - 1].tables.find( (t) => t === selectedDatabaseTable, ) ?? databases[selectedDatabase - 1].tables[0] : undefined, [state.selectedDatabase, state.databases, state.selectedDatabaseTable], ); return ( <Layout.Container grow> <Toolbar position="top"> <Radio.Group value={state.viewMode} onChange={onViewModeChanged}> <Radio.Button value="data" onClick={onDataClicked}> <TableOutlined style={{marginRight: 5}} /> <Typography.Text>Data</Typography.Text> </Radio.Button> <Radio.Button onClick={onStructureClicked} value="structure"> <SettingOutlined style={{marginRight: 5}} /> <Typography.Text>Structure</Typography.Text> </Radio.Button> <Radio.Button onClick={onSQLClicked} value="SQL"> <ConsoleSqlOutlined style={{marginRight: 5}} /> <Typography.Text>SQL</Typography.Text> </Radio.Button> <Radio.Button onClick={onTableInfoClicked} value="tableInfo"> <DatabaseOutlined style={{marginRight: 5}} /> <Typography.Text>Table Info</Typography.Text> </Radio.Button> <Radio.Button onClick={onQueryHistoryClicked} value="queryHistory"> <HistoryOutlined style={{marginRight: 5}} /> <Typography.Text>Query History</Typography.Text> </Radio.Button> </Radio.Group> </Toolbar> {state.viewMode === 'data' || state.viewMode === 'structure' || state.viewMode === 'tableInfo' ? ( <Toolbar position="top"> <BoldSpan>Database</BoldSpan> <Select showSearch value={selectedDatabaseName} onChange={onDatabaseSelected} style={{flex: 1}} dropdownMatchSelectWidth={false}> {databaseOptions} </Select> <BoldSpan>Table</BoldSpan> <Select showSearch value={selectedTableName} onChange={onDatabaseTableSelected} style={{flex: 1}} dropdownMatchSelectWidth={false}> {tableOptions} </Select> <div /> <Button onClick={onRefreshClicked} type="default"> Refresh </Button> </Toolbar> ) : null} {state.viewMode === 'SQL' ? ( <Layout.Container> <Toolbar position="top"> <BoldSpan>Database</BoldSpan> <Select showSearch value={selectedDatabaseName} onChange={onDatabaseSelected} dropdownMatchSelectWidth={false}> {databaseOptions} </Select> </Toolbar> <Layout.Horizontal pad={theme.space.small} style={{paddingBottom: 0}}> <TextArea onChange={onQueryChanged} onKeyPress={onQueryTextareaKeyPress} placeholder="Type query here.." value={ state.query !== null && typeof state.query !== 'undefined' ? state.query.value : undefined } /> </Layout.Horizontal> <Toolbar position="top"> <Layout.Right> <div /> <Layout.Horizontal gap={theme.space.small}> <Button icon={ state.query && favorites.includes(state.query.value) ? ( <StarFilled /> ) : ( <StarOutlined /> ) } onClick={onFavoriteButtonClicked} /> <Dropdown overlay={ <FavoritesMenu favorites={favorites} onClick={onFavoriteQuerySelected} /> }> <Button onClick={() => {}}> Choose from previous queries <DownOutlined /> </Button> </Dropdown> <Button type="primary" onClick={onExecuteClicked} title={'Execute SQL [Ctrl+Return]'}> Execute </Button> </Layout.Horizontal> </Layout.Right> </Toolbar> </Layout.Container> ) : null} <Layout.Horizontal grow> <Layout.Container grow> {state.viewMode === 'data' ? ( <DataTable page={state.currentPage} highlightedRowsChanged={pageHighlightedRowsChanged} onRowEdited={onRowEdited} sortOrderChanged={sortOrderChanged} currentSort={state.currentSort} currentStructure={state.currentStructure} /> ) : null} {state.viewMode === 'structure' && state.currentStructure ? ( <DatabaseStructure structure={state.currentStructure} /> ) : null} {state.viewMode === 'SQL' ? ( <QueryTable query={state.queryResult} highlightedRowsChanged={queryHighlightedRowsChanged} /> ) : null} {state.viewMode === 'tableInfo' ? ( <Layout.Horizontal grow pad={theme.space.small} style={{paddingBottom: 0}}> <TextArea value={sqlFormatter.format(state.tableInfo)} readOnly /> </Layout.Horizontal> ) : null} {state.viewMode === 'queryHistory' ? ( <QueryHistory history={state.queryHistory} /> ) : null} </Layout.Container> </Layout.Horizontal> <Toolbar position="bottom" style={{paddingLeft: 8}}> <Layout.Horizontal grow> {state.viewMode === 'SQL' && state.executionTime !== 0 ? ( <Text> {state.executionTime} ms </Text> ) : null} {state.viewMode === 'data' && state.currentPage ? ( <PageInfo currentRow={state.currentPage.start} count={state.currentPage.count} totalRows={state.currentPage.total} onChange={onGoToRow} /> ) : null} {state.viewMode === 'data' && state.currentPage ? ( <ButtonNavigation canGoBack={state.currentPage.start > 0} canGoForward={ state.currentPage.start + state.currentPage.count < state.currentPage.total } onBack={onPreviousPageClicked} onForward={onNextPageClicked} /> ) : null} </Layout.Horizontal> </Toolbar> {state.error && ( <ErrorBar>{getStringFromErrorLike(state.error)}</ErrorBar> )} </Layout.Container> ); }
the_stack
import GL from '@luma.gl/constants'; import { render } from '@luma.gl/shadertools/test/gpu-test-utils'; import {isWebGL2} from '../utils/webgl-checks'; import {GLParameters} from './webgl-parameters'; // DEFAULT SETTINGS - FOR FAST CACHE INITIALIZATION AND CONTEXT RESETS /* eslint-disable no-shadow */ export const GL_PARAMETER_DEFAULTS: GLParameters = { [GL.BLEND]: false, [GL.BLEND_COLOR]: new Float32Array([0, 0, 0, 0]), [GL.BLEND_EQUATION_RGB]: GL.FUNC_ADD, [GL.BLEND_EQUATION_ALPHA]: GL.FUNC_ADD, [GL.BLEND_SRC_RGB]: GL.ONE, [GL.BLEND_DST_RGB]: GL.ZERO, [GL.BLEND_SRC_ALPHA]: GL.ONE, [GL.BLEND_DST_ALPHA]: GL.ZERO, [GL.COLOR_CLEAR_VALUE]: new Float32Array([0, 0, 0, 0]), // TBD [GL.COLOR_WRITEMASK]: [true, true, true, true], [GL.CULL_FACE]: false, [GL.CULL_FACE_MODE]: GL.BACK, [GL.DEPTH_TEST]: false, [GL.DEPTH_CLEAR_VALUE]: 1, [GL.DEPTH_FUNC]: GL.LESS, [GL.DEPTH_RANGE]: new Float32Array([0, 1]), // TBD [GL.DEPTH_WRITEMASK]: true, [GL.DITHER]: true, [GL.CURRENT_PROGRAM]: null, // FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state. [GL.FRAMEBUFFER_BINDING]: null, [GL.RENDERBUFFER_BINDING]: null, [GL.VERTEX_ARRAY_BINDING]: null, [GL.ARRAY_BUFFER_BINDING]: null, [GL.FRONT_FACE]: GL.CCW, [GL.GENERATE_MIPMAP_HINT]: GL.DONT_CARE, [GL.LINE_WIDTH]: 1, [GL.POLYGON_OFFSET_FILL]: false, [GL.POLYGON_OFFSET_FACTOR]: 0, [GL.POLYGON_OFFSET_UNITS]: 0, [GL.SAMPLE_ALPHA_TO_COVERAGE]: false, [GL.SAMPLE_COVERAGE]: false, [GL.SAMPLE_COVERAGE_VALUE]: 1.0, [GL.SAMPLE_COVERAGE_INVERT]: false, [GL.SCISSOR_TEST]: false, // Note: Dynamic value. If scissor test enabled we expect users to set correct scissor box [GL.SCISSOR_BOX]: new Int32Array([0, 0, 1024, 1024]), [GL.STENCIL_TEST]: false, [GL.STENCIL_CLEAR_VALUE]: 0, [GL.STENCIL_WRITEMASK]: 0xffffffff, [GL.STENCIL_BACK_WRITEMASK]: 0xffffffff, [GL.STENCIL_FUNC]: GL.ALWAYS, [GL.STENCIL_REF]: 0, [GL.STENCIL_VALUE_MASK]: 0xffffffff, [GL.STENCIL_BACK_FUNC]: GL.ALWAYS, [GL.STENCIL_BACK_REF]: 0, [GL.STENCIL_BACK_VALUE_MASK]: 0xffffffff, [GL.STENCIL_FAIL]: GL.KEEP, [GL.STENCIL_PASS_DEPTH_FAIL]: GL.KEEP, [GL.STENCIL_PASS_DEPTH_PASS]: GL.KEEP, [GL.STENCIL_BACK_FAIL]: GL.KEEP, [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: GL.KEEP, [GL.STENCIL_BACK_PASS_DEPTH_PASS]: GL.KEEP, // Dynamic value: We use [0, 0, 1024, 1024] as default, but usually this is updated in each frame. [GL.VIEWPORT]: [0, 0, 1024, 1024], // WEBGL1 PIXEL PACK/UNPACK MODES [GL.PACK_ALIGNMENT]: 4, [GL.UNPACK_ALIGNMENT]: 4, [GL.UNPACK_FLIP_Y_WEBGL]: false, [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: false, [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: GL.BROWSER_DEFAULT_WEBGL, // WEBGL2 / EXTENSIONS // gl1: 'OES_standard_derivatives' [GL.TRANSFORM_FEEDBACK_BINDING]: null, [GL.COPY_READ_BUFFER_BINDING]: null, [GL.COPY_WRITE_BUFFER_BINDING]: null, [GL.PIXEL_PACK_BUFFER_BINDING]: null, [GL.PIXEL_UNPACK_BUFFER_BINDING]: null, [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: GL.DONT_CARE, [GL.READ_FRAMEBUFFER_BINDING]: null, [GL.RASTERIZER_DISCARD]: false, [GL.PACK_ROW_LENGTH]: 0, [GL.PACK_SKIP_PIXELS]: 0, [GL.PACK_SKIP_ROWS]: 0, [GL.UNPACK_ROW_LENGTH]: 0, [GL.UNPACK_IMAGE_HEIGHT]: 0, [GL.UNPACK_SKIP_PIXELS]: 0, [GL.UNPACK_SKIP_ROWS]: 0, [GL.UNPACK_SKIP_IMAGES]: 0 }; // SETTER TABLES - ENABLES SETTING ANY PARAMETER WITH A COMMON API const enable = (gl, value, key) => (value ? gl.enable(key) : gl.disable(key)); const hint = (gl, value, key) => gl.hint(key, value); const pixelStorei = (gl, value, key) => gl.pixelStorei(key, value); const bindFramebuffer = (gl, value, key) => { let target; if (key === GL.FRAMEBUFFER_BINDING) { target = isWebGL2(gl) ? GL.DRAW_FRAMEBUFFER : GL.FRAMEBUFFER; } else { // GL.READ_FRAMEBUFFER_BINDING target = GL.READ_FRAMEBUFFER; } return gl.bindFramebuffer(target, value); }; const bindBuffer = (gl, value, key) => { const target = ({ [GL.ARRAY_BUFFER_BINDING]: [GL.ARRAY_BUFFER], [GL.COPY_READ_BUFFER_BINDING]: [GL.COPY_READ_BUFFER], [GL.COPY_WRITE_BUFFER_BINDING]: [GL.COPY_WRITE_BUFFER], [GL.PIXEL_PACK_BUFFER_BINDING]: [GL.PIXEL_PACK_BUFFER], [GL.PIXEL_UNPACK_BUFFER_BINDING]: [GL.PIXEL_UNPACK_BUFFER] })[key]; gl.bindBuffer(target, value); }; // Utility function isArray(array) { return Array.isArray(array) || ArrayBuffer.isView(array); } // Map from WebGL parameter names to corresponding WebGL setter functions // WegGL constants are read by parameter names, but set by function names // NOTE: When value type is a string, it will be handled by 'GL_COMPOSITE_PARAMETER_SETTERS' export const GL_PARAMETER_SETTERS = { [GL.BLEND]: enable, [GL.BLEND_COLOR]: (gl, value) => gl.blendColor(...value), [GL.BLEND_EQUATION_RGB]: 'blendEquation', [GL.BLEND_EQUATION_ALPHA]: 'blendEquation', [GL.BLEND_SRC_RGB]: 'blendFunc', [GL.BLEND_DST_RGB]: 'blendFunc', [GL.BLEND_SRC_ALPHA]: 'blendFunc', [GL.BLEND_DST_ALPHA]: 'blendFunc', [GL.COLOR_CLEAR_VALUE]: (gl, value) => gl.clearColor(...value), [GL.COLOR_WRITEMASK]: (gl, value) => gl.colorMask(...value), [GL.CULL_FACE]: enable, [GL.CULL_FACE_MODE]: (gl, value) => gl.cullFace(value), [GL.DEPTH_TEST]: enable, [GL.DEPTH_CLEAR_VALUE]: (gl, value) => gl.clearDepth(value), [GL.DEPTH_FUNC]: (gl, value) => gl.depthFunc(value), [GL.DEPTH_RANGE]: (gl, value) => gl.depthRange(...value), [GL.DEPTH_WRITEMASK]: (gl, value) => gl.depthMask(value), [GL.DITHER]: enable, [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: hint, [GL.CURRENT_PROGRAM]: (gl, value) => gl.useProgram(value), [GL.RENDERBUFFER_BINDING]: (gl, value) => gl.bindRenderbuffer(GL.RENDERBUFFER, value), [GL.TRANSFORM_FEEDBACK_BINDING]: (gl, value) => gl.bindTransformFeedback?.(GL.TRANSFORM_FEEDBACK, value), [GL.VERTEX_ARRAY_BINDING]: (gl, value) => gl.bindVertexArray(value), // NOTE: FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state. [GL.FRAMEBUFFER_BINDING]: bindFramebuffer, [GL.READ_FRAMEBUFFER_BINDING]: bindFramebuffer, // Buffers [GL.ARRAY_BUFFER_BINDING]: bindBuffer, [GL.COPY_READ_BUFFER_BINDING]: bindBuffer, [GL.COPY_WRITE_BUFFER_BINDING]: bindBuffer, [GL.PIXEL_PACK_BUFFER_BINDING]: bindBuffer, [GL.PIXEL_UNPACK_BUFFER_BINDING]: bindBuffer, [GL.FRONT_FACE]: (gl, value) => gl.frontFace(value), [GL.GENERATE_MIPMAP_HINT]: hint, [GL.LINE_WIDTH]: (gl, value) => gl.lineWidth(value), [GL.POLYGON_OFFSET_FILL]: enable, [GL.POLYGON_OFFSET_FACTOR]: 'polygonOffset', [GL.POLYGON_OFFSET_UNITS]: 'polygonOffset', [GL.RASTERIZER_DISCARD]: enable, [GL.SAMPLE_ALPHA_TO_COVERAGE]: enable, [GL.SAMPLE_COVERAGE]: enable, [GL.SAMPLE_COVERAGE_VALUE]: 'sampleCoverage', [GL.SAMPLE_COVERAGE_INVERT]: 'sampleCoverage', [GL.SCISSOR_TEST]: enable, [GL.SCISSOR_BOX]: (gl, value) => gl.scissor(...value), [GL.STENCIL_TEST]: enable, [GL.STENCIL_CLEAR_VALUE]: (gl, value) => gl.clearStencil(value), [GL.STENCIL_WRITEMASK]: (gl, value) => gl.stencilMaskSeparate(GL.FRONT, value), [GL.STENCIL_BACK_WRITEMASK]: (gl, value) => gl.stencilMaskSeparate(GL.BACK, value), [GL.STENCIL_FUNC]: 'stencilFuncFront', [GL.STENCIL_REF]: 'stencilFuncFront', [GL.STENCIL_VALUE_MASK]: 'stencilFuncFront', [GL.STENCIL_BACK_FUNC]: 'stencilFuncBack', [GL.STENCIL_BACK_REF]: 'stencilFuncBack', [GL.STENCIL_BACK_VALUE_MASK]: 'stencilFuncBack', [GL.STENCIL_FAIL]: 'stencilOpFront', [GL.STENCIL_PASS_DEPTH_FAIL]: 'stencilOpFront', [GL.STENCIL_PASS_DEPTH_PASS]: 'stencilOpFront', [GL.STENCIL_BACK_FAIL]: 'stencilOpBack', [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: 'stencilOpBack', [GL.STENCIL_BACK_PASS_DEPTH_PASS]: 'stencilOpBack', [GL.VIEWPORT]: (gl, value) => gl.viewport(...value), // WEBGL1 PIXEL PACK/UNPACK MODES [GL.PACK_ALIGNMENT]: pixelStorei, [GL.UNPACK_ALIGNMENT]: pixelStorei, [GL.UNPACK_FLIP_Y_WEBGL]: pixelStorei, [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: pixelStorei, [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: pixelStorei, // WEBGL2 PIXEL PACK/UNPACK MODES // RASTERIZER_DISCARD ... [GL.PACK_ROW_LENGTH]: pixelStorei, [GL.PACK_SKIP_PIXELS]: pixelStorei, [GL.PACK_SKIP_ROWS]: pixelStorei, [GL.UNPACK_ROW_LENGTH]: pixelStorei, [GL.UNPACK_IMAGE_HEIGHT]: pixelStorei, [GL.UNPACK_SKIP_PIXELS]: pixelStorei, [GL.UNPACK_SKIP_ROWS]: pixelStorei, [GL.UNPACK_SKIP_IMAGES]: pixelStorei, // Function-style setters framebuffer: (gl, framebuffer) => { // accepts 1) a WebGLFramebuffer 2) null (default framebuffer), or 3) luma.gl Framebuffer class // framebuffer is null when restoring to default framebuffer, otherwise use the WebGL handle. const handle = framebuffer && 'handle' in framebuffer ? framebuffer.handle : framebuffer; return gl.bindFramebuffer(GL.FRAMEBUFFER, handle); }, blend: (gl, value) => (value ? gl.enable(GL.BLEND) : gl.disable(GL.BLEND)), blendColor: (gl, value) => gl.blendColor(...value), blendEquation: (gl, args) => { args = isArray(args) ? args : [args, args]; gl.blendEquationSeparate(...args); }, blendFunc: (gl, args) => { args = isArray(args) && args.length === 2 ? [...args, ...args] : args; gl.blendFuncSeparate(...args); }, clearColor: (gl, value) => gl.clearColor(...value), clearDepth: (gl, value) => gl.clearDepth(value), clearStencil: (gl, value) => gl.clearStencil(value), colorMask: (gl, value) => gl.colorMask(...value), cull: (gl, value) => (value ? gl.enable(GL.CULL_FACE) : gl.disable(GL.CULL_FACE)), cullFace: (gl, value) => gl.cullFace(value), depthTest: (gl, value) => (value ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST)), depthFunc: (gl, value) => gl.depthFunc(value), depthMask: (gl, value) => gl.depthMask(value), depthRange: (gl, value) => gl.depthRange(...value), dither: (gl, value) => (value ? gl.enable(GL.DITHER) : gl.disable(GL.DITHER)), derivativeHint: (gl, value) => { // gl1: 'OES_standard_derivatives' gl.hint(GL.FRAGMENT_SHADER_DERIVATIVE_HINT, value); }, frontFace: (gl, value) => gl.frontFace(value), mipmapHint: (gl, value) => gl.hint(GL.GENERATE_MIPMAP_HINT, value), lineWidth: (gl, value) => gl.lineWidth(value), polygonOffsetFill: (gl, value) => value ? gl.enable(GL.POLYGON_OFFSET_FILL) : gl.disable(GL.POLYGON_OFFSET_FILL), polygonOffset: (gl, value) => gl.polygonOffset(...value), sampleCoverage: (gl, value) => gl.sampleCoverage(...value), scissorTest: (gl, value) => (value ? gl.enable(GL.SCISSOR_TEST) : gl.disable(GL.SCISSOR_TEST)), scissor: (gl, value) => gl.scissor(...value), stencilTest: (gl, value) => (value ? gl.enable(GL.STENCIL_TEST) : gl.disable(GL.STENCIL_TEST)), stencilMask: (gl, value) => { value = isArray(value) ? value : [value, value]; const [mask, backMask] = value; gl.stencilMaskSeparate(GL.FRONT, mask); gl.stencilMaskSeparate(GL.BACK, backMask); }, stencilFunc: (gl, args) => { args = isArray(args) && args.length === 3 ? [...args, ...args] : args; const [func, ref, mask, backFunc, backRef, backMask] = args; gl.stencilFuncSeparate(GL.FRONT, func, ref, mask); gl.stencilFuncSeparate(GL.BACK, backFunc, backRef, backMask); }, stencilOp: (gl, args) => { args = isArray(args) && args.length === 3 ? [...args, ...args] : args; const [sfail, dpfail, dppass, backSfail, backDpfail, backDppass] = args; gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass); gl.stencilOpSeparate(GL.BACK, backSfail, backDpfail, backDppass); }, viewport: (gl, value) => gl.viewport(...value) }; function getValue(glEnum, values, cache) { return values[glEnum] !== undefined ? values[glEnum] : cache[glEnum]; } // COMPOSITE_WEBGL_PARAMETER_ export const GL_COMPOSITE_PARAMETER_SETTERS = { blendEquation: (gl, values, cache) => gl.blendEquationSeparate( getValue(GL.BLEND_EQUATION_RGB, values, cache), getValue(GL.BLEND_EQUATION_ALPHA, values, cache) ), blendFunc: (gl, values, cache) => gl.blendFuncSeparate( getValue(GL.BLEND_SRC_RGB, values, cache), getValue(GL.BLEND_DST_RGB, values, cache), getValue(GL.BLEND_SRC_ALPHA, values, cache), getValue(GL.BLEND_DST_ALPHA, values, cache) ), polygonOffset: (gl, values, cache) => gl.polygonOffset( getValue(GL.POLYGON_OFFSET_FACTOR, values, cache), getValue(GL.POLYGON_OFFSET_UNITS, values, cache) ), sampleCoverage: (gl, values, cache) => gl.sampleCoverage( getValue(GL.SAMPLE_COVERAGE_VALUE, values, cache), getValue(GL.SAMPLE_COVERAGE_INVERT, values, cache) ), stencilFuncFront: (gl, values, cache) => gl.stencilFuncSeparate( GL.FRONT, getValue(GL.STENCIL_FUNC, values, cache), getValue(GL.STENCIL_REF, values, cache), getValue(GL.STENCIL_VALUE_MASK, values, cache) ), stencilFuncBack: (gl, values, cache) => gl.stencilFuncSeparate( GL.BACK, getValue(GL.STENCIL_BACK_FUNC, values, cache), getValue(GL.STENCIL_BACK_REF, values, cache), getValue(GL.STENCIL_BACK_VALUE_MASK, values, cache) ), stencilOpFront: (gl, values, cache) => gl.stencilOpSeparate( GL.FRONT, getValue(GL.STENCIL_FAIL, values, cache), getValue(GL.STENCIL_PASS_DEPTH_FAIL, values, cache), getValue(GL.STENCIL_PASS_DEPTH_PASS, values, cache) ), stencilOpBack: (gl, values, cache) => gl.stencilOpSeparate( GL.BACK, getValue(GL.STENCIL_BACK_FAIL, values, cache), getValue(GL.STENCIL_BACK_PASS_DEPTH_FAIL, values, cache), getValue(GL.STENCIL_BACK_PASS_DEPTH_PASS, values, cache) ) }; // Setter functions intercepted for cache updates export const GL_HOOKED_SETTERS = { // GENERIC SETTERS enable: (update, capability) => update({ [capability]: true }), disable: (update, capability) => update({ [capability]: false }), pixelStorei: (update, pname, value) => update({ [pname]: value }), hint: (update, pname, hint) => update({ [pname]: hint }), // SPECIFIC SETTERS useProgram: (update, value) => update({ [GL.CURRENT_PROGRAM]: value, }), bindRenderbuffer: (update, target, value) => update({ [GL.RENDERBUFFER_BINDING]: value }), bindTransformFeedback: (update, target, value) => update({ [GL.TRANSFORM_FEEDBACK_BINDING]: value }), bindVertexArray: (update, value) => update({ [GL.VERTEX_ARRAY_BINDING]: value }), bindFramebuffer: (update, target, framebuffer) => { switch (target) { case GL.FRAMEBUFFER: return update({ [GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer, [GL.READ_FRAMEBUFFER_BINDING]: framebuffer }); case GL.DRAW_FRAMEBUFFER: return update({[GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer}); case GL.READ_FRAMEBUFFER: return update({[GL.READ_FRAMEBUFFER_BINDING]: framebuffer}); default: return null; } }, bindBuffer: (update, target, buffer) => { const pname = ({ [GL.ARRAY_BUFFER]: [GL.ARRAY_BUFFER_BINDING], [GL.COPY_READ_BUFFER]: [GL.COPY_READ_BUFFER_BINDING], [GL.COPY_WRITE_BUFFER]: [GL.COPY_WRITE_BUFFER_BINDING], [GL.PIXEL_PACK_BUFFER]: [GL.PIXEL_PACK_BUFFER_BINDING], [GL.PIXEL_UNPACK_BUFFER]: [GL.PIXEL_UNPACK_BUFFER_BINDING] })[target]; if (pname) { return update({[pname]: buffer}); } // targets that should not be cached return {valueChanged: true}; }, blendColor: (update, r, g, b, a) => update({ [GL.BLEND_COLOR]: new Float32Array([r, g, b, a]) }), blendEquation: (update, mode) => update({ [GL.BLEND_EQUATION_RGB]: mode, [GL.BLEND_EQUATION_ALPHA]: mode }), blendEquationSeparate: (update, modeRGB, modeAlpha) => update({ [GL.BLEND_EQUATION_RGB]: modeRGB, [GL.BLEND_EQUATION_ALPHA]: modeAlpha }), blendFunc: (update, src, dst) => update({ [GL.BLEND_SRC_RGB]: src, [GL.BLEND_DST_RGB]: dst, [GL.BLEND_SRC_ALPHA]: src, [GL.BLEND_DST_ALPHA]: dst }), blendFuncSeparate: (update, srcRGB, dstRGB, srcAlpha, dstAlpha) => update({ [GL.BLEND_SRC_RGB]: srcRGB, [GL.BLEND_DST_RGB]: dstRGB, [GL.BLEND_SRC_ALPHA]: srcAlpha, [GL.BLEND_DST_ALPHA]: dstAlpha }), clearColor: (update, r, g, b, a) => update({ [GL.COLOR_CLEAR_VALUE]: new Float32Array([r, g, b, a]) }), clearDepth: (update, depth) => update({ [GL.DEPTH_CLEAR_VALUE]: depth }), clearStencil: (update, s) => update({ [GL.STENCIL_CLEAR_VALUE]: s }), colorMask: (update, r, g, b, a) => update({ [GL.COLOR_WRITEMASK]: [r, g, b, a] }), cullFace: (update, mode) => update({ [GL.CULL_FACE_MODE]: mode }), depthFunc: (update, func) => update({ [GL.DEPTH_FUNC]: func }), depthRange: (update, zNear, zFar) => update({ [GL.DEPTH_RANGE]: new Float32Array([zNear, zFar]) }), depthMask: (update, mask) => update({ [GL.DEPTH_WRITEMASK]: mask }), frontFace: (update, face) => update({ [GL.FRONT_FACE]: face }), lineWidth: (update, width) => update({ [GL.LINE_WIDTH]: width }), polygonOffset: (update, factor, units) => update({ [GL.POLYGON_OFFSET_FACTOR]: factor, [GL.POLYGON_OFFSET_UNITS]: units }), sampleCoverage: (update, value, invert) => update({ [GL.SAMPLE_COVERAGE_VALUE]: value, [GL.SAMPLE_COVERAGE_INVERT]: invert }), scissor: (update, x, y, width, height) => update({ [GL.SCISSOR_BOX]: new Int32Array([x, y, width, height]) }), stencilMask: (update, mask) => update({ [GL.STENCIL_WRITEMASK]: mask, [GL.STENCIL_BACK_WRITEMASK]: mask }), stencilMaskSeparate: (update, face, mask) => update({ [face === GL.FRONT ? GL.STENCIL_WRITEMASK : GL.STENCIL_BACK_WRITEMASK]: mask }), stencilFunc: (update, func, ref, mask) => update({ [GL.STENCIL_FUNC]: func, [GL.STENCIL_REF]: ref, [GL.STENCIL_VALUE_MASK]: mask, [GL.STENCIL_BACK_FUNC]: func, [GL.STENCIL_BACK_REF]: ref, [GL.STENCIL_BACK_VALUE_MASK]: mask }), stencilFuncSeparate: (update, face, func, ref, mask) => update({ [face === GL.FRONT ? GL.STENCIL_FUNC : GL.STENCIL_BACK_FUNC]: func, [face === GL.FRONT ? GL.STENCIL_REF : GL.STENCIL_BACK_REF]: ref, [face === GL.FRONT ? GL.STENCIL_VALUE_MASK : GL.STENCIL_BACK_VALUE_MASK]: mask }), stencilOp: (update, fail, zfail, zpass) => update({ [GL.STENCIL_FAIL]: fail, [GL.STENCIL_PASS_DEPTH_FAIL]: zfail, [GL.STENCIL_PASS_DEPTH_PASS]: zpass, [GL.STENCIL_BACK_FAIL]: fail, [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail, [GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass }), stencilOpSeparate: (update, face, fail, zfail, zpass) => update({ [face === GL.FRONT ? GL.STENCIL_FAIL : GL.STENCIL_BACK_FAIL]: fail, [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_FAIL : GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail, [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_PASS : GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass }), viewport: (update, x, y, width, height) => update({ [GL.VIEWPORT]: [x, y, width, height] }) }; // GETTER TABLE - FOR READING OUT AN ENTIRE CONTEXT const isEnabled = (gl, key) => gl.isEnabled(key); // Exceptions for any keys that cannot be queried by gl.getParameters export const GL_PARAMETER_GETTERS = { [GL.BLEND]: isEnabled, [GL.CULL_FACE]: isEnabled, [GL.DEPTH_TEST]: isEnabled, [GL.DITHER]: isEnabled, [GL.POLYGON_OFFSET_FILL]: isEnabled, [GL.SAMPLE_ALPHA_TO_COVERAGE]: isEnabled, [GL.SAMPLE_COVERAGE]: isEnabled, [GL.SCISSOR_TEST]: isEnabled, [GL.STENCIL_TEST]: isEnabled, // WebGL 2 [GL.RASTERIZER_DISCARD]: isEnabled }; export const NON_CACHE_PARAMETERS = new Set([ // setter not intercepted GL.ACTIVE_TEXTURE, GL.TRANSFORM_FEEDBACK_ACTIVE, GL.TRANSFORM_FEEDBACK_PAUSED, // setters bindBufferRange/bindBufferBase cannot be pruned based on cache GL.TRANSFORM_FEEDBACK_BUFFER_BINDING, GL.UNIFORM_BUFFER_BINDING, // states depending on VERTEX_ARRAY_BINDING GL.ELEMENT_ARRAY_BUFFER_BINDING, // states depending on READ_FRAMEBUFFER_BINDING GL.IMPLEMENTATION_COLOR_READ_FORMAT, GL.IMPLEMENTATION_COLOR_READ_TYPE, // states depending on FRAMEBUFFER_BINDING GL.READ_BUFFER, GL.DRAW_BUFFER0, GL.DRAW_BUFFER1, GL.DRAW_BUFFER2, GL.DRAW_BUFFER3, GL.DRAW_BUFFER4, GL.DRAW_BUFFER5, GL.DRAW_BUFFER6, GL.DRAW_BUFFER7, GL.DRAW_BUFFER8, GL.DRAW_BUFFER9, GL.DRAW_BUFFER10, GL.DRAW_BUFFER11, GL.DRAW_BUFFER12, GL.DRAW_BUFFER13, GL.DRAW_BUFFER14, GL.DRAW_BUFFER15, // states depending on ACTIVE_TEXTURE GL.SAMPLER_BINDING, GL.TEXTURE_BINDING_2D, GL.TEXTURE_BINDING_2D_ARRAY, GL.TEXTURE_BINDING_3D, GL.TEXTURE_BINDING_CUBE_MAP ]);
the_stack
import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { isDefined, isNumber, isObject, isString, } from '@dynatrace/barista-components/core'; import { DtFilterFieldValidator } from './filter-field-validation'; import { DtFilterFieldDataSource } from './filter-field-data-source'; import { DtNodeDef, dtAutocompleteDef, isDtGroupDef, isDtAutocompleteDef, dtOptionDef, dtGroupDef, dtFreeTextDef, dtRangeDef, dtMultiSelectDef, } from './types'; /** The simple Shape of an object to be usable as a option in an autocomplete or free-text */ export interface DtFilterFieldDefaultDataSourceSimpleOption { name: string; id?: string | number; disabled?: boolean; } export type DtFilterFieldDefaultDataSourceOption = | DtFilterFieldDefaultDataSourceSimpleOption | (DtFilterFieldDefaultDataSourceAutocomplete & DtFilterFieldDefaultDataSourceSimpleOption) | (DtFilterFieldDefaultDataSourceFreeText & DtFilterFieldDefaultDataSourceSimpleOption) | (DtFilterFieldDefaultDataSourceRange & DtFilterFieldDefaultDataSourceSimpleOption) | (DtFilterFieldDefaultDataSourceMultiSelect & DtFilterFieldDefaultDataSourceSimpleOption); /** Shape of an object to be usable as a group in a free-text */ export interface DtFilterFieldDefaultDataSourceSimpleGroup { name: string; options: Array<DtFilterFieldDefaultDataSourceSimpleOption>; } /** Shape of an object to be usable as a group in an autocomplete */ export interface DtFilterFieldDefaultDataSourceGroup extends DtFilterFieldDefaultDataSourceSimpleGroup { options: Array<DtFilterFieldDefaultDataSourceOption>; } /** Shape of an object to be usable as an autocomplete */ export interface DtFilterFieldDefaultDataSourceAutocomplete { autocomplete: Array< DtFilterFieldDefaultDataSourceOption | DtFilterFieldDefaultDataSourceGroup >; distinct?: boolean; async?: boolean; partial?: boolean; partialHintMessage?: string; } /** Shape of an object to be usable as an multiselect */ export interface DtFilterFieldDefaultDataSourceMultiSelect { multiOptions: Array< DtFilterFieldDefaultDataSourceOption | DtFilterFieldDefaultDataSourceGroup >; async?: boolean; partial?: boolean; } /** Shape of an object to be usable as a free text variant */ export interface DtFilterFieldDefaultDataSourceFreeText { suggestions: Array< | DtFilterFieldDefaultDataSourceSimpleOption | DtFilterFieldDefaultDataSourceSimpleGroup >; validators: DtFilterFieldValidator[]; async?: boolean; unique?: boolean; defaultSearch?: boolean; } export interface DtFilterFieldDefaultDataSourceRange { range: { unit: string; operators: { range?: boolean; equal?: boolean; greaterThanEqual?: boolean; lessThanEqual?: boolean; }; }; unique?: boolean; } export type DtFilterFieldDefaultDataSourceType = | DtFilterFieldDefaultDataSourceOption | DtFilterFieldDefaultDataSourceGroup | DtFilterFieldDefaultDataSourceAutocomplete | DtFilterFieldDefaultDataSourceMultiSelect | DtFilterFieldDefaultDataSourceFreeText | DtFilterFieldDefaultDataSourceRange; // tslint:disable: no-bitwise /** * DataSource that accepts a client side data object with a specific structure (described below) * and includes support for filtering autocomplete options and groups, as well as suggestions for free text fields. * It also allows for customizing the predicate function which will be used to filter options and groups. * * The DataSource can take object structures like the following: * * To render an autocomplete * ``` * { * autocomplete: [ * { name: "Option 1" }, // An option can be an object with a name property * "Option 2", // Or just a string * { * name: "Group 1", // It also accepts a group, that consists of a name property * options: [ // or child options * { name: "Option 3"}, * "Option 4" * ] * } * ] * } * ``` * * It is also possible to set a distinct property on the autocomplete object, so the user can select options only once: * { * distinct: true, * autocomplete: [ * { name: "Option 1" }, * "Option 2" * ] * } * * To render a free-text input * ``` * { * suggestions: [] // To render just an input field provide an empty suggestion array * } * ``` * or * ``` * { * suggestions: [ // Provide autocomplete options as suggestions * { name: "Suggestion 1" }, * "Suggestion 2" * ] * } * ``` * * To render a range input for all operators and the value is in seconds. * ``` * { * range: { * unit: 's', * operators: { * range: true, * equal: true, * greaterThanEqual: true, * lessThanEqual: true, * }, * } * } */ export class DtFilterFieldDefaultDataSource implements DtFilterFieldDataSource<DtFilterFieldDefaultDataSourceType> { private readonly _data$: BehaviorSubject<DtFilterFieldDefaultDataSourceType | null>; /** Structure of data that is used, transformed and rendered by the filter-field. */ get data(): DtFilterFieldDefaultDataSourceType | null { return this._data$.value; } set data(data: DtFilterFieldDefaultDataSourceType | null) { this._data$.next(data); } constructor(initialData?: DtFilterFieldDefaultDataSourceType) { this._data$ = new BehaviorSubject<DtFilterFieldDefaultDataSourceType | null>( initialData ? initialData : null, ); } /** * Used by the DtFilterField. Called when it connects to the data source. * Should return a stream of data that will be transformed, filtered and * displayed by the DtFilterFieldViewer (filter-field) */ connect(): Observable<DtNodeDef<DtFilterFieldDefaultDataSourceType> | null> { return this._data$.pipe(map((data) => this.transformObject(data))); } /** Used by the DtFilterField. Called when it is destroyed. No-op. */ disconnect(): void { this._data$.complete(); } /** Whether the provided data object is of type AutocompleteData */ isAutocomplete( // tslint:disable-next-line: no-any data: any, ): data is DtFilterFieldDefaultDataSourceAutocomplete { return isObject(data) && Array.isArray(data.autocomplete); } /** Whether the provided data object is of type OptionData */ // tslint:disable-next-line: no-any isOption(data: any): data is DtFilterFieldDefaultDataSourceOption { return isObject(data) && typeof data.name === 'string'; } /** Whether the provided data object is of type GroupData */ // tslint:disable-next-line: no-any isGroup(data: any): data is DtFilterFieldDefaultDataSourceGroup { return ( isObject(data) && typeof data.name === 'string' && Array.isArray(data.options) ); } /** Whether the provided data object is of type FreeTextData */ // tslint:disable-next-line: no-any isFreeText(data: any): data is DtFilterFieldDefaultDataSourceFreeText { return isObject(data) && Array.isArray(data.suggestions); } /** Whether the provided data object is of type MultiSelectData */ isMultiSelect( // tslint:disable-next-line: no-any data: any, ): data is DtFilterFieldDefaultDataSourceMultiSelect { return isObject(data) && Array.isArray(data.multiOptions); } /** Whether the provided data object is of type RangeData */ // tslint:disable-next-line: no-any isRange(data: any): data is DtFilterFieldDefaultDataSourceRange { return isObject(data) && isObject(data.range); } /** Transforms the provided data into a DtNodeDef which contains a DtAutocompleteDef. */ transformAutocomplete( data: DtFilterFieldDefaultDataSourceAutocomplete, ): DtNodeDef<DtFilterFieldDefaultDataSourceAutocomplete> { const def = dtAutocompleteDef( data, null, [], !!data.distinct, !!data.async, !!data.partial, data.partialHintMessage, ); def.autocomplete!.optionsOrGroups = this.transformList( data.autocomplete, def, ); return def; } /** Transforms the provided data into a DtNodeDef which contains a DtMultiSelectDef. */ transformMultiSelect( data: DtFilterFieldDefaultDataSourceMultiSelect, ): DtNodeDef<DtFilterFieldDefaultDataSourceMultiSelect> { const def = dtMultiSelectDef(data, null, [], !!data.async, !!data.partial); def.multiSelect!.multiOptions = this.transformList(data.multiOptions, def); return def; } /** Transforms the provided data into a DtNodeDef which contains a DtOptionDef. */ transformOption( data: DtFilterFieldDefaultDataSourceOption, parentAutocompleteOrOption: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, existingDef: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, ): DtNodeDef<DtFilterFieldDefaultDataSourceOption> { const parentGroup = isDtGroupDef< DtFilterFieldDefaultDataSourceGroup, DtFilterFieldDefaultDataSourceOption >(parentAutocompleteOrOption as any) ? parentAutocompleteOrOption : null; const parentAutocomplete = parentGroup !== null ? parentGroup.group!.parentAutocomplete : isDtAutocompleteDef(parentAutocompleteOrOption) ? (parentAutocompleteOrOption as DtNodeDef) : null; return dtOptionDef<DtFilterFieldDefaultDataSourceOption>( data, existingDef, data.name, isNumber(data.id) || isString(data.id) ? `${data.id}` : null, parentAutocomplete, parentGroup, data.disabled, ); } /** Transforms the provided data into a DtNodeDef which contains a DtGroupDef. */ transformGroup( data: DtFilterFieldDefaultDataSourceGroup, parentAutocomplete: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, existingDef: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, ): DtNodeDef<DtFilterFieldDefaultDataSourceGroup> { const def = dtGroupDef< DtFilterFieldDefaultDataSourceGroup, DtFilterFieldDefaultDataSourceOption >(data, existingDef, data.name, [], parentAutocomplete); def.group.options = this.transformList( data.options, def, ) as DtNodeDef<DtFilterFieldDefaultDataSourceOption>[]; return def; } /** Transforms the provided data into a DtNodeDef which contains a DtFreeTextDef. */ transformFreeText( data: DtFilterFieldDefaultDataSourceFreeText, ): DtNodeDef<DtFilterFieldDefaultDataSourceFreeText> { const def = dtFreeTextDef( data, null, [], data.validators, isDefined(data.unique) ? data.unique! : false, !!data.defaultSearch, !!data.async, ); def.freeText!.suggestions = this.transformList(data.suggestions, def); return def; } /** Transforms the provided data into a DtNodeDef which contains a DtRangeDef. */ transformRange( data: DtFilterFieldDefaultDataSourceRange, ): DtNodeDef<DtFilterFieldDefaultDataSourceRange> { return dtRangeDef( data, null, !!data.range.operators.range, !!data.range.operators.equal, !!data.range.operators.greaterThanEqual, !!data.range.operators.lessThanEqual, data.range.unit, isDefined(data.unique) ? data.unique! : false, ); } /** Transforms the provided data into a DtNodeDef. */ transformObject( data: DtFilterFieldDefaultDataSourceType | null, parent: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, ): DtNodeDef<DtFilterFieldDefaultDataSourceType> | null { let def: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null; if (this.isAutocomplete(data)) { def = this.transformAutocomplete(data); } else if (this.isFreeText(data)) { def = this.transformFreeText(data); } else if (this.isRange(data)) { def = this.transformRange(data); } else if (this.isMultiSelect(data)) { def = this.transformMultiSelect(data); } if (this.isGroup(data)) { def = this.transformGroup(data); } else if (this.isOption(data)) { def = this.transformOption( data, parent as DtNodeDef<DtFilterFieldDefaultDataSourceAutocomplete>, def, ); } return def; } /** Transforms the provided list of data objects into an array of DtNodeDefs. */ transformList( list: Array<DtFilterFieldDefaultDataSourceType>, parent: DtNodeDef<DtFilterFieldDefaultDataSourceType> | null = null, ): DtNodeDef<DtFilterFieldDefaultDataSourceType>[] { return list .map((item) => this.transformObject(item, parent)) .filter( (item) => item !== null, ) as DtNodeDef<DtFilterFieldDefaultDataSourceType>[]; } }
the_stack
import { loadModule, FILESTACK_MODULES } from '@filestack/loader'; import { FilestackError, FilestackErrorType } from './../filestack_error'; import { Client } from './client'; import { FSProgressEvent, UploadOptions, WorkflowConfig } from './api/upload/types'; import { getValidator, PickerParamsSchema } from './../schema'; export interface PickerInstance { /** * Close picker. This operation is idempotent. */ close: () => Promise<void>; /** * Cancel picker uploads. This operation is idempotent. */ cancel: () => Promise<void>; /** * Open picker. This operation is idempotent. */ open: () => Promise<void>; /** * Specify a list of files to open in the picker for cropping * * ### Example * * ```js * // <input id="fileSelect" type="file"> * * const inputEl = document.getElementById('fileSelect'); * const picker = client.picker({ * onUploadDone: res => console.log(res), * }); * * inputEl.addEventListener('change', (e) => { * picker.crop(e.target.files); * }); * * // Or pass an array of URL strings * const urls = [ * 'https://d1wtqaffaaj63z.cloudfront.net/images/fox_in_forest1.jpg', * 'https://d1wtqaffaaj63z.cloudfront.net/images/sail.jpg', * ]; * picker.crop(urls); * ``` */ crop: (files: any[]) => Promise<void>; } export interface PickerCroppedData { cropArea: { /** * [x, y] */ position: [number, number]; /** * [width, height] */ size: [number, number]; }; /** * [width, height] */ originalImageSize: [number, number]; } export enum RotateDirection { cw = 'CW', ccw= 'CCW', } export interface PickerRotatedData { /** * Amount rotated in degrees. */ value: number; /** * Can be CW or CCW (clockwise / counter-clockwise) */ direction: RotateDirection; } export interface PickerFileMetadata { /** * The cloud container for the uploaded file. */ container?: string; /** * Position and size information for cropped images. */ cropped?: PickerCroppedData; /** * Name of the file. */ filename: string; /** * Filestack handle for the uploaded file. */ handle: string; /** * The hash-prefixed cloud storage path. */ key?: string; /** * The MIME type of the file. */ mimetype: string; /** * Properties of the local binary file. Also see the pick option `exposeOriginalFile` if you want the underlying `File` object. */ originalFile?: object | File; /** * The origin of the file, e.g. /Folder/file.jpg. */ originalPath: string; /** * Direction and value information for rotated images. */ rotated?: PickerRotatedData; /** * Size in bytes of the uploaded file. */ size: number; /** * The source from where the file was picked. */ source: string; /** * Indicates Filestack transit status. */ status?: string; /** * A uuid for tracking this file in callbacks. */ uploadId: string; /** * The Filestack CDN URL for the uploaded file. */ url: string; } export interface CustomAuthTextOptions { [key: string]: { top?: string[], bottom?: string[] }; } export interface PickerResponse { filesUploaded: PickerFileMetadata[]; filesFailed: PickerFileMetadata[]; } export interface PickerFileCallback { (file: PickerFileMetadata): void | Promise<any>; } export interface PickerFileWithTokenCallback { (file: PickerFileMetadata, token?: {pause?: () => void, resume?: () => void, cancel?: () => void}): void | Promise<any>; } export interface PickerFileCancelCallback { (file: PickerFileMetadata): void; } export interface PickerFileErrorCallback { (file: PickerFileMetadata, error: Error): void; } export interface PickerFileProgressCallback { (file: PickerFileMetadata, event: FSProgressEvent): void; } export interface PickerUploadStartedCallback { (files: PickerFileMetadata[]): void; } export interface PickerUploadDoneCallback { (files: PickerResponse): void; } export enum PickerDisplayMode { inline = 'inline', overlay = 'overlay', dropPane = 'dropPane', } export interface PickerDropPaneOptions { /** * Toggle the crop UI for dropped files. */ cropFiles?: boolean; /** * Customize the text content in the drop pane. */ customText?: string; /** * Disable the file input on click. This does not disable the `onClick` callback. */ disableClick?: boolean; /** * Toggle the full-page drop zone overlay. */ overlay?: boolean; onDragEnter?: (evt: DragEvent) => void; onDragLeave?: () => void; onDragOver?: (evt: DragEvent) => void; onDrop?: (evt: DragEvent) => void; /** * `onSuccess` must be used instead of `onUploadDone`. The drop pane uses its own callbacks for compatibility purposes. This might eventually change. */ onSuccess?: (files: PickerFileMetadata[]) => void; onError?: (files: PickerFileMetadata[]) => void; onProgress?: (percent: number) => void; onClick?: (evt: any) => void; /** * Toggle icon element in drop pane. */ showIcon?: boolean; /** * Toggle upload progress display. */ showProgress?: boolean; } export interface PickerStoreOptions { /** * Location for stored file. One of 's3', 'gcs', 'azure', 'rackspace', or 'dropbox'. */ location?: string; /** * Specify storage container. */ container?: string; /** * Set container path. Indicate a folder by adding a trailing slash. Without a trailing slash all files will be stored to the same object. */ path?: string; /** * Specify S3 region. */ region?: string; /** * S3 container access. 'public' or 'private'. */ access?: string; /** * Workflows ids to run after upload */ workflows?: string[] | WorkflowConfig[]; } export interface PickerCustomText { // Actions Upload?: string; 'Upload more'?: string; 'Deselect All'?: string; 'View/Edit Selected'?: string; 'Sign Out'?: string; // Source Labels 'My Device'?: string; 'Web Search'?: string; 'Take Photo'?: string; 'Link (URL)'?: string; 'Record Video'?: string; 'Record Audio'?: string; // Custom Source 'Custom Source'?: string; // Footer Text Add?: string; 'more file'?: string; 'more files'?: string; // Cloud 'Connect {providerName}'?: string; 'Select Files from {providerName}'?: string; 'You need to authenticate with {providerName}.'?: string; 'A new page will open to connect your account.'?: string; 'We only extract images and never modify or delete them.'?: string; 'To disconnect from {providerName} click "Sign out" button in the menu.'?: string; 'Sign in with Google'?: string; 'Go back'?: string; 'This folder is empty.'?: string; // Summary Files?: string; Images?: string; Uploaded?: string; Uploading?: string; Completed?: string; Filter?: string; 'Cropped Images'?: string; 'Edited Images'?: string; 'Selected Files'?: string; 'Crop is required on images'?: string; // Transform Crop?: string; Circle?: string; Rotate?: string; Mask?: string; Revert?: string; Edit?: string; Reset?: string; Done?: string; Save?: string; Next?: string; 'Edit Image'?: string; 'This image cannot be edited'?: string; // Retry messaging 'Connection Lost'?: string; 'Failed While Uploading'?: string; 'Retrying in'?: string; 'Try again'?: string; 'Try now'?: string; // Local File Source 'Drag and Drop, Copy and Paste Files'?: string; 'or Drag and Drop, Copy and Paste Files'?: string; 'Select Files to Upload'?: string; 'Select From'?: string; 'Drop your files anywhere'?: string; // Input placeholders 'Enter a URL'?: string; 'Search images'?: string; // Webcam Source 'Webcam Disabled'?: string; 'Webcam Not Supported'?: string; 'Please enable your webcam to take a photo.'?: string; 'Your current browser does not support webcam functionality.'?: string; 'We suggest using Chrome or Firefox.'?: string; // Error Notifications 'File {displayName} is not an accepted file type. The accepted file types are {types}'?: string; 'File {displayName} is too big. The accepted file size is less than {roundFileSize}'?: string; 'Our file upload limit is {maxFiles} {filesText}'?: string; 'No search results found for "{search}"'?: string; 'An error occurred. Please try again.'?: string; } export interface PickerOptions { /** * Restrict file types that are allowed to be picked. Formats accepted: * - .pdf <- any file extension * - image/jpeg <- any mime type commonly known by browsers * - image/* <- accept all types of images * - video/* <- accept all types of video files * - audio/* <- accept all types of audio files * - application/* <- accept all types of application files * - text/* <- accept all types of text files */ accept?: string | string[]; /** * Custom accept check function * ```javascript * acceptFn: (file, options) => { * return options.mimeFromMagicBytes(file.originalFile).then((res) => { // we can check mimetype from magic bytes * //console.log(options.mimeFromExtension(file.originalFile.name)); // or check extension from filestack extensions database * // throw new Error('Cannot accept that file') // we can throw exception to block file upload * // return Promise.reject('Cannot accept that file'') // or reject a promise * return Promise.resolve(); * }); * } * ``` */ acceptFn?: (PickerFileMetadata, PickerAcceptFnOptions) => Promise<string>; /** * Prevent modal close on upload failure and allow users to retry. */ allowManualRetry?: boolean; /** * Valid sources are: * - local_file_system - Default * - url - Default * - imagesearch - Default * - facebook - Default * - instagram - Default * - googledrive - Default * - dropbox - Default * - webcam - Uses device menu on mobile. Not currently supported in Safari and IE. * - video - Uses device menu on mobile. Not currently supported in Safari and IE. * - audio - Uses device menu on mobile. Not currently supported in Safari and IE. * - box * - github * - gmail * - googlephotos * - onedrive * - onedriveforbusiness * - customsource - Configure this in your Filestack Dev Portal. * - unsplash */ fromSources?: string[]; /** * Container where picker should be appended. Only relevant for `inline` and `dropPane` display modes. */ container?: string | Node; /** * Turn on cleaning JPEG image exif. Method can keep image orientation or color profiles * ```javascript * cleanupImageExif: { * keepOrientation: true * keepICCandAPP: true * } * ``` */ cleanupImageExif?: boolean | { keepOrientation?: boolean, keepICCandAPP?: boolean }; /** * Customize the text on the cloud authentication screen in Picker. * Use a cloud source name (see [[PickerOptions.fromSources]]) * or a 'default' as a key, then put your custom notice or consent * to the 'top' or the 'bottom' key to show it respectivly above or under 'Connect button'. * * ```javascript * customAuthText: { * // use it for every cloud authentication screen * default: { * top: [ * 'default top first line', * 'default top second line' * ], * bottom: [ * 'default bottom first line', * 'default bottom second line' * ] * }, * // override a default bottom text for only gmail * gmail: { * bottom: [ * 'We need your permission to access your data and', * 'process it with our machine learning system.' * ] * } * } * ``` */ customAuthText?: CustomAuthTextOptions; /** * Picker display mode, one of `'inline'`, `'overlay'`, `'dropPane'` - default is `'overlay'`. */ displayMode?: PickerDisplayMode; /** * Max number of files to upload concurrently. Default is 4. */ concurrency?: number; /** * Set the default container for your custom source. */ customSourceContainer?: string; /** * Set the default path for your custom source container. */ customSourcePath?: string; /** * Set the display name for the custom source. */ customSourceName?: string; /** * Provide an object for mapping picker strings to your own strings. * Strings surrounded by brackets, `{ foobar }`, are interpolated with runtime values. * Source labels are also available to override, e.g. Facebook, Instagram, Dropbox, etc. */ customText?: PickerCustomText; /** * set support email to display in case of error */ supportEmail?: string; /** * When true removes the hash prefix on stored files. */ disableStorageKey?: boolean; /** * When true removes ability to edit images. */ disableTransformer?: boolean; /** * Disables local image thumbnail previews in the summary screen. */ disableThumbnails?: boolean; /** * Configure the drop pane behavior, i.e. when `displayMode` is `dropPane`. */ dropPane?: PickerDropPaneOptions; /** * When true the `originalFile` metadata will be the actual `File` object instead of a POJO */ exposeOriginalFile?: boolean; /** * Toggle the drop zone to be active on all views. Default is active only on local file source. */ globalDropZone?: boolean; /** * Hide the picker modal UI once uploading begins. Defaults to `false`. */ hideModalWhenUploading?: boolean; /** * Specify image dimensions. e.g. [800, 600]. Only for JPEG, PNG, and BMP files. * Local and cropped images will be resized (upscaled or downscaled) to the specified dimensions before uploading. * The original height to width ratio is maintained. To resize all images based on the width, set [width, null], e.g. [800, null]. * For the height set [null, height], e.g. [null, 600]. */ imageDim?: [number, number]; /** * Specify maximum image dimensions. e.g. [800, 600]. Only for JPEG, PNG, and BMP files. * Images bigger than the specified dimensions will be resized to the maximum size while maintaining the original aspect ratio. * The output will not be exactly 800x600 unless the imageMax matches the aspect ratio of the original image. */ imageMax?: [number, number]; /** * Specify minimum image dimensions. e.g. [800, 600]. Only for JPEG, PNG, and BMP files. * Images smaller than the specified dimensions will be upscaled to the minimum size while maintaining the original aspect ratio. * The output will not be exactly 800x600 unless the imageMin matches the aspect ratio of the original image. */ imageMin?: [number, number]; /** * Sets locale. Accepts: ca, da, de, en, es, fr, he, it, ja, ko, nl, no, pl, pt, sv, ru, vi, zh, tr */ lang?: string; /** * Minimum number of files required to start uploading. Defaults to 1. */ minFiles?: number; /** * Maximum number of files allowed to upload. Defaults to 1. */ maxFiles?: number; /** * Restrict selected files to a maximum number of bytes. (e.g. 10 \* 1024 \* 1024 for 10MB limit). */ maxSize?: number; /** * Default view type option for file browser */ viewType?: 'grid' | 'list'; /** * Timeout for error messages */ errorsTimeout?: number; /** * Specify [width, height] in pixels of the desktop modal. */ modalSize?: [number, number]; /** * Called when all uploads in a pick are cancelled. */ onCancel?: PickerUploadDoneCallback; /** * Called when the UI is exited. */ onClose?: () => void; /** * Called when the UI is mounted. * @param PickerInstance application handle */ onOpen?: (handle: PickerInstance) => void; /** * Called whenever user selects a file. * ### Example * * ```js * // Using to veto file selection * // If you throw any error in this function it will reject the file selection. * // The error message will be displayed to the user as an alert. * onFileSelected(file) { * if (file.size > 1000 * 1000) { * throw new Error('File too big, select something smaller than 1MB'); * } * } * * // Using to change selected file name * // NOTE: This currently only works for local uploads * onFileSelected(file) { * // It's important to return a new file by the end of this function. * return { ...file, name: 'foo' }; * } * ``` * * The callback function can also return a Promise to allow asynchronous validation logic. * You can pass a file object to `resolve` for changing the file name, it will behave the same as when * the file is returned from the non-async callback. * * ```js * onFileSelected(file) { * return new Promise((resolve, reject) => { * // Do something async * resolve(); * // Or reject the selection with reject() * }); * } * ``` */ onFileSelected?: PickerFileCallback; /** * Called when a file upload has been canceled. */ onFileUploadCancel?: PickerFileCancelCallback; /** * Called when a file begins uploading. */ onFileUploadStarted?: PickerFileWithTokenCallback; /** * Called when a file is done uploading. */ onFileUploadFinished?: PickerFileCallback; /** * Called when uploading a file fails. */ onFileUploadFailed?: PickerFileErrorCallback; /** * Called during multi-part upload progress events. Local files only. */ onFileUploadProgress?: PickerFileProgressCallback; /** * Called when file is cropped in picker */ onFileCropped?: PickerFileCallback; /** * Called when uploading starts (user initiates uploading). */ onUploadStarted?: PickerUploadStartedCallback; /** * Called when all files have been uploaded. */ onUploadDone?: PickerUploadDoneCallback; /** * Define a unique id for the application mount point. * May be useful for more advanced use cases. * For example, if you wish to have more than one picker instance open at once, * then each will need their own unique rootId. * * **Note:** This option is ignored when `displayMode` is `dropPane`. */ rootId?: string; /** * Whether to start uploading automatically when maxFiles is hit. Defaults to `false`. */ startUploadingWhenMaxFilesReached?: boolean; /** * Options for file storage. */ storeTo?: PickerStoreOptions; /** * Specify options for images passed to the crop UI. */ transformations?: PickerTransformationOptions; /** * Options for local file uploads. */ uploadConfig?: UploadOptions; /** * Start uploading immediately on file selection. Defaults to `true`. * @important The feature is can be enabled only if crop is disabled - disableTransformer: true */ uploadInBackground?: boolean; /** * Sets the resolution of recorded video. One of "320x240", "640x480" or "1280x720". Default is `"640x480"`. */ videoResolution?: string; /** * Use Sentry Breadcrumbs mechanism to log information about occured errors. * It can override global objects like console, error etc. Defaults to `true`. */ useSentryBreadcrumbs?: boolean; /** * Specify which Picker instance should respond to paste event. * By default only hovered instance responds to event. * @param {boolean = false} pasteToFirstInViewPort If none instance is hovered take first picker instance fully visible in viewport * @param {boolean = false} pasteToFirstInstance If none instance is hovered take first picker instance that is initialized * @pasteToFirstInViewPort is checked first */ pasteMode?: { pasteToFirstInViewPort?: boolean, pasteToFirstInstance?: boolean }; } export interface PickerCropOptions { /** * Maintain aspect ratio for crop selection. (e.g. 16/9, 800/600). */ aspectRatio?: number; /** * Force all images to be cropped before uploading. */ force?: boolean; } export interface PickerTransformationOptions { /** * Enable crop. Defaults to `true`. */ crop?: boolean | PickerCropOptions; /** * Enable circle crop. Disabled if crop.aspectRatio is defined and not 1. Converts to PNG. Defaults to `true`. */ circle?: boolean; /** * Enable image rotation. Defaults to `true`. */ rotate?: boolean; /** * Global force crop option. Can be use ie with circle */ force?: boolean; } export interface PickerAcceptFnOptions { /** * Provided accept string */ accept: string[]; /** * Accept string converted to mimetype */ acceptMime: string[]; /** * Mimetype based magic bytes * {@link https://filestack.github.io/filestack-js/globals.html#getmimetype} */ mimeFromMagicBytes: Promise<string>; /** * Mimetype based on file extension * {@link https://filestack.github.io/filestack-js/globals.html#extensiontomime} */ mimeFromExtension: string; } /** * @private * A synchronous-looking wrapper for loading the picker and calling its methods. * This is currently needed because the picker module is loaded asynchronously. * Eventually we should offer a bundle with the picker module included. */ class PickerLoader { private _initialized: Promise<PickerInstance>; constructor(client: Client, options?: PickerOptions) { const validateRes = getValidator(PickerParamsSchema)(options); if (validateRes.errors.length) { throw new FilestackError(`Invalid picker params`, validateRes.errors, FilestackErrorType.VALIDATION); } this._initialized = this.loadModule(client, options); } async open(): Promise<void> { const picker = await this._initialized; await picker.open(); } async crop(files: any[]): Promise<void> { const picker = await this._initialized; await picker.crop(files); } async close(): Promise<void> { const picker = await this._initialized; await picker.close(); } async cancel(): Promise<void> { const picker = await this._initialized; await picker.cancel(); } private async loadModule(client: Client, options?: PickerOptions): Promise<PickerInstance> { const { session: { urls: { pickerUrl: url } } } = client; const Picker = await loadModule(FILESTACK_MODULES.PICKER, url); return new Picker(client, options); } } /** * Loads and creates picker instance * * @private * @param client * @param options */ export const picker = (client: Client, options?: PickerOptions): PickerInstance => { return new PickerLoader(client, options); };
the_stack
import { arrayWith, expect as expectCDK, haveResource, haveResourceLike, stringLike, } from '@aws-cdk/assert'; import { GenericWindowsImage, IVpc, SecurityGroup, SubnetSelection, SubnetType, Vpc, } from '@aws-cdk/aws-ec2'; import { DockerImageAsset, } from '@aws-cdk/aws-ecr-assets'; import { CfnService, ContainerImage, } from '@aws-cdk/aws-ecs'; import { ILogGroup, } from '@aws-cdk/aws-logs'; import { ISecret, Secret, } from '@aws-cdk/aws-secretsmanager'; import { App, CfnElement, Stack, } from '@aws-cdk/core'; import { testConstructTags, } from '../../core/test/tag-helpers'; import { IVersion, IWorkerFleet, RenderQueue, Repository, SecretsManagementRegistrationStatus, SecretsManagementRole, SubnetIdentityRegistrationSettingsProps, UsageBasedLicense, UsageBasedLicensing, UsageBasedLicensingImages, UsageBasedLicensingProps, VersionQuery, WorkerInstanceFleet, } from '../lib'; const env = { region: 'us-east-1', }; let app: App; let certificateSecret: ISecret; let versionedInstallers: IVersion; let dependencyStack: Stack; let dockerContainer: DockerImageAsset; let images: UsageBasedLicensingImages; let licenses: UsageBasedLicense[]; let rcsImage: ContainerImage; let renderQueue: RenderQueue; let stack: Stack; let vpc: IVpc; let workerFleet: IWorkerFleet; const DEFAULT_CONSTRUCT_ID = 'UBL'; describe('UsageBasedLicensing', () => { beforeEach(() => { // GIVEN app = new App(); dependencyStack = new Stack(app, 'DependencyStack', { env }); versionedInstallers = new VersionQuery(dependencyStack, 'VersionQuery'); vpc = new Vpc(dependencyStack, 'VPC'); rcsImage = ContainerImage.fromDockerImageAsset(new DockerImageAsset(dependencyStack, 'Image', { directory: __dirname, })); renderQueue = new RenderQueue(dependencyStack, 'RQ-NonDefaultPort', { vpc, images: { remoteConnectionServer: rcsImage }, repository: new Repository(dependencyStack, 'RepositoryNonDefault', { vpc, version: versionedInstallers, }), version: versionedInstallers, }); jest.spyOn(renderQueue, 'configureSecretsManagementAutoRegistration'); stack = new Stack(app, 'Stack', { env }); certificateSecret = Secret.fromSecretArn(stack, 'CertSecret', 'arn:aws:secretsmanager:us-west-2:675872700355:secret:CertSecret-j1kiFz'); dockerContainer = new DockerImageAsset(stack, 'license-forwarder', { directory: __dirname, }); images = { licenseForwarder: ContainerImage.fromDockerImageAsset(dockerContainer), }; licenses = [UsageBasedLicense.forMaya()]; }); function createUbl(props?: Partial<UsageBasedLicensingProps>): UsageBasedLicensing { return new UsageBasedLicensing(stack, DEFAULT_CONSTRUCT_ID, { certificateSecret, images, licenses, renderQueue, vpc, ...props, }); } test('vpcSubnets specified => does not emit warnings', () => { // GIVEN const vpcSubnets: SubnetSelection = { subnetType: SubnetType.PRIVATE, }; // WHEN const ubl = createUbl({ vpcSubnets, }); // THEN expect(ubl.node.metadataEntry).not.toContainEqual(expect.objectContaining({ type: 'aws:cdk:warning', data: expect.stringMatching(/dedicated subnet/i), })); }); test('vpcSubnets not specified => emits warning about dedicated subnets', () => { // WHEN const ubl = createUbl(); // THEN expect(ubl.node.metadataEntry).toContainEqual(expect.objectContaining({ type: 'aws:cdk:warning', data: 'Deadline Secrets Management is enabled on the Repository and VPC subnets have not been supplied. Using dedicated subnets is recommended. See https://github.com/aws/aws-rfdk/blobs/release/packages/aws-rfdk/lib/deadline/README.md#using-dedicated-subnets-for-deadline-components', })); }); describe('configures auto registration', () => { test('default to private subnets', () => { // WHEN const ubl = createUbl(); // THEN const expectedCall: SubnetIdentityRegistrationSettingsProps = { dependent: ubl.service.node.defaultChild as CfnService, registrationStatus: SecretsManagementRegistrationStatus.REGISTERED, role: SecretsManagementRole.CLIENT, vpc, vpcSubnets: { subnetType: SubnetType.PRIVATE }, }; // THEN expect(renderQueue.configureSecretsManagementAutoRegistration).toHaveBeenCalledWith(expectedCall); }); test.each<[SubnetSelection]>([ [{ subnetType: SubnetType.PUBLIC, }], ])('%s', (vpcSubnets) => { // WHEN const ubl = createUbl({ vpcSubnets, }); // THEN const expectedCall: SubnetIdentityRegistrationSettingsProps = { dependent: ubl.service.node.defaultChild as CfnService, registrationStatus: SecretsManagementRegistrationStatus.REGISTERED, role: SecretsManagementRole.CLIENT, vpc, vpcSubnets, }; // THEN expect(renderQueue.configureSecretsManagementAutoRegistration).toHaveBeenCalledWith(expectedCall); }); }); test('creates an ECS cluster', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Cluster')); }); describe('creates an ASG', () => { test('defaults', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MinSize: '1', MaxSize: '1', VPCZoneIdentifier: [ { 'Fn::ImportValue': stringLike(`${dependencyStack.stackName}:ExportsOutputRefVPCPrivateSubnet1Subnet*`), }, { 'Fn::ImportValue': stringLike(`${dependencyStack.stackName}:ExportsOutputRefVPCPrivateSubnet2Subnet*`), }, ], })); }); test('capacity can be specified', () => { // WHEN createUbl({ desiredCount: 2, }); // THEN expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MinSize: '2', MaxSize: '2', })); }); test('gives write access to log group', () => { // GIVEN const ubl = createUbl(); // WHEN const logGroup = ubl.node.findChild(`${DEFAULT_CONSTRUCT_ID}LogGroup`) as ILogGroup; const asgRoleLogicalId = Stack.of(ubl).getLogicalId(ubl.asg.role.node.defaultChild as CfnElement); // THEN expectCDK(stack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: { Statement: arrayWith( { Action: arrayWith( 'logs:CreateLogStream', 'logs:PutLogEvents', ), Effect: 'Allow', Resource: stack.resolve(logGroup.logGroupArn), }, ), Version: '2012-10-17', }, Roles: arrayWith( { Ref: asgRoleLogicalId }, ), })); }); test('uses the supplied security group', () => { // GIVEN const securityGroup = new SecurityGroup(stack, 'UblSecurityGroup', { vpc, }); // WHEN createUbl({ securityGroup }); // THEN expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::LaunchConfiguration', { SecurityGroups: arrayWith(stack.resolve(securityGroup.securityGroupId)), })); }); }); describe('creates an ECS service', () => { test('associated with the cluster', () => { // WHEN const ubl = createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { Cluster: { Ref: stack.getLogicalId(ubl.cluster.node.defaultChild as CfnElement) }, })); }); describe('DesiredCount', () => { test('defaults to 1', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { DesiredCount: 1, })); }); test('can be specified', () => { // GIVEN const desiredCount = 2; // WHEN createUbl({ desiredCount }); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { DesiredCount: desiredCount, })); }); }); test('sets launch type to EC2', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { LaunchType: 'EC2', })); }); test('sets distinct instance placement constraint', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { PlacementConstraints: arrayWith( { Type: 'distinctInstance' }, ), })); }); test('uses the task definition', () => { // WHEN const ubl = createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { TaskDefinition: { Ref: stack.getLogicalId(ubl.service.taskDefinition.node.defaultChild as CfnElement) }, })); }); test('with the correct deployment configuration', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { MaximumPercent: 100, MinimumHealthyPercent: 0, }, })); }); }); describe('creates a task definition', () => { test('container name is LicenseForwarderContainer', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Name: 'LicenseForwarderContainer', }, ], })); }); test('container is marked essential', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Essential: true, }, ], })); }); test('with increased ulimits', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Ulimits: [ { HardLimit: 200000, Name: 'nofile', SoftLimit: 200000, }, { HardLimit: 64000, Name: 'nproc', SoftLimit: 64000, }, ], }, ], })); }); test('with awslogs log driver', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': {}, 'awslogs-stream-prefix': 'LicenseForwarder', 'awslogs-region': env.region, }, }, }, ], })); }); test('configures UBL certificates', () => { // GIVEN const ubl = createUbl(); // WHEN const taskRoleLogicalId = Stack.of(ubl).getLogicalId(ubl.service.taskDefinition.taskRole.node.defaultChild as CfnElement); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: arrayWith( { Name: 'UBL_CERTIFICATES_URI', Value: certificateSecret.secretArn, }, ), }, ], TaskRoleArn: { 'Fn::GetAtt': [ taskRoleLogicalId, 'Arn', ], }, })); expectCDK(stack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: { Statement: arrayWith( { Action: [ 'secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret', ], Effect: 'Allow', Resource: certificateSecret.secretArn, }, ), Version: '2012-10-17', }, Roles: [ { Ref: Stack.of(ubl).getLogicalId(ubl.service.taskDefinition.taskRole.node.defaultChild as CfnElement) }, ], })); }); test('uses host networking', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { NetworkMode: 'host', })); }); test('is marked EC2 compatible only', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { RequiresCompatibilities: [ 'EC2' ], })); }); }); test('License Forwarder subnet selection', () => { // GIVEN const publicSubnetIds = ['PublicSubnet1', 'PublicSubnet2']; const vpcFromAttributes = Vpc.fromVpcAttributes(dependencyStack, 'AttrVpc', { availabilityZones: ['us-east-1a', 'us-east-1b'], vpcId: 'vpcid', publicSubnetIds, }); // WHEN createUbl({ vpc: vpcFromAttributes, vpcSubnets: { subnetType: SubnetType.PUBLIC }, }); // THEN expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { VPCZoneIdentifier: publicSubnetIds, })); }); test.each([ 'test-prefix/', '', ])('License Forwarder is created with correct LogGroup prefix %s', (testPrefix: string) => { // GIVEN const id = DEFAULT_CONSTRUCT_ID; // WHEN createUbl({ logGroupProps: { logGroupPrefix: testPrefix, }, }); // THEN expectCDK(stack).to(haveResource('Custom::LogRetention', { LogGroupName: testPrefix + id, })); }); describe('license limits', () => { test('multiple licenses with limits', () => { // WHEN createUbl({ licenses: [ UsageBasedLicense.forMaya(10), UsageBasedLicense.forVray(10), ], }); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: arrayWith( { Name: 'UBL_LIMITS', Value: 'maya:10;vray:10', }, ), }, ], })); }); test.each([ ['3dsMax', UsageBasedLicense.for3dsMax(10), [27002]], ['Arnold', UsageBasedLicense.forArnold(10), [5056, 7056]], ['Cinema4D', UsageBasedLicense.forCinema4D(10), [5057, 7057]], ['Clarisse', UsageBasedLicense.forClarisse(10), [40500]], ['Houdini', UsageBasedLicense.forHoudini(10), [1715]], ['Katana', UsageBasedLicense.forKatana(10), [4151, 6101]], ['KeyShot', UsageBasedLicense.forKeyShot(10), [27003, 2703]], ['Krakatoa', UsageBasedLicense.forKrakatoa(10), [27000, 2700]], ['Mantra', UsageBasedLicense.forMantra(10), [1716]], ['Maxwell', UsageBasedLicense.forMaxwell(10), [5555, 7055]], ['Maya', UsageBasedLicense.forMaya(10), [27002, 2702]], ['Nuke', UsageBasedLicense.forNuke(10), [4101, 6101]], ['RealFlow', UsageBasedLicense.forRealFlow(10), [5055, 7055]], ['RedShift', UsageBasedLicense.forRedShift(10), [5054, 7054]], ['Vray', UsageBasedLicense.forVray(10), [30306]], ['Yeti', UsageBasedLicense.forYeti(10), [5053, 7053]], ])('Test open port for license type %s', (_licenseName: string, license: UsageBasedLicense, ports: number[]) => { // GIVEN const ubl = createUbl(); const workerStack = new Stack(app, 'WorkerStack', { env }); workerFleet = new WorkerInstanceFleet(workerStack, 'workerFleet', { vpc, workerMachineImage: new GenericWindowsImage({ 'us-east-1': 'ami-any', }), renderQueue, securityGroup: SecurityGroup.fromSecurityGroupId(workerStack, 'SG', 'sg-123456789', { allowAllOutbound: false, }), }); // WHEN ubl.grantPortAccess(workerFleet, [license]); // THEN ports.forEach( port => { expectCDK(workerStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: port, GroupId: { 'Fn::ImportValue': stringLike(`${Stack.of(ubl).stackName}:ExportsOutputFnGetAttUBLClusterASGInstanceSecurityGroup*`), }, SourceSecurityGroupId: 'sg-123456789', })); }); }); test('requires one usage based license', () => { // Without any licenses expect(() => { createUbl({ licenses: [] }); }).toThrowError('Should be specified at least one license with defined limit.'); }); }); describe('configures render queue', () => { test('adds ingress rule from UsageBasedLicensing ASG to RenderQueue ASG', () => { // GIVEN const renderQueueSecurityGroup = renderQueue.connections.securityGroups[0]; // WHEN const ubl = createUbl(); const ublSecurityGroup = ubl.connections.securityGroups[0]; expectCDK(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', FromPort: 4433, ToPort: 4433, GroupId: stack.resolve(renderQueueSecurityGroup.securityGroupId), SourceSecurityGroupId: stack.resolve(ublSecurityGroup.securityGroupId), })); }); test('adds ingress rule from RenderQueue ASG to UsageBasedLicensing ASG', () => { // GIVEN const renderQueueSecurityGroup = renderQueue.backendConnections.securityGroups[0]; // WHEN const ubl = createUbl(); const ublSecurityGroup = ubl.connections.securityGroups[0]; expectCDK(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', FromPort: 17004, ToPort: 17004, GroupId: stack.resolve(ublSecurityGroup.securityGroupId), SourceSecurityGroupId: stack.resolve(renderQueueSecurityGroup.securityGroupId), })); }); test('sets RENDER_QUEUE_URI environment variable', () => { // WHEN createUbl(); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: arrayWith( { Name: 'RENDER_QUEUE_URI', Value: stack.resolve(`${renderQueue.endpoint.applicationProtocol.toLowerCase()}://${renderQueue.endpoint.socketAddress}`), }, ), }, ], })); }); }); describe('tagging', () => { testConstructTags({ constructName: 'UsageBasedLicensing', createConstruct: () => { createUbl(); return stack; }, resourceTypeCounts: { 'AWS::ECS::Cluster': 1, 'AWS::EC2::SecurityGroup': 1, 'AWS::IAM::Role': 5, 'AWS::AutoScaling::AutoScalingGroup': 1, 'AWS::Lambda::Function': 1, 'AWS::SNS::Topic': 1, 'AWS::ECS::TaskDefinition': 1, 'AWS::ECS::Service': 1, }, }); }); });
the_stack
import { Component } from 'react' import { Button, IconButton } from '@instructure/ui-buttons' import { Flex } from '@instructure/ui-flex' import { Img } from '@instructure/ui-img' import { Link } from '@instructure/ui-link' import { List } from '@instructure/ui-list' import { Text } from '@instructure/ui-text' import { View } from '@instructure/ui-view' import { IconGithubSolid, IconCheckMarkSolid, IconAnnouncementLine } from '@instructure/ui-icons' import { AccessibleContent } from '@instructure/ui-a11y-content' import { InlineSVG, SVGIcon } from '@instructure/ui-svg-images' import { withStyle, jsx } from '@instructure/emotion' import generateStyle from './styles' import generateComponentTheme from './theme' import { ColorBand } from '../ColorBand' import { ContentWrap } from '../ContentWrap' import { Search } from '../Search' import { Heading } from '../Heading' import type { HeroProps } from './props' import { propTypes, allowedProps } from './props' @withStyle(generateStyle, generateComponentTheme) class Hero extends Component<HeroProps> { static propTypes = propTypes static allowedProps = allowedProps static defaultProps = { description: undefined, docs: null } componentDidMount() { this.props.makeStyles?.() } componentDidUpdate() { this.props.makeStyles?.() } render() { const { version, layout, styles } = this.props const corpLogo = ( <SVGIcon viewBox="0 0 500 500"> <polygon fill="#2A7BA0" points="30.07,373.64 250.04,249.77 470,373.64 250.04,497.46 " /> <polygon fill="#FDCC10" points="140.03,64.02 30.07,125.9 140.08,187.84 250.04,125.9 " /> <polygon fill="#F78F20" points="249.99,2.08 140.08,63.97 250.04,125.9 359.99,64.02 " /> <polygon fill="#EB2227" points="359.99,64.02 250.04,125.9 359.99,187.84 469.95,125.9 " /> </SVGIcon> ) const canvasLogo = ( <InlineSVG viewBox="0 0 792 220" width="239px" height="66px"> <path fill="white" d="M48.2 109.4c0-13.8-10.3-25.1-23.7-26.7 -2.2 8.5-3.4 17.4-3.4 26.7s1.2 18.2 3.4 26.7C37.9 134.5 48.2 123 48.2 109.4z" /> <path fill="white" d="M63.8 100.9c-4.7 0-8.5 3.8-8.5 8.5s3.8 8.5 8.5 8.5c4.7 0 8.5-3.8 8.5-8.5S68.6 100.9 63.8 100.9z" /> <path fill="white" d="M180.5 109.4c0 13.8 10.3 25.1 23.7 26.7 2.2-8.5 3.4-17.4 3.4-26.7s-1.2-18.2-3.4-26.7C190.7 84.3 180.5 95.5 180.5 109.4z" /> <path fill="white" d="M164.6 100.9c-4.7 0-8.5 3.8-8.5 8.5s3.8 8.5 8.5 8.5c4.7 0 8.5-3.8 8.5-8.5S169.4 100.9 164.6 100.9z" /> <path fill="white" d="M114 175.6c-13.8 0-25.1 10.3-26.7 23.7 8.5 2.2 17.4 3.4 26.7 3.4 9.3 0 18.2-1.2 26.7-3.4C139.1 186.1 127.9 175.6 114 175.6z" /> <path fill="white" d="M114 151.5c-4.7 0-8.5 3.8-8.5 8.5 0 4.7 3.8 8.5 8.5 8.5 4.7 0 8.5-3.8 8.5-8.5C122.5 155.4 118.8 151.5 114 151.5z" /> <path fill="white" d="M114 43.3c13.8 0 25.1-10.3 26.7-23.7 -8.5-2.2-17.4-3.4-26.7-3.4 -9.3 0-18.2 1.2-26.7 3.4C88.9 33.1 100.4 43.3 114 43.3z" /> <path fill="white" d="M114 50.7c-4.7 0-8.5 3.8-8.5 8.5s3.8 8.5 8.5 8.5c4.7 0 8.5-3.8 8.5-8.5C122.5 54.4 118.8 50.7 114 50.7z" /> <path fill="white" d="M160.9 156.2c-9.7 9.7-10.5 24.9-2.2 35.6 15.6-9.1 28.7-22.1 37.8-37.8C186 145.7 170.6 146.5 160.9 156.2z" /> <path fill="white" d="M143.9 139c-3.4 3.4-3.4 8.7 0 11.9 3.4 3.4 8.7 3.4 11.9 0 3.4-3.4 3.4-8.7 0-11.9C152.6 135.9 147.2 135.9 143.9 139z" /> <path fill="white" d="M67.4 62.7c9.7-9.7 10.5-24.9 2.2-35.6 -15.6 9.1-28.7 22.1-37.8 37.8C42.5 73 57.7 72.4 67.4 62.7z" /> <path fill="white" d="M72.5 67.7c-3.4 3.4-3.4 8.7 0 11.9 3.4 3.4 8.7 3.4 11.9 0 3.4-3.4 3.4-8.7 0-11.9C81.2 64.5 75.9 64.5 72.5 67.7z" /> <path fill="white" d="M160.9 62.5c9.7 9.7 24.9 10.5 35.6 2.2 -9.1-15.6-22.1-28.7-37.8-37.8C150.4 37.6 151.2 52.8 160.9 62.5z" /> <path fill="white" d="M155.7 79.5c3.4-3.4 3.4-8.7 0-11.9 -3.4-3.4-8.7-3.4-11.9 0 -3.4 3.4-3.4 8.7 0 11.9C147 82.9 152.4 82.9 155.7 79.5z" /> <path fill="white" d="M67.4 156c-9.7-9.7-24.9-10.5-35.6-2.2 9.1 15.6 22.1 28.7 37.8 37.8C77.9 181.1 77.1 165.7 67.4 156z" /> <path fill="white" d="M72.5 139c-3.4 3.4-3.4 8.7 0 11.9 3.4 3.4 8.7 3.4 11.9 0 3.4-3.4 3.4-8.7 0-11.9C81.2 135.7 75.7 135.7 72.5 139z" /> <path fill="white" d="M330.9 148.7c0 18.2-11.9 25.1-29.9 25.1h-0.4c-18 0-29.9-6.5-29.9-25.1v-71c0-17.6 11.9-25.1 29.9-25.1h0.4c18 0 29.9 7.5 29.9 25.1v14h-19.6V80.7c0-8.3-4.2-10.9-10.3-10.9s-10.3 2.6-10.3 10.9v64.8c0 8.3 4.2 10.9 10.3 10.9s10.3-2.6 10.3-10.9v-13.8h19.6V148.7z" /> <path fill="white" d="M400.3 145.9h-21.5l-4.2 26.3h-19l21.9-118.4h24.7l22.3 118.4h-20L400.3 145.9zM397.9 129.7l-8.3-52.6 -8.3 52.6H397.9z" /> <path fill="white" d="M451.3 172.4V54h19.6l24.9 73.1V54h18v118.4h-18.6l-25.9-76.9v76.9H451.3z" /> <path fill="white" d="M584.4 172.4h-21.5L540.5 54h20l13.6 87.8L587.7 54h19L584.4 172.4z" /> <path fill="white" d="M665.2 145.9h-21.5l-4.2 26.3h-19l21.9-118.4h24.7l22.3 118.4h-20L665.2 145.9zM662.6 129.7l-8.3-52.6 -8.3 52.6H662.6z" /> <path fill="white" d="M751.2 88.6v-8.9c0-7.5-4.2-10.1-9.9-10.1 -5.7 0-9.9 2.8-9.9 10.1v8.1c0 6.1 2 8.7 7.5 12.1l13.8 7.7c11.3 6.5 18.2 11.7 18.2 24.3v17c0 18.2-11.3 24.7-29.3 24.7h-0.4c-18 0-29.3-6.3-29.3-24.7v-12.5h19.4v9.9c0 7.3 4.2 10.5 10.1 10.5 5.9 0 10.1-3.2 10.1-10.5V137c0-6.1-1.8-9.1-7.7-12.3l-13.6-7.7c-11.5-6.5-18.2-12.1-18.2-24.3V77.1c0-17.6 12.9-24.3 29.1-24.3h0.4c16.2 0 29.1 6.7 29.1 24.3v11.7h-19.4V88.6z" /> </InlineSVG> ) const bigScreen = layout === 'large' || layout === 'x-large' const contentMaxWidth = '84rem' const checkmark = <IconCheckMarkSolid inline={false} color="success" /> const heroBodyContent = ( <View as="div"> <Heading as="h3" level="h2" margin="none none medium"> Components everyone can count on </Heading> <View as="div" margin="medium none"> <Text size="large"> Instructure UI is maintained by Instructure designers, developers, and accessibility experts. Our components and utilities offer support for: </Text> </View> <List size="large" itemSpacing="xx-small" margin="none none xx-large" isUnstyled > <List.Item> <Flex> <Flex.Item padding="none small none none">{checkmark}</Flex.Item> <Flex.Item> Leading screen readers: VoiceOver, NVDA, and JAWS </Flex.Item> </Flex> </List.Item> <List.Item> <Flex> <Flex.Item padding="none small none none">{checkmark}</Flex.Item> <Flex.Item shouldGrow shouldShrink> Keyboard only navigation </Flex.Item> </Flex> </List.Item> <List.Item> <Flex> <Flex.Item padding="none small none none">{checkmark}</Flex.Item> <Flex.Item>Right-to-left (RTL) languages</Flex.Item> </Flex> </List.Item> </List> <Heading as="h3" level="h2" margin="none none medium"> Getting started </Heading> <View as="p" margin="none none small"> <Text size="large"> Check out our <Link href="#usage">Developer Quick Start</Link> to spin up a starter app or integrate the library into an existing project. </Text> </View> <List margin="none none x-large" itemSpacing="xx-small"> <List.Item> <Text weight="bold">React support:</Text> 16.8.0 and later </List.Item> <List.Item> <Text weight="bold">Browser support:</Text> The last two versions of all modern browsers (Firefox, Safari, Chrome, Edge). </List.Item> <List.Item> <Text weight="bold">License:</Text> <Link href="#LICENSE">MIT</Link> </List.Item> </List> <Heading as="h3" level="h2" margin="none none medium"> Contribute </Heading> <View as="p" margin="none none small"> <Text size="large"> Whether it&apos;s finding a bug, committing a fix, or suggesting a feature, we welcome contributions. </Text> </View> <List margin="none none large" itemSpacing="xx-small"> <List.Item> <Link href="#contributing">Contributing Guidelines</Link> </List.Item> <List.Item> <Link href="#CODE_OF_CONDUCT">Code of Conduct</Link> </List.Item> <List.Item> <Link href="https://github.com/instructure/instructure-ui"> Instructure UI on Github </Link> </List.Item> </List> <Heading as="h3" level="h2" margin="none none medium"> Acknowledgements </Heading> <View as="p" margin="none none small"> <a href="https://www.netlify.com"> <img src="https://www.netlify.com/img/global/badges/netlify-dark.svg" alt="Deploys by Netlify" /> </a> </View> </View> ) const sidebarContent = ( <View as="aside"> <View as="div" background="secondary" padding="large"> <Flex> <Flex.Item> <IconAnnouncementLine inline={false} size="small" /> </Flex.Item> <Flex.Item padding="none none none small"> <Heading as="h3" level="h3"> What&apos;s New? </Heading> </Flex.Item> </Flex> <List isUnstyled margin="small none none"> <List.Item> <Link href="#v8-upgrade-guide">Version 8.0 Upgrade Guide</Link> </List.Item> <List.Item> <Link href="#CHANGELOG">Change Log ({version})</Link> </List.Item> </List> </View> <Link display="block" href="https://www.instructure.com/canvas/" isWithinText={false} themeOverride={{ hoverTextDecorationOutsideText: 'none' }} > <View display="block" background="danger" margin="x-large none none" padding="large" textAlign="center" > <AccessibleContent alt="Instructure UI powers Canvas"> <Text size="large">Instructure UI powers</Text> </AccessibleContent> <View display="block" margin="xx-small none none"> {canvasLogo} </View> </View> </Link> </View> ) return ( <View as="section"> <View as="div" minHeight={layout === 'small' ? undefined : '100vh'} position="relative" > <div css={styles?.overlayLayout}> <Img src="https://instui-docs.s3.us-east-2.amazonaws.com/hero2.jpg" display="block" constrain="cover" overlay={{ color: styles?.backgroundColor as string, opacity: 10, blend: 'multiply' }} /> </div> <View as="div" position="relative" css={styles?.contentLayout} minHeight={layout === 'small' ? undefined : '100vh'} > <View as="header" background="primary" position="relative" shadow="resting" > <Flex padding={bigScreen ? 'small' : 'small x-small'} justifyItems="space-between" > <Flex.Item size="4rem"></Flex.Item> <Flex.Item shouldShrink={!bigScreen} shouldGrow={!bigScreen} size={bigScreen ? '36%' : undefined} padding={bigScreen ? 'none' : 'none x-small none none'} > <Search options={this.props.docs} /> </Flex.Item> <Flex.Item> <IconButton href="https://github.com/instructure/instructure-ui" renderIcon={<IconGithubSolid />} screenReaderLabel="Contribute on Github" withBackground={false} withBorder={false} size={bigScreen ? 'large' : 'medium'} /> <IconButton href="http://instructure.com" renderIcon={corpLogo} screenReaderLabel="Instructure" withBackground={false} withBorder={false} size={bigScreen ? 'large' : 'medium'} /> </Flex.Item> </Flex> </View> <View display="block" css={styles?.content}> <ContentWrap padding={ layout === 'small' ? 'xx-large large' : 'x-large xx-large' } maxWidth={contentMaxWidth} > <View as="div" maxWidth={bigScreen ? '66%' : undefined} padding={bigScreen ? 'none x-large none none' : 'none'} > <Flex margin="0 0 large"> <Flex.Item padding="0 x-small 0 0"> <Heading as="h1" level="h3" color="primary-inverse"> Instructure UI </Heading> </Flex.Item> <Flex.Item> <Button size="small" withBackground={false} color="primary-inverse" href="#CHANGELOG" > {version} </Button> </Flex.Item> </Flex> <Heading as="h2" level="h1" themeOverride={{ h1FontSize: bigScreen ? '4rem' : '3.25rem' }} color="primary-inverse" > Create beautiful, accessible React apps. </Heading> <View as="p" margin="large 0"> <Text size={bigScreen ? 'large' : 'medium'} color="primary-inverse" > Use open source components millions of learners rely on every day when they use Instructure products like Canvas LMS. </Text> </View> <View as="p" margin="0"> <Button withBackground={false} color="primary-inverse" href="#usage" margin="0 x-small x-small 0" size={bigScreen ? 'large' : 'medium'} > Developer Quick Start </Button> <Button withBackground={false} color="primary-inverse" renderIcon={IconGithubSolid} href="https://github.com/instructure/instructure-ui" size={bigScreen ? 'large' : 'medium'} margin="0 x-small x-small 0" > Github </Button> <Button focusColor="inverse" color="success" href="#v8-upgrade-guide" size={bigScreen ? 'large' : 'medium'} margin="0 x-small x-small 0" > 8.0 Upgrade Guide </Button> </View> </View> </ContentWrap> </View> <ContentWrap padding={bigScreen ? 'none xx-large' : 'none'} maxWidth={contentMaxWidth} > <ColorBand /> </ContentWrap> </View> </View> <ContentWrap padding={layout === 'small' ? 'large' : 'xx-large'} maxWidth={contentMaxWidth} > {bigScreen ? ( <Flex alignItems="start" padding="medium none none"> <Flex.Item shouldGrow shouldShrink padding="none xx-large none none" > {heroBodyContent} </Flex.Item> <Flex.Item size="32%">{sidebarContent}</Flex.Item> </Flex> ) : ( <div> {heroBodyContent} {sidebarContent} </div> )} </ContentWrap> </View> ) } } export default Hero export { Hero }
the_stack
import {forkJoin, Observable, of} from 'rxjs'; import {isNullOrUndefined} from '../common/util'; import {catchError, map} from 'rxjs/operators'; import { FILETYPE_XTB, FORMAT_XMB, IICUMessage, IICUMessageTranslation, ITranslationMessagesFile, ITransUnit, TranslationMessagesFileFactory } from '@ngx-i18nsupport/ngx-i18nsupport-lib'; import {TranslationUnit} from './translation-unit'; import {AutoTranslateServiceAPI} from './auto-translate-service-api'; import {AutoTranslateSummaryReport} from './auto-translate-summary-report'; import {AutoTranslateResult} from './auto-translate-result'; import {IFileDescription} from '../file-accessors/common/i-file-description'; import {DownloadUploadFileDescription} from '../file-accessors/download-upload/download-upload-file-description'; import {IFile} from '../file-accessors/common/i-file'; import {SerializationService} from './serialization.service'; import {GenericFile} from '../file-accessors/common/generic-file'; /** * A single xlf or xmb file ready for work. * This is a wrapper around ITranslationMessagesFile. * It can read from uploaded files and adds errorhandling. * Created by roobm on 22.03.2017. */ // internal representation of serialized form. // format used since v0.15 interface ISerializedTranslationFileV2 { version: string; file: string; // serialized editedContent: string; master?: string; // serialized explicitSourceLanguage: string; } // elder internal representation of serialized form. // old format, used until v0.14 interface ISerializedTranslationFile { name: string; size: number; fileContent: string; editedContent: string; masterContent: string; masterName: string; explicitSourceLanguage: string; } export class TranslationFile { private _file: IFile; private _error: string = null; private _master?: IFile; private _translationFile: ITranslationMessagesFile; private _explicitSourceLanguage: string; /** * all TransUnits read from file. */ private _allTransUnits: TranslationUnit[]; /** * Create a TranslationFile from the read file. * @param loadedFile read in translation file (xliff, xmb) * @param loadedMasterXmbFile optional master for xmb file */ static fromFile(loadedFile: IFile, loadedMasterXmbFile?: IFile): TranslationFile { const newInstance = new TranslationFile(); newInstance._file = loadedFile; if (loadedFile.content) { try { let optionalMaster: any = null; if (loadedMasterXmbFile && loadedMasterXmbFile.content) { optionalMaster = { path: loadedMasterXmbFile.description.name, xmlContent: loadedMasterXmbFile.content, encoding: null }; newInstance._master = loadedMasterXmbFile; } newInstance._translationFile = TranslationMessagesFileFactory.fromUnknownFormatFileContent( loadedFile.content, loadedFile.description.name, 'utf-8', optionalMaster); if (newInstance._translationFile.i18nFormat() === FORMAT_XMB) { newInstance._error = 'xmb files cannot be translated, use xtb instead'; // TODO i18n } newInstance.readTransUnits(); } catch (err) { newInstance._error = err.toString(); } } return newInstance; } /** * Create a translation file from the serialization. * @param serializationService serializationService * @param serializationString serializationString * @return TranslationFile */ static deserialize(serializationService: SerializationService, serializationString: string): TranslationFile { const deserializedObject = <ISerializedTranslationFile> JSON.parse(serializationString); return TranslationFile.fromDeserializedObject(serializationService, deserializedObject); } static fromDeserializedObject( serializationService: SerializationService, deserializedJsonObject: ISerializedTranslationFile|ISerializedTranslationFileV2|any): TranslationFile { let deserializedObject: ISerializedTranslationFileV2; if (deserializedJsonObject.version) { deserializedObject = deserializedJsonObject as ISerializedTranslationFileV2; } else { // migration from old format const v1Object = deserializedJsonObject as ISerializedTranslationFile; deserializedObject = { version: '1', file: new GenericFile(DownloadUploadFileDescription.deserialize(serializationService, null), v1Object.name, v1Object.size, v1Object.fileContent) .serialize(serializationService), editedContent: v1Object.editedContent, explicitSourceLanguage: v1Object.explicitSourceLanguage }; if (v1Object.masterContent) { deserializedObject.master = new GenericFile(DownloadUploadFileDescription.deserialize(serializationService, null), v1Object.masterName, 0, v1Object.masterContent) .serialize(serializationService); } } const newInstance = new TranslationFile(); newInstance._file = serializationService.deserializeIFile(deserializedObject.file); newInstance._explicitSourceLanguage = deserializedObject.explicitSourceLanguage; try { const encoding = null; // unknown, lib can find it let optionalMaster: {xmlContent: string, path: string, encoding: string} = null; if (deserializedObject.master) { newInstance._master = serializationService.deserializeIFile(deserializedObject.master); optionalMaster = { xmlContent: newInstance._master.content, path: newInstance._master.description.name, encoding: encoding }; } newInstance._translationFile = TranslationMessagesFileFactory.fromUnknownFormatFileContent( deserializedObject.editedContent, newInstance._file.description.name, encoding, optionalMaster); newInstance.readTransUnits(); } catch (err) { newInstance._error = err.toString(); } return newInstance; } constructor() { this._allTransUnits = []; } private readTransUnits() { this._allTransUnits = []; if (this._translationFile) { this._translationFile.forEachTransUnit((tu: ITransUnit) => { this._allTransUnits.push(new TranslationUnit(this, tu)); }); } } get name(): string { return (this._file && this._file.description) ? this._file.description.name : ''; } /** * In case of xmb/xtb the name of the master xmb file. * @return name of master file or null */ get masterName(): string|null { return (this._master) ? this._master.description.name : null; } get size(): number { return this._file.size; } get numberOfTransUnits(): number { return this._allTransUnits.length; } get numberOfUntranslatedTransUnits(): number { return (this._translationFile) ? this._translationFile.numberOfUntranslatedTransUnits() : 0; } public fileDescription(): IFileDescription { return this._file.description; } public editedFile(): IFile { const content = this.editedContent(); return this._file.copyWithNewContent(content); } /** * Type of file. * Currently 'xlf', 'xlf2', 'xmb' or or 'xtb' * @return type of file */ public fileType(): string { if (this._translationFile) { return this._translationFile.fileType(); } else { // try to get it by name if (this.name && this.name.endsWith('xtb')) { return FILETYPE_XTB; } else { return null; } } } /** * Source language as stored in translation file. * @return source language */ public sourceLanguageFromFile(): string { return this._translationFile ? this._translationFile.sourceLanguage() : 'unknown'; } /** * Source language from file or explicitly set. * @return source language */ public sourceLanguage(): string { if (this._translationFile) { const srcLang = this._translationFile.sourceLanguage(); if (isNullOrUndefined(srcLang)) { return this._explicitSourceLanguage ? this._explicitSourceLanguage : ''; } else { return srcLang; } } else { return ''; } } /** * Explicitly set source language. * Only used, when file format does not store this (xmb case). * @param srcLang source language */ public setSourceLanguage(srcLang: string) { this._explicitSourceLanguage = srcLang; } public targetLanguage(): string { return this._translationFile ? this._translationFile.targetLanguage() : ''; } public percentageUntranslated(): number { if (this.numberOfTransUnits === 0) { return 100; } return 100 * this.numberOfUntranslatedTransUnits / this.numberOfTransUnits; } public percentageTranslated(): number { return 100 - this.percentageUntranslated(); } public hasErrors(): boolean { return !isNullOrUndefined(this._error); } public canTranslate(): boolean { return !this.hasErrors() && this.numberOfTransUnits > 0; } get error(): string { return this._error; } /** * Show warnings detected in file. * @return array of warnings */ public warnings(): string[] { return this._translationFile ? this._translationFile.warnings() : []; } /** * Check, wether file is changed. * @return wether file is changed. */ public isDirty(): boolean { return this._translationFile && this._file.content !== this.editedContent(); } /** * return content with all changes. */ public editedContent(): string { if (this._translationFile) { return this._translationFile.editedContent(); } else { this._error = 'cannot save, no valid file'; } } /** * Mark file as "exported". * This means, that the file was downloaded. * So the new file content is the edited one. */ public markExported() { this._file.content = this.editedContent(); } /** * Return all trans units found in file. * @return all trans units found in file */ public allTransUnits(): TranslationUnit[] { return this._allTransUnits; } /** * Return a string representation of translation file content. * This will be stored in BackendService. */ public serialize(serializationService: SerializationService): string { const serializedObject: ISerializedTranslationFileV2 = { version: '2', file: this._file.serialize(serializationService), editedContent: this.editedContent(), master: (this._master) ? this._master.serialize(serializationService) : null, explicitSourceLanguage: this._explicitSourceLanguage }; return JSON.stringify(serializedObject); } /** * Auto translate this file via Google Translate. * Translates all untranslated units. * @param autoTranslateService the service for the raw text translation via Google Translate * @return a summary of the run (how many units are handled, how many sucessful, errors, ..) */ public autoTranslateUsingService(autoTranslateService: AutoTranslateServiceAPI): Observable<AutoTranslateSummaryReport> { return forkJoin([ this.doAutoTranslateNonICUMessages(autoTranslateService), ...this.doAutoTranslateICUMessages(autoTranslateService)]) .pipe( map((summaries: AutoTranslateSummaryReport[]) => { const summary = summaries[0]; for (let i = 1; i < summaries.length; i++) { summary.merge(summaries[i]); } return summary; } )); } /** * Auto translate this file via Google Translate. * Translates all untranslated units. * @param autoTranslateService the service for the raw text translation via Google Translate * @return a summary of the run (how many units are handled, how many sucessful, errors, ..) */ private doAutoTranslateNonICUMessages(autoTranslateService: AutoTranslateServiceAPI): Observable<AutoTranslateSummaryReport> { // collect all units, that should be auto translated const allUntranslated: TranslationUnit[] = this.allTransUnits().filter((tu) => !tu.isTranslated()); const allTranslatable = allUntranslated.filter((tu) => !tu.sourceContentNormalized().isICUMessage()); const allMessages: string[] = allTranslatable.map((tu) => { return tu.sourceContentNormalized().dislayText(true); }); return autoTranslateService.translateMultipleStrings(allMessages, this.sourceLanguage(), this.targetLanguage()) .pipe( map((translations: string[]) => { const summary = new AutoTranslateSummaryReport(); for (let i = 0; i < translations.length; i++) { const tu = allTranslatable[i]; const translationText = translations[i]; const result = tu.autoTranslateNonICUUnit(translationText); summary.addSingleResult(result); } return summary; } )); } private doAutoTranslateICUMessages(autoTranslateService: AutoTranslateServiceAPI): Observable<AutoTranslateSummaryReport>[] { // collect all units, that should be auto translated const allUntranslated: TranslationUnit[] = this.allTransUnits().filter((tu) => !tu.isTranslated()); const allTranslatableICU = allUntranslated.filter((tu) => !isNullOrUndefined(tu.sourceContentNormalized().getICUMessage())); return allTranslatableICU.map((tu) => { return this.doAutoTranslateICUMessage(autoTranslateService, tu); }); } /** * Translate single ICU Messages. * @param autoTranslateService autoTranslateService * @param tu transunit to translate (must contain ICU Message) * @return summaryReport */ private doAutoTranslateICUMessage( autoTranslateService: AutoTranslateServiceAPI, tu: TranslationUnit): Observable<AutoTranslateSummaryReport> { const icuMessage: IICUMessage = tu.sourceContentNormalized().getICUMessage(); const categories = icuMessage.getCategories(); // check for nested ICUs, we do not support that if (categories.find((category) => !isNullOrUndefined(category.getMessageNormalized().getICUMessage()))) { const summary = new AutoTranslateSummaryReport(); summary.addSingleResult(AutoTranslateResult.Ignored(tu, 'nested icu message')); return of(summary); } const allMessages: string[] = categories.map((category) => category.getMessageNormalized().asDisplayString()); return autoTranslateService.translateMultipleStrings(allMessages, this.sourceLanguage(), this.targetLanguage()) .pipe( map((translations: string[]) => { const summary = new AutoTranslateSummaryReport(); const icuTranslation: IICUMessageTranslation = {}; for (let i = 0; i < translations.length; i++) { icuTranslation[categories[i].getCategory()] = translations[i]; } const result = tu.autoTranslateICUUnit(icuTranslation); summary.addSingleResult(result); return summary; } ), catchError((err) => { const failSummary = new AutoTranslateSummaryReport(); failSummary.addSingleResult(AutoTranslateResult.Failed(tu, err.message)); return of(failSummary); } )); } }
the_stack
import * as Fs from 'fs' import { v4 as uuid } from 'uuid' import { findIndex, fromPairs, omit } from 'lodash' import { ApplicationWindow } from '@main/application-window' import { state } from '@lib/state' import { Project as ProjectState } from '@lib/state/project' import { ProjectEventEmitter } from '@lib/frameworks/emitter' import { FrameworkStatus, parseFrameworkStatus } from '@lib/frameworks/status' import { ProgressLedger } from '@lib/frameworks/progress' import { RepositoryOptions, IRepository, Repository } from '@lib/frameworks/repository' import { FrameworkWithContext, IFramework } from '@lib/frameworks/framework' import { Nugget } from '@lib/frameworks/nugget' /** * The minimal options to identify a project by. */ export type ProjectIdentifier = { id?: string name?: string } /** * The models currently active in a project */ export type ProjectActiveIdentifiers = { framework: string | null repository: string | null } /** * The models currently active in a project */ export type ProjectActiveModels = { framework: IFramework | null repository: IRepository | null } export type ProjectEntities = { project: IProject repository: IRepository framework: IFramework nuggets?: Array<Nugget> nugget?: Nugget } /** * Options to instantiate a Project with. */ export type ProjectOptions = { id?: string name?: string active?: ProjectActiveIdentifiers repositories?: Array<RepositoryOptions> status?: FrameworkStatus } export interface IProject extends ProjectEventEmitter { name: string repositories: Array<IRepository> status: FrameworkStatus selected: boolean getId (): string start (): void refresh (): void stop (): Promise<any> reset (): Promise<any> isReady (): boolean isRunning (): boolean isRefreshing (): boolean isBusy (): boolean empty (): boolean render (): ProjectOptions persist (): ProjectOptions save (): void updateOptions (options: ProjectOptions): void delete (): Promise<void> addRepository (options: RepositoryOptions): Promise<IRepository> removeRepository (id: string): void getActive (): ProjectActiveModels setActiveFramework (framework: ProjectActiveIdentifiers['framework']): void getRepositoryById (id: string): IRepository | undefined getContextByFrameworkId (id: string): FrameworkWithContext | undefined getEmptyRepositories (): Array<IRepository> getProgressLedger (): ProgressLedger getProgress (): number emitRepositoriesToRenderer (): void } export class Project extends ProjectEventEmitter implements IProject { public name: string public repositories: Array<IRepository> = [] public status: FrameworkStatus = 'loading' public selected = false protected readonly id: string protected state: ProjectState protected active: ProjectActiveIdentifiers protected parsed = false protected ready = false protected hasRepositories = false protected initialRepositoryCount = 0 protected initialRepositoryReady = 0 constructor (window: ApplicationWindow, identifier: ProjectIdentifier) { super(window) this.id = identifier.id || uuid() this.state = state.project({ ...identifier, id: this.id }) this.name = this.state.get('options.name') // Load options from the persistent project state. const options = this.state.get('options') this.initialRepositoryCount = (options.repositories || []).length this.hasRepositories = this.initialRepositoryCount > 0 this.active = options.active || { framework: null } // If options include repositories already (i.e. persisted state), add them. this.loadRepositories(options.repositories || []) // If this project doesn't yet exist, create it. if (!identifier.id) { this.save() } } /** * Get this project's id. */ public getId (): string { return this.id } /** * Run all of this project's repositories. */ public start (): void { this.repositories.forEach((repository: IRepository) => { repository.start() }) } /** * Refresh all of this project's repositories. */ public refresh (): void { this.repositories.forEach((repository: IRepository) => { repository.refresh() }) } /** * Stop any repository in this project that might be running. */ public async stop (): Promise<any> { return Promise.all(this.repositories.map((repository: IRepository) => { return repository.stop() })) } /** * Reset this project's state. */ public async reset (): Promise<any> { return Promise.all(this.repositories.map((repository: IRepository) => { return repository.reset() })) } /** * Whether this project is ready. */ public isReady (): boolean { return this.ready } /** * Whether this project is running. */ public isRunning (): boolean { return this.repositories.some((repository: IRepository) => repository.isRunning()) } /** * Whether this project is refreshing. */ public isRefreshing (): boolean { return this.repositories.some((repository: IRepository) => repository.isRefreshing()) } /** * Whether this project is busy. */ public isBusy (): boolean { return this.repositories.some((repository: IRepository) => repository.isBusy()) } /** * Whether this project has any repositories. * This is used for layout purposes, so it's not enough to just rely on * an "empty" status, because they will render different calls-to-action. */ public empty (): boolean { return !this.hasRepositories } /** * Prepares the project for sending out to renderer process. */ public render (): ProjectOptions { return { id: this.id, name: this.name, active: this.active, status: this.status } } /** * Prepares the project for persistence. */ public persist (): ProjectOptions { return omit({ ...this.render(), repositories: this.repositories.map(repository => repository.persist()) }, 'status') } /** * Save this project in the persistent store. */ public save (): void { this.state.save(this.persist()) } /** * Update this project's options. * * @param options The new set of options. */ public updateOptions (options: ProjectOptions): void { // Currently only the name is editable this.name = options.name || '' state.updateProject({ id: this.id, name: this.name }) this.save() } /** * Delete this project. */ public async delete (): Promise<void> { await this.stop() return new Promise((resolve, reject) => { Fs.rmdir(this.state.getPath(), { recursive: true }, error => { if (error) { reject(error) return } resolve() }) }) } /** * A function to run when a child repository changes its status. */ protected statusListener () { this.updateStatus(parseFrameworkStatus(this.repositories.map(repository => repository.status))) } /** * A function to run when a child repository changes its state (i.e. runs, stops, etc). */ protected stateListener (): void { const isBusy = this.isBusy() this.state.set('busy', isBusy) this.emit('busy', isBusy) // If project is no longer busy, reset all progress ledgers. if (!isBusy) { this.repositories.forEach((repository: IRepository) => { repository.resetProgressLedger() }) } // Emit progress event, even if progress is currently zero. // This will allow the window to start progress count and feed back to // the user that the window is currently running the project, or reset // the progress if project is no longer running. this.emit('progress', this.getProgress()) } /** * A function to run when a child repository changes. */ protected changeListener (): void { this.save() } /** * A function to run when a child repository progresses. */ protected progressListener (): void { this.emit('progress', this.getProgress()) } /** * Prepare the project for parsed state. */ protected onParsed (): void { this.parsed = true if (!this.initialRepositoryCount) { this.onReady() } this.emit('parsed', this) } /** * Prepare the project for ready state. */ protected onReady (): void { // Ready event will only trigger once. if (this.ready) { return } this.ready = true if (!this.initialRepositoryCount) { this.updateStatus() } this.emit('ready', this) } /** * Listener for when a child framework is ready. */ protected onRepositoryReady (): void { this.initialRepositoryReady++ if (this.initialRepositoryReady >= this.initialRepositoryCount) { this.onReady() } this.save() } /** * Update this project's status. * * @param to The status we're updating to. */ protected updateStatus (to?: FrameworkStatus): void { if (typeof to === 'undefined') { to = parseFrameworkStatus(this.repositories.map(repository => repository.status)) } const from = this.status if (to !== from) { this.status = to this.emit('status', to, from) this.emitToRenderer(`${this.id}:status:index`, to, from) this.emitToRenderer(`${this.id}:status:sidebar`, to, from) } } /** * Load a group of repositories to this project on first instantiation. * * @param repositories The repositories to add to this project. */ protected async loadRepositories (repositories: Array<RepositoryOptions>): Promise<void> { return new Promise((resolve, reject) => { setTimeout(() => { Promise.all(repositories.map((repository: RepositoryOptions) => { return this.addRepository(repository) })).then(() => { this.onParsed() resolve() }) }) }) } /** * Add a child repository to this project. * * @param options The options with which to instantiate the new repository. */ public async addRepository (options: RepositoryOptions): Promise<IRepository> { return new Promise((resolve, reject) => { const repository = new Repository(this.window, options) repository .on('ready', this.onRepositoryReady.bind(this)) .on('status', this.statusListener.bind(this)) .on('state', this.stateListener.bind(this)) .on('change', this.changeListener.bind(this)) .on('progress', this.progressListener.bind(this)) this.repositories.push(repository) this.hasRepositories = true this.updateStatus() resolve(repository) }) } /** * Remove a child repository from this project using its unique id. * * @param id The id of the repository to remove. */ public removeRepository (id: string): void { const index = findIndex(this.repositories, repository => repository.getId() === id) if (index > -1) { this.repositories[index].removeAllListeners() this.repositories.splice(index, 1) this.updateStatus() } if (!this.repositories.length) { this.hasRepositories = false } this.save() } /** * Get the project's active models. */ public getActive (): ProjectActiveModels { // If an active framework is set, attempt to return it, if it still exists. if (this.active.framework) { let framework for (let i = this.repositories.length - 1; i >= 0; i--) { framework = this.repositories[i].getFrameworkById(this.active.framework) if (framework) { return { framework, repository: this.repositories[i] } } } } // Otherwise, iterate through the repositories and return the first // available framework. for (let i = this.repositories.length - 1; i >= 0; i--) { if (this.repositories[i].frameworks.length) { return { framework: this.repositories[i].frameworks[0], repository: this.repositories[i] } } } return { framework: null, repository: null } } /** * Set the project's active framework. */ public setActiveFramework (framework: ProjectActiveIdentifiers['framework']): void { this.active.framework = framework } /** * Retrieve a repository from this project by its id. * * @param id The id of the repository to retrieve. */ public getRepositoryById (id: string): IRepository | undefined { const index = findIndex(this.repositories, repository => repository.getId() === id) if (index > -1) { return this.repositories[index] } return undefined } /** * Retrieve a framework and its repository from this project * using only the framework id. * * @param id The id of the framework to retrieve. */ public getContextByFrameworkId (id: string): FrameworkWithContext | undefined { const map: { [key: string]: [number, number] } = fromPairs( this.repositories .map( (repository, i) => repository.frameworks.map( (framework, j) => [framework.getId(), [i, j]] ) ) .flat() ) if (map[id]) { return { repository: this.repositories[map[id][0]], framework: this.repositories[map[id][0]].frameworks[map[id][1]] } } return } /** * Get an array of repositories without frameworks. */ public getEmptyRepositories (): Array<IRepository> { return this.repositories.filter((repository: IRepository) => repository.empty()) } /** * Return the project's progress ledger. */ public getProgressLedger (): ProgressLedger { return this.repositories.reduce((ledger: ProgressLedger, reopsitory: IRepository) => { const reopsitoryLedger: ProgressLedger = reopsitory.getProgressLedger() ledger.run += reopsitoryLedger.run ledger.total += reopsitoryLedger.total return ledger }, { run: 0, total: 0 }) } /** * Return the project's progress. */ public getProgress (): number { const ledger = this.getProgressLedger() return ledger.total ? ledger.run / ledger.total : -1 } /** * Send project's repositories to the renderer process. */ public emitRepositoriesToRenderer (): void { this.emitToRenderer(`${this.id}:repositories`, this.repositories.map((repository: IRepository) => repository.render())) } }
the_stack
namespace phasereditor2d.scene.core.code { import io = colibri.core.io; import ISceneGameObject = ui.sceneobjects.ISceneGameObject; import Container = ui.sceneobjects.Container; import Layer = ui.sceneobjects.Layer; export class SceneCodeDOMBuilder { private _scene: ui.Scene; private _isPrefabScene: boolean; private _sceneFile: io.FilePath; private _unit: UnitCodeDOM; constructor(scene: ui.Scene, file: io.FilePath) { this._scene = scene; this._sceneFile = file; this._isPrefabScene = this._scene.isPrefabSceneType(); } async build(): Promise<UnitCodeDOM> { const settings = this._scene.getSettings(); const methods: MemberDeclCodeDOM[] = []; const unit = new UnitCodeDOM([]); this._unit = unit; if (settings.onlyGenerateMethods) { const createMethodDecl = this.buildCreateMethod(); await this.buildPreloadMethod(unit.getBody() as any); unit.getBody().push(createMethodDecl); } else { const clsName = this._sceneFile.getNameWithoutExtension(); const clsDecl = new ClassDeclCodeDOM(clsName); clsDecl.setExportClass(settings.exportClass); let superCls: string; if (this._isPrefabScene) { const obj = this._scene.getPrefabObject(); if (!obj) { return null; } const support = obj.getEditorSupport(); if (obj.getEditorSupport().isPrefabInstance()) { superCls = support.getPrefabName(); } else { superCls = support.getPhaserType(); } superCls = settings.superClassName.trim().length === 0 ? superCls : settings.superClassName; } else { superCls = settings.superClassName.trim().length === 0 ? "Phaser.Scene" : settings.superClassName; } clsDecl.setSuperClass(superCls); if (superCls.startsWith("Phaser.")) { unit.addImport("Phaser", "phaser"); } if (this._isPrefabScene) { // prefab constructor const ctrMethod = this.buildPrefabConstructorMethod(); methods.push(ctrMethod); } else { // scene constructor const key = settings.sceneKey; if (key.trim().length > 0) { const ctrMethod = this.buildSceneConstructorMethod(key); methods.push(ctrMethod); } // scene preload method await this.buildPreloadMethod(methods); // scene create method const createMethodDecl = this.buildCreateMethod(); methods.push(createMethodDecl); } const fields: MemberDeclCodeDOM[] = []; this.buildObjectClassFields(fields, this._scene.getDisplayListChildren()); this.buildListClassFields(fields); if (this._isPrefabScene) { this.buildPrefabPropertiesFields(fields); } clsDecl.getBody().push(...methods); clsDecl.getBody().push(...fields); if (this._isPrefabScene) { clsDecl.getBody().push(new UserSectionCodeDOM( "/* START-USER-CODE */", "/* END-USER-CODE */", "\n\n\t// Write your code here.\n\n\t")); } else { const defaultContent = [ "", "", "// Write your code here", "", "create() {", "", "\tthis.editorCreate();", "}", "", ""].join("\n\t"); clsDecl.getBody().push(new UserSectionCodeDOM( "/* START-USER-CODE */", "/* END-USER-CODE */", defaultContent)); } unit.getBody().push(clsDecl); } if (!settings.autoImport) { unit.removeImports(); } return unit; } buildPrefabPropertiesFields(fields: MemberDeclCodeDOM[]) { const decls = this._scene.getPrefabUserProperties() .getProperties() .filter(prop => !prop.isCustomDefinition()) .flatMap(prop => prop.buildFieldDeclarationCode()); fields.push(...decls); } private buildListClassFields(fields: MemberDeclCodeDOM[]) { const objMap = this._scene.buildObjectIdMap(); for (const list of this._scene.getObjectLists().getLists()) { if (list.getScope() !== ui.sceneobjects.ObjectScope.METHOD) { const listType = list.inferType(objMap); const dom = new FieldDeclCodeDOM( formatToValidVarName(list.getLabel()), listType, list.getScope() === ui.sceneobjects.ObjectScope.PUBLIC); dom.setAllowUndefined(!this._scene.isPrefabSceneType()); fields.push(dom); } } } private buildObjectClassFields(fields: MemberDeclCodeDOM[], children: ISceneGameObject[]) { for (const obj of children) { const support = obj.getEditorSupport(); const isMethodScope = support.getScope() === ui.sceneobjects.ObjectScope.METHOD; const isPrefabObj = this._scene.isPrefabSceneType() && this._scene.getPrefabObject() === obj; const isPrefabScene = this._scene.isPrefabSceneType(); if (!isMethodScope && !isPrefabObj) { const varName = code.formatToValidVarName(support.getLabel()); const type = support.isPrefabInstance() ? support.getPrefabName() : support.getPhaserType(); const isPublic = support.isPublic(); const field = new FieldDeclCodeDOM(varName, type, isPublic); // Allow undefined if the object is part of a scene. // In a prefab, the objects are created in the constructor field.setAllowUndefined(!isPrefabScene); fields.push(field); } if ((obj instanceof Container || obj instanceof Layer) && !obj.getEditorSupport().isPrefabInstance()) { this.buildObjectClassFields(fields, obj.getChildren()); } } } private buildPrefabConstructorMethod() { const ctrDecl = new code.MethodDeclCodeDOM("constructor"); const body = ctrDecl.getBody(); const prefabObj = this._scene.getPrefabObject(); if (!prefabObj) { throw new Error("Invalid prefab scene state: missing object."); } const type = prefabObj.getEditorSupport().getObjectType(); const ext = ScenePlugin.getInstance().getGameObjectExtensionByObjectType(type); const objBuilder = ext.getCodeDOMBuilder(); ctrDecl.arg("scene", "Phaser.Scene"); objBuilder.buildPrefabConstructorDeclarationCodeDOM({ ctrDeclCodeDOM: ctrDecl }); { const superCall = new MethodCallCodeDOM("super"); superCall.arg("scene"); objBuilder.buildPrefabConstructorDeclarationSupperCallCodeDOM({ superMethodCallCodeDOM: superCall, prefabObj: prefabObj }); body.push(superCall); body.push(new RawCodeDOM("")); } const lazyStatements: CodeDOM[] = []; const result = this.buildSetObjectProperties({ obj: prefabObj, varname: "this" }); lazyStatements.push(...result.lazyStatements); body.push(...result.statements); if (prefabObj instanceof Container || prefabObj instanceof Layer) { this.addChildrenObjects({ createMethodDecl: ctrDecl, obj: prefabObj, lazyStatements }); } this.addCreateAllPlainObjectCode(ctrDecl); this.addCreateListsCode(body); body.push(...lazyStatements); this.addFieldInitCode(body); { // prefab awake handler const settings = this._scene.getSettings(); if (settings.generateAwakeHandler) { body.push(new RawCodeDOM("// awake handler")); body.push(new RawCodeDOM("this.scene.events.once(\"scene-awake\", () => this.awake());")); body.push(new RawCodeDOM("")); } } body.push(new RawCodeDOM("")); body.push(new UserSectionCodeDOM("/* START-USER-CTR-CODE */", "/* END-USER-CTR-CODE */", "\n\t\t// Write your code here.\n\t\t")) this.buildCustomPropertiesInit(body); return ctrDecl; } private buildCustomPropertiesInit(body: code.CodeDOM[]) { const userProps = this._scene.getPrefabUserProperties(); const assignDomList = userProps.getProperties() .filter(prop => prop.isCustomDefinition()) .map(prop => { const fieldDecl = prop.buildFieldDeclarationCode(); const assignDom = new code.AssignPropertyCodeDOM(fieldDecl.getName(), "this"); assignDom.value(fieldDecl.getInitialValueExpr()); return assignDom; }); if (assignDomList.length > 0) { body.push(new code.RawCodeDOM("\n")); body.push(new code.RawCodeDOM("// custom definition props")); } body.push(...assignDomList); } private buildCreateMethod() { const settings = this._scene.getSettings(); const createMethodDecl = new MethodDeclCodeDOM(settings.createMethodName); createMethodDecl.setReturnType("void"); if (settings.onlyGenerateMethods && this._scene.isPrefabSceneType()) { createMethodDecl.arg("scene", "Phaser.Scene"); } const body = createMethodDecl.getBody(); this.addCreateAllPlainObjectCode(createMethodDecl); const lazyStatements: CodeDOM[] = []; for (const obj of this._scene.getDisplayListChildren()) { if (obj.getEditorSupport().isMutableNestedPrefabInstance()) { this.addCreateObjectCodeOfNestedPrefab(obj, createMethodDecl, lazyStatements); } else { body.push(new RawCodeDOM("")); body.push(new RawCodeDOM("// " + obj.getEditorSupport().getLabel())); this.addCreateObjectCode(obj, createMethodDecl, lazyStatements); } } this.addCreateListsCode(body); body.push(...lazyStatements); this.addFieldInitCode(body); body.push(new RawCodeDOM("")); body.push(new RawCodeDOM(`this.events.emit("scene-awake");`)); return createMethodDecl; } private addCreateAllPlainObjectCode(createMethodDecl: MethodDeclCodeDOM) { const body = createMethodDecl.getBody(); for (const obj of this._scene.getPlainObjects()) { body.push(new RawCodeDOM("")); body.push(new RawCodeDOM("// " + obj.getEditorSupport().getLabel())); this.addCreatePlainObjectCode(obj, createMethodDecl); } } private addCreateListsCode(body: CodeDOM[]) { const lists = this._scene.getObjectLists().getLists(); if (lists.length > 0) { body.push( new RawCodeDOM(""), new RawCodeDOM("// lists")); } for (const list of lists) { const map = this._scene.buildObjectIdMap(); const objectVarnames: string[] = []; for (const objId of list.getObjectIds()) { const obj = map.get(objId); if (obj) { objectVarnames.push(formatToValidVarName(obj.getEditorSupport().getLabel())); } } const varname = formatToValidVarName(list.getLabel()); let dom: RawCodeDOM; const isTsOutput = this._scene.getSettings().compilerOutputLanguage === "TYPE_SCRIPT"; if (isTsOutput && objectVarnames.length === 0) { dom = new RawCodeDOM(`const ${varname}: Array<any> = [${objectVarnames.join(", ")}]`); } else { dom = new RawCodeDOM(`const ${varname} = [${objectVarnames.join(", ")}]`); } body.push(dom); } } private addFieldInitCode(body: CodeDOM[]) { const fields: CodeDOM[] = []; this._scene.visitAskChildren(obj => { const support = obj.getEditorSupport(); const prefabObj = this._scene.isPrefabSceneType() ? this._scene.getPrefabObject() : null; if (!support.isMethodScope() && prefabObj !== obj) { const varname = formatToValidVarName(support.getLabel()); const dom = new AssignPropertyCodeDOM(varname, "this"); dom.value(varname); fields.push(dom); } return !support.isPrefabInstance(); }); for (const obj of this._scene.getPlainObjects()) { const editorSupport = obj.getEditorSupport(); if (editorSupport.getScope() !== ui.sceneobjects.ObjectScope.METHOD) { const varname = formatToValidVarName(editorSupport.getLabel()); const dom = new AssignPropertyCodeDOM(varname, "this"); dom.value(varname); fields.push(dom); } } for (const list of this._scene.getObjectLists().getLists()) { if (list.getScope() !== ui.sceneobjects.ObjectScope.METHOD) { const varname = formatToValidVarName(list.getLabel()); const dom = new AssignPropertyCodeDOM(varname, "this"); dom.value(varname); fields.push(dom); } } if (fields.length > 0) { body.push(new RawCodeDOM("")); body.push(...fields); } } private addCreatePlainObjectCode( obj: ui.sceneobjects.IScenePlainObject, createMethodDecl: MethodDeclCodeDOM) { const objSupport = obj.getEditorSupport(); const varname = formatToValidVarName(objSupport.getLabel()); const createObjectMethodCalls = objSupport.getExtension().buildCreateObjectWithFactoryCodeDOM({ gameObjectFactoryExpr: this._scene.isPrefabSceneType() ? "scene" : "this", obj: obj, varname }) createMethodDecl.getBody().push(...createObjectMethodCalls); const mainCreateMethodCall = createObjectMethodCalls[0]; mainCreateMethodCall.setDeclareReturnToVar(true); if (!objSupport.isMethodScope()) { mainCreateMethodCall.setDeclareReturnToVar(true); mainCreateMethodCall.setDeclareReturnToField(true); } if (mainCreateMethodCall.isDeclareReturnToVar()) { mainCreateMethodCall.setReturnToVar(varname); } } private addCreateObjectCodeOfNestedPrefab(obj: ISceneGameObject, createMethodDecl: MethodDeclCodeDOM, lazyStatements: CodeDOM[]) { const varname = this.getPrefabInstanceVarName(obj); const result = this.buildSetObjectProperties({ obj, varname }); lazyStatements.push(...result.lazyStatements); createMethodDecl.getBody().push(...result.statements); if (obj instanceof Container || obj instanceof Layer) { this.addChildrenObjects({ createMethodDecl, obj, lazyStatements }); } } private addCreateObjectCode(obj: ISceneGameObject, createMethodDecl: MethodDeclCodeDOM, lazyStatements: CodeDOM[]) { const objSupport = obj.getEditorSupport(); let createObjectMethodCall: MethodCallCodeDOM; if (objSupport.isPrefabInstance()) { const clsName = objSupport.getPrefabName(); const type = objSupport.getObjectType(); const ext = ScenePlugin.getInstance().getGameObjectExtensionByObjectType(type); createObjectMethodCall = new code.MethodCallCodeDOM(clsName); createObjectMethodCall.setConstructor(true); const prefabSerializer = objSupport.getPrefabSerializer(); if (prefabSerializer) { const builder = ext.getCodeDOMBuilder(); builder.buildCreatePrefabInstanceCodeDOM({ obj, methodCallDOM: createObjectMethodCall, sceneExpr: this._isPrefabScene ? "scene" : "this", prefabSerializer }); const filePath = code.getImportPath(this._sceneFile, objSupport.getPrefabFile()); this._unit.addImport(clsName, filePath); } else { throw new Error(`Cannot find prefab with id ${objSupport.getPrefabId()}.`); } } else { const builder = objSupport.getExtension().getCodeDOMBuilder(); createObjectMethodCall = builder.buildCreateObjectWithFactoryCodeDOM({ gameObjectFactoryExpr: this._scene.isPrefabSceneType() ? "scene.add" : "this.add", obj: obj }); } const varname = formatToValidVarName(objSupport.getLabel()); const objParent = ui.sceneobjects.getObjectParent(obj); createMethodDecl.getBody().push(createObjectMethodCall); if (objSupport.isPrefabInstance()) { createObjectMethodCall.setDeclareReturnToVar(true); if (!objParent) { const addToScene = new MethodCallCodeDOM("existing", "this.add"); addToScene.arg(varname); createMethodDecl.getBody().push(addToScene); } } const result = this.buildSetObjectProperties({ obj, varname }); if (result.statements.length + result.lazyStatements.length > 0) { createObjectMethodCall.setDeclareReturnToVar(true); } lazyStatements.push(...result.lazyStatements); createMethodDecl.getBody().push(...result.statements); if (objParent) { createObjectMethodCall.setDeclareReturnToVar(true); const parentIsPrefabObject = this._scene.isPrefabSceneType() && objParent === this._scene.getPrefabObject(); const parentVarname = parentIsPrefabObject ? "this" : formatToValidVarName(objParent.getEditorSupport().getLabel()); const addToParentCall = new MethodCallCodeDOM("add", parentVarname); addToParentCall.arg(varname); createMethodDecl.getBody().push(addToParentCall); } if (obj instanceof Container || obj instanceof Layer) { createObjectMethodCall.setDeclareReturnToVar(true); this.addChildrenObjects({ createMethodDecl, obj, lazyStatements }); } { const lists = objSupport.getScene().getObjectLists().getListsByObjectId(objSupport.getId()); if (lists.length > 0) { createObjectMethodCall.setDeclareReturnToVar(true); } } if (!objSupport.isMethodScope()) { createObjectMethodCall.setDeclareReturnToVar(true); createObjectMethodCall.setDeclareReturnToField(true); } if (createObjectMethodCall.isDeclareReturnToVar()) { createObjectMethodCall.setReturnToVar(varname); } } private getPrefabInstanceVarName(obj: ISceneGameObject) { const support = obj.getEditorSupport(); const parent = ui.sceneobjects.getObjectParent(obj); const varName = support.isScenePrefabObject() ? "this" : formatToValidVarName(support.getLabel()); if (support.isNestedPrefabInstance()) { const parentVarName = this.getPrefabInstanceVarName(parent); return parentVarName + "." + varName; } return varName; } private buildSetObjectProperties(args: { obj: ISceneGameObject, varname: string }) { const obj = args.obj; const support = obj.getEditorSupport(); const varname = args.varname; let prefabSerializer: json.Serializer = null; if (support.isPrefabInstance()) { prefabSerializer = support.getPrefabSerializer(); } const statements: CodeDOM[] = []; const lazyStatements: CodeDOM[] = []; for (const comp of support.getComponents()) { comp.buildSetObjectPropertiesCodeDOM({ statements, lazyStatements, objectVarName: varname, prefabSerializer: prefabSerializer, unit: this._unit, sceneFile: this._sceneFile }); } return { statements, lazyStatements }; } private addChildrenObjects(args: { obj: Container | Layer, createMethodDecl: MethodDeclCodeDOM, lazyStatements: CodeDOM[] }) { const body = args.createMethodDecl.getBody(); const parentIsPrefab = args.obj.getEditorSupport().isPrefabInstance(); for (const child of args.obj.getChildren()) { if (child.getEditorSupport().isMutableNestedPrefabInstance()) { this.addCreateObjectCodeOfNestedPrefab(child, args.createMethodDecl, args.lazyStatements); } else if (!parentIsPrefab) { body.push(new RawCodeDOM("")); body.push(new RawCodeDOM("// " + child.getEditorSupport().getLabel())); this.addCreateObjectCode(child, args.createMethodDecl, args.lazyStatements); } } } private buildSceneConstructorMethod(sceneKey: string) { const methodDecl = new MethodDeclCodeDOM("constructor"); const superCall = new MethodCallCodeDOM("super", null); superCall.argLiteral(sceneKey); const body = methodDecl.getBody(); body.push(superCall); body.push(new RawCodeDOM("")); body.push(new UserSectionCodeDOM("/* START-USER-CTR-CODE */", "/* END-USER-CTR-CODE */", "\n\t\t// Write your code here.\n\t\t")) return methodDecl; } private async buildPreloadMethod(methods: MemberDeclCodeDOM[]) { const settings = this._scene.getSettings(); if (settings.preloadPackFiles.length === 0) { return; } const preloadDom = new MethodDeclCodeDOM(settings.preloadMethodName); preloadDom.setReturnType("void"); preloadDom.getBody().push(new RawCodeDOM("")); const ctx = (this._isPrefabScene ? "scene" : "this"); for (const fileName of settings.preloadPackFiles) { const call = new MethodCallCodeDOM("pack", ctx + ".load"); const parts = fileName.split("/"); const namePart = parts[parts.length - 1]; const key = namePart.substring(0, namePart.length - 5); const file = colibri.ui.ide.FileUtils.getFileFromPath(fileName); let fileUrl = parts.slice(1).join("/"); if (file) { fileUrl = pack.core.AssetPackUtils.getUrlFromAssetFile(file.getParent(), file); } call.argLiteral(key); call.argLiteral(fileUrl); preloadDom.getBody().push(call); } methods.push(preloadDom); } } }
the_stack
import 'jest-extended'; import FormData from 'form-data'; import { BaseResource, RequesterType } from '@gitbeaker/requester-utils'; import { RequestHelper } from '../../../src/infrastructure/RequestHelper'; /* eslint no-empty-pattern: 0 */ /* eslint prefer-destructuring: 0 */ function mockLink(url: string, page: number, perPage: number, maxPages: number) { const type = { prev: page - 1 > 0 ? page - 1 : undefined, current: page, next: page + 1 <= maxPages ? page + 1 : undefined, first: 1, last: maxPages, }; const links = Object.entries(type).reduce((acc, [k, v]) => { if (v) acc.push(`<${url}?page=${v}&per_page=${perPage}>; rel="${k}"`); return acc; }, [] as string[]); return { link: links.join(','), pagination: type }; } function mockedGetMany(url: string, { query }, maxPages = 10) { const { page = 1, perPage = 2, }: { perPage: number; page: number; } = query; // Only load pages needed for the test const { link, pagination } = mockLink(url, page, perPage, maxPages); return { body: new Array(perPage).fill(null).map((_, i) => ({ prop1: (page - 1) * perPage + i + 1, // Index from 1, not 0 prop2: `test property ${(page - 1) * perPage + i + 1}`, })), headers: { link, 'x-next-page': pagination.next, 'x-page': page, 'x-per-page': perPage, 'x-prev-page': pagination.prev, 'x-total': maxPages * perPage, 'x-total-pages': maxPages, }, }; } function mockedGetOne() { return { status: 200, body: { prop1: 5, prop2: 'test property', }, headers: { 'X-Page': 1, 'X-Total-Pages': 1, }, }; } let service: BaseResource; beforeEach(() => { service = new BaseResource({ requesterFn: () => ({} as RequesterType), host: 'https://testing.com', token: 'token', }); }); describe('RequestHelper.get()', () => { it('should respond with the proper get url without pagination', async () => { service.requester.get = jest.fn(() => Promise.resolve(mockedGetOne())); await RequestHelper.get()(service, 'test'); expect(service.requester.get).toHaveBeenCalledWith('test', { query: {}, sudo: undefined, }); }); it('should respond with the a wrapped body', async () => { service.requester.get = jest.fn(() => Promise.resolve(mockedGetOne())); const response = await RequestHelper.get()(service, 'test', { showExpanded: true }); expect(response).toMatchObject({ data: { prop1: 5, prop2: 'test property', }, headers: { 'X-Page': 1, }, status: 200, }); }); it('should respond with an object', async () => { service.requester.get = jest.fn(() => Promise.resolve(mockedGetOne())); const response = await RequestHelper.get()(service, 'test'); expect(response.prop1).toBe(5); expect(response.prop2).toBe('test property'); }); it('should be paginated when links are present', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test'); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); expect(response).toHaveLength(20); }); it('should handle large paginated (50 pages) results when links are present', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query }, 50)), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { maxPages: 50, }); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); expect(response).toHaveLength(100); }); it('should be paginated but limited by the maxPages option', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query }, 3)), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { maxPages: 3, }); expect(response).toHaveLength(6); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); }); it('should be paginated but limited by the page option', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { page: 2, }); expect(response).toHaveLength(2); response.forEach((l, index) => { expect(l.prop1).toBe(3 + index); expect(l.prop2).toBe(`test property ${3 + index}`); }); }); it('should show the pagination information when the showExpanded option is given', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { page: 2, showExpanded: true, }); expect(response.data).toHaveLength(2); response.data.forEach((l, index) => { expect(l.prop1).toBe(3 + index); expect(l.prop2).toBe(`test property ${3 + index}`); }); expect(response.paginationInfo).toMatchObject({ total: 20, previous: 1, current: 2, next: 3, perPage: 2, totalPages: 10, }); }); it('should not show the pagination information when the showExpanded option is undefined or false', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { page: 2, showExpanded: false, }); expect(response).toHaveLength(2); response.forEach((l, index) => { expect(l.prop1).toBe(3 + index); expect(l.prop2).toBe(`test property ${3 + index}`); }); }); it('should not show the pagination information when using keyset pagination', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { pagination: 'keyset', }); expect(response).toHaveLength(20); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); }); it('should support maxPages when using keyset pagination', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query }, 2)), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { pagination: 'keyset', maxPages: 2, }); expect(response).toHaveLength(4); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); }); it('should not show the pagination information when using keyset pagination and showExpanded is given', async () => { service.requester.get = jest.fn((endpoint, options = {}) => Promise.resolve(mockedGetMany(`${service.url}${endpoint}`, { query: options.query })), ); const response = await RequestHelper.get<Record<string, unknown>[]>()(service, 'test', { pagination: 'keyset', showExpanded: true, }); expect(response).toHaveLength(20); response.forEach((l, index) => { expect(l.prop1).toBe(1 + index); expect(l.prop2).toBe(`test property ${1 + index}`); }); }); it('should return simple response with camelized keys when using the camelize option', async () => { const s = new BaseResource({ requesterFn: () => ({} as RequesterType), host: 'https://testing.com', token: 'token', camelize: true, }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore s.show = jest.fn(() => RequestHelper.get()(s, 'test')); s.requester.get = jest.fn(() => Promise.resolve({ body: [ { id: 3, gravatar_enable: true }, // eslint-disable-line { id: 4, gravatar_enable: false }, // eslint-disable-line ], headers: {}, }), ); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const results = await s.show(); expect(results).toIncludeSameMembers([ { id: 3, gravatarEnable: true }, { id: 4, gravatarEnable: false }, ]); }); it('should return simple response with default keys without camelize option', async () => { class SpecialService extends BaseResource { show() { return RequestHelper.get()(this, 'test'); } } const specialService = new SpecialService({ requesterFn: () => ({} as RequesterType), host: 'https://testing.com', token: 'token', }); specialService.requester.get = jest.fn(() => Promise.resolve({ body: { id: 3, gravatar_enable: true }, headers: {}, }), ); const results = await specialService.show(); expect(results).toMatchObject({ id: 3, gravatar_enable: true }); // eslint-disable-line }); }); describe('RequestHelper.stream()', () => { it('should throw an error when the stream function isnt available', () => { service.requester.stream = undefined; expect(() => RequestHelper.stream(service, 'test')).toThrow( 'Stream method is not implementated in requester!', ); }); it('should not throw an error when the stream function is available', () => { service.requester.stream = jest.fn(); RequestHelper.stream(service, 'test'); expect(service.requester.stream).toBeCalled(); }); }); describe('RequestHelper.post()', () => { it('should pass the correct arguments to the Requester', async () => { service.requester.post = jest.fn(() => Promise.resolve({ body: '' })); await RequestHelper.post()(service, 'test', { sudo: 'yes' }); expect(service.requester.post).toBeCalledWith('test', { body: {}, sudo: 'yes' }); }); it('should respond with the a wrapped body', async () => { const responseTemplate = { status: 200, headers: { test: 1 }, body: '' }; service.requester.post = jest.fn(() => Promise.resolve(responseTemplate)); const response = await RequestHelper.post()(service, 'test', { showExpanded: true }); expect(response).toMatchObject({ data: responseTemplate.body, headers: responseTemplate.headers, status: responseTemplate.status, }); }); it('should pass arguments as form arguments if the isForm flag is passed', async () => { service.requester.post = jest.fn(() => Promise.resolve({ body: '' })); await RequestHelper.post()(service, 'test', { isForm: true, test: 3 }); expect(service.requester.post).toBeCalledWith('test', { body: expect.any(FormData), sudo: undefined, }); }); }); describe('RequestHelper.put()', () => { it('should pass the correct arguments to the Requester', async () => { service.requester.put = jest.fn(() => Promise.resolve({ body: '' })); await RequestHelper.put()(service, 'test', { sudo: 'yes' }); expect(service.requester.put).toBeCalledWith('test', { body: {}, sudo: 'yes' }); }); it('should respond with the a wrapped body', async () => { const responseTemplate = { status: 200, headers: { test: 1 }, body: '' }; service.requester.put = jest.fn(() => Promise.resolve(responseTemplate)); const response = await RequestHelper.put()(service, 'test', { showExpanded: true }); expect(response).toMatchObject({ data: responseTemplate.body, headers: responseTemplate.headers, status: responseTemplate.status, }); }); }); describe('RequestHelper.del()', () => { it('should pass the correct arguments to the Requester', async () => { service.requester.delete = jest.fn(() => Promise.resolve({ body: '' })); await RequestHelper.del()(service, 'test', { sudo: 'yes' }); expect(service.requester.delete).toBeCalledWith('test', { query: {}, sudo: 'yes' }); }); });
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateClusterCommand, CreateClusterCommandInput, CreateClusterCommandOutput, } from "./commands/CreateClusterCommand"; import { CreateControlPanelCommand, CreateControlPanelCommandInput, CreateControlPanelCommandOutput, } from "./commands/CreateControlPanelCommand"; import { CreateRoutingControlCommand, CreateRoutingControlCommandInput, CreateRoutingControlCommandOutput, } from "./commands/CreateRoutingControlCommand"; import { CreateSafetyRuleCommand, CreateSafetyRuleCommandInput, CreateSafetyRuleCommandOutput, } from "./commands/CreateSafetyRuleCommand"; import { DeleteClusterCommand, DeleteClusterCommandInput, DeleteClusterCommandOutput, } from "./commands/DeleteClusterCommand"; import { DeleteControlPanelCommand, DeleteControlPanelCommandInput, DeleteControlPanelCommandOutput, } from "./commands/DeleteControlPanelCommand"; import { DeleteRoutingControlCommand, DeleteRoutingControlCommandInput, DeleteRoutingControlCommandOutput, } from "./commands/DeleteRoutingControlCommand"; import { DeleteSafetyRuleCommand, DeleteSafetyRuleCommandInput, DeleteSafetyRuleCommandOutput, } from "./commands/DeleteSafetyRuleCommand"; import { DescribeClusterCommand, DescribeClusterCommandInput, DescribeClusterCommandOutput, } from "./commands/DescribeClusterCommand"; import { DescribeControlPanelCommand, DescribeControlPanelCommandInput, DescribeControlPanelCommandOutput, } from "./commands/DescribeControlPanelCommand"; import { DescribeRoutingControlCommand, DescribeRoutingControlCommandInput, DescribeRoutingControlCommandOutput, } from "./commands/DescribeRoutingControlCommand"; import { DescribeSafetyRuleCommand, DescribeSafetyRuleCommandInput, DescribeSafetyRuleCommandOutput, } from "./commands/DescribeSafetyRuleCommand"; import { ListAssociatedRoute53HealthChecksCommand, ListAssociatedRoute53HealthChecksCommandInput, ListAssociatedRoute53HealthChecksCommandOutput, } from "./commands/ListAssociatedRoute53HealthChecksCommand"; import { ListClustersCommand, ListClustersCommandInput, ListClustersCommandOutput, } from "./commands/ListClustersCommand"; import { ListControlPanelsCommand, ListControlPanelsCommandInput, ListControlPanelsCommandOutput, } from "./commands/ListControlPanelsCommand"; import { ListRoutingControlsCommand, ListRoutingControlsCommandInput, ListRoutingControlsCommandOutput, } from "./commands/ListRoutingControlsCommand"; import { ListSafetyRulesCommand, ListSafetyRulesCommandInput, ListSafetyRulesCommandOutput, } from "./commands/ListSafetyRulesCommand"; import { UpdateControlPanelCommand, UpdateControlPanelCommandInput, UpdateControlPanelCommandOutput, } from "./commands/UpdateControlPanelCommand"; import { UpdateRoutingControlCommand, UpdateRoutingControlCommandInput, UpdateRoutingControlCommandOutput, } from "./commands/UpdateRoutingControlCommand"; import { UpdateSafetyRuleCommand, UpdateSafetyRuleCommandInput, UpdateSafetyRuleCommandOutput, } from "./commands/UpdateSafetyRuleCommand"; import { Route53RecoveryControlConfigClient } from "./Route53RecoveryControlConfigClient"; /** * <p>Recovery Control Configuration API Reference for Amazon Route 53 Application Recovery Controller</p> */ export class Route53RecoveryControlConfig extends Route53RecoveryControlConfigClient { /** * <p>Create a new cluster. A cluster is a set of redundant Regional endpoints against which you can run API calls to update or get the state of one or more routing controls. Each cluster has a name, status, Amazon Resource Name (ARN), and an array of the five cluster endpoints (one for each supported Amazon Web Services Region) that you can use with API calls to the Amazon Route 53 Application Recovery Controller cluster data plane.</p> */ public createCluster( args: CreateClusterCommandInput, options?: __HttpHandlerOptions ): Promise<CreateClusterCommandOutput>; public createCluster( args: CreateClusterCommandInput, cb: (err: any, data?: CreateClusterCommandOutput) => void ): void; public createCluster( args: CreateClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateClusterCommandOutput) => void ): void; public createCluster( args: CreateClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateClusterCommandOutput) => void), cb?: (err: any, data?: CreateClusterCommandOutput) => void ): Promise<CreateClusterCommandOutput> | void { const command = new CreateClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new control panel. A control panel represents a group of routing controls that can be changed together in a single transaction. You can use a control panel to centrally view the operational status of applications across your organization, and trigger multi-app failovers in a single transaction, for example, to fail over an Availability Zone or AWS Region.</p> */ public createControlPanel( args: CreateControlPanelCommandInput, options?: __HttpHandlerOptions ): Promise<CreateControlPanelCommandOutput>; public createControlPanel( args: CreateControlPanelCommandInput, cb: (err: any, data?: CreateControlPanelCommandOutput) => void ): void; public createControlPanel( args: CreateControlPanelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateControlPanelCommandOutput) => void ): void; public createControlPanel( args: CreateControlPanelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateControlPanelCommandOutput) => void), cb?: (err: any, data?: CreateControlPanelCommandOutput) => void ): Promise<CreateControlPanelCommandOutput> | void { const command = new CreateControlPanelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new routing control.</p> <p>A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control traffic routing.</p> <p>To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.</p> */ public createRoutingControl( args: CreateRoutingControlCommandInput, options?: __HttpHandlerOptions ): Promise<CreateRoutingControlCommandOutput>; public createRoutingControl( args: CreateRoutingControlCommandInput, cb: (err: any, data?: CreateRoutingControlCommandOutput) => void ): void; public createRoutingControl( args: CreateRoutingControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateRoutingControlCommandOutput) => void ): void; public createRoutingControl( args: CreateRoutingControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateRoutingControlCommandOutput) => void), cb?: (err: any, data?: CreateRoutingControlCommandOutput) => void ): Promise<CreateRoutingControlCommandOutput> | void { const command = new CreateRoutingControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a safety rule in a control panel. Safety rules let you add safeguards around enabling and disabling routing controls, to help prevent unexpected outcomes.</p> <p>There are two types of safety rules: assertion rules and gating rules.</p> <p>Assertion rule: An assertion rule enforces that, when a routing control state is changed, the criteria set by the rule configuration is met. Otherwise, the change to the routing control is not accepted.</p> <p>Gating rule: A gating rule verifies that a set of gating controls evaluates as true, based on a rule configuration that you specify. If the gating rule evaluates to true, Amazon Route 53 Application Recovery Controller allows a set of routing control state changes to run and complete against the set of target controls.</p> */ public createSafetyRule( args: CreateSafetyRuleCommandInput, options?: __HttpHandlerOptions ): Promise<CreateSafetyRuleCommandOutput>; public createSafetyRule( args: CreateSafetyRuleCommandInput, cb: (err: any, data?: CreateSafetyRuleCommandOutput) => void ): void; public createSafetyRule( args: CreateSafetyRuleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateSafetyRuleCommandOutput) => void ): void; public createSafetyRule( args: CreateSafetyRuleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSafetyRuleCommandOutput) => void), cb?: (err: any, data?: CreateSafetyRuleCommandOutput) => void ): Promise<CreateSafetyRuleCommandOutput> | void { const command = new CreateSafetyRuleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Delete a cluster.</p> */ public deleteCluster( args: DeleteClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteClusterCommandOutput>; public deleteCluster( args: DeleteClusterCommandInput, cb: (err: any, data?: DeleteClusterCommandOutput) => void ): void; public deleteCluster( args: DeleteClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteClusterCommandOutput) => void ): void; public deleteCluster( args: DeleteClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteClusterCommandOutput) => void), cb?: (err: any, data?: DeleteClusterCommandOutput) => void ): Promise<DeleteClusterCommandOutput> | void { const command = new DeleteClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a control panel.</p> */ public deleteControlPanel( args: DeleteControlPanelCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteControlPanelCommandOutput>; public deleteControlPanel( args: DeleteControlPanelCommandInput, cb: (err: any, data?: DeleteControlPanelCommandOutput) => void ): void; public deleteControlPanel( args: DeleteControlPanelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteControlPanelCommandOutput) => void ): void; public deleteControlPanel( args: DeleteControlPanelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteControlPanelCommandOutput) => void), cb?: (err: any, data?: DeleteControlPanelCommandOutput) => void ): Promise<DeleteControlPanelCommandOutput> | void { const command = new DeleteControlPanelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a routing control.</p> */ public deleteRoutingControl( args: DeleteRoutingControlCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteRoutingControlCommandOutput>; public deleteRoutingControl( args: DeleteRoutingControlCommandInput, cb: (err: any, data?: DeleteRoutingControlCommandOutput) => void ): void; public deleteRoutingControl( args: DeleteRoutingControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteRoutingControlCommandOutput) => void ): void; public deleteRoutingControl( args: DeleteRoutingControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteRoutingControlCommandOutput) => void), cb?: (err: any, data?: DeleteRoutingControlCommandOutput) => void ): Promise<DeleteRoutingControlCommandOutput> | void { const command = new DeleteRoutingControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a safety rule.</p>/&gt; */ public deleteSafetyRule( args: DeleteSafetyRuleCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteSafetyRuleCommandOutput>; public deleteSafetyRule( args: DeleteSafetyRuleCommandInput, cb: (err: any, data?: DeleteSafetyRuleCommandOutput) => void ): void; public deleteSafetyRule( args: DeleteSafetyRuleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteSafetyRuleCommandOutput) => void ): void; public deleteSafetyRule( args: DeleteSafetyRuleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSafetyRuleCommandOutput) => void), cb?: (err: any, data?: DeleteSafetyRuleCommandOutput) => void ): Promise<DeleteSafetyRuleCommandOutput> | void { const command = new DeleteSafetyRuleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Display the details about a cluster. The response includes the cluster name, endpoints, status, and Amazon Resource Name (ARN).</p> */ public describeCluster( args: DescribeClusterCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeClusterCommandOutput>; public describeCluster( args: DescribeClusterCommandInput, cb: (err: any, data?: DescribeClusterCommandOutput) => void ): void; public describeCluster( args: DescribeClusterCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeClusterCommandOutput) => void ): void; public describeCluster( args: DescribeClusterCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeClusterCommandOutput) => void), cb?: (err: any, data?: DescribeClusterCommandOutput) => void ): Promise<DescribeClusterCommandOutput> | void { const command = new DescribeClusterCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays details about a control panel.</p> */ public describeControlPanel( args: DescribeControlPanelCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeControlPanelCommandOutput>; public describeControlPanel( args: DescribeControlPanelCommandInput, cb: (err: any, data?: DescribeControlPanelCommandOutput) => void ): void; public describeControlPanel( args: DescribeControlPanelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeControlPanelCommandOutput) => void ): void; public describeControlPanel( args: DescribeControlPanelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeControlPanelCommandOutput) => void), cb?: (err: any, data?: DescribeControlPanelCommandOutput) => void ): Promise<DescribeControlPanelCommandOutput> | void { const command = new DescribeControlPanelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays details about a routing control. A routing control has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing.</p> <p>To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.</p> */ public describeRoutingControl( args: DescribeRoutingControlCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeRoutingControlCommandOutput>; public describeRoutingControl( args: DescribeRoutingControlCommandInput, cb: (err: any, data?: DescribeRoutingControlCommandOutput) => void ): void; public describeRoutingControl( args: DescribeRoutingControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeRoutingControlCommandOutput) => void ): void; public describeRoutingControl( args: DescribeRoutingControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRoutingControlCommandOutput) => void), cb?: (err: any, data?: DescribeRoutingControlCommandOutput) => void ): Promise<DescribeRoutingControlCommandOutput> | void { const command = new DescribeRoutingControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the safety rules (that is, the assertion rules and gating rules) for the routing controls in a control panel.</p> */ public describeSafetyRule( args: DescribeSafetyRuleCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeSafetyRuleCommandOutput>; public describeSafetyRule( args: DescribeSafetyRuleCommandInput, cb: (err: any, data?: DescribeSafetyRuleCommandOutput) => void ): void; public describeSafetyRule( args: DescribeSafetyRuleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeSafetyRuleCommandOutput) => void ): void; public describeSafetyRule( args: DescribeSafetyRuleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeSafetyRuleCommandOutput) => void), cb?: (err: any, data?: DescribeSafetyRuleCommandOutput) => void ): Promise<DescribeSafetyRuleCommandOutput> | void { const command = new DescribeSafetyRuleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of all Amazon Route 53 health checks associated with a specific routing control.</p> */ public listAssociatedRoute53HealthChecks( args: ListAssociatedRoute53HealthChecksCommandInput, options?: __HttpHandlerOptions ): Promise<ListAssociatedRoute53HealthChecksCommandOutput>; public listAssociatedRoute53HealthChecks( args: ListAssociatedRoute53HealthChecksCommandInput, cb: (err: any, data?: ListAssociatedRoute53HealthChecksCommandOutput) => void ): void; public listAssociatedRoute53HealthChecks( args: ListAssociatedRoute53HealthChecksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssociatedRoute53HealthChecksCommandOutput) => void ): void; public listAssociatedRoute53HealthChecks( args: ListAssociatedRoute53HealthChecksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssociatedRoute53HealthChecksCommandOutput) => void), cb?: (err: any, data?: ListAssociatedRoute53HealthChecksCommandOutput) => void ): Promise<ListAssociatedRoute53HealthChecksCommandOutput> | void { const command = new ListAssociatedRoute53HealthChecksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of all the clusters in an account.</p> */ public listClusters( args: ListClustersCommandInput, options?: __HttpHandlerOptions ): Promise<ListClustersCommandOutput>; public listClusters(args: ListClustersCommandInput, cb: (err: any, data?: ListClustersCommandOutput) => void): void; public listClusters( args: ListClustersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListClustersCommandOutput) => void ): void; public listClusters( args: ListClustersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListClustersCommandOutput) => void), cb?: (err: any, data?: ListClustersCommandOutput) => void ): Promise<ListClustersCommandOutput> | void { const command = new ListClustersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of control panels for a cluster.</p> */ public listControlPanels( args: ListControlPanelsCommandInput, options?: __HttpHandlerOptions ): Promise<ListControlPanelsCommandOutput>; public listControlPanels( args: ListControlPanelsCommandInput, cb: (err: any, data?: ListControlPanelsCommandOutput) => void ): void; public listControlPanels( args: ListControlPanelsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListControlPanelsCommandOutput) => void ): void; public listControlPanels( args: ListControlPanelsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListControlPanelsCommandOutput) => void), cb?: (err: any, data?: ListControlPanelsCommandOutput) => void ): Promise<ListControlPanelsCommandOutput> | void { const command = new ListControlPanelsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of routing controls for a control panel. A routing control is an Amazon Route 53 Application Recovery Controller construct that has one of two states: ON and OFF. You can map the routing control state to the state of an Amazon Route 53 health check, which can be used to control routing.</p> */ public listRoutingControls( args: ListRoutingControlsCommandInput, options?: __HttpHandlerOptions ): Promise<ListRoutingControlsCommandOutput>; public listRoutingControls( args: ListRoutingControlsCommandInput, cb: (err: any, data?: ListRoutingControlsCommandOutput) => void ): void; public listRoutingControls( args: ListRoutingControlsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListRoutingControlsCommandOutput) => void ): void; public listRoutingControls( args: ListRoutingControlsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRoutingControlsCommandOutput) => void), cb?: (err: any, data?: ListRoutingControlsCommandOutput) => void ): Promise<ListRoutingControlsCommandOutput> | void { const command = new ListRoutingControlsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List the safety rules (the assertion rules and gating rules) that you've defined for the routing controls in a control panel.</p> */ public listSafetyRules( args: ListSafetyRulesCommandInput, options?: __HttpHandlerOptions ): Promise<ListSafetyRulesCommandOutput>; public listSafetyRules( args: ListSafetyRulesCommandInput, cb: (err: any, data?: ListSafetyRulesCommandOutput) => void ): void; public listSafetyRules( args: ListSafetyRulesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListSafetyRulesCommandOutput) => void ): void; public listSafetyRules( args: ListSafetyRulesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListSafetyRulesCommandOutput) => void), cb?: (err: any, data?: ListSafetyRulesCommandOutput) => void ): Promise<ListSafetyRulesCommandOutput> | void { const command = new ListSafetyRulesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a control panel. The only update you can make to a control panel is to change the name of the control panel.</p> */ public updateControlPanel( args: UpdateControlPanelCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateControlPanelCommandOutput>; public updateControlPanel( args: UpdateControlPanelCommandInput, cb: (err: any, data?: UpdateControlPanelCommandOutput) => void ): void; public updateControlPanel( args: UpdateControlPanelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateControlPanelCommandOutput) => void ): void; public updateControlPanel( args: UpdateControlPanelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateControlPanelCommandOutput) => void), cb?: (err: any, data?: UpdateControlPanelCommandOutput) => void ): Promise<UpdateControlPanelCommandOutput> | void { const command = new UpdateControlPanelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a routing control. You can only update the name of the routing control. To get or update the routing control state, see the Recovery Cluster (data plane) API actions for Amazon Route 53 Application Recovery Controller.</p> */ public updateRoutingControl( args: UpdateRoutingControlCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateRoutingControlCommandOutput>; public updateRoutingControl( args: UpdateRoutingControlCommandInput, cb: (err: any, data?: UpdateRoutingControlCommandOutput) => void ): void; public updateRoutingControl( args: UpdateRoutingControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateRoutingControlCommandOutput) => void ): void; public updateRoutingControl( args: UpdateRoutingControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateRoutingControlCommandOutput) => void), cb?: (err: any, data?: UpdateRoutingControlCommandOutput) => void ): Promise<UpdateRoutingControlCommandOutput> | void { const command = new UpdateRoutingControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update a safety rule (an assertion rule or gating rule) for the routing controls in a control panel. You can only update the name and the waiting period for a safety rule. To make other updates, delete the safety rule and create a new safety rule.</p> */ public updateSafetyRule( args: UpdateSafetyRuleCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateSafetyRuleCommandOutput>; public updateSafetyRule( args: UpdateSafetyRuleCommandInput, cb: (err: any, data?: UpdateSafetyRuleCommandOutput) => void ): void; public updateSafetyRule( args: UpdateSafetyRuleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateSafetyRuleCommandOutput) => void ): void; public updateSafetyRule( args: UpdateSafetyRuleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSafetyRuleCommandOutput) => void), cb?: (err: any, data?: UpdateSafetyRuleCommandOutput) => void ): Promise<UpdateSafetyRuleCommandOutput> | void { const command = new UpdateSafetyRuleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import path from 'path'; import markdownMagic from 'markdown-magic'; import logDefinitions, { LogDefinitionTypes } from '../resources/netlog_defs'; import NetRegexes from '../resources/netregexes'; import { UnreachableCode } from '../resources/not_reached'; import Regexes from '../resources/regexes'; import LogRepository from '../ui/raidboss/emulator/data/network_log_converter/LogRepository'; import ParseLine from '../ui/raidboss/emulator/data/network_log_converter/ParseLine'; const curPath = path.resolve(); // For compatibility with the path of the LogGuide.md file const languages = ['en-US', 'de-DE', 'fr-FR', 'ja-JP', 'ko-KR', 'zh-CN', 'zh-TW'] as const; type Lang = typeof languages[number]; const isLang = (lang?: string): lang is Lang => { return languages.includes(lang as Lang); }; type LocaleObject<T> = & { 'en-US': T; } & { [lang in Exclude<Lang, 'en-US'>]?: T; }; const translate = <T>(lang: Lang, obj: LocaleObject<T>): T => { return obj[lang] ?? obj['en-US']; }; type LocaleText = LocaleObject<string>; // Exclude these types since they're not relevant or covered elsewhere type ExcludedLineDocs = | 'None' | 'NetworkAOEAbility' | 'NetworkWorld' | 'NetworkEffectResult' | 'ParserInfo' | 'ProcessInfo' | 'Debug' | 'PacketDump' | 'Version' | 'Error'; type LineDocTypes = Exclude<LogDefinitionTypes, ExcludedLineDocs>; type LineDocType = { // We can generate `network` type automatically for everything but regex regexes?: { network: string; logLine?: string; }; examples: LocaleObject<readonly string[]>; }; type LineDocs = { [type in LineDocTypes]: LineDocType; }; type Titles = Record< | 'structure' | 'networkLogLineStructure' | 'actLogLineStructure' | 'regexes' | 'networkLogLineRegexes' | 'actLogLineRegexes' | 'examples' | 'networkLogLineExamples' | 'actLogLineExamples', LocaleText >; const titles: Titles = { structure: { 'en-US': 'Structure', 'ja-JP': '構造', 'zh-CN': '结构', 'zh-TW': '結構', }, networkLogLineStructure: { 'en-US': 'Network Log Line Structure:', 'ja-JP': 'ネットワークログライン構造:', 'zh-CN': '网络日志行结构:', 'zh-TW': '網路日誌行結構:', }, actLogLineStructure: { 'en-US': 'ACT Log Line Structure:', 'ja-JP': 'ACTログライン構造:', 'zh-CN': 'ACT日志行结构:', 'zh-TW': 'ACT日誌行結構:', }, regexes: { 'en-US': 'Regexes', 'ja-JP': '正規表現', 'zh-CN': '正则表达式', 'zh-TW': '正規表示式', }, networkLogLineRegexes: { 'en-US': 'Network Log Line Regex:', 'ja-JP': 'ネットワークログライン正規表現:', 'zh-CN': '网络日志行正则表达式:', 'zh-TW': '網路日誌行正規表示式:', }, actLogLineRegexes: { 'en-US': 'ACT Log Line Regex:', 'ja-JP': 'ACTログライン正規表現:', 'zh-CN': 'ACT日志行正则表达式:', 'zh-TW': 'ACT日誌行正規表示式:', }, examples: { 'en-US': 'Examples', 'ja-JP': '例', 'zh-CN': '示例', 'zh-TW': '示例', }, networkLogLineExamples: { 'en-US': 'Network Log Line Examples:', 'ja-JP': 'ネットワークログライン例:', 'zh-CN': '网络日志行示例:', 'zh-TW': '網路日誌行示例:', }, actLogLineExamples: { 'en-US': 'ACT Log Line Examples:', 'ja-JP': 'ACTログライン例:', 'zh-CN': 'ACT日志行示例:', 'zh-TW': 'ACT日誌行示例:', }, }; const lineDocs: LineDocs = { GameLog: { regexes: { network: NetRegexes.gameLog({ capture: true }).source, logLine: Regexes.gameLog({ capture: true }).source, }, examples: { 'en-US': [ '00|2021-04-26T14:12:30.0000000-04:00|0839||You change to warrior.|d8c450105ea12854e26eb687579564df', '00|2021-04-26T16:57:41.0000000-04:00|0840||You can now summon the antelope stag mount.|caa3526e9f127887766e9211e87e0e8f', '00|2021-04-26T14:17:11.0000000-04:00|0B3A||You defeat the embodiment.|ef3b7b7f1e980f2c08e903edd51c70c7', '00|2021-04-26T14:12:30.0000000-04:00|302B||The gravity node uses Forked Lightning.|45d50c5f5322adf787db2bd00d85493d', '00|2021-04-26T14:12:30.0000000-04:00|322A||The attack misses.|f9f57724eb396a6a94232e9159175e8c', '00|2021-07-05T18:01:21.0000000-04:00|0044|Tsukuyomi|Oh...it\'s going to be a long night.|1a81d186fd4d19255f2e01a1694c7607', ], }, }, ChangeZone: { regexes: { network: NetRegexes.changeZone({ capture: true }).source, logLine: Regexes.changeZone({ capture: true }).source, }, examples: { 'en-US': [ '01|2021-04-26T14:13:17.9930000-04:00|326|Kugane Ohashi|b9f401c0aa0b8bc454b239b201abc1b8', '01|2021-04-26T14:22:04.5490000-04:00|31F|Alphascape (V2.0)|8299b97fa36500118fc3a174ed208fe4', ], }, }, ChangedPlayer: { examples: { 'en-US': [ '02|2021-04-26T14:11:31.0200000-04:00|10FF0001|Tini Poutini|5b0a5800460045f29db38676e0c3f79a', '02|2021-04-26T14:13:17.9930000-04:00|10FF0002|Potato Chippy|34b657d75218545f5a49970cce218ce6', ], }, }, AddedCombatant: { regexes: { network: NetRegexes.addedCombatantFull({ capture: true }).source, logLine: Regexes.addedCombatantFull({ capture: true }).source, }, examples: { 'en-US': [ '03|2021-06-16T20:46:38.5450000-07:00|10FF0001|Tini Poutini|24|46|0000|28|Jenova|0|0|30460|30460|10000|10000|0|0|-0.76|15.896|0|-3.141593|c0e6f1c201e7285884fb6bf107c533ee', '03|2021-06-16T21:35:11.3060000-07:00|4000B364|Catastrophe|00|46|0000|00||5631|6358|57250|57250|0|10000|0|0|0|0|0|-4.792213E-05|9c22c852e1995ed63ff4b71c09b7d1a7', '03|2021-06-16T21:35:11.3060000-07:00|4000B363|Catastrophe|00|46|0000|00||5631|6358|57250|57250|0|10000|0|0|0|0|0|-4.792213E-05|9438b02195d9b785e07383bc84b2bf37', '03|2021-06-16T21:35:11.3060000-07:00|4000B362|Catastrophe|00|46|0000|00||5631|7305|13165210|13165210|10000|10000|0|0|0|-15|0|-4.792213E-05|1c4bc8f27640fab6897dc90c02bba79d', '03|2021-06-16T21:35:11.4020000-07:00|4000B365|Catastrophe|00|46|0000|00||5631|6358|57250|57250|0|10000|0|0|0|0|0|-4.792213E-05|8b3f6cf1939428dd9ab0a319aba44910', '03|2021-06-16T21:35:11.4020000-07:00|4000B36a|Catastrophe|00|46|0000|00||5631|6358|57250|57250|0|10000|0|0|0|0|0|-4.792213E-05|b3b3b4f926bcadd8b6ef008232d58922', ], }, }, RemovedCombatant: { regexes: { network: NetRegexes.removingCombatant({ capture: true }).source, logLine: Regexes.removingCombatant({ capture: true }).source, }, examples: { 'en-US': [ '04|2021-07-23T23:01:27.5480000-07:00|10FF0001|Tini Poutini|05|1E|0000|35|Jenova|0|0|816|816|10000|10000|0|0|-66.24337|-292.0904|20.06466|1.789943|4fbfc851937873eacf94f1f69e0e2ba9', '04|2021-06-16T21:37:36.0740000-07:00|4000B39C|Petrosphere|00|46|0000|00||6712|7308|0|57250|0|10000|0|0|-16.00671|-0.01531982|0|1.53875|980552ad636f06249f1b5c7a6e675aad', ], }, }, PartyList: { examples: { 'en-US': [ '11|2021-06-16T20:46:38.5450000-07:00|8|10FF0002|10FF0003|10FF0004|10FF0001|10FF0005|10FF0006|10FF0007|10FF0008|', '11|2021-06-16T21:47:56.7170000-07:00|4|10FF0002|10FF0001|10FF0003|10FF0004|', ], }, }, PlayerStats: { regexes: { network: NetRegexes.statChange({ capture: true }).source, logLine: Regexes.statChange({ capture: true }).source, }, examples: { 'en-US': [ '12|2021-04-26T14:30:07.4910000-04:00|21|5456|326|6259|135|186|340|5456|380|3863|135|186|2628|1530|380|0|1260|4000174AE14AB6|3c03ce9ee4afccfaae74695376047054', '12|2021-04-26T14:31:25.5080000-04:00|24|189|360|5610|356|5549|1431|189|1340|3651|5549|5549|1661|380|1547|0|380|4000174AE14AB6|53b98d383806c5a29dfe33720f514288', '12|2021-08-06T10:29:35.3400000-04:00|38|308|4272|4443|288|271|340|4272|1210|2655|288|271|2002|1192|380|0|380|4000174AE14AB6|4ce3eac3dbd0eb1d6e0044425d9e091d', ], }, }, StartsUsing: { regexes: { network: NetRegexes.startsUsing({ capture: true }).source, logLine: Regexes.startsUsing({ capture: true }).source, }, examples: { 'en-US': [ '20|2021-07-27T12:47:23.1740000-04:00|40024FC4|The Manipulator|F63|Carnage|40024FC4|The Manipulator|4.70|-0.01531982|-13.86256|10.59466|-4.792213E-05|488abf3044202807c62fa32c2e36ee81', '20|2021-07-27T12:48:33.5420000-04:00|10FF0001|Tini Poutini|DF0|Stone III|40024FC4|The Manipulator|2.35|-0.06491255|-9.72675|10.54466|-3.141591|2a24845eab5ed48d4f043f7b6269ef70', '20|2021-07-27T12:48:36.0460000-04:00|10FF0002|Potato Chippy|BA|Succor|10FF0002|Potato Chippy|1.93|-0.7477417|-5.416992|10.54466|2.604979|99a70e6f12f3fcb012e59b3f098fd69b', '20|2021-07-27T12:48:29.7830000-04:00|40024FD0|The Manipulator|13BE|Judgment Nisi|10FF0001|Tini Poutini|3.20|8.055649|-17.03842|10.58736|-4.792213E-05|bc1c3d72782de2199bfa90637dbfa9b8', '20|2021-07-27T12:48:36.1310000-04:00|40024FCE|The Manipulator|13D0|Seed Of The Sky|E0000000||2.70|8.055649|-17.03842|10.58736|-4.792213E-05|5377da9551e7ca470709dc08e996bb75', ], }, }, Ability: { regexes: { network: NetRegexes.abilityFull({ capture: true }).source, logLine: Regexes.abilityFull({ capture: true }).source, }, examples: { 'en-US': [ '21|2021-07-27T12:48:22.4630000-04:00|40024FD1|Steam Bit|F67|Aetherochemical Laser|10FF0001|Tini Poutini|750003|4620000|1B|F678000|0|0|0|0|0|0|0|0|0|0|0|0|36022|36022|5200|10000|0|1000|1.846313|-12.31409|10.60608|-2.264526|16000|16000|8840|10000|0|1000|-9.079163|-14.02307|18.7095|1.416605|0000DE1F|0|5d60825d70bb46d7fcc8fc0339849e8e', '21|2021-07-27T12:46:22.9530000-04:00|10FF0002|Potato Chippy|07|Attack|40024FC5|Right Foreleg|710003|3910000|0|0|0|0|0|0|0|0|0|0|0|0|0|0|378341|380640|8840|10000|0|1000|-6.37015|-7.477235|10.54466|0.02791069|26396|26396|10000|10000|0|1000|-5.443688|-1.163282|10.54466|-2.9113|0000DB6E|0|58206bdd1d0bd8d70f27f3fb2523912b', '21|2021-07-27T12:46:21.5820000-04:00|10FF0001|Tini Poutini|03|Sprint|10FF0001|Tini Poutini|1E00000E|320000|0|0|0|0|0|0|0|0|0|0|0|0|0|0|19053|26706|10000|10000|0|1000|-1.210526|17.15058|10.69944|-2.88047|19053|26706|10000|10000|0|1000|-1.210526|17.15058|10.69944|-2.88047|0000DB68|0|29301d52854712315e0951abff146adc', '21|2021-07-27T12:47:28.4670000-04:00|40025026|Steam Bit|F6F|Laser Absorption|40024FC4|The Manipulator|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|685814|872320|8840|10000|0|1000|-0.01531982|-13.86256|10.59466|-4.792213E-05|16000|16000|8840|10000|0|1000|0|22.5|10.64999|-3.141593|0000DCEC|0|0f3be60aec05333aae73a042edb7edb4', '21|2021-07-27T12:48:39.1260000-04:00|40024FCE|The Manipulator|13D0|Seed Of The Sky|E0000000||0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|||||||||||16000|16000|8840|10000|0|1000|8.055649|-17.03842|10.58736|-4.792213E-05|0000DE92|0|ca5594611cf4ca4e276f64f2cfba5ffa', ], }, }, NetworkCancelAbility: { examples: { 'en-US': [ '23|2021-07-27T13:04:38.7790000-04:00|10FF0002|Potato Chippy|408D|Veraero II|Cancelled|dbce3801c08020cb8ae7da9102034131', '23|2021-07-27T13:04:39.0930000-04:00|40000132|Garm|D10|The Dragon\'s Voice|Interrupted|bd936fde66bab0e8cf2874ebd75df77c', '23|2021-07-27T13:04:39.1370000-04:00|4000012F||D52|Unknown_D52|Cancelled|8a15bad31745426d65cc13b8e0d50005', ], }, }, NetworkDoT: { examples: { 'en-US': [ '24|2021-07-27T12:47:05.5100000-04:00|10FF0002|Potato Chippy|HoT|0|3A1|21194|21194|8964|10000|0|1000|-1.815857|-5.630676|10.55192|2.929996|63d7d7e99108018a1890f367f89eae43', '24|2021-07-27T12:47:05.5990000-04:00|10FF0001|Tini Poutini|HoT|0|3BC|26396|26396|10000|10000|0|1000|-0.1373901|-8.438293|10.54466|3.122609|21b814e6f165bc1cde4a6dc23046ecb0', '24|2021-07-27T12:47:06.9340000-04:00|40024FC4|The Manipulator|DoT|0|B7F|709685|872320|8840|10000|0|1000|-0.01531982|-13.86256|10.59466|-4.792213E-05|ce3fd23ca493a37ab7663b8212044e78', ], }, }, WasDefeated: { regexes: { network: NetRegexes.wasDefeated({ capture: true }).source, logLine: Regexes.wasDefeated({ capture: true }).source, }, examples: { 'en-US': [ '25|2021-07-27T13:11:08.6990000-04:00|10FF0002|Potato Chippy|4000016E|Angra Mainyu|fd3760add061a5d2e23f63003cd7101d', '25|2021-07-27T13:11:09.4110000-04:00|10FF0001|Tini Poutini|4000016E|Angra Mainyu|933d5e946659aa9cc493079d4f6934b3', '25|2021-07-27T13:11:11.6840000-04:00|4000016E|Angra Mainyu|10FF0002|Potato Chippy|0b79669140c20f9aa92ad5559be75022', '25|2021-07-27T13:13:10.6310000-04:00|400001D1|Queen Scylla|10FF0001|Tini Poutini|8798f2cb87c42fde4601258ae94ffb7f', ], }, }, GainsEffect: { regexes: { network: NetRegexes.gainsEffect({ capture: true }).source, logLine: Regexes.gainsEffect({ capture: true }).source, }, examples: { 'en-US': [ '26|2021-04-26T14:36:09.4340000-04:00|35|Physical Damage Up|15.00|400009D5|Dark General|400009D5|Dark General|00|48865|48865|cbcfac4df1554b8f59f343f017ebd793', '26|2021-04-26T14:23:38.7560000-04:00|13B|Whispering Dawn|21.00|4000B283|Selene|10FF0002|Potato Chippy|4000016E|00|51893|49487|c7400f0eed1fe9d29834369affc22d3b', '26|2021-07-02T21:57:07.9110000-04:00|D2|Doom|9.97|40003D9F||10FF0001|Tini Poutini|00|26396|26396|86ff6bf4cfdd68491274fce1db5677e8', ], }, }, HeadMarker: { regexes: { network: NetRegexes.headMarker({ capture: true }).source, logLine: Regexes.headMarker({ capture: true }).source, }, examples: { 'en-US': [ '27|2021-04-26T14:17:31.6980000-04:00|10FF0001|Tini Poutini|0000|A9B9|0057|0000|0000|0000|4fb326d8899ffbd4cbfeb29bbc3080f8', '27|2021-05-11T13:48:45.3370000-04:00|40000950|Copied Knave|0000|0000|0117|0000|0000|0000|fa2e93fccf397a41aac73a3a38aa7410', ], }, }, NetworkRaidMarker: { examples: { 'en-US': [ '28|2021-04-26T19:04:39.1920000-04:00|Delete|7|10FF0001|Tini Poutini|0|0|0|b714a8b5b34ea60f8bf9f480508dc427', '28|2021-04-26T19:27:23.5340000-04:00|Add|4|10FF0001|Tini Poutini|76.073|110.588|0|bcf81fb146fe88230333bbfd649eb240', ], }, }, NetworkTargetMarker: { examples: { 'en-US': [ '29|2021-06-10T20:15:15.1000000-04:00|Delete|0|10FF0001|Tini Poutini|4000641D||50460af5ff3f8ec9ad03e6953d3d1ba9', '29|2021-05-25T22:54:32.5660000-04:00|Add|6|10FF0001|Tini Poutini|10FF0002|Potato Chippy|70a8c8a728d09af83e0a486e8271cc57', ], }, }, LosesEffect: { regexes: { network: NetRegexes.losesEffect({ capture: true }).source, logLine: Regexes.losesEffect({ capture: true }).source, }, examples: { 'en-US': [ '30|2021-04-26T14:38:09.6990000-04:00|13A|Inferno|0.00|400009FF|Ifrit-Egi|400009FD|Scylla|00|941742|4933|19164478551c91375dc13d0998365130', '30|2021-04-26T14:37:12.8740000-04:00|77B|Summon Order|0.00|400009E8|Eos|400009E8|Eos|01|5810|5810|b1736ae2cf65864623f9779635c361cd', '30|2021-04-26T14:23:38.8440000-04:00|BD|Bio II|0.00|10FF0001|Tini Poutini|4000B262|Midgardsormr|00|10851737|51654|e34ec8d3a8db783fe34f152178775804', ], }, }, NetworkGauge: { examples: { 'en-US': [ '31|2019-11-27T23:22:40.6960000-05:00|10FF0001|FA753019|FD37|E9A55201|7F47|f17ea56b26ff020d1c0580207f6f4673', '31|2021-04-28T00:26:19.1320000-04:00|10FF0002|BF000018|10035|40006600|00|f31bf7667388ce9b11bd5dd2626c7b99', ], }, }, ActorControl: { regexes: { network: NetRegexes.network6d({ capture: true }).source, logLine: Regexes.network6d({ capture: true }).source, }, examples: { 'en-US': [ '33|2021-04-26T17:23:28.6780000-04:00|80034E6C|40000010|B5D|00|00|00|f777621829447c53c82c9a24aa25348f', '33|2021-04-26T14:17:31.6980000-04:00|80034E5B|8000000C|16|FFFFFFFF|00|00|b543f3c5c715e93d9de2aa65b8fe83ad', '33|2021-04-26T14:18:39.0120000-04:00|80034E5B|40000007|00|01|00|00|7a2b827bbc7a58ecc0c5edbdf14a2c14', ], }, }, NameToggle: { regexes: { network: NetRegexes.nameToggle({ capture: true }).source, logLine: NetRegexes.nameToggle({ capture: true }).source, }, examples: { 'en-US': [ '34|2021-04-26T14:19:48.0400000-04:00|4001C51C|Dragon\'s Head|4001C51C|Dragon\'s Head|00|a7248aab1da528bf94faf2f4b1728fc3', '34|2021-04-26T14:22:19.1960000-04:00|4000B283|Selene|4000B283|Selene|01|734eef0f5b1b10810af8f7257d738c67', ], }, }, Tether: { regexes: { network: NetRegexes.tether({ capture: true }).source, logLine: Regexes.tether({ capture: true }).source, }, examples: { 'en-US': [ '35|2021-04-26T17:27:07.0310000-04:00|40003202|Articulated Bit|10FF0001|Tini Poutini|0000|0000|0001|10029769|000F|0000|ad71d456437e6792f68b19dbef9507d5', '35|2021-04-27T22:36:58.1060000-04:00|10FF0001|Tini Poutini|4000943B|Bomb Boulder|0000|0000|0007|4000943B|000F|0000|a6adfcdf5dad0ef891deeade4d285eb2', '35|2021-06-13T17:41:34.2230000-04:00|10FF0001|Tini Poutini|10FF0002|Potato Chippy|0000|0000|006E|1068E3EF|000F|0000|c022382c6803d1d6c1f84681b7d8db20', ], }, }, LimitBreak: { examples: { 'en-US': [ '36|2021-04-26T14:20:09.6880000-04:00|6A90|3|88ce578cb8f05d74feb3a7fa155bedc5', '36|2021-04-26T14:20:19.6580000-04:00|4E20|2|a3bf154ba550e147d4fbbd4266db4eb9', '36|2021-04-26T14:20:23.9040000-04:00|0000|0|703872b50849730773f7b21897698d00', '36|2021-04-26T14:22:03.8370000-04:00|0000|1|c85f02ac4780e208357383afb6cbc232', ], }, }, StatusEffect: { regexes: { network: NetRegexes.statusEffectExplicit({ capture: true }).source, logLine: Regexes.statusEffectExplicit({ capture: true }).source, }, examples: { 'en-US': [ '38|2021-04-26T14:13:16.2760000-04:00|10FF0001|Tini Poutini|46504615|75407|75407|10000|10000|24|0|-645.238|-802.7854|8|1.091302|1500|3C|0|0A016D|41F00000|E0000000|1E016C|41F00000|E0000000|c1b3e1d63f03a265ffa85f1517c1501e', '38|2021-04-26T14:13:16.2760000-04:00|10FF0001||46504621|49890|49890|10000|10000|24|0|||||1500|3C|0|f62dbda5c947fa4c11b63c90c6ee4cd9', '38|2021-04-26T14:13:44.5020000-04:00|10FF0002|Potato Chippy|46504621|52418|52418|10000|10000|32|0|99.93127|113.8475|-1.862645E-09|3.141593|200F|20|0|0A016D|41F00000|E0000000|1E016C|41F00000|E0000000|0345|41E8D4FC|10FF0001|0347|80000000|10FF0002|d57fd29c6c4856c091557968667da39d', ], }, }, NetworkUpdateHP: { examples: { 'en-US': [ '39|2021-04-26T14:12:38.5160000-04:00|10FF0001|Tini Poutini|178669|191948|10000|10000|0|0|-648.3234|-804.5252|8.570148|1.010669|7ebe348673aa2a11e4036274becabc81', '39|2021-04-26T14:13:21.6370000-04:00|10592642|Senor Esteban|54792|54792|10000|10000|0|0|100.268|114.22|-1.837917E-09|3.141593|883da0db11a9c950eefdbcbc50e86eca', '39|2021-04-26T14:13:21.6370000-04:00|106F5D49|O\'ndanya Voupin|79075|79075|10000|10000|0|0|99.93127|114.2443|-1.862645E-09|-3.141593|8ed73ee57c4ab7159628584e2f4d5243', ], }, }, Map: { regexes: { network: NetRegexes.map({ capture: true }).source, logLine: Regexes.map({ capture: true }).source, }, examples: { 'en-US': [ '40|2021-07-30T19:43:08.6270000-07:00|578|Norvrandt|The Copied Factory|Upper Stratum|ee5b5fc06ab4610ef6b4f030fc95c90c', '40|2021-07-30T19:46:49.3830000-07:00|575|Norvrandt|Excavation Tunnels||41e6dae1ab1a3fe18ce3754d7c45a5d0', '40|2021-07-30T19:49:19.8180000-07:00|192|La Noscea|Mist|Mist Subdivision|f3506f063945500b5e7df2172e2ca4d3', ], }, }, SystemLogMessage: { regexes: { network: NetRegexes.systemLogMessage({ capture: true }).source, logLine: Regexes.systemLogMessage({ capture: true }).source, }, examples: { 'en-US': [ '41|2021-11-21T10:38:40.0660000-08:00|00|901|619A9200|00|3C|c6fcd8a8b198a5da28b9cfe6a3f544f4', '41|2021-11-21T10:50:13.5650000-08:00|8004001E|7DD|FF5FDA02|E1B|00|4eeb89399fce54820eb19e06b4d6d95a', '41|2021-11-21T10:55:06.7070000-08:00|8004001E|B3A|00|00|E0000000|1f600f85ec8d36d2b04d233e19f93d39', ], }, }, } as const; type LogGuideOptions = { lang?: string; type?: string; }; const isLineType = (type?: string): type is LineDocTypes => { return type !== undefined && type in lineDocs; }; const mappedLogLines: LocaleObject<LineDocTypes[]> = { 'en-US': [], }; const config: markdownMagic.Configuration = { transforms: { logLines(_content, options: LogGuideOptions): string { const language = options.lang; const lineType = options.type; if (!isLang(language)) { console.error(`Received invalid lang specification: ${language ?? 'undefined'}`); process.exit(-1); } if (!isLineType(lineType)) { console.error(`Received invalid type specification: ${lineType ?? 'undefined'}`); process.exit(-2); } const lineDoc = lineDocs[lineType]; if (!lineDoc) { console.error(`Received missing type specification: ${lineType ?? 'undefined'}`); process.exit(-3); } mappedLogLines[language] ??= []; mappedLogLines[language]?.push(lineType); const logRepo = new LogRepository(); // Add the default combatants to the repo for name lookup when names are blank logRepo.Combatants['10FF0001'] = { spawn: 0, despawn: 0, name: 'Tini Poutini' }; logRepo.Combatants['10FF0002'] = { spawn: 0, despawn: 0, name: 'Potato Chippy' }; let ret = ''; const lineDef = logDefinitions[lineType]; const structureNetworkArray = [ lineDef.type, '2021-04-26T14:11:35.0000000-04:00', ]; let lastIndex = 0; for (const [name, index] of Object.entries(lineDef.fields)) { if (['type', 'timestamp'].includes(name)) continue; structureNetworkArray[index] = `[${name}]`; lastIndex = Math.max(lastIndex, index); } for (let index = 2; index <= lastIndex; ++index) structureNetworkArray[index] ??= '[?]'; let structureNetwork = structureNetworkArray.join('|'); structureNetworkArray.push('placeholder for hash removal'); const structureLogLine = ParseLine.parse(logRepo, structureNetworkArray.join('|')); let structureLog = structureLogLine?.convertedLine; if (!structureLog) throw new UnreachableCode(); // Replace default timestamp with `[timestamp]` indicator // We have to do this here because LineEvent needs to parse the timestamp to convert structureNetwork = structureNetwork.replace(/^(\d+)\|[^|]+\|/, '$1|[timestamp]|'); structureLog = structureLog.replace(/^\[[^\]]+\]/, '[timestamp]'); // Correct the structure for the AddedCombatant line not allowing a placeholder for job if (lineType === 'AddedCombatant') structureLog = structureLog.replace(/Job: NONE/, 'Job: [job]'); const examples = translate(language, lineDoc.examples); const examplesNetwork = examples.join('\n') ?? ''; const examplesLogLine = examples.map((e) => { const line = ParseLine.parse(logRepo, e); if (!line) throw new UnreachableCode(); return line?.convertedLine; }).join('\n') ?? ''; const regexes = lineDoc.regexes; ret += ` #### ${translate(language, titles.structure)} \`\`\`log ${translate(language, titles.networkLogLineStructure)} ${structureNetwork} ${translate(language, titles.actLogLineStructure)} ${structureLog} \`\`\` `; if (regexes) { ret += ` #### ${translate(language, titles.regexes)} \`\`\`log ${translate(language, titles.networkLogLineRegexes)} ${regexes.network} `; if (regexes.logLine) { ret += ` ${translate(language, titles.actLogLineRegexes)} ${regexes.logLine} `; } ret += '```\n'; } ret += ` #### ${translate(language, titles.examples)} \`\`\`log ${translate(language, titles.networkLogLineExamples)} ${examplesNetwork} ${translate(language, titles.actLogLineExamples)} ${examplesLogLine} \`\`\` `; return ret; }, }, }; const enLogGuidePath = path.posix.relative( curPath, path.posix.join(curPath, 'docs', 'LogGuide.md'), ); markdownMagic( [ enLogGuidePath, path.posix.relative(curPath, path.posix.join(curPath, 'docs', '*', 'LogGuide.md')), ], config, (_error, output) => { let exitCode = 0; for (const file of output) { const filePath = file.originalPath; // Figure out what language this file is by checking the path, default to 'en' const lang = languages.filter((lang) => RegExp(('[^\\w]' + lang + '[^\\w]')).exec(filePath.toLowerCase()) )[0] ?? 'en-US'; const convertedLines = mappedLogLines[lang]; for (const type in logDefinitions) { if (!isLineType(type)) continue; if (!convertedLines?.includes(type)) { console.error(`Language ${lang} is missing LogGuide doc entry for type ${type}`); exitCode = 1; } } } process.exit(exitCode); }, );
the_stack
import { lint } from "stylelint" import { containsDeprecatedKaizenTokenWithNoReplacement, cssVariableUsedWithinUnsupportedFunction, invalidEquationContainingKaizenTokenMessage, kaizenVariableUsedNextToOperatorMessage, negatedKaizenVariableMessage, replacementCssVariableUsedWithinUnsupportedFunction, deprecatedTokenInVariableMessage, } from "./messages" import { Language } from "./types" jest.setTimeout(10000) const baseConfig = require("../dev-config") const testStylelintConfig = { ...baseConfig, rules: { "kaizen/no-tokens-in-variables": [ true, { severity: "warning", disableFixing: false }, ], ...baseConfig.rules, }, } type TestExample = { language: Language testName: string input: string expectedOutput: string only?: boolean } & ( | { expectedWarningMessages: string[] } | { expectedWarnings: number } ) const testExamples: TestExample[] = [ { language: "scss", testName: "asserts that missing imports are added", input: "@media (min-width: $kz-layout-breakpoints-large) { .test { color: $kz-color-wisteria-800 } }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @import "~@kaizen/design-tokens/sass/layout"; @media (min-width: $layout-breakpoints-large) { .test { color: $color-purple-800 } }', expectedWarnings: 0, }, { language: "less", testName: "asserts that missing imports are added", input: "@media (min-width: @kz-layout-breakpoints-large) { .test { color: @kz-color-wisteria-800 } }", expectedOutput: '@import "~@kaizen/design-tokens/less/color"; @import "~@kaizen/design-tokens/less/layout"; @media (min-width: @layout-breakpoints-large) { .test { color: @color-purple-800 } }', expectedWarnings: 0, }, { language: "scss", testName: "asserts that unnecessary imports are removed", input: '@import "~@kaizen/design-tokens/sass/color-vars"; @import "~@kaizen/design-tokens/sass/layout"; @media (min-width: $kz-layout-breakpoints-large) { .test { color: red; } }', expectedOutput: '@import "~@kaizen/design-tokens/sass/layout"; @media (min-width: $layout-breakpoints-large) { .test { color: red; } }', expectedWarnings: 0, }, { language: "less", testName: "asserts that unnecessary imports are removed", input: '@import "~@kaizen/design-tokens/less/color-vars"; @import "~@kaizen/design-tokens/less/layout"; @media (min-width: @kz-layout-breakpoints-large) { .test { color: red; } }', expectedOutput: '@import "~@kaizen/design-tokens/less/layout"; @media (min-width: @layout-breakpoints-large) { .test { color: red; } }', expectedWarnings: 0, }, { language: "scss", testName: "doesn't fix variables within @media queries, but still fixes imports for variables in AtRule parameters", input: "@media (min-width: $kz-layout-breakpoints-large) {}", expectedOutput: '@import "~@kaizen/design-tokens/sass/layout"; @media (min-width: $layout-breakpoints-large) {}', expectedWarnings: 0, }, { language: "less", testName: "doesn't fix variables within @media queries, but still fixes imports for variables in AtRule parameters", input: "@media (min-width: @kz-layout-breakpoints-large) {}", expectedOutput: '@import "~@kaizen/design-tokens/less/layout"; @media (min-width: @layout-breakpoints-large) {}', expectedWarnings: 0, }, { language: "scss", testName: "doesn't fix variables when used as equation terms", input: ".foo { padding: $kz-spacing-md * 2; }", expectedOutput: ` .foo { padding: $kz-spacing-md * 2; } `, expectedWarningMessages: [invalidEquationContainingKaizenTokenMessage], }, { language: "less", testName: "doesn't fix variables when used as equation terms", input: ".foo { padding: @kz-spacing-md * 2; }", expectedOutput: ` .foo { padding: @kz-spacing-md * 2; } `, expectedWarningMessages: [invalidEquationContainingKaizenTokenMessage], }, { language: "scss", testName: "fixes variables when used next to an equation", input: ".foo { padding: 0 1px 5 * 10px $kz-spacing-md; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: 0 1px 5 * 10px $spacing-md; }', expectedWarnings: 0, }, { language: "less", testName: "fixes variables when used next to an equation", input: ".foo { padding: 0 1px 5 * 10px @kz-spacing-md; }", expectedOutput: '@import "~@kaizen/design-tokens/less/spacing"; .foo { padding: 0 1px 5 * 10px @spacing-md; }', expectedWarnings: 0, }, { language: "scss", testName: "fixes tokens in other cases", input: ".foo { padding: $kz-spacing-md; color: $kz-color-wisteria-800; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: $spacing-md; color: $color-purple-800; }', expectedWarnings: 0, }, { language: "less", testName: "fixes tokens in other cases", input: ".foo { padding: @kz-spacing-md; color: @kz-color-wisteria-800; }", expectedOutput: '@import "~@kaizen/design-tokens/less/color"; @import "~@kaizen/design-tokens/less/spacing"; .foo { padding: @spacing-md; color: @color-purple-800; }', expectedWarnings: 0, }, { language: "scss", testName: "fixes add-alpha, rgba, and rgb functions to use -rgb", input: ".foo { color: add-alpha($kz-color-wisteria-800, 80); background-color: rgba($kz-color-cluny-600, 0.5); border-color: rgb($kz-color-yuzu-600) }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 0.8); background-color: rgba($color-blue-600-rgb, 0.5); border-color: rgb($color-yellow-600-rgb) }', expectedWarnings: 0, }, { language: "less", testName: "fixes add-alpha, rgba, and rgb functions to use -rgb", input: ".foo { color: add-alpha(@kz-color-wisteria-800, 80%); background-color: rgba(@kz-color-cluny-600, 0.5); border-color: rgb(@kz-color-yuzu-600) }", expectedOutput: '@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800-rgb, 0.8); background-color: rgba(@color-blue-600-rgb, 0.5); border-color: rgb(@color-yellow-600-rgb) }', expectedWarnings: 0, }, { language: "scss", testName: "fixes basic usages of tokens", input: ".foo { color: $kz-color-wisteria-800; background-color: $kz-color-cluny-600; border-color: $kz-color-yuzu-600 } @media (min-width: $kz-layout-breakpoints-large) {}", expectedOutput: '@import "~@kaizen/design-tokens/sass/layout"; @import "~@kaizen/design-tokens/sass/color"; .foo { color: $color-purple-800; background-color: $color-blue-600; border-color: $color-yellow-600 } @media (min-width: $layout-breakpoints-large) {}', expectedWarnings: 0, }, { language: "less", testName: "fixes basic usages of tokens", input: ".foo { color: @kz-color-wisteria-800; background-color: @kz-color-cluny-600; border-color: @kz-color-yuzu-600 } @media (min-width: @kz-layout-breakpoints-large) {}", expectedOutput: '@import "~@kaizen/design-tokens/less/layout"; @import "~@kaizen/design-tokens/less/color"; .foo { color: @color-purple-800; background-color: @color-blue-600; border-color: @color-yellow-600 } @media (min-width: @layout-breakpoints-large) {}', expectedWarnings: 0, }, { language: "scss", testName: "knows not to change a token to a CSS variable within a function that doesn't support them", input: ` .foo { background-color: darken($kz-color-cluny-700, 0.8); }`, expectedOutput: ` .foo { background-color: darken($kz-color-cluny-700, 0.8); }`, expectedWarningMessages: [ replacementCssVariableUsedWithinUnsupportedFunction( "kz-color-cluny-700", "color-blue-700", "darken" ), ], }, { language: "scss", testName: "migrates tokens within rgba, rgb, add-alpha, and other functions we don't know about", input: ` @import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($kz-color-wisteria-800, 0.4); test: something-else($kz-color-yuzu-400); another: rgb($kz-color-cluny-200); foo: add-alpha($kz-color-wisteria-700, 90); }`, expectedOutput: ` @import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 0.4); test: something-else($color-yellow-400); another: rgb($color-blue-200-rgb); foo: rgba($color-purple-700-rgb, 0.9); }`, expectedWarningMessages: [], }, { language: "less", testName: "doesn't fix functions other than rgba, rgb, or add-alpha", input: `@import "~@kaizen/design-tokens/less/color"; @import "~@kaizen/design-tokens/less/color-vars"; .foo { color: rgba(@kz-color-wisteria-800, 0.4); background-color: darken(@kz-color-cluny-700, 0.8); test: something-else(@kz-color-yuzu-400); another: rgb(@kz-color-cluny-200); foo: add-alpha(@kz-color-wisteria-700, 90%); }`, expectedOutput: `@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800-rgb, 0.4); background-color: darken(@kz-color-cluny-700, 0.8); test: something-else(@color-yellow-400); another: rgb(@color-blue-200-rgb); foo: rgba(@color-purple-700-rgb, 0.9); }`, expectedWarningMessages: [ replacementCssVariableUsedWithinUnsupportedFunction( "kz-color-cluny-700", "color-blue-700", "darken" ), ], }, { language: "scss", testName: "doesn't fix tokens within variables", input: "$foo: $kz-color-wisteria-800;", expectedOutput: "$foo: $kz-color-wisteria-800;", expectedWarningMessages: [ // Note that this warning message may change when breaking design tokens, and `kz-color-wisteria-800` ceases to exist. deprecatedTokenInVariableMessage( "kz-color-wisteria-800", "color-purple-800" ), ], }, { language: "scss", testName: "fixes new kaizen css variable tokens when used incorrectly in rgba|rgb|add-alpha", input: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800, 80%) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 80%) }', expectedWarnings: 0, }, { language: "less", testName: "fixes new kaizen css variable tokens when used incorrectly in rgba|rgb|add-alpha", input: '@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800, 80%) }', expectedOutput: '@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800-rgb, 80%) }', expectedWarnings: 0, }, { language: "scss", testName: "fixes tokens used in calc() without string interpolations", input: '@import "~@kaizen/design-tokens/sass/spacing-vars"; .foo { padding: calc(5px + $kz-spacing-md) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: calc(5px + #{$spacing-md}) }', expectedWarnings: 0, }, { language: "less", testName: "nothing unfixable showing up for valid use cases", input: '@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800-rgb, 80%) }', expectedOutput: '@import "~@kaizen/design-tokens/less/color"; .foo { color: rgba(@color-purple-800-rgb, 80%) }', expectedWarnings: 0, }, { language: "scss", testName: "interpolated tokens are still fixed", input: '@import "~@kaizen/design-tokens/sass/spacing-vars"; .foo { padding: #{$kz-spacing-lg} }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: #{$spacing-lg} }', expectedWarnings: 0, }, { language: "scss", testName: "negation of old token is detected as an equation, and then fixed with a calc()", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: -$kz-spacing-lg; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: calc(-1 * #{$spacing-lg}); }', expectedWarnings: 0, }, { language: "scss", testName: "negation of old token is detected as an equation, and then fixed with a calc(), but not if it's already within one", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: calc(-$kz-spacing-lg); }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: calc((-1 * #{$spacing-lg})); }', expectedWarnings: 0, }, { language: "scss", testName: "negation of old token is detected as an equation, and then fixed with a calc(), even when it's part of a value with multiple 'sides' ", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: 5px -$kz-spacing-lg; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: 5px calc(-1 * #{$spacing-lg}); }', expectedWarnings: 0, }, { language: "scss", testName: "negation of old token is detected as an equation, and then fixed with a calc(), even when it's part of a value with multiple 'sides', and with another kaizen token next to it ", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: $kz-spacing-md -$kz-spacing-lg; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: $spacing-md calc(-1 * #{$spacing-lg}); }', expectedWarnings: 0, }, { language: "scss", testName: "doesn't fix ambiguous case of negation (knows if it's an equation and not a negation - all it takes is a space)", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: 5px - $spacing-lg; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: 5px - $spacing-lg; }', expectedWarningMessages: [ invalidEquationContainingKaizenTokenMessage, kaizenVariableUsedNextToOperatorMessage, ], }, { language: "less", testName: "negation of CSS var token is detected as an equation, but not fixed in LESS", input: '@import "~@kaizen/design-tokens/less/spacing"; .foo { padding: -@spacing-lg; }', expectedOutput: '@import "~@kaizen/design-tokens/less/spacing"; .foo { padding: -@spacing-lg; }', expectedWarningMessages: [ invalidEquationContainingKaizenTokenMessage, negatedKaizenVariableMessage, ], }, { language: "scss", testName: "fixes variables even though next to an operator but separated by a comma", input: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: rgba(+, $kz-spacing-md) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: rgba(+, $spacing-md) }', expectedWarnings: 0, }, { language: "scss", testName: "warns about usage of variable tokens in color mixing functions mix() shade() tint() darken() lighten() adjust-hue() saturate() desaturate()", input: ` @import "~@kaizen/design-tokens/sass/color"; $white: white; $amount: 80%; .mix { color: mix($color-purple-800, $white, 80%); } .shade { color: shade($color-purple-800, $amount); } .tint { color: tint($color-purple-800, $amount); } .darken { color: darken($color-purple-800, $amount); } .lighten { color: lighten($color-purple-800, $amount); } .adjust-hue { color: adjust-hue($color-purple-800, $amount); } .saturate { color: saturate($color-purple-800, $amount); } .desaturate { color: desaturate($color-purple-800, $amount); } `, expectedOutput: ` @import "~@kaizen/design-tokens/sass/color"; $white: white; $amount: 80%; .mix { color: mix($color-purple-800, $white, 80%); } .shade { color: shade($color-purple-800, $amount); } .tint { color: tint($color-purple-800, $amount); } .darken { color: darken($color-purple-800, $amount); } .lighten { color: lighten($color-purple-800, $amount); } .adjust-hue { color: adjust-hue($color-purple-800, $amount); } .saturate { color: saturate($color-purple-800, $amount); } .desaturate { color: desaturate($color-purple-800, $amount); } `, expectedWarningMessages: [ cssVariableUsedWithinUnsupportedFunction("color-purple-800", "mix"), cssVariableUsedWithinUnsupportedFunction("color-purple-800", "shade"), cssVariableUsedWithinUnsupportedFunction("color-purple-800", "tint"), cssVariableUsedWithinUnsupportedFunction("color-purple-800", "darken"), cssVariableUsedWithinUnsupportedFunction("color-purple-800", "lighten"), cssVariableUsedWithinUnsupportedFunction( "color-purple-800", "adjust-hue" ), cssVariableUsedWithinUnsupportedFunction("color-purple-800", "saturate"), cssVariableUsedWithinUnsupportedFunction( "color-purple-800", "desaturate" ), ], }, { language: "scss", testName: "also warns about deprecated tokens in color mixing functions", input: ` $white: white; $amount: 80%; .mix { color: mix($kz-color-wisteria-800, $white, 80%); } .shade { color: shade($kz-color-wisteria-800, $amount); } .tint { color: tint($kz-color-wisteria-800, $amount); } .darken { color: darken($kz-color-wisteria-800, $amount); } .lighten { color: lighten($kz-color-wisteria-800, $amount); } .adjust-hue { color: adjust-hue($kz-color-wisteria-800, $amount); } .saturate { color: saturate($kz-color-wisteria-800, $amount); } .desaturate { color: desaturate($kz-color-wisteria-800, $amount); } `, expectedOutput: ` $white: white; $amount: 80%; .mix { color: mix($kz-color-wisteria-800, $white, 80%); } .shade { color: shade($kz-color-wisteria-800, $amount); } .tint { color: tint($kz-color-wisteria-800, $amount); } .darken { color: darken($kz-color-wisteria-800, $amount); } .lighten { color: lighten($kz-color-wisteria-800, $amount); } .adjust-hue { color: adjust-hue($kz-color-wisteria-800, $amount); } .saturate { color: saturate($kz-color-wisteria-800, $amount); } .desaturate { color: desaturate($kz-color-wisteria-800, $amount); } `, expectedWarnings: 8, }, { language: "scss", testName: "does not warn about color mix functions that don't have tokens", input: ` $white: white; $blue: blue; $amount: 80%; .mix { color: mix(blue, $white, 80%); } .shade { color: shade(blue, $amount); } .tint { color: tint(blue, $amount); } .darken { color: darken(blue, $amount); } .lighten { color: lighten(blue, $amount); } .adjust-hue { color: adjust-hue(blue, $amount); } .saturate { color: saturate(blue, $amount); } .desaturate { color: desaturate(blue, $amount); } `, expectedOutput: ` $white: white; $blue: blue; $amount: 80%; .mix { color: mix(blue, $white, 80%); } .shade { color: shade(blue, $amount); } .tint { color: tint(blue, $amount); } .darken { color: darken(blue, $amount); } .lighten { color: lighten(blue, $amount); } .adjust-hue { color: adjust-hue(blue, $amount); } .saturate { color: saturate(blue, $amount); } .desaturate { color: desaturate(blue, $amount); } `, expectedWarnings: 0, }, { language: "scss", testName: "add-alpha percentage parameter is normalised", input: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: add-alpha($color-purple-800, 70) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 0.7) }', expectedWarnings: 0, }, { language: "scss", testName: "add-alpha percentage parameter is normalised and supports floats", input: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: add-alpha($color-purple-800, 70.1234) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 0.701234) }', expectedWarnings: 0, }, { language: "scss", testName: "transitive kaizen tokens are fixed", input: '@import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800; .foo { color: $foo; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800; .foo { color: $color-purple-800; }', expectedWarnings: 0, }, { language: "scss", testName: "transitive kaizen tokens containing multiple values are fixed", input: '@import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800 $color-purple-700 $color-purple-800; .foo { color: $foo; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800 $color-purple-700 $color-purple-800; .foo { color: $color-purple-800 $color-purple-700 $color-purple-800; }', expectedWarnings: 0, }, { language: "scss", testName: "color manipulation functions are not warned about (SASS compiler is responsible for them), even when a transitive kaizen token is used", input: ` @import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800; .foo { color: mix($foo, $white, 80%); }`, expectedOutput: ` @import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-800; .foo { color: mix($color-purple-800, $white, 80%); }`, expectedWarnings: 1, }, { language: "scss", testName: "color manipulation functions are not warned about (SASS compiler is responsible for them), even when a transitive kaizen token defined in the same block is used", input: ` @import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-600; .foo { $foo: $color-purple-800; color: mix($foo, $white, 80%); }`, expectedOutput: ` @import "~@kaizen/design-tokens/sass/color"; $foo: $color-purple-600; .foo { $foo: $color-purple-800; color: mix($color-purple-800, $white, 80%); }`, expectedWarnings: 1, }, { language: "scss", testName: "transitive tokens are fixed correctly when their usages are negated, and their replacements are simple", input: '@import "~@kaizen/design-tokens/sass/spacing"; $foo: $spacing-md; .foo { top: -$foo; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; $foo: $spacing-md; .foo { top: calc(-1 * #{$spacing-md}); }', expectedWarnings: 0, }, { language: "scss", testName: "transitive tokens are fixed correctly when their usages are interpolated", input: '@import "~@kaizen/design-tokens/sass/spacing"; $foo: $spacing-md; .foo { top: #{$foo}; }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; $foo: $spacing-md; .foo { top: #{$spacing-md}; }', expectedWarnings: 0, }, { language: "scss", testName: "transparentize functions are fixed and decimals are parsed and converted correctly", input: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: transparentize($color-purple-800, 0.654); }', expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { color: rgba($color-purple-800-rgb, 0.346); }', expectedWarningMessages: [], }, { language: "scss", testName: "no errors are reported for a valid calc function", input: '@import "~@kaizen/design-tokens/sass/spacing-vars"; .foo { transform: translateX(calc(-1 * #{$kz-var-spacing-md})); }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { transform: translateX(calc(-1 * #{$spacing-md})); }', expectedWarnings: 0, }, { testName: "deprecated kaizen tokens are migrated and interpolated, when within a calc function", language: "scss", input: ".test { border-radius: calc(2 * $kz-border-solid-border-radius); }", expectedOutput: '@import "~@kaizen/design-tokens/sass/border"; .test { border-radius: calc(2 * #{$border-solid-border-radius}); }', expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-wisteria-100 $kz-var-color-wisteria-200 $kz-var-color-wisteria-300 $kz-var-color-wisteria-400 $kz-var-color-wisteria-500 $kz-var-color-wisteria-600 $kz-var-color-wisteria-700 $kz-var-color-wisteria-800; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-purple-100 $color-purple-200 $color-purple-300 $color-purple-400 $color-purple-500 $color-purple-600 $color-purple-700 $color-purple-800; }', testName: "wisteria is renamed to purple in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-cluny-100 $kz-var-color-cluny-200 $kz-var-color-cluny-300 $kz-var-color-cluny-400 $kz-var-color-cluny-500 $kz-var-color-cluny-600 $kz-var-color-cluny-700; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-blue-100 $color-blue-200 $color-blue-300 $color-blue-400 $color-blue-500 $color-blue-600 $color-blue-700; }', testName: "cluny is renamed to blue in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-yuzu-100 $kz-var-color-yuzu-200 $kz-var-color-yuzu-300 $kz-var-color-yuzu-400 $kz-var-color-yuzu-500 $kz-var-color-yuzu-600 $kz-var-color-yuzu-700; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-yellow-100 $color-yellow-200 $color-yellow-300 $color-yellow-400 $color-yellow-500 $color-yellow-600 $color-yellow-700; }', testName: "yuzu is renamed to yellow in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-coral-100 $kz-var-color-coral-200 $kz-var-color-coral-300 $kz-var-color-coral-400 $kz-var-color-coral-500 $kz-var-color-coral-600 $kz-var-color-coral-700; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-red-100 $color-red-200 $color-red-300 $color-red-400 $color-red-500 $color-red-600 $color-red-700; }', testName: "coral is renamed to red in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-coral-800 $kz-var-color-coral-700 $kz-var-blah;}", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $kz-var-color-coral-800 $color-red-700 $kz-var-blah;}', testName: "doesn't rename anything that would result in a non-existent kaizen-token", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-seedling-100 $kz-var-color-seedling-200 $kz-var-color-seedling-300 $kz-var-color-seedling-400 $kz-var-color-seedling-500 $kz-var-color-seedling-600 $kz-var-color-seedling-700; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-green-100 $color-green-200 $color-green-300 $color-green-400 $color-green-500 $color-green-600 $color-green-700; }', testName: "seedling is renamed to green in declarations", expectedWarnings: 0, }, { // The input contains a kaizen var `$border-dashed-border-style;` that has `ash` as a substring, which should not be replaced. language: "scss", input: ".foo { test-prop: $border-dashed-border-style; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/border"; .foo { test-prop: $border-dashed-border-style; }', testName: "accidental renames don't occur", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-peach-100 $kz-var-color-peach-200 $kz-var-color-peach-300 $kz-var-color-peach-400 $kz-var-color-peach-500 $kz-var-color-peach-600 $kz-var-color-peach-700; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-orange-100 $color-orange-200 $color-orange-300 $color-orange-400 $color-orange-500 $color-orange-600 $color-orange-700; }', testName: "peach is renamed to orange in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-white $kz-var-color-stone $kz-var-color-ash $kz-var-color-iron $kz-var-color-slate; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-white $color-gray-100 $color-gray-300 $color-gray-500 $color-gray-600; }', testName: "grays are renamed in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-cluny-100, $kz-var-spacing-md $kz-var-shadow-large-box-shadow; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/shadow"; @import "~@kaizen/design-tokens/sass/spacing"; @import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-blue-100, $spacing-md $shadow-large-box-shadow; }', testName: "kz-var prefix is removed in declarations", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-id-color-cluny-100; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-blue-100-id; }', testName: "kz-var-id-* is replaced with *-id ", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: ($kz-var-id-color-cluny-100); }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: ($color-blue-100-id); }', testName: "kz-var-id-* is replaced with *-id and handles brackets", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: #{$kz-var-id-color-cluny-100}; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: #{$color-blue-100-id}; }', testName: "kz-var-id-* is replaced with *-id and handles interpolation", expectedWarnings: 0, }, { language: "scss", input: ".foo { test-prop: $kz-var-color-cluny-100-rgb-params; }", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; .foo { test-prop: $color-blue-100-rgb; }', testName: "-rgb-params is replaced with -rgb", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-wisteria-100 $kz-var-color-wisteria-200 $kz-var-color-wisteria-300 $kz-var-color-wisteria-400 $kz-var-color-wisteria-500 $kz-var-color-wisteria-600 $kz-var-color-wisteria-700 $kz-var-color-wisteria-800)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-purple-100 $color-purple-200 $color-purple-300 $color-purple-400 $color-purple-500 $color-purple-600 $color-purple-700 $color-purple-800)', testName: "wisteria is renamed to purple in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-cluny-100 $kz-var-color-cluny-200 $kz-var-color-cluny-300 $kz-var-color-cluny-400 $kz-var-color-cluny-500 $kz-var-color-cluny-600 $kz-var-color-cluny-700)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-blue-100 $color-blue-200 $color-blue-300 $color-blue-400 $color-blue-500 $color-blue-600 $color-blue-700)', testName: "cluny is renamed to blue in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-yuzu-100 $kz-var-color-yuzu-200 $kz-var-color-yuzu-300 $kz-var-color-yuzu-400 $kz-var-color-yuzu-500 $kz-var-color-yuzu-600 $kz-var-color-yuzu-700)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-yellow-100 $color-yellow-200 $color-yellow-300 $color-yellow-400 $color-yellow-500 $color-yellow-600 $color-yellow-700)', testName: "yuzu is renamed to yellow in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-coral-100 $kz-var-color-coral-200 $kz-var-color-coral-300 $kz-var-color-coral-400 $kz-var-color-coral-500 $kz-var-color-coral-600 $kz-var-color-coral-700)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-red-100 $color-red-200 $color-red-300 $color-red-400 $color-red-500 $color-red-600 $color-red-700)', testName: "coral is renamed to red in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-peach-100 $kz-var-color-peach-200 $kz-var-color-peach-300 $kz-var-color-peach-400 $kz-var-color-peach-500 $kz-var-color-peach-600 $kz-var-color-peach-700)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-orange-100 $color-orange-200 $color-orange-300 $color-orange-400 $color-orange-500 $color-orange-600 $color-orange-700)', testName: "peach is renamed to orange in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-seedling-100 $kz-var-color-seedling-200 $kz-var-color-seedling-300 $kz-var-color-seedling-400 $kz-var-color-seedling-500 $kz-var-color-seedling-600 $kz-var-color-seedling-700)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-green-100 $color-green-200 $color-green-300 $color-green-400 $color-green-500 $color-green-600 $color-green-700)', testName: "seedling is renamed to green in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule(test-prop: $kz-var-color-white $kz-var-color-stone $kz-var-color-ash $kz-var-color-iron $kz-var-color-slate)", expectedOutput: '@import "~@kaizen/design-tokens/sass/color"; @testrule(test-prop: $color-white $color-gray-100 $color-gray-300 $color-gray-500 $color-gray-600)', testName: "grays are renamed in at-rules", expectedWarnings: 0, }, { language: "scss", input: "@testrule($kz-var-color-cluny-100, $kz-var-spacing-md $kz-var-shadow-large-box-shadow)", expectedOutput: '@import "~@kaizen/design-tokens/sass/shadow"; @import "~@kaizen/design-tokens/sass/spacing"; @import "~@kaizen/design-tokens/sass/color"; @testrule($color-blue-100, $spacing-md $shadow-large-box-shadow)', testName: "kz-var prefix is removed in at-rules", expectedWarnings: 0, }, { testName: "benign usage of color mixing functions don't cause any warnings", language: "scss", input: ".test { color: mix($test, $white, 0.6) }", expectedOutput: ".test { color: mix($test, $white, 0.6) }", expectedWarnings: 0, }, { testName: "usage of non-deprecated tokens in other functions is allowed and not warned of", language: "scss", input: '@import "~@kaizen/design-tokens/sass/spacing"; .test { padding: @include ca-margin($start: $spacing-md) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .test { padding: @include ca-margin($start: $spacing-md) }', expectedWarnings: 0, }, { testName: "removed tokens are warned about within variables but not replaced", language: "scss", input: "$foo: $kz-var-color-wisteria-100", expectedOutput: "$foo: $kz-var-color-wisteria-100", expectedWarnings: 1, }, { testName: "tokens within variable definitions can be replaced when the replacement is not a CSS variable", language: "scss", input: '@import "~@kaizen/design-tokens/sass/layout-vars"; $foo: $kz-var-layout-breakpoints-large @media (max-width: $foo){}', expectedOutput: '@import "~@kaizen/design-tokens/sass/layout"; $foo: $layout-breakpoints-large @media (max-width: $foo){}', expectedWarnings: 0, }, { testName: "tokens within functions can be safely replaced when the current/existing token is a CSS variable", language: "scss", input: '@import "~@kaizen/design-tokens/sass/spacing-vars"; .test { padding: ca-padding($kz-var-spacing-md) }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .test { padding: ca-padding($spacing-md) }', expectedWarnings: 0, }, { testName: "tokens are migrated within compiler at-rules (@include ...)", language: "scss", input: ` .test { @include ca-margin($start: $kz-var-spacing-sm); }`, expectedOutput: ` @import "~@kaizen/design-tokens/sass/spacing"; .test { @include ca-margin($start: $spacing-sm); }`, expectedWarnings: 0, }, { testName: "custom atrules with functions and non-deprecated tokens are not warned about", language: "scss", input: ` @import "~@kaizen/design-tokens/sass/spacing"; .test { @include ca-margin($start: $spacing-sm); }`, expectedOutput: ` @import "~@kaizen/design-tokens/sass/spacing"; .test { @include ca-margin($start: $spacing-sm); }`, expectedWarnings: 0, }, { testName: "reports on deprecated tokens in CSS variable identifiers", language: "scss", input: ` .test { color: var(--kz-var-color-wisteria-100); } `, expectedOutput: ` .test { color: var(--kz-var-color-wisteria-100); } `, expectedWarningMessages: [ containsDeprecatedKaizenTokenWithNoReplacement( "kz-var-color-wisteria-100" ), ], }, { language: "scss", testName: "use-deprecated-component-library-helpers-scss-imports: replaces styles/type", input: ` @import "~@kaizen/some-other-import"; @import "~@kaizen/component-library/styles/type"; @import "~@kaizen/some-other-import-2"; `, expectedOutput: ` @import "~@kaizen/some-other-import"; @import "~@kaizen/deprecated-component-library-helpers/styles/type"; @import "~@kaizen/some-other-import-2"; `, expectedWarnings: 0, }, { language: "scss", testName: "use-deprecated-component-library-helpers-scss-imports: replaces styles/color", input: '@import "~@kaizen/component-library/styles/color"', expectedOutput: '@import "~@kaizen/deprecated-component-library-helpers/styles/color"', expectedWarnings: 0, }, { language: "scss", testName: "use-deprecated-component-library-helpers-scss-imports: replaces styles/layout", input: '@import "~@kaizen/component-library/styles/layout"', expectedOutput: '@import "~@kaizen/deprecated-component-library-helpers/styles/layout"', expectedWarnings: 0, }, { language: "scss", testName: "use-deprecated-component-library-helpers-scss-imports: preserves single quotes", input: "@import '~@kaizen/component-library/styles/type'", expectedOutput: "@import '~@kaizen/deprecated-component-library-helpers/styles/type'", expectedWarnings: 0, }, { language: "less", testName: "use-deprecated-component-library-helpers-scss-imports: also works in less", input: '@import "~@kaizen/component-library/styles/color"', expectedOutput: '@import "~@kaizen/deprecated-component-library-helpers/styles/color"', expectedWarnings: 0, }, { language: "scss", testName: "use-deprecated-component-library-helpers-scss-imports: does not leave duplicates, and keeps the last import if there are duplicates", input: ` @import "some-other-import"; @import "~@kaizen/component-library/styles/color"; @import "another-import"; @import "~@kaizen/deprecated-component-library-helpers/styles/color"; `, expectedOutput: ` @import "some-other-import"; @import "another-import"; @import "~@kaizen/deprecated-component-library-helpers/styles/color"; `, expectedWarnings: 0, }, ] describe("Codemod", () => { const testExample = ({ language, testName, input, expectedOutput, only, ...warnings }: TestExample) => { const testFn = only ? test.only : test testFn(`${language}: ${testName}`, async () => { const result = await lint({ codeFilename: `input.${language}`, config: testStylelintConfig, code: input, fix: true, }) if ("expectedWarnings" in warnings) { if (result.results[0]?.warnings.length !== warnings.expectedWarnings) { // eslint-disable-next-line no-console console.warn( `Unexpected warnings for test: ${language}: ${testName}`, result.results[0]?.warnings ) } expect(result.results[0]?.warnings.length).toBe( warnings.expectedWarnings ) } else { expect(new Set(warnings.expectedWarningMessages)).toEqual( new Set(result.results[0]?.warnings.map(warning => warning.text)) ) } expect(result.output.replace(/(\n|\t| )+/g, " ").trim()).toBe( expectedOutput.replace(/(\n|\t| )+/g, " ").trim() ) }) } testExamples.forEach(testExample) // Test a single example by adding "only" to an example up above // OR // Test a single example like so: /* testExample({ language: "scss", testName: "test", input: '@import "~@kaizen/design-tokens/sass/spacing-vars"; .foo { padding: $kz-var-spacing-lg calc(-1 * #{$kz-var-spacing-md}); }', expectedOutput: '@import "~@kaizen/design-tokens/sass/spacing"; .foo { padding: $spacing-lg calc(-1 * #{$spacing-md}); }', expectedUnmigratableTokens: 0, }) */ })
the_stack
import * as fse from 'fs-extra'; import * as crypto from 'crypto'; import * as io from './io'; import { join, relative, normalize, extname, } from './path'; import { Repository } from './repository'; import { getPartHash, HashBlock, MB20, StatsSubset, } from './common'; const sortPaths = require('sort-paths'); export const enum FILEMODE { UNREADABLE = 0, TREE = 16384, BLOB = 33188, EXECUTABLE = 33261, LINK = 40960, COMMIT = 57344, } const textFileExtensions = new Set([ '.txt', '.html', '.plist', '.htm', '.css', '.js', '.jsx', '.less', '.scss', '.wasm', '.php', '.c', '.cc', '.class', '.clj', '.cpp', '.cs', '.cxx', '.el', '.go', '.h', '.java', '.lua', '.m', '.m4', '.php', '.pl', '.po', '.py', '.rb', '.rs', '.info', '.sh', '.swift', '.vb', '.vcxproj', '.xcodeproj', '.xml', '.diff', '.patch', '.html', '.js', '.ts', ]); export const enum DETECTIONMODE { /** * Uses SIZE_AND_HASH_FOR_SMALL_FILES for all known text files and ONLY_SIZE_AND_MKTIME for everything else. */ DEFAULT = 1, /** * Only perform a size and mktime check. If the modified time differs between the commited file * and the one in the working directory, the file is identified as modified. * If the modified time is the same, the file is not identified as modified. */ ONLY_SIZE_AND_MKTIME = 2, /** * Perform a size and hash check for all files smaller than 20 MB. */ SIZE_AND_HASH_FOR_SMALL_FILES = 3, /** * Perform a size and hash check for all files. Please note, * that this is the slowest of all detection modes. */ SIZE_AND_HASH_FOR_ALL_FILES = 4 } export function calculateSizeAndHash(items: TreeEntry[]): [number, string] { const hash = crypto.createHash('sha256'); let size = 0; // Here we ensure that the hash of the tree entries is not dependend on their order items = sortPaths(items, (item) => item.path, '/'); for (const r of items) { size += r.stats.size; hash.update(r.hash.toString()); } return [size, hash.digest('hex')]; } export abstract class TreeEntry { constructor( public hash: string, public path: string, public stats: StatsSubset, ) { } isDirectory(): boolean { return this instanceof TreeDir; } isFile(): boolean { return this instanceof TreeFile; } abstract clone(parent?: TreeDir): TreeEntry; } function generateSizeAndCaches(item: TreeEntry): [number, string] { if (item instanceof TreeDir) { for (const subitem of item.children) { if (subitem instanceof TreeDir) { generateSizeAndCaches(subitem); } } const calcs = calculateSizeAndHash(item.children); item.stats.size = calcs[0]; item.hash = calcs[1]; return [calcs[0], calcs[1]]; } return [item.stats.size, item.hash]; } export class TreeFile extends TreeEntry { constructor( hash: string, path: string, stats: StatsSubset, public ext: string, public parent: TreeDir, ) { super(hash, path, stats); } clone(parent?: TreeDir): TreeFile { return new TreeFile( this.hash, this.path, StatsSubset.clone(this.stats), this.ext, parent, ); } toJsonObject(): any { if (!this.parent && this.path) { throw new Error('parent has no path'); } else if (this.parent && !this.path) { // only the root path with no parent has no path throw new Error('item must have path'); } const output: any = { hash: this.hash, path: this.path, ext: this.ext, stats: { size: this.stats.size, ctime: this.stats.ctime.getTime(), mtime: this.stats.mtime.getTime(), birthtime: this.stats.birthtime.getTime(), }, }; return output; } isFileModified(repo: Repository, detectionMode: DETECTIONMODE): Promise<{file : TreeFile; modified : boolean, newStats: fse.Stats}> { const filepath = join(repo.workdir(), this.path); return io.stat(filepath).then((newStats: fse.Stats) => { // first we check for for modification time and file size if (this.stats.size !== newStats.size) { return { file: this, modified: true, newStats }; } // When a commit is checked out, 'mtime' of restored items is set by fse.utimes. // The fractional part (microseconds) of mtime comes from JSON and might be // clamped (rounding errors). It's also not guaranteed that all filesystems support // microseconds. That's why all items are identified if the mtime from the commit // and the mtime from the file on disk is greater than 1ms, everything below is // considered equal. if (Math.abs(+this.stats.mtime - (+newStats.mtime)) >= 1.0) { switch (detectionMode) { case DETECTIONMODE.DEFAULT: { const ext = extname(filepath); // Text files are more prone to mtime changes than other files, // so by default text files are checked for content changes than rather relying only on mtime. if (!textFileExtensions.has(ext)) { // If not a text file, use same heuristics as ONLY_SIZE_AND_MKTIME return { file: this, modified: true, newStats }; } // If a text file, fall through to SIZE_AND_HASH_FOR_SMALL_FILES /* falls through */ } // eslint-disable-next-line no-fallthrough case DETECTIONMODE.SIZE_AND_HASH_FOR_SMALL_FILES: // A file bigger than 20 MB is considered as changed if the mtime is different ... if (this.stats.size >= MB20) { return { file: this, modified: true, newStats }; } // ... otherwise break and check the file hash. break; case DETECTIONMODE.ONLY_SIZE_AND_MKTIME: return { file: this, modified: true, newStats }; case DETECTIONMODE.SIZE_AND_HASH_FOR_ALL_FILES: default: break; } return getPartHash(filepath) .then((hashBlock: HashBlock) => { return { file: this, modified: this.hash !== hashBlock.hash, newStats }; }); } return { file: this, modified: false, newStats }; }); } } export class TreeDir extends TreeEntry { static ROOT = undefined; hash: string; children: (TreeEntry)[] = []; constructor( public path: string, public stats: StatsSubset, public parent: TreeDir = null, ) { super('', path, stats); } static createRootTree(): TreeDir { return new TreeDir('', { size: 0, ctime: new Date(0), mtime: new Date(0), birthtime: new Date(0), }); } clone(parent?: TreeDir): TreeDir { const newTree = new TreeDir(this.path, StatsSubset.clone(this.stats), parent); newTree.children = this.children.map((c: TreeEntry) => c.clone(newTree)); return newTree; } /** * Merge two trees, with target having the precedence in case * the element is already located in 'source. */ static merge(source: TreeEntry, target: TreeEntry): TreeDir { function privateMerge(source: TreeEntry, target: TreeEntry) { // walk source nodes... if (source instanceof TreeDir && target instanceof TreeDir) { const newItems = new Map<string, TreeEntry>(); for (const child of source.children) { newItems.set(child.path, child); } for (const child of target.children) { newItems.set(child.path, child); } for (const sourceItem of source.children) { for (const targetItem of target.children) { if (targetItem.path === sourceItem.path) { const res = privateMerge(sourceItem, targetItem); newItems.set(res.path, res); } } } target.children = Array.from(newItems.values()); const calcs = generateSizeAndCaches(target); target.stats.size = calcs[0]; target.hash = calcs[1]; } return target; } return privateMerge(source, target.clone()) as TreeDir; } toJsonObject(includeChildren?: boolean): any { if (!this.parent && this.path) { throw new Error('parent has no path'); } else if (this.parent && (!this.path || this.path.length === 0)) { // only the root path with no parent has no path throw new Error('item must have path'); } const children: string[] = this.children.map((value: TreeDir | TreeFile) => value.toJsonObject(includeChildren)); const stats: any = { size: this.stats.size, ctime: this.stats.ctime.getTime(), mtime: this.stats.mtime.getTime(), birthtime: this.stats.birthtime.getTime(), }; return { hash: this.hash, path: this.path ?? '', stats, children, }; } getAllTreeFiles(opt: {entireHierarchy: boolean, includeDirs: boolean}): Map<string, TreeEntry> { const visit = (obj: TreeEntry[] | TreeEntry, map: Map<string, TreeEntry>) => { if (Array.isArray(obj)) { return obj.forEach((c: any) => visit(c, map)); } if (obj instanceof TreeDir) { if (opt.includeDirs) { map.set(obj.path, obj); } return obj.children.forEach((c: any) => visit(c, map)); } map.set(obj.path, obj); }; const map: Map<string, TreeEntry> = new Map(); if (opt.entireHierarchy) { visit(this.children, map); } else { this.children.forEach((o: TreeDir | TreeFile) => { if (o instanceof TreeFile || opt.entireHierarchy) { map.set(o.path, o); } }); } return map; } find(relativePath: string): TreeEntry | null { if (relativePath === this.path) { return this; } let tree: TreeEntry | null = null; // TODO: (Seb) return faster if found TreeDir.walk(this, (entry: TreeDir | TreeFile) => { if (entry.path === relativePath) { tree = entry; } }); return tree; } /** * Browse through the entire hierarchy of the tree and remove the given item. */ static remove( tree: TreeDir, cb: (entry: TreeEntry, index: number, array: TreeEntry[]) => boolean, ): void { for (const child of tree.children) { if (child instanceof TreeDir) { TreeDir.remove(child, cb); } } tree.children = tree.children.filter((value: TreeEntry, index: number, array: TreeEntry[]) => !cb(value, index, array)); } static walk( tree: TreeDir, cb: (entry: TreeDir | TreeFile, index: number, length: number) => void, ): void { let i = 0; for (const entry of tree.children) { cb(<TreeFile>entry, i, tree.children.length); if (entry instanceof TreeDir) { TreeDir.walk(entry, cb); } i++; } } } // This function has the same basic functioanlity as io.osWalk(..) but works with Tree export function constructTree( dirPath: string, tree?: TreeDir, root?: string, ): Promise<TreeDir> { if (dirPath.endsWith('/')) { // if directory ends with a seperator, we cut it of to ensure // we don't return a path like /foo/directory//file.jpg dirPath = dirPath.substr(0, dirPath.length - 1); } if (!root) { root = dirPath; } if (!tree) { tree = TreeDir.createRootTree(); } return new Promise<string[]>((resolve, reject) => { io.readdir(dirPath, (error, entries: string[]) => { if (error) { reject(error); return; } resolve(entries.map(normalize)); }); }) .then((entries: string[]) => { const promises: Promise<any>[] = []; for (const entry of entries) { if (entry === '.snow' || entry === '.git' || entry === '.DS_Store' || entry === 'thumbs.db') { continue; } const absPath = `${dirPath}/${entry}`; const relPath = relative(root, absPath); promises.push( io.stat(absPath).then((stat: fse.Stats) => { if (stat.isDirectory()) { // hash is later added to subtree (see next promise task) const subtree: TreeDir = new TreeDir(relative(root, absPath), StatsSubset.clone(stat), tree); tree.children.push(subtree); return constructTree(absPath, subtree, root); } const entry: TreeFile = new TreeFile('', relPath, StatsSubset.clone(stat), extname(relPath), tree); tree.children.push(entry); }), ); } return Promise.all(promises); }) .then(() => { // calculate the size of the directory let size = 0; for (const r of tree.children) { size += r.stats.size; } tree.stats.size = size; return tree; }); }
the_stack
import { ElementLayouter, PdfLayoutResult, PdfLayoutParams } from './element-layouter'; import { RectangleF, SizeF, PointF } from './../../../drawing/pdf-drawing'; import { PdfPage } from './../../../pages/pdf-page'; import { PdfShapeElement } from './pdf-shape-element'; import { PdfLayoutBreakType, PdfLayoutType } from './../../figures/enum'; import { BeginPageLayoutEventArgs, EndPageLayoutEventArgs } from './../../../structured-elements/grid/layout/grid-layouter'; import { PdfGraphics, PdfGraphicsState } from './../../pdf-graphics'; /** * ShapeLayouter class. * @private */ export class ShapeLayouter extends ElementLayouter { // Fields /** * Initializes the object to store `older form elements` of previous page. * @default 0 * @private */ public olderPdfForm : number = 0; /** * Initializes the offset `index`. * * @default 0 * @private */ private static index : number = 0; /** * Initializes the `difference in page height`. * * @default 0 * @private */ private static splitDiff : number = 0; /** * Determines the `end of Vertical offset` values. * * @default false * @private */ private static last : boolean = false; /** * Determines the document link annotation `border width`. * * @default 0 * @private */ private static readonly borderWidth : number = 0; /** * Checks weather `is pdf grid` or not. * @private */ public isPdfGrid : boolean; /** * The `bounds` of the shape element. * * @default new RectangleF() * @private */ public shapeBounds : RectangleF = new RectangleF(); /** * The `bottom cell padding`. * @private */ public bottomCellPadding : number; /** * Total Page size of the web page. * * @default 0 * @private */ private totalPageSize : number = 0; // Constructors /** * Initializes a new instance of the `ShapeLayouter` class. * @private */ public constructor(element : PdfShapeElement) { super(element); } // Properties /** * Gets shape element. * @private */ public get element() : PdfShapeElement { return (this.elements as PdfShapeElement); } // Implementation /** * Layouts the element. * @private */ protected layoutInternal(param : PdfLayoutParams) : PdfLayoutResult { let currentPage : PdfPage = param.page; let currentBounds : RectangleF = param.bounds; let shapeLayoutBounds : RectangleF = this.element.getBounds(); shapeLayoutBounds.x = 0; shapeLayoutBounds.y = 0; /* tslint:disable */ let isEmpty : boolean = (this.shapeBounds.x === this.shapeBounds.y && this.shapeBounds.y === this.shapeBounds.width && this.shapeBounds.width === this.shapeBounds.height && this.shapeBounds.height === 0) ? true : false; /* tslint:enable */ if ((this.isPdfGrid) && (!(isEmpty))) { shapeLayoutBounds = this.shapeBounds; } let result : PdfLayoutResult = null; let pageResult : ShapeLayoutResult = new ShapeLayoutResult(); pageResult.page = currentPage; /*tslint:disable:no-constant-condition */ while (true) { // Raise event. let result1 : { currentBounds: RectangleF, cancel : boolean } = this.raiseBeforePageLayout(currentPage, currentBounds); currentBounds = result1.currentBounds; let endArgs : EndPageLayoutEventArgs = null; if (!result1.cancel) { pageResult = this.layoutOnPage(currentPage, currentBounds, shapeLayoutBounds, param); // Raise event. endArgs = this.raiseEndPageLayout(pageResult); result1.cancel = (endArgs === null) ? false : endArgs.cancel; } if (!pageResult.end && !result1.cancel) { currentBounds = this.getPaginateBounds(param); shapeLayoutBounds = this.getNextShapeBounds(shapeLayoutBounds, pageResult); currentPage = (endArgs === null || endArgs.nextPage === null) ? this.getNextPage(currentPage) : endArgs.nextPage; if (this.isPdfGrid) { result = this.getLayoutResult(pageResult); break; } } else { result = this.getLayoutResult(pageResult); break; } } return result; } /** * Raises BeforePageLayout event. * @private */ private raiseBeforePageLayout(currentPage: PdfPage, currentBounds: RectangleF): { currentBounds : RectangleF, cancel : boolean } { let cancel: boolean = false; if (this.element.raiseBeginPageLayout) { let args: BeginPageLayoutEventArgs = new BeginPageLayoutEventArgs(currentBounds, currentPage); this.element.onBeginPageLayout(args); cancel = args.cancel; currentBounds = args.bounds; } return { currentBounds : currentBounds, cancel : cancel}; } /** * Raises PageLayout event if needed. * @private */ private raiseEndPageLayout(pageResult: ShapeLayoutResult): EndPageLayoutEventArgs { let args: EndPageLayoutEventArgs = null; if (this.element.raiseEndPageLayout) { let res: PdfLayoutResult = this.getLayoutResult(pageResult); args = new EndPageLayoutEventArgs(res); this.element.onEndPageLayout(args); } return args; } /** * Creates layout result. * @private */ private getLayoutResult(pageResult: ShapeLayoutResult): PdfLayoutResult { let result: PdfLayoutResult = new PdfLayoutResult(pageResult.page, pageResult.bounds); return result; } /** * Calculates the next active shape bounds. * @private */ private getNextShapeBounds(shapeLayoutBounds: RectangleF, pageResult: ShapeLayoutResult): RectangleF { let layoutedBounds: RectangleF = pageResult.bounds; shapeLayoutBounds.y = (shapeLayoutBounds.y + layoutedBounds.height); shapeLayoutBounds.height = (shapeLayoutBounds.height - layoutedBounds.height); return shapeLayoutBounds; } /** * Layouts the element on the current page. * @private */ private layoutOnPage(currentPage: PdfPage, curBounds: RectangleF, sBounds: RectangleF, param: PdfLayoutParams): ShapeLayoutResult { let result: ShapeLayoutResult = new ShapeLayoutResult(); curBounds = this.checkCorrectCurrentBounds(currentPage, curBounds, param); let fitToPage: boolean = this.fitsToBounds(curBounds, sBounds); let canDraw: boolean = !((param.format.break === PdfLayoutBreakType.FitElement) && (!fitToPage && (currentPage === param.page))); let shapeFinished: boolean = false; if (canDraw) { let drawRectangle: RectangleF = this.getDrawBounds(curBounds, sBounds); this.drawShape(currentPage.graphics, curBounds, drawRectangle); result.bounds = this.getPageResultBounds(curBounds, sBounds); shapeFinished = ((<number>(curBounds.height)) >= (<number>(sBounds.height))); } result.end = (shapeFinished || (param.format.layout === PdfLayoutType.OnePage)); result.page = currentPage; return result; } /** * Returns Rectangle for element drawing on the page. * @private */ private getDrawBounds(currentBounds: RectangleF, shapeLayoutBounds: RectangleF): RectangleF { let result: RectangleF = currentBounds; result.y = (result.y - shapeLayoutBounds.y); result.height = (result.height + shapeLayoutBounds.y); return result; } /** * Draws the shape. * @private */ private drawShape(g: PdfGraphics, currentBounds: RectangleF, drawRectangle: RectangleF): void { let gState: PdfGraphicsState = g.save(); try { g.setClip(currentBounds); this.element.drawGraphicsHelper(g, new PointF(drawRectangle.x, drawRectangle.y)); } finally { g.restore(gState); } } /** * Corrects current bounds on the page. * @protected */ protected checkCorrectCurrentBounds(currentPage: PdfPage, curBounds: RectangleF, param: PdfLayoutParams): RectangleF { let pageSize: SizeF = currentPage.graphics.clientSize; curBounds.width = (curBounds.width > 0) ? curBounds.width : (pageSize.width - curBounds.x); curBounds.height = (curBounds.height > 0) ? curBounds.height : (pageSize.height - curBounds.y); if (this.isPdfGrid) { curBounds.height = (curBounds.height - this.bottomCellPadding); } return curBounds; } /** * Calculates bounds where the shape was layout on the page. * @private */ private getPageResultBounds(currentBounds: RectangleF, shapeLayoutBounds: RectangleF): RectangleF { let result: RectangleF = currentBounds; result.height = Math.min(result.height, shapeLayoutBounds.height); return result; } /** * Checks whether shape rectangle fits to the lay outing bounds. * @private */ private fitsToBounds(currentBounds: RectangleF, shapeLayoutBounds: RectangleF): boolean { let fits: boolean = (shapeLayoutBounds.height <= currentBounds.height); return fits; } } /** * Contains lay outing result settings. * @private */ class ShapeLayoutResult { /** * The last page where the element was drawn. * @private */ public page : PdfPage; /** * The bounds of the element on the last page where it was drawn. * @private */ public bounds : RectangleF; /** * Indicates whether the lay outing has been finished. * @private */ public end : boolean; }
the_stack
import { Vec3, v3 } from './Vec3'; import { Euler } from './Euler'; import { Quat } from './Quat'; export class Mat4 { elements: number[] = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; isMat4: boolean = true; constructor() { if (arguments.length > 0) { console.error( " Mat4: the constructor no longer reads arguments. use .set() instead." ); } } set( n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number ) { var te = this.elements; te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14; te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24; te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34; te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44; return this; } static get Identity() { return new Mat4(); } identity() { this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return this; } clone() { return new Mat4().fromArray(this.elements); } copy(m: Mat4) { var te = this.elements; var me = m.elements; te[0] = me[0]; te[1] = me[1]; te[2] = me[2]; te[3] = me[3]; te[4] = me[4]; te[5] = me[5]; te[6] = me[6]; te[7] = me[7]; te[8] = me[8]; te[9] = me[9]; te[10] = me[10]; te[11] = me[11]; te[12] = me[12]; te[13] = me[13]; te[14] = me[14]; te[15] = me[15]; return this; } copyPosition(m: { elements: any; }) { var te = this.elements, me = m.elements; te[12] = me[12]; te[13] = me[13]; te[14] = me[14]; return this; } extractBasis(xAxis: Vec3, yAxis: Vec3, zAxis: Vec3) { xAxis.setFromMatColumn(this, 0); yAxis.setFromMatColumn(this, 1); zAxis.setFromMatColumn(this, 2); return this; } makeBasis(xAxis: Vec3, yAxis: Vec3, zAxis: Vec3) { this.set( xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1 ); return this; } extractRotation(m: Mat4) { // this method does not support reflection matrices var te = this.elements; var me = m.elements; var scaleX = 1 / _v1.setFromMatColumn(m, 0).length(); var scaleY = 1 / _v1.setFromMatColumn(m, 1).length(); var scaleZ = 1 / _v1.setFromMatColumn(m, 2).length(); te[0] = me[0] * scaleX; te[1] = me[1] * scaleX; te[2] = me[2] * scaleX; te[3] = 0; te[4] = me[4] * scaleY; te[5] = me[5] * scaleY; te[6] = me[6] * scaleY; te[7] = 0; te[8] = me[8] * scaleZ; te[9] = me[9] * scaleZ; te[10] = me[10] * scaleZ; te[11] = 0; te[12] = 0; te[13] = 0; te[14] = 0; te[15] = 1; return this; } makeRotationFromEuler(euler: Euler) { if (!(euler && euler.isEuler)) { console.error( " Mat4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vec3 and order." ); } var te = this.elements; var x = euler.x, y = euler.y, z = euler.z; var a = Math.cos(x), b = Math.sin(x); var c = Math.cos(y), d = Math.sin(y); var e = Math.cos(z), f = Math.sin(z); if (euler.order === "XYZ") { var ae = a * e, af = a * f, be = b * e, bf = b * f; te[0] = c * e; te[4] = -c * f; te[8] = d; te[1] = af + be * d; te[5] = ae - bf * d; te[9] = -b * c; te[2] = bf - ae * d; te[6] = be + af * d; te[10] = a * c; } else if (euler.order === "YXZ") { var ce = c * e, cf = c * f, de = d * e, df = d * f; te[0] = ce + df * b; te[4] = de * b - cf; te[8] = a * d; te[1] = a * f; te[5] = a * e; te[9] = -b; te[2] = cf * b - de; te[6] = df + ce * b; te[10] = a * c; } else if (euler.order === "ZXY") { var ce = c * e, cf = c * f, de = d * e, df = d * f; te[0] = ce - df * b; te[4] = -a * f; te[8] = de + cf * b; te[1] = cf + de * b; te[5] = a * e; te[9] = df - ce * b; te[2] = -a * d; te[6] = b; te[10] = a * c; } else if (euler.order === "ZYX") { var ae = a * e, af = a * f, be = b * e, bf = b * f; te[0] = c * e; te[4] = be * d - af; te[8] = ae * d + bf; te[1] = c * f; te[5] = bf * d + ae; te[9] = af * d - be; te[2] = -d; te[6] = b * c; te[10] = a * c; } else if (euler.order === "YZX") { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[0] = c * e; te[4] = bd - ac * f; te[8] = bc * f + ad; te[1] = f; te[5] = a * e; te[9] = -b * e; te[2] = -d * e; te[6] = ad * f + bc; te[10] = ac - bd * f; } else if (euler.order === "XZY") { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[0] = c * e; te[4] = -f; te[8] = d * e; te[1] = ac * f + bd; te[5] = a * e; te[9] = ad * f - bc; te[2] = bc * f - ad; te[6] = b * e; te[10] = bd * f + ac; } // bottom row te[3] = 0; te[7] = 0; te[11] = 0; // last column te[12] = 0; te[13] = 0; te[14] = 0; te[15] = 1; return this; } makeRotationFromQuat(q: any) { return this.compose(_zero, q, _one); } lookAt(eye: Vec3, target: Vec3, up: Vec3) { var te = this.elements; _z.subVecs(eye, target); if (_z.lengthSq() === 0) { // eye and target are in the same position _z.z = 1; } _z.normalize(); _x.crossVecs(up, _z); if (_x.lengthSq() === 0) { // up and z are parallel if (Math.abs(up.z) === 1) { _z.x += 0.0001; } else { _z.z += 0.0001; } _z.normalize(); _x.crossVecs(up, _z); } _x.normalize(); _y.crossVecs(_z, _x); te[0] = _x.x; te[4] = _y.x; te[8] = _z.x; te[1] = _x.y; te[5] = _y.y; te[9] = _z.y; te[2] = _x.z; te[6] = _y.z; te[10] = _z.z; return this; } multiply(m: Mat4, n?: Mat4) { if (n !== undefined) { return this.multiplyMats(m, n); } return this.multiplyMats(this, m); } premultiply(m: Mat4) { return this.multiplyMats(m, this); } multiplyMats(a: Mat4, b: Mat4) { var ae = a.elements; var be = b.elements; var te = this.elements; var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; } multiplyScalar(s: number) { var te = this.elements; te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s; te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s; te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s; te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s; return this; } applyToBufferAttribute(attribute: { count: any; getX: (arg0: number) => number; getY: (arg0: number) => number; getZ: (arg0: number) => number; setXYZ: (arg0: number, arg1: number, arg2: number, arg3: number) => void; }) { for (var i = 0, l = attribute.count; i < l; i++) { _v1.x = attribute.getX(i); _v1.y = attribute.getY(i); _v1.z = attribute.getZ(i); _v1.applyMat4(this); attribute.setXYZ(i, _v1.x, _v1.y, _v1.z); } return attribute; } determinant() { var te = this.elements; var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; //TODO: make this more efficient //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) return ( n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31) ); } transpose() { var te = this.elements; var tmp; tmp = te[1]; te[1] = te[4]; te[4] = tmp; tmp = te[2]; te[2] = te[8]; te[8] = tmp; tmp = te[6]; te[6] = te[9]; te[9] = tmp; tmp = te[3]; te[3] = te[12]; te[12] = tmp; tmp = te[7]; te[7] = te[13]; te[13] = tmp; tmp = te[11]; te[11] = te[14]; te[14] = tmp; return this; } setPosition(x: number | Vec3 | any, y?: number, z?: number) { var te = this.elements; if (x.isVec3) { te[12] = x.x; te[13] = x.y; te[14] = x.z; } else if (y !== undefined && z !== undefined) { te[12] = x; te[13] = y; te[14] = z; } else { if (x.x !== undefined && x.y !== undefined && x.z !== undefined) { te[12] = x.x; te[13] = x.y; te[14] = x.z; } } return this; } /** * 矩阵求逆 * @returns 自己 */ invert(): Mat4 { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const detInv = 1 / det; te[0] = t11 * detInv; te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; te[4] = t12 * detInv; te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; te[8] = t13 * detInv; te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; te[12] = t14 * detInv; te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; return this; } getInverse(m: Mat4, throwOnDegenerate: boolean = true) { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm var te = this.elements, me = m.elements, n11 = me[0], n21 = me[1], n31 = me[2], n41 = me[3], n12 = me[4], n22 = me[5], n32 = me[6], n42 = me[7], n13 = me[8], n23 = me[9], n33 = me[10], n43 = me[11], n14 = me[12], n24 = me[13], n34 = me[14], n44 = me[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if (det === 0) { var msg = " Mat4: .getInverse() can't invert matrix, determinant is 0"; if (throwOnDegenerate === true) { throw new Error(msg); } else { console.warn(msg); } return this.identity(); } var detInv = 1 / det; te[0] = t11 * detInv; te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; te[4] = t12 * detInv; te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; te[8] = t13 * detInv; te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; te[12] = t14 * detInv; te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; return this; } scale(v: { x: any; y: any; z: any; }) { var te = this.elements; var x = v.x, y = v.y, z = v.z; te[0] *= x; te[4] *= y; te[8] *= z; te[1] *= x; te[5] *= y; te[9] *= z; te[2] *= x; te[6] *= y; te[10] *= z; te[3] *= x; te[7] *= y; te[11] *= z; return this; } getMaxScaleOnAxis() { var te = this.elements; var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); } makeTranslation(x: number, y: number, z: number) { this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); return this; } makeRotationX(theta: number) { var c = Math.cos(theta), s = Math.sin(theta); this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); return this; } makeRotationY(theta: number) { var c = Math.cos(theta), s = Math.sin(theta); this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); return this; } makeRotationZ(theta: number) { var c = Math.cos(theta), s = Math.sin(theta); this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return this; } makeRotationAxis(axis: { x: any; y: any; z: any; }, angle: number) { // Based on http://www.gamedev.net/reference/articles/article1199.asp var c = Math.cos(angle); var s = Math.sin(angle); var t = 1 - c; var x = axis.x, y = axis.y, z = axis.z; var tx = t * x, ty = t * y; this.set( tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1 ); return this; } makeScale(x: number, y: number, z: number) { this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); return this; } /** * 6个参数 都是由两个值来影响 [v1][v2] v1表示v2轴在v1轴产生效果 * @param xy * @param xz * @param yx * @param yz * @param zx * @param zy * @returns */ makeShear(xy: number, xz: number, yx: number, yz: number, zx: number, zy: number) { this.set( 1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1 ); return this; } compose(position: Vec3, quat: Quat, scale: Euler | Vec3) { var te = this.elements; var x = quat._x, y = quat._y, z = quat._z, w = quat._w; var x2 = x + x, y2 = y + y, z2 = z + z; var xx = x * x2, xy = x * y2, xz = x * z2; var yy = y * y2, yz = y * z2, zz = z * z2; var wx = w * x2, wy = w * y2, wz = w * z2; var sx = scale.x, sy = scale.y, sz = scale.z; te[0] = (1 - (yy + zz)) * sx; te[1] = (xy + wz) * sx; te[2] = (xz - wy) * sx; te[3] = 0; te[4] = (xy - wz) * sy; te[5] = (1 - (xx + zz)) * sy; te[6] = (yz + wx) * sy; te[7] = 0; te[8] = (xz + wy) * sz; te[9] = (yz - wx) * sz; te[10] = (1 - (xx + yy)) * sz; te[11] = 0; te[12] = position.x; te[13] = position.y; te[14] = position.z; te[15] = 1; return this; } decompose(position: Vec3, quat: Quat, scale: Vec3) { var te = this.elements; var sx = _v1.set(te[0], te[1], te[2]).length(); var sy = _v1.set(te[4], te[5], te[6]).length(); var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale var det = this.determinant(); if (det < 0) sx = -sx; position.x = te[12]; position.y = te[13]; position.z = te[14]; // scale the rotation part _m1.copy(this); var invSX = 1 / sx; var invSY = 1 / sy; var invSZ = 1 / sz; _m1.elements[0] *= invSX; _m1.elements[1] *= invSX; _m1.elements[2] *= invSX; _m1.elements[4] *= invSY; _m1.elements[5] *= invSY; _m1.elements[6] *= invSY; _m1.elements[8] *= invSZ; _m1.elements[9] *= invSZ; _m1.elements[10] *= invSZ; quat.setFromRotationMat(_m1); scale.x = sx; scale.y = sy; scale.z = sz; return this; } makePerspective(left: number, right: number, top: number, bottom: number, near: number, far: number) { if (far === undefined) { console.warn( " Mat4: .makePerspective() has been redefined and has a new signature. Please check the docs." ); } var te = this.elements; var x = (2 * near) / (right - left); var y = (2 * near) / (top - bottom); var a = (right + left) / (right - left); var b = (top + bottom) / (top - bottom); var c = -(far + near) / (far - near); var d = (-2 * far * near) / (far - near); te[0] = x; te[4] = 0; te[8] = a; te[12] = 0; te[1] = 0; te[5] = y; te[9] = b; te[13] = 0; te[2] = 0; te[6] = 0; te[10] = c; te[14] = d; te[3] = 0; te[7] = 0; te[11] = -1; te[15] = 0; return this; } makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number) { var te = this.elements; var w = 1.0 / (right - left); var h = 1.0 / (top - bottom); var p = 1.0 / (far - near); var x = (right + left) * w; var y = (top + bottom) * h; var z = (far + near) * p; te[0] = 2 * w; te[4] = 0; te[8] = 0; te[12] = -x; te[1] = 0; te[5] = 2 * h; te[9] = 0; te[13] = -y; te[2] = 0; te[6] = 0; te[10] = -2 * p; te[14] = -z; te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1; return this; } equals(matrix: { elements: any; }) { var te = this.elements; var me = matrix.elements; for (var i = 0; i < 16; i++) { if (te[i] !== me[i]) return false; } return true; } fromArray(array: number[], offset: number = 0) { for (var i = 0; i < 16; i++) { this.elements[i] = array[i + offset]; } return this; } toArray(array: number[] = [], offset: number = 0) { var te = this.elements; array[offset] = te[0]; array[offset + 1] = te[1]; array[offset + 2] = te[2]; array[offset + 3] = te[3]; array[offset + 4] = te[4]; array[offset + 5] = te[5]; array[offset + 6] = te[6]; array[offset + 7] = te[7]; array[offset + 8] = te[8]; array[offset + 9] = te[9]; array[offset + 10] = te[10]; array[offset + 11] = te[11]; array[offset + 12] = te[12]; array[offset + 13] = te[13]; array[offset + 14] = te[14]; array[offset + 15] = te[15]; return array; } } const _v1 = v3(); const _m1 = m4(); const _m2 = m4(); const _zero = v3(0, 0, 0); const _one = v3(1, 1, 1); const _x = v3(); const _y = v3(); const _z = v3(); export function m4() { return new Mat4(); }
the_stack
// @ts-ignore import * as gax from 'google-gax'; // @ts-ignore import {Callback, CallOptions, ClientOptions, Descriptors, GaxCall, LROperation, PaginationCallback,} from 'google-gax'; // @ts-ignore import {RequestType} from 'google-gax/build/src/apitypes'; import {Transform} from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); /** * Client JSON configuration object, loaded from * `src/v1beta1/echo_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this * library. */ import * as gapicConfig from './echo_client_config.json'; //@ts-ignore import {operationsProtos} from 'google-gax'; const version = require('../../package.json').version; /** * This service is used showcase the four main types of rpcs - unary, server * side streaming, client side streaming, and bidirectional streaming. This * service also exposes methods that explicitly implement server delay, and * paginated calls. Set the 'showcase-trailer' metadata key on any method * to have the values echoed in the response trailers. * @class * @memberof v1beta1 */ export class EchoClient { private _terminated = false; private _opts: ClientOptions; private _providedCustomServicePath: boolean; private _gaxModule: typeof gax|typeof gax.fallback; private _gaxGrpc: gax.GrpcClient|gax.fallback.GrpcClient; private _protos: {}; private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, stream: {}, longrunning: {}, batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: {[name: string]: Function}; pathTemplates: {[name: string]: gax.PathTemplate}; operationsClient: gax.OperationsClient; echoStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of EchoClient. * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail * in [this * document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] * @param {string} [options.credentials.private_key] * @param {string} [options.email] - Account email address. Required when * using a .pem or .p12 keyFilename. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or * .p12 key downloaded from the Google Developers Console. If you provide * a path to a JSON file, the projectId option below is not necessary. * NOTE: .pem and .p12 require you to specify options.email as well. * @param {number} [options.port] - The port on which to connect to * the remote host. * @param {string} [options.projectId] - The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports * {@link * https://developers.google.com/identity/protocols/application-default-credentials * Application Default Credentials}, your project ID will be detected * automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration * override. Follows the structure of {@link gapicConfig}. * @param {boolean} [options.fallback] - Use HTTP fallback mode. * In fallback mode, a special browser-compatible transport implementation * is used instead of gRPC transport. In browser context (if the `window` * object is defined) the fallback mode is enabled automatically; set * `options.fallback` to `false` if you need to override this behavior. */ constructor(opts?: ClientOptions) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; const servicePath = opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath; this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // If scopes are unset in options and we're connecting to a non-default // endpoint, set scopes just in case. if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; } // Choose either gRPC or proto-over-HTTP implementation of google-gax. this._gaxModule = opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options sent to the // client. this._gaxGrpc = new this._gaxModule.GrpcClient(opts); // Save options to use in initialize() method. this._opts = opts; // Save the auth object to the client, for use by other methods. this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = staticMembers.servicePath; // Set the default scopes in auth client if needed. if (servicePath === staticMembers.servicePath) { this.auth.defaultScopes = staticMembers.scopes; } // Determine the client header string. const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } // Load the applicable protos. this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}/blueprints/{blueprint}'), roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room_id}'), roomIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate('rooms/{room_id}/blurbs/{blurb_id}'), sessionPathTemplate: new this._gaxModule.PathTemplate('sessions/{session}'), testPathTemplate: new this._gaxModule.PathTemplate('sessions/{session}/tests/{test}'), userPathTemplate: new this._gaxModule.PathTemplate('users/{user_id}'), userIdProfileBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'user/{user_id}/profile/blurbs/{blurb_id}'), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { pagedExpand: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', 'responses'), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { expand: new this._gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), collect: new this._gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), chat: new this._gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING), }; const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. this.operationsClient = this._gaxModule .lro({ auth: this.auth, grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }) .operationsClient(opts); const waitResponse = protoFilesRoot.lookup('.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup('.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), waitMetadata.decode.bind(waitMetadata)), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this.innerApiCalls = {}; // Add a warn function to the client constructor so it can be easily tested. this.warn = gax.warn; } /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the * client. This function will be called automatically when any class method is * called for the first time, but if you need to initialize it before calling * an actual method, feel free to call initialize() directly. * * You can await on this method if you want to make sure the client is * initialized. * * @returns {Promise} A promise that resolves to an authenticated service * stub. */ initialize() { // If the client stub promise is already initialized, return immediately. if (this.echoStub) { return this.echoStub; } // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root) .lookupService( 'google.showcase.v1beta1.Echo') : // eslint-disable-next-line // @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Echo, this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. const echoStubMethods = [ 'echo', 'expand', 'collect', 'chat', 'pagedExpand', 'wait', 'block', ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( stub => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); } const func = stub[methodName]; return func.apply(stub, args); }, (err: Error|null|undefined) => () => { throw err; }); const descriptor = this.descriptors.page[methodName] || this.descriptors.stream[methodName] || this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor); this.innerApiCalls[methodName] = apiCall; } return this.echoStub; } /** * The DNS address for this API service. * @returns {string} The DNS address for this service. */ static get servicePath() { return 'localhost'; } /** * The DNS address for this API service - same as servicePath(), * exists for compatibility reasons. * @returns {string} The DNS address for this service. */ static get apiEndpoint() { return 'localhost'; } /** * The port for this API service. * @returns {number} The default port for this service. */ static get port() { return 7469; } /** * The scopes needed to make gRPC calls for every method defined * in this service. * @returns {string[]} List of default scopes. */ static get scopes() { return []; } getProjectId(): Promise<string>; getProjectId(callback: Callback<string, undefined, undefined>): void; /** * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project * ID. */ getProjectId(callback?: Callback<string, undefined, undefined>): Promise<string>|void { if (callback) { this.auth.getProjectId(callback); return; } return this.auth.getProjectId(); } // ------------------- // -- Service calls -- // ------------------- /** * @param {Object} request * The request object that will be sent. * @param {string} request.content * The content to be echoed by the server. * @param {google.rpc.Status} request.error * The error to be thrown by the server. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * [EchoResponse]{@link google.showcase.v1beta1.EchoResponse}. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1beta1/echo.echo.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Echo_async */ echo( request?: protos.google.showcase.v1beta1.IEchoRequest, options?: CallOptions): Promise<[ protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>; echo( request: protos.google.showcase.v1beta1.IEchoRequest, options: CallOptions, callback: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): void; echo( request: protos.google.showcase.v1beta1.IEchoRequest, callback: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): void; echo( request?: protos.google.showcase.v1beta1.IEchoRequest, optionsOrCallback?:|CallOptions|Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>, callback?: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): Promise<[ protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize(); return this.innerApiCalls.echo(request, options, callback); } /** * This method will block (wait) for the requested amount of time * and then return the response or error. * This method showcases how a client handles delays or retries. * * @param {Object} request * The request object that will be sent. * @param {google.protobuf.Duration} request.responseDelay * The amount of time to block before returning a response. * @param {google.rpc.Status} request.error * The error that will be returned by the server. If this code is specified * to be the OK rpc code, an empty response will be returned. * @param {google.showcase.v1beta1.BlockResponse} request.success * The response to be returned that will signify successful method call. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * [BlockResponse]{@link google.showcase.v1beta1.BlockResponse}. Please see * the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1beta1/echo.block.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Block_async */ block( request?: protos.google.showcase.v1beta1.IBlockRequest, options?: CallOptions): Promise<[ protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined ]>; block( request: protos.google.showcase.v1beta1.IBlockRequest, options: CallOptions, callback: Callback< protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|null|undefined, {}|null|undefined>): void; block( request: protos.google.showcase.v1beta1.IBlockRequest, callback: Callback< protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|null|undefined, {}|null|undefined>): void; block( request?: protos.google.showcase.v1beta1.IBlockRequest, optionsOrCallback?:|CallOptions|Callback< protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|null|undefined, {}|null|undefined>, callback?: Callback< protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|null|undefined, {}|null|undefined>): Promise<[ protos.google.showcase.v1beta1.IBlockResponse, protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize(); return this.innerApiCalls.block(request, options, callback); } /** * This method split the given content into words and will pass each word back * through the stream. This method showcases server-side streaming rpcs. * * @param {Object} request * The request object that will be sent. * @param {string} request.content * The content that will be split into words and returned on the stream. * @param {google.rpc.Status} request.error * The error that is thrown after all words are sent on the stream. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Stream} * An object stream which emits [EchoResponse]{@link * google.showcase.v1beta1.EchoResponse} on 'data' event. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming) * for more details and examples. * @example * <caption>include:samples/generated/v1beta1/echo.expand.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Expand_async */ expand( request?: protos.google.showcase.v1beta1.IExpandRequest, options?: CallOptions): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize(); return this.innerApiCalls.expand(request, options); } /** * This method will collect the words given to it. When the stream is closed * by the client, this method will return the a concatenation of the strings * passed to it. This method showcases client-side streaming rpcs. * * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Stream} - A writable stream which accepts objects representing * [EchoRequest]{@link google.showcase.v1beta1.EchoRequest}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming) * for more details and examples. * @example * <caption>include:samples/generated/v1beta1/echo.collect.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Collect_async */ collect( options?: CallOptions, callback?: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): gax.CancellableStream; collect(callback?: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): gax.CancellableStream; collect( optionsOrCallback?:|CallOptions|Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>, callback?: Callback< protos.google.showcase.v1beta1.IEchoResponse, protos.google.showcase.v1beta1.IEchoRequest|null|undefined, {}|null|undefined>): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { callback = optionsOrCallback; optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; this.initialize(); return this.innerApiCalls.collect(null, options, callback); } /** * This method, upon receiving a request on the stream, the same content will * be passed back on the stream. This method showcases bidirectional * streaming rpcs. * * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects * representing [EchoRequest]{@link google.showcase.v1beta1.EchoRequest} for * write() method, and will emit objects representing [EchoResponse]{@link * google.showcase.v1beta1.EchoResponse} on 'data' event asynchronously. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming) * for more details and examples. * @example <caption>include:samples/generated/v1beta1/echo.chat.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Chat_async */ chat(options?: CallOptions): gax.CancellableStream { this.initialize(); return this.innerApiCalls.chat(options); } /** * This method will wait the requested amount of and then return. * This method showcases how a client handles a request timing out. * * @param {Object} request * The request object that will be sent. * @param {google.protobuf.Timestamp} request.endTime * The time that this operation will complete. * @param {google.protobuf.Duration} request.ttl * The duration of this operation. * @param {google.rpc.Status} request.error * The error that will be returned by the server. If this code is specified * to be the OK rpc code, an empty response will be returned. * @param {google.showcase.v1beta1.WaitResponse} request.success * The response to be returned on operation completion. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. * @example <caption>include:samples/generated/v1beta1/echo.wait.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Wait_async */ wait( request?: protos.google.showcase.v1beta1.IWaitRequest, options?: CallOptions): Promise<[ LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|undefined, {}|undefined ]>; wait( request: protos.google.showcase.v1beta1.IWaitRequest, options: CallOptions, callback: Callback< LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|null|undefined, {}|null|undefined>): void; wait( request: protos.google.showcase.v1beta1.IWaitRequest, callback: Callback< LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|null|undefined, {}|null|undefined>): void; wait( request?: protos.google.showcase.v1beta1.IWaitRequest, optionsOrCallback?:|CallOptions|Callback< LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|null|undefined, {}|null|undefined>, callback?: Callback< LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|null|undefined, {}|null|undefined>): Promise<[ LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata>, protos.google.longrunning.IOperation|undefined, {}|undefined ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize(); return this.innerApiCalls.wait(request, options, callback); } /** * Check the status of the long running operation returned by `wait()`. * @param {String} name * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get * information from. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. * @example <caption>include:samples/generated/v1beta1/echo.wait.js</caption> * region_tag:localhost_v1beta1_generated_Echo_Wait_async */ async checkWaitProgress(name: string): Promise<LROperation< protos.google.showcase.v1beta1.WaitResponse, protos.google.showcase.v1beta1.WaitMetadata>> { const request = new operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new gax.Operation( operation, this.descriptors.longrunning.wait, gax.createDefaultBackoffSettings()); return decodeOperation as LROperation< protos.google.showcase.v1beta1.WaitResponse, protos.google.showcase.v1beta1.WaitMetadata>; } /** * This is similar to the Expand method but instead of returning a stream of * expanded words, this method returns a paged list of expanded words. * * @param {Object} request * The request object that will be sent. * @param {string} request.content * The string to expand. * @param {number} request.pageSize * The amount of words to returned in each page. * @param {string} request.pageToken * The position of the page to be returned. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of [EchoResponse]{@link * google.showcase.v1beta1.EchoResponse}. The client library will perform * auto-pagination by default: it will call the API as many times as needed * and will merge results from all the pages into this array. Note that it can * affect your quota. We recommend using `pagedExpandAsync()` method described * below for async iteration which you can stop as needed. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ pagedExpand( request?: protos.google.showcase.v1beta1.IPagedExpandRequest, options?: CallOptions): Promise<[ protos.google.showcase.v1beta1.IEchoResponse[], protos.google.showcase.v1beta1.IPagedExpandRequest|null, protos.google.showcase.v1beta1.IPagedExpandResponse ]>; pagedExpand( request: protos.google.showcase.v1beta1.IPagedExpandRequest, options: CallOptions, callback: PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, protos.google.showcase.v1beta1.IEchoResponse>): void; pagedExpand( request: protos.google.showcase.v1beta1.IPagedExpandRequest, callback: PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, protos.google.showcase.v1beta1.IEchoResponse>): void; pagedExpand( request?: protos.google.showcase.v1beta1.IPagedExpandRequest, optionsOrCallback?:|CallOptions|PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, |protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, protos.google.showcase.v1beta1.IEchoResponse>, callback?: PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, protos.google.showcase.v1beta1.IEchoResponse>): Promise<[ protos.google.showcase.v1beta1.IEchoResponse[], protos.google.showcase.v1beta1.IPagedExpandRequest|null, protos.google.showcase.v1beta1.IPagedExpandResponse ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize(); return this.innerApiCalls.pagedExpand(request, options, callback); } /** * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream * object. * @param {Object} request * The request object that will be sent. * @param {string} request.content * The string to expand. * @param {number} request.pageSize * The amount of words to returned in each page. * @param {string} request.pageToken * The position of the page to be returned. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Stream} * An object stream which emits an object representing [EchoResponse]{@link * google.showcase.v1beta1.EchoResponse} on 'data' event. The client library * will perform auto-pagination by default: it will call the API as many times * as needed. Note that it can affect your quota. We recommend using * `pagedExpandAsync()` method described below for async iteration which you * can stop as needed. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ pagedExpandStream( request?: protos.google.showcase.v1beta1.IPagedExpandRequest, options?: CallOptions): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); this.initialize(); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as gax.GaxCall, request, callSettings); } /** * Equivalent to `pagedExpand`, but returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response * elements on-demand. * @param {Object} request * The request object that will be sent. * @param {string} request.content * The string to expand. * @param {number} request.pageSize * The amount of words to returned in each page. * @param {string} request.pageToken * The position of the page to be returned. * @param {object} [options] * Call options. See {@link * https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @returns {Object} * An iterable Object that allows [async * iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). * When you iterate the returned iterable, each element will be an object * representing [EchoResponse]{@link google.showcase.v1beta1.EchoResponse}. * The API will be called under the hood as needed, once per the page, so you * can stop the iteration when you don't need more results. Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. * @example * <caption>include:samples/generated/v1beta1/echo.paged_expand.js</caption> * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async */ pagedExpandAsync( request?: protos.google.showcase.v1beta1.IPagedExpandRequest, options?: CallOptions): AsyncIterable<protos.google.showcase.v1beta1.IEchoResponse> { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); this.initialize(); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as unknown as RequestType, callSettings) as AsyncIterable<protos.google.showcase.v1beta1.IEchoResponse>; } // -------------------- // -- Path templates -- // -------------------- /** * Return a fully-qualified blueprint resource name string. * * @param {string} session * @param {string} test * @param {string} blueprint * @returns {string} Resource name string. */ blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, blueprint: blueprint, }); } /** * Parse the session from Blueprint resource. * * @param {string} blueprintName * A fully-qualified path representing Blueprint resource. * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { return this.pathTemplates.blueprintPathTemplate.match(blueprintName) .session; } /** * Parse the test from Blueprint resource. * * @param {string} blueprintName * A fully-qualified path representing Blueprint resource. * @returns {string} A string representing the test. */ matchTestFromBlueprintName(blueprintName: string) { return this.pathTemplates.blueprintPathTemplate.match(blueprintName).test; } /** * Parse the blueprint from Blueprint resource. * * @param {string} blueprintName * A fully-qualified path representing Blueprint resource. * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { return this.pathTemplates.blueprintPathTemplate.match(blueprintName) .blueprint; } /** * Return a fully-qualified room resource name string. * * @param {string} room_id * @returns {string} Resource name string. */ roomPath(roomId: string) { return this.pathTemplates.roomPathTemplate.render({ room_id: roomId, }); } /** * Parse the room_id from Room resource. * * @param {string} roomName * A fully-qualified path representing Room resource. * @returns {string} A string representing the room_id. */ matchRoomIdFromRoomName(roomName: string) { return this.pathTemplates.roomPathTemplate.match(roomName).room_id; } /** * Return a fully-qualified roomIdBlurbId resource name string. * * @param {string} room_id * @param {string} blurb_id * @returns {string} Resource name string. */ roomIdBlurbIdPath(roomId: string, blurbId: string) { return this.pathTemplates.roomIdBlurbIdPathTemplate.render({ room_id: roomId, blurb_id: blurbId, }); } /** * Parse the room_id from RoomIdBlurbId resource. * * @param {string} roomIdBlurbIdName * A fully-qualified path representing room_id_blurb_id resource. * @returns {string} A string representing the room_id. */ matchRoomIdFromRoomIdBlurbIdName(roomIdBlurbIdName: string) { return this.pathTemplates.roomIdBlurbIdPathTemplate.match(roomIdBlurbIdName) .room_id; } /** * Parse the blurb_id from RoomIdBlurbId resource. * * @param {string} roomIdBlurbIdName * A fully-qualified path representing room_id_blurb_id resource. * @returns {string} A string representing the blurb_id. */ matchBlurbIdFromRoomIdBlurbIdName(roomIdBlurbIdName: string) { return this.pathTemplates.roomIdBlurbIdPathTemplate.match(roomIdBlurbIdName) .blurb_id; } /** * Return a fully-qualified session resource name string. * * @param {string} session * @returns {string} Resource name string. */ sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); } /** * Parse the session from Session resource. * * @param {string} sessionName * A fully-qualified path representing Session resource. * @returns {string} A string representing the session. */ matchSessionFromSessionName(sessionName: string) { return this.pathTemplates.sessionPathTemplate.match(sessionName).session; } /** * Return a fully-qualified test resource name string. * * @param {string} session * @param {string} test * @returns {string} Resource name string. */ testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, }); } /** * Parse the session from Test resource. * * @param {string} testName * A fully-qualified path representing Test resource. * @returns {string} A string representing the session. */ matchSessionFromTestName(testName: string) { return this.pathTemplates.testPathTemplate.match(testName).session; } /** * Parse the test from Test resource. * * @param {string} testName * A fully-qualified path representing Test resource. * @returns {string} A string representing the test. */ matchTestFromTestName(testName: string) { return this.pathTemplates.testPathTemplate.match(testName).test; } /** * Return a fully-qualified user resource name string. * * @param {string} user_id * @returns {string} Resource name string. */ userPath(userId: string) { return this.pathTemplates.userPathTemplate.render({ user_id: userId, }); } /** * Parse the user_id from User resource. * * @param {string} userName * A fully-qualified path representing User resource. * @returns {string} A string representing the user_id. */ matchUserIdFromUserName(userName: string) { return this.pathTemplates.userPathTemplate.match(userName).user_id; } /** * Return a fully-qualified userIdProfileBlurbId resource name string. * * @param {string} user_id * @param {string} blurb_id * @returns {string} Resource name string. */ userIdProfileBlurbIdPath(userId: string, blurbId: string) { return this.pathTemplates.userIdProfileBlurbIdPathTemplate.render({ user_id: userId, blurb_id: blurbId, }); } /** * Parse the user_id from UserIdProfileBlurbId resource. * * @param {string} userIdProfileBlurbIdName * A fully-qualified path representing user_id_profile_blurb_id resource. * @returns {string} A string representing the user_id. */ matchUserIdFromUserIdProfileBlurbIdName(userIdProfileBlurbIdName: string) { return this.pathTemplates.userIdProfileBlurbIdPathTemplate .match(userIdProfileBlurbIdName) .user_id; } /** * Parse the blurb_id from UserIdProfileBlurbId resource. * * @param {string} userIdProfileBlurbIdName * A fully-qualified path representing user_id_profile_blurb_id resource. * @returns {string} A string representing the blurb_id. */ matchBlurbIdFromUserIdProfileBlurbIdName(userIdProfileBlurbIdName: string) { return this.pathTemplates.userIdProfileBlurbIdPathTemplate .match(userIdProfileBlurbIdName) .blurb_id; } /** * Terminate the gRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise<void> { this.initialize(); if (!this._terminated) { return this.echoStub!.then(stub => { this._terminated = true; stub.close(); this.operationsClient.close(); }); } return Promise.resolve(); } }
the_stack
import type * as grpc from '@grpc/grpc-js' import type { MethodDefinition } from '@grpc/proto-loader' import type { BlockRequest as _google_showcase_v1beta1_BlockRequest, BlockRequest__Output as _google_showcase_v1beta1_BlockRequest__Output } from '../../../google/showcase/v1beta1/BlockRequest'; import type { BlockResponse as _google_showcase_v1beta1_BlockResponse, BlockResponse__Output as _google_showcase_v1beta1_BlockResponse__Output } from '../../../google/showcase/v1beta1/BlockResponse'; import type { EchoRequest as _google_showcase_v1beta1_EchoRequest, EchoRequest__Output as _google_showcase_v1beta1_EchoRequest__Output } from '../../../google/showcase/v1beta1/EchoRequest'; import type { EchoResponse as _google_showcase_v1beta1_EchoResponse, EchoResponse__Output as _google_showcase_v1beta1_EchoResponse__Output } from '../../../google/showcase/v1beta1/EchoResponse'; import type { ExpandRequest as _google_showcase_v1beta1_ExpandRequest, ExpandRequest__Output as _google_showcase_v1beta1_ExpandRequest__Output } from '../../../google/showcase/v1beta1/ExpandRequest'; import type { Operation as _google_longrunning_Operation, Operation__Output as _google_longrunning_Operation__Output } from '../../../google/longrunning/Operation'; import type { PagedExpandRequest as _google_showcase_v1beta1_PagedExpandRequest, PagedExpandRequest__Output as _google_showcase_v1beta1_PagedExpandRequest__Output } from '../../../google/showcase/v1beta1/PagedExpandRequest'; import type { PagedExpandResponse as _google_showcase_v1beta1_PagedExpandResponse, PagedExpandResponse__Output as _google_showcase_v1beta1_PagedExpandResponse__Output } from '../../../google/showcase/v1beta1/PagedExpandResponse'; import type { WaitRequest as _google_showcase_v1beta1_WaitRequest, WaitRequest__Output as _google_showcase_v1beta1_WaitRequest__Output } from '../../../google/showcase/v1beta1/WaitRequest'; /** * This service is used showcase the four main types of rpcs - unary, server * side streaming, client side streaming, and bidirectional streaming. This * service also exposes methods that explicitly implement server delay, and * paginated calls. Set the 'showcase-trailer' metadata key on any method * to have the values echoed in the response trailers. */ export interface EchoClient extends grpc.Client { /** * This method will block (wait) for the requested amount of time * and then return the response or error. * This method showcases how a client handles delays or retries. */ Block(argument: _google_showcase_v1beta1_BlockRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; Block(argument: _google_showcase_v1beta1_BlockRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; Block(argument: _google_showcase_v1beta1_BlockRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; Block(argument: _google_showcase_v1beta1_BlockRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; /** * This method will block (wait) for the requested amount of time * and then return the response or error. * This method showcases how a client handles delays or retries. */ block(argument: _google_showcase_v1beta1_BlockRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; block(argument: _google_showcase_v1beta1_BlockRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; block(argument: _google_showcase_v1beta1_BlockRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; block(argument: _google_showcase_v1beta1_BlockRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_BlockResponse__Output) => void): grpc.ClientUnaryCall; /** * This method, upon receiving a request on the stream, the same content will * be passed back on the stream. This method showcases bidirectional * streaming rpcs. */ Chat(metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientDuplexStream<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse__Output>; Chat(options?: grpc.CallOptions): grpc.ClientDuplexStream<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse__Output>; /** * This method, upon receiving a request on the stream, the same content will * be passed back on the stream. This method showcases bidirectional * streaming rpcs. */ chat(metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientDuplexStream<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse__Output>; chat(options?: grpc.CallOptions): grpc.ClientDuplexStream<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse__Output>; /** * This method will collect the words given to it. When the stream is closed * by the client, this method will return the a concatenation of the strings * passed to it. This method showcases client-side streaming rpcs. */ Collect(metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; Collect(metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; Collect(options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; Collect(callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; /** * This method will collect the words given to it. When the stream is closed * by the client, this method will return the a concatenation of the strings * passed to it. This method showcases client-side streaming rpcs. */ collect(metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; collect(metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; collect(options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; collect(callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientWritableStream<_google_showcase_v1beta1_EchoRequest>; /** * This method simply echos the request. This method is showcases unary rpcs. */ Echo(argument: _google_showcase_v1beta1_EchoRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; Echo(argument: _google_showcase_v1beta1_EchoRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; Echo(argument: _google_showcase_v1beta1_EchoRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; Echo(argument: _google_showcase_v1beta1_EchoRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; /** * This method simply echos the request. This method is showcases unary rpcs. */ echo(argument: _google_showcase_v1beta1_EchoRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; echo(argument: _google_showcase_v1beta1_EchoRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; echo(argument: _google_showcase_v1beta1_EchoRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; echo(argument: _google_showcase_v1beta1_EchoRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_EchoResponse__Output) => void): grpc.ClientUnaryCall; /** * This method split the given content into words and will pass each word back * through the stream. This method showcases server-side streaming rpcs. */ Expand(argument: _google_showcase_v1beta1_ExpandRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_google_showcase_v1beta1_EchoResponse__Output>; Expand(argument: _google_showcase_v1beta1_ExpandRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_google_showcase_v1beta1_EchoResponse__Output>; /** * This method split the given content into words and will pass each word back * through the stream. This method showcases server-side streaming rpcs. */ expand(argument: _google_showcase_v1beta1_ExpandRequest, metadata: grpc.Metadata, options?: grpc.CallOptions): grpc.ClientReadableStream<_google_showcase_v1beta1_EchoResponse__Output>; expand(argument: _google_showcase_v1beta1_ExpandRequest, options?: grpc.CallOptions): grpc.ClientReadableStream<_google_showcase_v1beta1_EchoResponse__Output>; /** * This is similar to the Expand method but instead of returning a stream of * expanded words, this method returns a paged list of expanded words. */ PagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; PagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; PagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; PagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; /** * This is similar to the Expand method but instead of returning a stream of * expanded words, this method returns a paged list of expanded words. */ pagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; pagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; pagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; pagedExpand(argument: _google_showcase_v1beta1_PagedExpandRequest, callback: (error?: grpc.ServiceError, result?: _google_showcase_v1beta1_PagedExpandResponse__Output) => void): grpc.ClientUnaryCall; /** * This method will wait the requested amount of and then return. * This method showcases how a client handles a request timing out. */ Wait(argument: _google_showcase_v1beta1_WaitRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; Wait(argument: _google_showcase_v1beta1_WaitRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; Wait(argument: _google_showcase_v1beta1_WaitRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; Wait(argument: _google_showcase_v1beta1_WaitRequest, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; /** * This method will wait the requested amount of and then return. * This method showcases how a client handles a request timing out. */ wait(argument: _google_showcase_v1beta1_WaitRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; wait(argument: _google_showcase_v1beta1_WaitRequest, metadata: grpc.Metadata, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; wait(argument: _google_showcase_v1beta1_WaitRequest, options: grpc.CallOptions, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; wait(argument: _google_showcase_v1beta1_WaitRequest, callback: (error?: grpc.ServiceError, result?: _google_longrunning_Operation__Output) => void): grpc.ClientUnaryCall; } /** * This service is used showcase the four main types of rpcs - unary, server * side streaming, client side streaming, and bidirectional streaming. This * service also exposes methods that explicitly implement server delay, and * paginated calls. Set the 'showcase-trailer' metadata key on any method * to have the values echoed in the response trailers. */ export interface EchoHandlers extends grpc.UntypedServiceImplementation { /** * This method will block (wait) for the requested amount of time * and then return the response or error. * This method showcases how a client handles delays or retries. */ Block: grpc.handleUnaryCall<_google_showcase_v1beta1_BlockRequest__Output, _google_showcase_v1beta1_BlockResponse>; /** * This method, upon receiving a request on the stream, the same content will * be passed back on the stream. This method showcases bidirectional * streaming rpcs. */ Chat: grpc.handleBidiStreamingCall<_google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse>; /** * This method will collect the words given to it. When the stream is closed * by the client, this method will return the a concatenation of the strings * passed to it. This method showcases client-side streaming rpcs. */ Collect: grpc.handleClientStreamingCall<_google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse>; /** * This method simply echos the request. This method is showcases unary rpcs. */ Echo: grpc.handleUnaryCall<_google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse>; /** * This method split the given content into words and will pass each word back * through the stream. This method showcases server-side streaming rpcs. */ Expand: grpc.handleServerStreamingCall<_google_showcase_v1beta1_ExpandRequest__Output, _google_showcase_v1beta1_EchoResponse>; /** * This is similar to the Expand method but instead of returning a stream of * expanded words, this method returns a paged list of expanded words. */ PagedExpand: grpc.handleUnaryCall<_google_showcase_v1beta1_PagedExpandRequest__Output, _google_showcase_v1beta1_PagedExpandResponse>; /** * This method will wait the requested amount of and then return. * This method showcases how a client handles a request timing out. */ Wait: grpc.handleUnaryCall<_google_showcase_v1beta1_WaitRequest__Output, _google_longrunning_Operation>; } export interface EchoDefinition extends grpc.ServiceDefinition { Block: MethodDefinition<_google_showcase_v1beta1_BlockRequest, _google_showcase_v1beta1_BlockResponse, _google_showcase_v1beta1_BlockRequest__Output, _google_showcase_v1beta1_BlockResponse__Output> Chat: MethodDefinition<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse, _google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse__Output> Collect: MethodDefinition<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse, _google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse__Output> Echo: MethodDefinition<_google_showcase_v1beta1_EchoRequest, _google_showcase_v1beta1_EchoResponse, _google_showcase_v1beta1_EchoRequest__Output, _google_showcase_v1beta1_EchoResponse__Output> Expand: MethodDefinition<_google_showcase_v1beta1_ExpandRequest, _google_showcase_v1beta1_EchoResponse, _google_showcase_v1beta1_ExpandRequest__Output, _google_showcase_v1beta1_EchoResponse__Output> PagedExpand: MethodDefinition<_google_showcase_v1beta1_PagedExpandRequest, _google_showcase_v1beta1_PagedExpandResponse, _google_showcase_v1beta1_PagedExpandRequest__Output, _google_showcase_v1beta1_PagedExpandResponse__Output> Wait: MethodDefinition<_google_showcase_v1beta1_WaitRequest, _google_longrunning_Operation, _google_showcase_v1beta1_WaitRequest__Output, _google_longrunning_Operation__Output> }
the_stack
export interface CacheObject { /** Subresource Integrity hash for the content this entry refers to. */ integrity: string; /** Key the entry was looked up under. Matches the key argument. */ key: string; /** User-assigned metadata associated with the entry/content. */ metadata?: any; /** Filesystem path where content is stored, joined with cache argument. */ path: string; /** Timestamp the entry was first added on. */ time: number; } export interface GetCacheObject { metadata?: any; integrity: string; data: Buffer; size: number; } export namespace get { interface HasContentObject { size: number; sri: { algorithm: string; digest: string; options: any[]; source: string; }; } interface Options { integrity?: string; memoize?: boolean; size?: number; } namespace copy { function byDigest(cachePath: string, hash: string, dest: string, opts?: Options): Promise<string>; } namespace stream { function byDigest(cachePath: string, hash: string, opts?: Options): NodeJS.ReadableStream; } function byDigest(cachePath: string, hash: string, opts?: Options): Promise<string>; function copy(cachePath: string, key: string, dest: string, opts?: Options): Promise<CacheObject>; /** * Looks up a Subresource Integrity hash in the cache. If content exists * for this `integrity`, it will return an object, with the specific single * integrity hash that was found in sri key, and the size of the found * content as size. If no content exists for this integrity, it will return * `false`. */ function hasContent(cachePath: string, hash: string): Promise<HasContentObject | false>; function hasContentnc(cachePath: string, hash: string): HasContentObject | false; /** * Looks up `key` in the cache index, returning information about the entry * if one exists. */ function info(cachePath: string, key: string): Promise<CacheObject>; /** * Returns a Readable Stream of the cached data identified by `key`. * * If there is no content identified by `key`, or if the locally-stored data * does not pass the validity checksum, an error will be emitted. * * `metadata` and `integrity` events will be emitted before the stream * closes, if you need to collect that extra data about the cached entry. * * A sub-function, `get.stream.byDigest` may be used for identical behavior, * except lookup will happen by integrity hash, bypassing the index * entirely. This version does not emit the `metadata` and `integrity` * events at all. */ function stream(cachePath: string, key: string, opts?: Options): NodeJS.ReadableStream; function sync(cachePath: string, key: string, opts?: Options): CacheObject; function syncDigest(cachePath: string, key: string, opts?: Options): CacheObject; } export namespace ls { type Cache = Record<string, CacheObject & { size: number }>; /** * Lists info for all entries currently in the cache as a single large * object. * * This works just like `ls`, except `get.info` entries are returned as * `'data'` events on the returned stream. */ function stream(cachePath: string): NodeJS.ReadableStream; } export namespace put { interface Options { /** * Default: `['sha512']` * * Hashing algorithms to use when calculating the subresource integrity * digest for inserted data. Can use any algorithm listed in * `crypto.getHashes()` or `'omakase'`/`'お任せします'` to pick a random * hash algorithm on each insertion. You may also use any anagram of * `'modnar'` to use this feature. * * Currently only supports one algorithm at a time (i.e., an array * length of exactly `1`). Has no effect if `opts.integrity` is present. */ algorithms?: string[]; /** * If present, the pre-calculated digest for the inserted content. If * this option if provided and does not match the post-insertion digest, * insertion will fail with an `EINTEGRITY` error. * * `algorithms` has no effect if this option is present. */ integrity?: string; /** Arbitrary metadata to be attached to the inserted key. */ metadata?: any; /** * Default: `null` * * If provided, cacache will memoize the given cache insertion in * memory, bypassing any filesystem checks for that key or digest in * future cache fetches. Nothing will be written to the in-memory cache * unless this option is explicitly truthy. * * If `opts.memoize` is an object or a `Map`-like (that is, an object * with `get` and `set` methods), it will be written to instead of the * global memoization cache. * * Reading from disk data can be forced by explicitly passing * `memoize: false` to the reader functions, but their default will be * to read from memory. */ memoize?: null | boolean; /** * If provided, the data stream will be verified to check that enough * data was passed through. If there's more or less data than expected, * insertion will fail with an `EBADSIZE` error. */ size?: number; } /** * Returns a Writable Stream that inserts data written to it into the cache. * Emits an `integrity` event with the digest of written contents when it * succeeds. */ function stream(cachePath: string, key: string, opts?: Options): NodeJS.WritableStream; } export namespace rm { /** * Clears the entire cache. Mainly by blowing away the cache directory * itself. */ function all(cachePath: string): Promise<void>; /** * Removes the index entry for `key`. Content will still be accessible if * requested directly by content address (`get.stream.byDigest`). * * To remove the content itself (which might still be used by other * entries), use `rm.content`. Or, to safely vacuum any unused content, * use `verify`. */ function entry(cachePath: string, key: string): Promise<CacheObject>; /** * Removes the content identified by `integrity`. Any index entries * referring to it will not be usable again until the content is re-added * to the cache with an identical digest. */ function content(cachePath: string, hash: string): Promise<boolean>; } export namespace tmp { type Callback = (dir: string) => void; interface Options { tmpPrefix?: string; } /** * Sets the `uid` and `gid` properties on all files and folders within the * tmp folder to match the rest of the cache. * * Use this after manually writing files into `tmp.mkdir` or `tmp.withTmp`. */ function fix(cachePath: string): Promise<void>; /** * Returns a unique temporary directory inside the cache's `tmp` dir. This * directory will use the same safe user assignment that all the other stuff * use. * * Once the directory is made, it's the user's responsibility that all files * within are given the appropriate `gid`/`uid` ownership settings to match * the rest of the cache. If not, you can ask cacache to do it for you by * calling `tmp.fix()`, which will fix all tmp directory permissions. * * If you want automatic cleanup of this directory, use `tmp.withTmp()` */ function mkdir(cachePath: string, opts?: Options): Promise<string>; /** * Creates a temporary directory with `tmp.mkdir()` and calls `cb` with it. * The created temporary directory will be removed when the return value of * `cb()` resolves -- that is, if you return a Promise from `cb()`, the tmp * directory will be automatically deleted once that promise completes. * * The same caveats apply when it comes to managing permissions for the tmp dir's contents. */ function withTmp(cachePath: string, opts: Options, cb: Callback): void; function withTmp(cachePath: string, cb: Callback): void; } export namespace verify { interface Options { /** * Receives a formatted entry. Return false to remove it. * Note: might be called more than once on the same entry. */ filter: false | string; } /** * Returns a Date representing the last time `cacache.verify` was run on * `cache`. */ function lastRun(cachePath: string): Promise<Date>; } export function clearMemoized(): Record<string, CacheObject>; /** * Returns an object with the cached data, digest, and metadata identified by * `key`. The `data` property of this object will be a Buffer instance that * presumably holds some data that means something to you. I'm sure you know * what to do with it! cacache just won't care. * * `integrity` is a Subresource Integrity string. That is, a string that can be * used to verify `data`, which looks like * `<hash-algorithm>-<base64-integrity-hash>`. * * If there is no content identified by key, or if the locally-stored data does * not pass the validity checksum, the promise will be rejected. * * A sub-function, `get.byDigest` may be used for identical behavior, except * lookup will happen by integrity hash, bypassing the index entirely. This * version of the function only returns data itself, without any wrapper. * * **Note** * * This function loads the entire cache entry into memory before returning it. * If you're dealing with Very Large data, consider using `get.stream` instead. */ export function get(cachePath: string, key: string, options?: get.Options): Promise<GetCacheObject>; /** * Lists info for all entries currently in the cache as a single large object. * Each entry in the object will be keyed by the unique index key, with * corresponding `get.info` objects as the values. */ export function ls(cachePath: string): Promise<ls.Cache>; /** * Inserts data passed to it into the cache. The returned Promise resolves with * a digest (generated according to `opts.algorithms`) after the cache entry has * been successfully written. */ export function put(cachePath: string, key: string, data: any, opts?: put.Options): Promise<string>; /** * Removes the index entry for `key`. Content will still be accessible if * requested directly by content address (`get.stream.byDigest`). * * To remove the content itself (which might still be used by other * entries), use `rm.content`. Or, to safely vacuum any unused content, * use `verify`. */ export function rm(cachePath: string, key: string): Promise<any>; /** * Configure the language/locale used for messages and errors coming from * cacache. The list of available locales is in the `./locales` directory in the * project root. */ export function setLocale(locale: string): any; /** * Checks out and fixes up your cache: * * - Cleans up corrupted or invalid index entries * - Custom entry filtering options * - Garbage collects any content entries not referenced by the index * - Checks integrity for all content entries and removes invalid content * - Fixes cache ownership * - Removes the `tmp` directory in the cache and all its contents. * * When it's done, it'll return an object with various stats about the * verification process, including amount of storage reclaimed, number of valid * entries, number of entries removed, etc. */ export function verify(cachePath: string, opts?: verify.Options): Promise<any>;
the_stack
import { not } from "../../Data/Bool" import { cnst } from "../../Data/Function" import { fmap } from "../../Data/Functor" import { Lens_, over, view } from "../../Data/Lens" import { elemF, filter, fromArray, List } from "../../Data/List" import { bindF, ensure, fromMaybe, Just, liftM2, Maybe, Nothing, or } from "../../Data/Maybe" import { alter, elems, insert, lookup, lookupF, OrderedMap, sdelete, update } from "../../Data/OrderedMap" import { IdPrefixes } from "../Constants/IdPrefixes" import { createPlainActivatableDependent } from "../Models/ActiveEntries/ActivatableDependent" import { createInactiveActivatableSkillDependent } from "../Models/ActiveEntries/ActivatableSkillDependent" import { AttributeDependent, createPlainAttributeDependent } from "../Models/ActiveEntries/AttributeDependent" import { createPlainSkillDependent, createSkillDependentWithValue6 } from "../Models/ActiveEntries/SkillDependent" import { HeroModel, HeroModelL, HeroModelRecord } from "../Models/Hero/HeroModel" import { Dependent } from "../Models/Hero/heroTypeHelpers" import { Skill } from "../Models/Wiki/Skill" import { EntryWithGroup } from "../Models/Wiki/wikiTypeHelpers" import { getIdPrefix } from "./IDUtils" import { pipe } from "./pipe" export type HeroStateMapKey = "advantages" | "attributes" | "combatTechniques" | "disadvantages" | "liturgicalChants" | "skills" | "specialAbilities" | "spells" export type HeroStateListKey = HeroStateMapKey | "blessings" | "cantrips" export type HeroStateListGetter<K extends HeroStateListKey = HeroStateListKey> = (hero: HeroModelRecord) => HeroModel[K] export type HeroStateListLens<K extends HeroStateListKey = HeroStateListKey> = Lens_<HeroModelRecord, HeroModel[K]> export type HeroStateMapLens<K extends HeroStateMapKey = HeroStateMapKey> = Lens_<HeroModelRecord, HeroModel[K]> /** * Returns a getter function for a `Hero` object based on the prefix of the * passed id. Returns lenses for `OrderedMap`s and `OrderedSet`s, else * `Nothing`. */ export const getHeroStateListLensById = (id: string): Maybe<HeroStateListLens> => { switch (getIdPrefix (id)) { case IdPrefixes.ADVANTAGES: return Just<HeroStateListLens> (HeroModelL.advantages as HeroStateListLens) case IdPrefixes.ATTRIBUTES: return Just<HeroStateListLens> (HeroModelL.attributes as HeroStateListLens) case IdPrefixes.BLESSINGS: return Just<HeroStateListLens> (HeroModelL.blessings as HeroStateListLens) case IdPrefixes.CANTRIPS: return Just<HeroStateListLens> (HeroModelL.cantrips as HeroStateListLens) case IdPrefixes.COMBAT_TECHNIQUES: return Just<HeroStateListLens> (HeroModelL.combatTechniques as HeroStateListLens) case IdPrefixes.DISADVANTAGES: return Just<HeroStateListLens> (HeroModelL.disadvantages as HeroStateListLens) case IdPrefixes.LITURGICAL_CHANTS: return Just<HeroStateListLens> (HeroModelL.liturgicalChants as HeroStateListLens) case IdPrefixes.SPECIAL_ABILITIES: return Just<HeroStateListLens> (HeroModelL.specialAbilities as HeroStateListLens) case IdPrefixes.SPELLS: return Just<HeroStateListLens> (HeroModelL.spells as HeroStateListLens) case IdPrefixes.SKILLS: return Just<HeroStateListLens> (HeroModelL.skills as HeroStateListLens) default: return Nothing } } /** * Returns a getter function for a `Hero` object based on the prefix of the * passed id. Only returns lenses for `OrderedMaps`, else `Nothing`. */ export const getHeroStateMapLensById = (id: string): Maybe<HeroStateMapLens> => { switch (getIdPrefix (id)) { case IdPrefixes.ADVANTAGES: return Just<HeroStateMapLens> (HeroModelL.advantages as HeroStateMapLens) case IdPrefixes.ATTRIBUTES: return Just<HeroStateMapLens> (HeroModelL.attributes as HeroStateMapLens) case IdPrefixes.COMBAT_TECHNIQUES: return Just<HeroStateMapLens> (HeroModelL.combatTechniques as HeroStateMapLens) case IdPrefixes.DISADVANTAGES: return Just<HeroStateMapLens> (HeroModelL.disadvantages as HeroStateMapLens) case IdPrefixes.LITURGICAL_CHANTS: return Just<HeroStateMapLens> (HeroModelL.liturgicalChants as HeroStateMapLens) case IdPrefixes.SPECIAL_ABILITIES: return Just<HeroStateMapLens> (HeroModelL.specialAbilities as HeroStateMapLens) case IdPrefixes.SPELLS: return Just<HeroStateMapLens> (HeroModelL.spells as HeroStateMapLens) case IdPrefixes.SKILLS: return Just<HeroStateMapLens> (HeroModelL.skills as HeroStateMapLens) default: return Nothing } } /** * Returns a getter function for a `Hero` object based on the prefix of the * passed id. */ export const getHeroStateListGetterById = (id: string): Maybe<HeroStateListGetter> => { switch (getIdPrefix (id)) { case IdPrefixes.ADVANTAGES: return Just<HeroStateListGetter> (HeroModel.AL.advantages) case IdPrefixes.ATTRIBUTES: return Just<HeroStateListGetter> (HeroModel.AL.attributes) case IdPrefixes.BLESSINGS: return Just<HeroStateListGetter> (HeroModel.AL.blessings) case IdPrefixes.CANTRIPS: return Just<HeroStateListGetter> (HeroModel.AL.cantrips) case IdPrefixes.COMBAT_TECHNIQUES: return Just<HeroStateListGetter> (HeroModel.AL.combatTechniques) case IdPrefixes.DISADVANTAGES: return Just<HeroStateListGetter> (HeroModel.AL.disadvantages) case IdPrefixes.LITURGICAL_CHANTS: return Just<HeroStateListGetter> (HeroModel.AL.liturgicalChants) case IdPrefixes.SPECIAL_ABILITIES: return Just<HeroStateListGetter> (HeroModel.AL.specialAbilities) case IdPrefixes.SPELLS: return Just<HeroStateListGetter> (HeroModel.AL.spells) case IdPrefixes.SKILLS: return Just<HeroStateListGetter> (HeroModel.AL.skills) default: return Nothing } } /** * Returns a matching creator for elements in the `OrderedMap` specified by the * passed key in a `Hero` object. */ export const getEntryCreatorById = (id: string): Maybe<(id: string) => Dependent> => { switch (getIdPrefix (id)) { case IdPrefixes.ADVANTAGES: case IdPrefixes.DISADVANTAGES: case IdPrefixes.SPECIAL_ABILITIES: return Just (createPlainActivatableDependent) case IdPrefixes.ATTRIBUTES: return Just (createPlainAttributeDependent) case IdPrefixes.COMBAT_TECHNIQUES: return Just (createSkillDependentWithValue6) case IdPrefixes.SKILLS: return Just (createPlainSkillDependent) case IdPrefixes.LITURGICAL_CHANTS: case IdPrefixes.SPELLS: return Just (createInactiveActivatableSkillDependent) default: return Nothing } } export const getHeroStateItem = (hero: HeroModelRecord) => (id: string) => pipe ( fmap ((lens: HeroStateMapLens) => view (lens) (hero)) as (l: Maybe<HeroStateMapLens>) => Maybe<OrderedMap<string, Dependent>>, bindF (lookup (id)) ) (getHeroStateMapLensById (id)) export const setHeroStateItem = (id: string) => (item: Dependent) => (state: HeroModelRecord) => fmap ((lens: HeroStateMapLens) => over (lens) (insert (id) (item) as (m: HeroModel[HeroStateMapKey]) => HeroModel[HeroStateMapKey]) (state)) (getHeroStateMapLensById (id)) export const removeHeroStateItem = (id: string) => (state: HeroModelRecord) => fmap ((lens: HeroStateMapLens) => over (lens) (sdelete (id) as (m: HeroModel[HeroStateMapKey]) => HeroModel[HeroStateMapKey]) (state)) (getHeroStateMapLensById (id)) /** * ```haskell * updateEntryDef :: Dependent a => (a -> Maybe a) -> String -> Hero -> Hero * ``` * * `updateEntryDef f id hero` adjusts a entry, specified by `id`, from a state * slice. If the entry is not present, a plain entry of the needed type will be * created with the given `id`, e.g. `SkillDependent` when `id` is like * `SKILL_X`. `f` will then be called either on the already present or created * object. If `f` returns a `Nothing`, the entry will be removed from the state * slice. */ export const updateEntryDef = <D extends Dependent> (f: (value: D) => Maybe<D>) => (id: string) => (state: HeroModelRecord) => fromMaybe<HeroModelRecord> (state) (liftM2 ((creator: (id: string) => D) => (lens: HeroStateMapLens) => over (lens) (alter<D> (pipe (fromMaybe (creator (id)), f)) (id) as unknown as (m: HeroModel[HeroStateMapKey]) => HeroModel[HeroStateMapKey]) (state)) (getEntryCreatorById (id) as Maybe<(id: string) => D>) (getHeroStateMapLensById (id))) /** * ```haskell * adjustEntryDef :: Dependent a * => (a -> a) -> (a -> Bool) -> String -> Hero -> Hero * ``` * * `adjustEntryDef f unused id hero` adjusts a entry, specified by `id`, from a * state slice. If the entry is not present, a plain entry of the needed type * will be created with the given `id`. `f` will then be called either on the * already present or created object. If `unused` returns the adjusted entry is * unused, this function will remove the entry from the state slice. */ export const adjustRemoveEntryDef = <D extends Dependent> (unused: (value: D) => boolean) => (f: (value: D) => D) => updateEntryDef (pipe (f, ensure<D> (pipe (unused, not)))) /** * ```haskell * modifyEntryDef :: Dependent a => (a -> a) -> String -> Hero -> Hero * ``` * * `modifyEntryDef f id hero` adjusts a entry, specified by `id`, from a state * slice. If the entry is not present, a plain entry of the needed type will be * created with the given `id`. `f` will then be called either on the already * present or created object. */ export const adjustEntryDef = <D extends Dependent> (f: (value: D) => D) => adjustRemoveEntryDef<D> (cnst (false)) (f) /** * ```haskell * updateSliceEntry :: (Dependent a, (OrderedMap String) m) * => (a -> Maybe a) -> (a -> Bool) -> String -> m a -> m a * ``` * * `updateSliceEntry f unused id map` adjusts a entry, specified by `id`, from a * state slice (`map`). If the entry is not present, this function will return * the original map. `f` will then be called on the already present object. If * `unused` returns the adjusted entry is unused, this function will remove the * entry from the state slice. */ export const updateSliceEntry = <D extends Dependent> (f: (value: D) => D) => (unused: (value: D) => boolean) => update (pipe ( f, ensure<D> (pipe (unused, not)) )) /** * Filters the passed `list` by the specified groups. */ export const getAllEntriesByGroup = (wiki_slice: OrderedMap<string, EntryWithGroup>) => <I extends Dependent = Dependent> (hero_slice: OrderedMap<string, I>) => (...groups: number[]): List<I> => filter<I> (pipe ( AttributeDependent.AL.id, lookupF (wiki_slice), fmap (Skill.AL.gr), fmap (elemF (fromArray (groups))), or )) (elems (hero_slice))
the_stack
import utils from '@eventcatalog/utils'; import path from 'path'; import fs from 'fs-extra'; import plugin from '../index'; import awsClientSchemasMocks from './assets/aws-mock-responses/client-schemas'; import awsEventBridgeMocks from './assets/aws-mock-responses/client-eventbridge'; import eventSnapshots from './assets/event-markdown-snapshot'; import { PluginOptions, SchemaTypes } from '../types'; declare global { namespace jest { interface Matchers<R> { toMatchMarkdown(expect: string): R; } } } let PROJECT_DIR: any; // @aws-sdk/client-schemas mocks const mockListSchemas = jest.fn(() => awsClientSchemasMocks.listSchemas); const mockExportSchema = jest.fn(() => awsClientSchemasMocks.exportSchema); const mockDescribeSchema = jest.fn(() => awsClientSchemasMocks.describeSchemas); // @aws-sdk/client-eventbridge mocks const mockListRules = jest.fn(() => awsEventBridgeMocks.listRules); const mockListTargetsByRule = jest.fn(() => awsEventBridgeMocks.listTargetsForRules); jest.mock('@aws-sdk/client-eventbridge', () => ({ ...jest.requireActual('@aws-sdk/client-eventbridge'), EventBridge: jest.fn(() => ({ listRules: mockListRules, listTargetsByRule: mockListTargetsByRule, })), })); jest.mock('@aws-sdk/client-schemas', () => ({ ...jest.requireActual('@aws-sdk/client-schemas'), Schemas: jest.fn(() => ({ listSchemas: mockListSchemas, exportSchema: mockExportSchema, describeSchema: mockDescribeSchema, })), })); const pluginOptions: PluginOptions = { credentials: { secretAccessKey: 'some-secret', accessKeyId: 'access-key', }, region: 'eu-west-1', eventBusName: 'test-event-bus', registryName: 'discovered-schemas', }; describe('eventcatalog-plugin-generator-amazon-eventbridge', () => { beforeAll(() => { PROJECT_DIR = process.env.PROJECT_DIR; process.env.PROJECT_DIR = path.join(__dirname, 'tmp'); }); beforeEach(() => { jest.clearAllMocks(); // eslint-disable-next-line @typescript-eslint/no-empty-function jest.spyOn(console, 'error').mockImplementation(() => {}); }); afterAll(() => { process.env.PROJECT_DIR = PROJECT_DIR; }); afterEach(() => { try { fs.rmdirSync(path.join(__dirname, 'tmp'), { recursive: true }); } catch (error) { console.log('Nothing to remove'); } }); describe('plugin', () => { it('creates catalog events, examples and schemas with events from amazon eventbridge schema registry', async () => { await plugin({}, pluginOptions); // just wait for files to be there in time. await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { raw: eventFile, data: event } = getEventFromCatalog('users@UserCreated'); // known issue with utils that will default props... replace it for now expect(eventFile).toMatchMarkdown(eventSnapshots.userCreated); // verify the schema next to the event is the JSONDraft4 from EventBridge const expectedSchemaForEvent = JSON.parse(awsClientSchemasMocks.exportSchema.Content); const generatedSchemaForEvent = fs.readFileSync( path.join(process.env.PROJECT_DIR, 'events', event.name, 'schema.json'), 'utf-8' ); expect(generatedSchemaForEvent).toEqual(JSON.stringify(expectedSchemaForEvent, null, 4)); // verify the code examples next to the event is the open-api version of the event const expectedCodeExampleForEvent = JSON.parse(awsClientSchemasMocks.describeSchemas.Content); const generatedCodeExampleForEvent = fs.readFileSync( path.join(process.env.PROJECT_DIR, 'events', event.name, 'examples', 'users@UserCreated-openapi-schema.json'), 'utf-8' ); expect(generatedCodeExampleForEvent).toEqual(JSON.stringify(expectedCodeExampleForEvent, null, 4)); }); describe('when user has existing events in their event catalog', () => { it('when the schema versions (from AWS) match the current version of the event in the catalog, the event is overriden and not versioned', async () => { const oldEvent = { name: 'users@UserCreated', version: '1', summary: 'Old event from Amazon EventBridge that was created', }; const { writeEventToCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); await writeEventToCatalog(oldEvent, { schema: { extension: 'json', fileContent: 'hello' }, }); await plugin({}, pluginOptions); // just wait for files to be there in time. await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { data: event } = getEventFromCatalog('users@UserCreated'); expect(event.summary).toEqual('Found on the "test-event-bus" Amazon EventBridge bus.'); }); it('when the schema versions (from AWS) do not match the current version of the event, the event in the catalog is versioned and the new event documentation is created', async () => { const oldEventFromAWSAlreadyInCatalog = { name: 'users@UserCreated', version: '0.1', summary: 'really old version of this event', }; const eventPath = path.join(process.env.PROJECT_DIR, 'events', 'users@UserCreated'); const { writeEventToCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); await writeEventToCatalog(oldEventFromAWSAlreadyInCatalog, { schema: { extension: 'json', fileContent: 'some-old-schema-example' }, }); expect(fs.existsSync(path.join(eventPath, 'versioned'))).toEqual(false); await plugin({}, pluginOptions); await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { raw: eventFile } = getEventFromCatalog('users@UserCreated'); expect(eventFile).toMatchMarkdown(eventSnapshots.userCreated); // Check the version has been set expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'index.md'))).toEqual(true); expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'schema.json'))).toEqual(true); }); it('when new events are created in the catalog the `owners` from the previous version of the event is used in the new event metdata', async () => { const oldEventFromAWSAlreadyInCatalog = { name: 'users@UserCreated', version: '0.1', summary: 'really old version of this event', owners: ['dboyne', 'tSmith'], }; const eventPath = path.join(process.env.PROJECT_DIR, 'events', 'users@UserCreated'); const { writeEventToCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); await writeEventToCatalog(oldEventFromAWSAlreadyInCatalog, { schema: { extension: 'json', fileContent: 'some-old-schema-example' }, }); await plugin({}, pluginOptions); await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { data: newEventData } = getEventFromCatalog('users@UserCreated'); // Check the version has been set expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'index.md'))).toEqual(true); expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'schema.json'))).toEqual(true); expect(newEventData.version).toEqual('1'); expect(newEventData.owners).toEqual(['dboyne', 'tSmith']); }); }); describe('plugin options', () => { describe('versionEvents', () => { it('when `versionEvents` is set to false, no events will be versioned and everything is overriden', async () => { const oldEventFromAWSAlreadyInCatalog = { name: 'users@UserCreated', version: '0.1', summary: 'really old version of this event', }; const eventPath = path.join(process.env.PROJECT_DIR, 'events', 'users@UserCreated'); const { writeEventToCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); await writeEventToCatalog(oldEventFromAWSAlreadyInCatalog, { schema: { extension: 'json', fileContent: 'some-old-schema-example' }, }); await plugin({}, { ...pluginOptions, versionEvents: false }); await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { raw: eventFile } = getEventFromCatalog('users@UserCreated'); // Check the version has NOT been set expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'index.md'))).toEqual(false); expect(fs.existsSync(path.join(eventPath, 'versioned', '0.1', 'schema.json'))).toEqual(false); expect(eventFile).toMatchMarkdown(eventSnapshots.userCreated); }); }); describe('schemaTypeToRenderToEvent', () => { it('when the `schemaTypeToRenderToEvent` is set to `JSONSchemaDraft4` then the schema rendered in the document is the JSON Draft version', async () => { await plugin({}, { ...pluginOptions, schemaTypeToRenderToEvent: SchemaTypes.JSONSchemaDraft4 }); await new Promise((r) => setTimeout(r, 200)); // verify the schema next to the event is the JSONDraft4 from EventBridge const expectedSchemaForEvent = JSON.parse(awsClientSchemasMocks.exportSchema.Content); const generatedSchemaForEvent = fs.readFileSync( path.join(process.env.PROJECT_DIR, 'events', 'users@UserCreated', 'schema.json'), 'utf-8' ); expect(generatedSchemaForEvent).toEqual(JSON.stringify(expectedSchemaForEvent, null, 4)); }); it('when the `schemaTypeToRenderToEvent` is set to `OpenAPI` then the schema rendered in the document is the OpenAPI version', async () => { await plugin({}, { ...pluginOptions, schemaTypeToRenderToEvent: SchemaTypes.OpenAPI }); await new Promise((r) => setTimeout(r, 200)); // verify the schema next to the event is the OPEN API one const expectedSchemaForEvent = JSON.parse(awsClientSchemasMocks.describeSchemas.Content); const generatedSchemaForEvent = fs.readFileSync( path.join(process.env.PROJECT_DIR, 'events', 'users@UserCreated', 'schema.json'), 'utf-8' ); expect(generatedSchemaForEvent).toEqual(JSON.stringify(expectedSchemaForEvent, null, 4)); }); }); it('when events do not have any targets or rules the target and rule diagrams are not rendered in the markdown files', async () => { mockExportSchema.mockImplementation(({ SchemaName }) => awsClientSchemasMocks.buildSchema({ eventName: SchemaName })); mockDescribeSchema.mockImplementation(({ SchemaName }) => awsClientSchemasMocks.buildOpenAPIResponse({ eventName: SchemaName }) ); await plugin({}, pluginOptions); // just wait for files to be there in time. await new Promise((r) => setTimeout(r, 200)); const { getEventFromCatalog } = utils({ catalogDirectory: process.env.PROJECT_DIR }); const { raw: eventFile } = getEventFromCatalog('users@UserDeleted'); // known issue with utils that will default props... replace it for now expect(eventFile).toMatchMarkdown(eventSnapshots.userDeletedWithNoTargetsOrRules.replace('owners: []', '')); }); }); }); });
the_stack
import { GraphTooltip } from './graph_tooltip'; import { ThresholdManager } from './threshold_manager'; import { convertValuesToHistogram, getSeriesValues } from './histogram'; import { GraphCtrl } from './module'; import $ from 'jquery'; import './vendor/flot/jquery.flot'; import './vendor/flot/jquery.flot.selection'; import './vendor/flot/jquery.flot.time'; import './vendor/flot/jquery.flot.stack'; import './vendor/flot/jquery.flot.stackpercent'; import './vendor/flot/jquery.flot.fillbelow'; import './vendor/flot/jquery.flot.crosshair'; import './vendor/flot/jquery.flot.dashes'; import './vendor/flot/jquery.flot.events'; import './vendor/flot/jquery.flot.orderbars'; import { EventManager } from './vendor/grafana/event_manager'; import { updateLegendValues } from './vendor/grafana/time_series2'; import { tickStep } from './vendor/grafana/ticks'; import { appEvents } from 'grafana/app/core/core'; import kbn from 'grafana/app/core/utils/kbn'; import _ from 'lodash'; import moment from 'moment'; export class GraphRenderer { private data: any; private tooltip: GraphTooltip; private thresholdManager: ThresholdManager; private panelWidth: number; private plot: any; private sortedSeries: any; private ctrl: GraphCtrl; private dashboard: any; private panel: any; private eventManager; private flotOptions: any = {} private annotations: any[]; private _graphMousePosition: any; constructor (private $elem, private timeSrv, private contextSrv, scope) { this.$elem = $elem; this.ctrl = scope.ctrl; this.dashboard = this.ctrl.dashboard; this.panel = this.ctrl.panel; this.annotations = []; this.panelWidth = 0; this.eventManager = new EventManager(this.ctrl); this.flotOptions = {} this.thresholdManager = new ThresholdManager(this.ctrl); this.tooltip = new GraphTooltip( $elem, this.dashboard, scope, () => this.sortedSeries ); // panel events this.ctrl.events.on('panel-teardown', () => { this.thresholdManager = null; if (this.plot) { this.plot.destroy(); this.plot = null; } }); // global events appEvents.on('graph-hover', this._onGraphHover.bind(this), scope); appEvents.on('graph-hover-clear', this._onGraphHoverClear.bind(this), scope); this.$elem.bind('plotselected', (event, selectionEvent) => { if (this.panel.xaxis.mode !== 'time') { // Skip if panel in histogram or series mode this.plot.clearSelection(); return; } if ((selectionEvent.ctrlKey || selectionEvent.metaKey) && this.contextSrv.isEditor) { // Add annotation setTimeout(() => { this.eventManager.updateTime(selectionEvent.xaxis); }, 100); } else { scope.$apply(() => { this.timeSrv.setTime({ from: moment.utc(selectionEvent.xaxis.from), to: moment.utc(selectionEvent.xaxis.to), }); }); } }); this.$elem.bind('plotclick', (event, flotEvent, item) => { if (this.panel.xaxis.mode !== 'time') { // Skip if panel in histogram or series mode return; } if ((flotEvent.ctrlKey || flotEvent.metaKey) && this.contextSrv.isEditor) { // Skip if range selected (added in "plotselected" event handler) let isRangeSelection = flotEvent.x !== flotEvent.x1; if (!isRangeSelection) { setTimeout(() => { this.eventManager.updateTime({ from: flotEvent.x, to: null }); }, 100); } } }); this.$elem.mouseleave(() => { if (this.panel.tooltip.shared) { var plot = this.$elem.data().plot; if (plot) { this.tooltip.clear(plot); } } appEvents.emit('graph-hover-clear'); }); this.$elem.bind("plothover", (event, pos, item) => { this.tooltip.show(pos, item); pos.panelRelY = (pos.pageY - this.$elem.offset().top) / this.$elem.height(); this._graphMousePosition = this.plot.p2c(pos); appEvents.emit('graph-hover', { pos: pos, panel: this.panel }); }); this.$elem.bind("plotclick", (event, pos, item) => { appEvents.emit('graph-click', { pos: pos, panel: this.panel, item: item }); }); } public render(renderData) { this.data = renderData || this.data; if (!this.data) { return; } // this.annotations = this.ctrl.annotations || []; this._buildFlotPairs(this.data); updateLegendValues(this.data, this.panel); if(this.tooltip.visible) { var pos = this.plot.c2p(this._graphMousePosition); var canvasOffset = this.$elem.find('.flot-overlay').offset(); this.tooltip.show(pos); this.plot.setCrosshair(pos); } } private _onGraphHover(evt: any) { if (!this.dashboard.sharedTooltipModeEnabled()) { return; } // ignore if we are the emitter if (!this.plot || evt.panel.id === this.panel.id || this.ctrl.otherPanelInFullscreenMode()) { return; } this._graphMousePosition = this.plot.p2c(evt.pos); this.tooltip.show(evt.pos); } private _onGraphHoverClear() { if (this.plot) { this.tooltip.clear(this.plot); } } private _shouldAbortRender() { if (!this.data) { return true; } if (this.panelWidth === 0) { return true; } return false; } private _drawHook(plot) { // add left axis labels if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) { $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>") .text(this.panel.yaxes[0].label) .appendTo(this.$elem); } // add right axis labels if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) { $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>") .text(this.panel.yaxes[1].label) .appendTo(this.$elem); } if (this.ctrl.dataWarning) { $(`<div class="datapoints-warning flot-temp-elem">${this.ctrl.dataWarning.title}</div>`).appendTo(this.$elem); } this.thresholdManager.draw(plot); } private _processOffsetHook(plot, gridMargin) { var left = this.panel.yaxes[0]; var right = this.panel.yaxes[1]; if (left.show && left.label) { gridMargin.left = 20; } if (right.show && right.label) { gridMargin.right = 20; } // apply y-axis min/max options var yaxis = plot.getYAxes(); for (var i = 0; i < yaxis.length; i++) { var axis = yaxis[i]; var panelOptions = this.panel.yaxes[i]; axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max; axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min; } } // Series could have different timeSteps, // let's find the smallest one so that bars are correctly rendered. // In addition, only take series which are rendered as bars for this. private _getMinTimeStepOfSeries(data) { var min = Number.MAX_VALUE; for (let i = 0; i < data.length; i++) { if (!data[i].stats.timeStep) { continue; } if (this.panel.bars) { if (data[i].bars && data[i].bars.show === false) { continue; } } else { if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) { continue; } } if (data[i].stats.timeStep < min) { min = data[i].stats.timeStep; } } return min; } // Function for rendering panel public renderPanel() { this.panelWidth = this.$elem.width(); if (this._shouldAbortRender()) { return; } // give space to alert editing this.thresholdManager.prepare(this.$elem, this.data); // un-check dashes if lines are unchecked this.panel.dashes = this.panel.lines ? this.panel.dashes : false; // Populate element this._buildFlotOptions(this.panel); this.sortedSeries = this._sortSeries(this.data, this.panel); this._prepareXAxis(this.panel); this._configureYAxisOptions(this.data); this.thresholdManager.addFlotOptions(this.flotOptions, this.panel); this.eventManager.addFlotEvents(this.annotations, this.flotOptions); this._callPlot(true); } private _buildFlotPairs(data) { for (let i = 0; i < data.length; i++) { let series = data[i]; series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode); // if hidden remove points and disable stack if (this.ctrl.hiddenSeries[series.alias]) { series.data = []; series.stack = false; } } } private _prepareXAxis(panel) { switch (panel.xaxis.mode) { case 'series': { this.flotOptions.series.bars.barWidth = 0.7; this.flotOptions.series.bars.align = 'center'; for (let i = 0; i < this.data.length; i++) { let series = this.data[i]; series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]]; } this._addXSeriesAxis(); break; } case 'histogram': { let bucketSize: number; let values = getSeriesValues(this.data); if (this.data.length && values.length) { let histMin = _.min(_.map(this.data, (s:any) => s.stats.min)); let histMax = _.max(_.map(this.data, (s:any) => s.stats.max)); let ticks = panel.xaxis.buckets || this.panelWidth / 50; bucketSize = tickStep(histMin, histMax, ticks); let histogram = convertValuesToHistogram(values, bucketSize); this.data[0].data = histogram; this.flotOptions.series.bars.barWidth = bucketSize * 0.8; } else { bucketSize = 0; } this._addXHistogramAxis(bucketSize); break; } case 'table': { this.flotOptions.series.bars.barWidth = 0.7; this.flotOptions.series.bars.align = 'center'; this._addXTableAxis(); break; } default: { let minTimeStep = this._getMinTimeStepOfSeries(this.data); if(minTimeStep >= (this._timeMax - this._timeMin)) { minTimeStep = this._timeMax - this._timeMin } this.flotOptions.series.bars.barWidth = minTimeStep / 1.5; if(this._shouldDisplaySideBySide()) { this._displaySideBySide(this.flotOptions); } this._addTimeAxis(minTimeStep); break; } } } private _shouldDisplaySideBySide() { return this.panel.displayBarsSideBySide && !this.panel.stack && this.panel.xaxis.mode === 'time'; } private _displaySideBySide(options) { let barsSeries = _.filter(this.sortedSeries, series => series.bars && series.bars.show !== false); let barWidth = options.series.bars.barWidth / barsSeries.length; for(let i = 0; i < barsSeries.length; ++i) { barsSeries[i].bars.order = i; barsSeries[i].bars.barWidth = barWidth; } } private _callPlot(incrementRenderCounter) { try { this.plot = $.plot(this.$elem, this.sortedSeries, this.flotOptions); if ((this.ctrl as any).renderError) { delete this.ctrl.error; delete this.ctrl.inspector; } } catch (e) { console.log('flotcharts error', e); this.ctrl.error = e.message || 'Render Error'; (this.ctrl as any).renderError = true; this.ctrl.inspector = { error: e }; } if (incrementRenderCounter) { this.ctrl.renderingCompleted(); } } private _buildFlotOptions(panel) { const stack = panel.stack ? true : null; this.flotOptions = { hooks: { draw: [this._drawHook.bind(this)], processOffset: [this._processOffsetHook.bind(this)], }, legend: { show: false }, series: { stackpercent: panel.stack ? panel.percentage : false, stack: panel.percentage ? null : stack, lines: { show: panel.lines, zero: false, fill: this._translateFillOption(panel.fill), lineWidth: panel.dashes ? 0 : panel.linewidth, steps: panel.steppedLine, }, dashes: { show: panel.dashes, lineWidth: panel.linewidth, dashLength: [panel.dashLength, panel.spaceLength], }, bars: { show: panel.bars, fill: 1, barWidth: 1, zero: false, lineWidth: 0, }, points: { show: panel.points, fill: 1, fillColor: false, radius: panel.points ? panel.pointradius : 2, }, shadowSize: 0, }, yaxes: [], xaxis: {}, grid: { minBorderMargin: 0, markings: [], backgroundColor: null, borderWidth: 0, hoverable: true, clickable: true, color: '#c8c8c8', margin: { left: 0, right: 0 }, labelMarginX: 0, }, selection: { mode: 'x', color: '#666' }, crosshair: { mode: 'x', }, }; } private _sortSeries(series, panel) { var sortBy = panel.legend.sort; var sortOrder = panel.legend.sortDesc; var haveSortBy = sortBy !== null || sortBy !== undefined; var haveSortOrder = sortOrder !== null || sortOrder !== undefined; var shouldSortBy = panel.stack && haveSortBy && haveSortOrder; var sortDesc = panel.legend.sortDesc === true ? -1 : 1; series.sort((x, y) => { if (x.zindex > y.zindex) { return 1; } if (x.zindex < y.zindex) { return -1; } if (shouldSortBy) { if (x.stats[sortBy] > y.stats[sortBy]) { return 1 * sortDesc; } if (x.stats[sortBy] < y.stats[sortBy]) { return -1 * sortDesc; } } return 0; }); return series; } private _translateFillOption(fill) { if (this.panel.percentage && this.panel.stack) { return fill === 0 ? 0.001 : fill / 10; } else { return fill / 10; } } private _addTimeAxis(minTimeStep: number) { let format; let min = this._timeMin; let max = this._timeMax; let ticks: any = this.panelWidth / 100; console.log('Sorted series length: ', this.sortedSeries.length); if(this.panel.bars && this.sortedSeries.length > 0 && this.sortedSeries[0].datapoints.length > 0) { console.log('First serie alias: ', this.sortedSeries[0].alias); let groupsAmount = (max - min) / minTimeStep; let generatedTicks = this._generateTicks(groupsAmount, ticks, min, max, minTimeStep); if(generatedTicks.length !== 0) { console.log('Time format'); console.log('Ticks amount: ', generatedTicks.length); if(this.panel.xaxis.customDateFormatShow) { format = this.panel.xaxis.customDateFormat; } else { format = this._timeFormat(generatedTicks, min, max); } const formatDate = ($.plot as any).formatDate; ticks = _.map(generatedTicks, tick => { const secondsInMinute = 60; const msInSecond = 1000; let date = new Date(tick[1]); if(this.dashboard.getTimezone() === 'utc') { date = new Date(date.getTime() + date.getTimezoneOffset() * secondsInMinute * msInSecond); } return [ tick[0], formatDate(date, format) ] }); } } console.log(this.dashboard.getTimezone()); console.log('Final ticks: ', ticks); this.flotOptions.xaxis = { timezone: this.dashboard.getTimezone(), show: this.panel.xaxis.show, mode: 'time', min, max, label: 'Datetime', ticks }; } private _generateTicks(groupsAmount: number, maxTicks: number, rangeFrom: number, rangeTo: number, timeStep: number) { console.log('Ticks generator'); console.log('Groups amount: ', groupsAmount); console.log('Max ticks: ', maxTicks); console.log('From: ', rangeFrom); console.log('To: ', rangeTo); console.log('Time step: ', timeStep); let ticks = []; const shiftedRangeFrom = rangeFrom - this.flotOptions.series.bars.barWidth; const shiftedRangeTo = rangeTo + this.flotOptions.series.bars.barWidth; let seriesInRange = _.map(this.sortedSeries, (serie: any) => serie.datapoints.filter( datapoint => datapoint[1] >= shiftedRangeFrom && datapoint[1] <= shiftedRangeTo ) ); let firstGroupTimestamp = Number.MAX_VALUE; let maxDatapoints = 0; _.each(seriesInRange, datapoints => { if(datapoints.length > maxDatapoints) { maxDatapoints = datapoints.length; } _.each(datapoints, datapoint => { if(datapoint[1] < firstGroupTimestamp) { firstGroupTimestamp = datapoint[1]; } }); }); console.log('First group timestamp: ', firstGroupTimestamp); console.log('Max datapoints: ', maxDatapoints); let groups = Math.max(maxDatapoints, groupsAmount); let multiplier = Math.floor(groups / maxTicks) || 1; let offset; if(this.panel.labelAlign === 'left') { offset = 0; } else if(this.panel.labelAlign === 'center') { offset = this.flotOptions.series.bars.barWidth / 2; } else { offset = this.flotOptions.series.bars.barWidth; } console.log('Align: ', this.panel.labelAlign); console.log('Offset: ', offset); let tick = firstGroupTimestamp + offset; let shiftedTick; while(tick <= rangeTo) { shiftedTick = tick - offset; if(tick >= rangeFrom) { ticks.push([tick, shiftedTick]); } tick += timeStep * multiplier; } return ticks; } private _addXSeriesAxis() { var ticks = _.map(this.data, function(series: any, index) { return [index + 1, series.alias]; }); this.flotOptions.xaxis = { timezone: this.dashboard.getTimezone(), show: this.panel.xaxis.show, mode: null, min: 0, max: ticks.length + 1, label: 'Datetime', ticks: ticks, }; } private _addXHistogramAxis(bucketSize) { let ticks, min, max; let defaultTicks = this.panelWidth / 50; if (this.data.length && bucketSize) { ticks = _.map(this.data[0].data, point => point[0]); min = _.min(ticks); max = _.max(ticks); // Adjust tick step let tickStep = bucketSize; let ticks_num = Math.floor((max - min) / tickStep); while (ticks_num > defaultTicks) { tickStep = tickStep * 2; ticks_num = Math.ceil((max - min) / tickStep); } // Expand ticks for pretty view min = Math.floor(min / tickStep) * tickStep; max = Math.ceil(max / tickStep) * tickStep; ticks = []; for (let i = min; i <= max; i += tickStep) { ticks.push(i); } } else { // Set defaults if no data ticks = defaultTicks / 2; min = 0; max = 1; } this.flotOptions.xaxis = { timezone: this.dashboard.getTimezone(), show: this.panel.xaxis.show, mode: null, min: min, max: max, label: 'Histogram', ticks: ticks, }; // Use 'short' format for histogram values this._configureAxisMode(this.flotOptions.xaxis, 'short'); } private _addXTableAxis() { var ticks = _.map(this.data, function(series: any, seriesIndex: any) { return _.map(series.datapoints, function(point, pointIndex) { var tickIndex = seriesIndex * series.datapoints.length + pointIndex; return [tickIndex + 1, point[1]]; }); }); ticks = _.flatten(ticks); this.flotOptions.xaxis = { timezone: this.dashboard.getTimezone(), show: this.panel.xaxis.show, mode: null, min: 0, max: ticks.length + 1, label: 'Datetime', ticks: ticks, }; } private _configureYAxisOptions(data) { var defaults = { position: 'left', show: this.panel.yaxes[0].show, index: 1, logBase: this.panel.yaxes[0].logBase || 1, min: this._parseNumber(this.panel.yaxes[0].min), max: this._parseNumber(this.panel.yaxes[0].max), tickDecimals: this.panel.yaxes[0].decimals, }; this.flotOptions.yaxes.push(defaults); if (_.find(data, { yaxis: 2 })) { var secondY = _.clone(defaults); secondY.index = 2; secondY.show = this.panel.yaxes[1].show; secondY.logBase = this.panel.yaxes[1].logBase || 1; secondY.position = 'right'; secondY.min = this._parseNumber(this.panel.yaxes[1].min); secondY.max = this._parseNumber(this.panel.yaxes[1].max); secondY.tickDecimals = this.panel.yaxes[1].decimals; this.flotOptions.yaxes.push(secondY); this._applyLogScale(this.flotOptions.yaxes[1], data); this._configureAxisMode(this.flotOptions.yaxes[1], this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format); } this._applyLogScale(this.flotOptions.yaxes[0], data); this._configureAxisMode(this.flotOptions.yaxes[0], this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format); } private _parseNumber(value: any) { if (value === null || typeof value === 'undefined') { return null; } return _.toNumber(value); } private _applyLogScale(axis, data) { if (axis.logBase === 1) { return; } const minSetToZero = axis.min === 0; if (axis.min < Number.MIN_VALUE) { axis.min = null; } if (axis.max < Number.MIN_VALUE) { axis.max = null; } var series, i; var max = axis.max, min = axis.min; for (i = 0; i < data.length; i++) { series = data[i]; if (series.yaxis === axis.index) { if (!max || max < series.stats.max) { max = series.stats.max; } if (!min || min > series.stats.logmin) { min = series.stats.logmin; } } } axis.transform = function(v) { return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase); }; axis.inverseTransform = function(v) { return Math.pow(axis.logBase, v); }; if (!max && !min) { max = axis.inverseTransform(+2); min = axis.inverseTransform(-2); } else if (!max) { max = min * axis.inverseTransform(+4); } else if (!min) { min = max * axis.inverseTransform(-4); } if (axis.min) { min = axis.inverseTransform(Math.ceil(axis.transform(axis.min))); } else { min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min))); } if (axis.max) { max = axis.inverseTransform(Math.floor(axis.transform(axis.max))); } else { max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max))); } if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) { return; } if (Number.isFinite(min) && Number.isFinite(max)) { if (minSetToZero) { axis.min = 0.1; min = 1; } axis.ticks = this._generateTicksForLogScaleYAxis(min, max, axis.logBase); if (minSetToZero) { axis.ticks.unshift(0.1); } if (axis.ticks[axis.ticks.length - 1] > axis.max) { axis.max = axis.ticks[axis.ticks.length - 1]; } } else { axis.ticks = [1, 2]; delete axis.min; delete axis.max; } } private _generateTicksForLogScaleYAxis(min, max, logBase) { let ticks = []; var nextTick; for (nextTick = min; nextTick <= max; nextTick *= logBase) { ticks.push(nextTick); } const maxNumTicks = Math.ceil(this.ctrl.height / 25); const numTicks = ticks.length; if (numTicks > maxNumTicks) { const factor = Math.ceil(numTicks / maxNumTicks) * logBase; ticks = []; for (nextTick = min; nextTick <= max * factor; nextTick *= factor) { ticks.push(nextTick); } } return ticks; } private _configureAxisMode(axis, format) { axis.tickFormatter = function(val, axis) { return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals); }; } private _timeFormat(ticks, min, max) { if (min && max && ticks) { let ticksAmount = ticks; if(_.isArray(ticks)) { ticksAmount = ticks.length; } var range = max - min; var secPerTick = range / ticksAmount / 1000; var oneDay = 86400000; var oneYear = 31536000000; if (secPerTick <= 45) { return '%H:%M:%S'; } if (secPerTick <= 7200 || range <= oneDay) { return '%H:%M'; } if (secPerTick <= 80000) { return '%m/%d %H:%M'; } if (secPerTick <= 2419200 || range <= oneYear) { return '%m/%d'; } return '%Y-%m'; } return '%H:%M'; } private get _timeMin() { return _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf(); } private get _timeMax() { return _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf(); } }
the_stack
import { BloomFilter } from 'bloomfilter' import { HighlightedLinkProps, offsetSum, RangePosition } from '../components/fuzzyFinder/HighlightedLink' import { FuzzySearch, IndexingFSM, FuzzySearchParameters, FuzzySearchResult, SearchValue } from './FuzzySearch' import { Hasher } from './Hasher' /** * We don't index filenames with length larger than this value. */ const MAX_VALUE_LENGTH = 100 // Normally, you need multiple hash functions to keep the false-positive ratio // low. However, non-empirical observations indicate that a single hash function // works fine and provides the fastest indexing time in large repositories like // Chromium. const DEFAULT_BLOOM_FILTER_HASH_FUNCTION_COUNT = 1 // The number of filenames to group together in a single bucket, and the number // string prefixes that each bloom can contain. Currently, every bucket can // contain up to 262.144 prefixes (conservatively large number). With bucket // size 50, my off-the-napkin calculation is that total memory usage with 400k // files (Chromium size) may be as large as ~261mb. It's usable on most // computers, but still a bit high. // Tracking issue to fine-tune these parameters: https://github.com/sourcegraph/sourcegraph/issues/21201 const DEFAULT_BUCKET_SIZE = 50 const DEFAULT_BLOOM_FILTER_SIZE = 2 << 17 /** * Returns true if the given query fuzzy matches the given value. */ export function fuzzyMatchesQuery(query: string, value: string): RangePosition[] { return fuzzyMatches(allFuzzyParts(query, true), value) } /** * Word-sensitive fuzzy search that * * Is specifically designed to support low-latency filtering in large * repositories (>100k files). * * NOTE(olafur): this is a reimplementation of the fuzzy finder in the Scala * language server that's documented in this blog post here * https://scalameta.org/metals/blog/2019/01/22/bloom-filters.html#fuzzy-symbol-search * * In a nutshell, bloom filters improve performance by allowing us to skip a * "bucket" of candidate files if we know that bucket does not match any words * in that query. For example, the query "SymPro" is split into the words "Sym" * and "Pro". If a bucket of 500 words is guaranteed to have to appearances of * the words "Sym" and "Pro", then we can skip those 500 words and move on to * the next bucket. * * One downside of the bloom filter approach is that it requires an indexing * phase that can take a couple of seconds to complete on a large input size * (>100k filenames). The indexing phase can take a while to complete because we * need to compute all possible words that the user may query. For example, * given the filename "SymbolProvider", we create a bloom filter with all * possible prefixes of "Symbol" and "Provider". Fortunately, bloom filters can be * serialized so that the indexing step only runs once per repoName/commitID pair. */ export class WordSensitiveFuzzySearch extends FuzzySearch { public totalFileCount = 0 constructor(public readonly buckets: Bucket[]) { super() for (const bucket of buckets) { this.totalFileCount += bucket.files.length } } public static fromSearchValuesAsync(files: SearchValue[], bucketSize: number = DEFAULT_BUCKET_SIZE): IndexingFSM { files.sort((a, b) => a.text.length - b.text.length) const indexer = new Indexer(files, bucketSize) function loop(): IndexingFSM { if (indexer.isDone()) { return { key: 'ready', value: indexer.complete() } } indexer.processBuckets(25000) return { key: 'indexing', indexedFileCount: indexer.indexedFileCount(), totalFileCount: indexer.totalFileCount(), partialFuzzy: indexer.complete(), continue: () => new Promise(resolve => resolve(loop())), } } return loop() } public static fromSearchValues( files: SearchValue[], bucketSize: number = DEFAULT_BUCKET_SIZE ): WordSensitiveFuzzySearch { const indexer = new Indexer(files, bucketSize) while (!indexer.isDone()) { indexer.processBuckets(bucketSize) } return indexer.complete() } public search(query: FuzzySearchParameters): FuzzySearchResult { if (query.query.length === 0) { return this.emptyResult(query) } let falsePositives = 0 const result: HighlightedLinkProps[] = [] const hashParts = allQueryHashParts(query.query) const queryParts = allFuzzyParts(query.query, true) const complete = (isComplete: boolean): FuzzySearchResult => this.sorted({ links: result, isComplete, falsePositiveRatio: falsePositives / this.buckets.length }) for (const bucket of this.buckets) { const matches = bucket.matches(query, queryParts, hashParts) if (!matches.skipped && matches.value.length === 0) { falsePositives++ } for (const value of matches.value) { if (result.length >= query.maxResults) { return complete(false) } result.push(value) } } return complete(true) } private sorted(result: FuzzySearchResult): FuzzySearchResult { result.links.sort((a, b) => { const byLength = a.text.length - b.text.length if (byLength !== 0) { return byLength } const byEarliestMatch = offsetSum(a) - offsetSum(b) if (byEarliestMatch !== 0) { return byEarliestMatch } return a.text.localeCompare(b.text) }) return result } private emptyResult(query: FuzzySearchParameters): FuzzySearchResult { const result: HighlightedLinkProps[] = [] const complete = (isComplete: boolean): FuzzySearchResult => this.sorted({ links: result, isComplete }) for (const bucket of this.buckets) { if (result.length > query.maxResults) { return complete(false) } for (const value of bucket.files) { result.push({ text: value.text, positions: [], url: query.createUrl ? query.createUrl(value.text) : undefined, onClick: query.onClick, }) if (result.length > query.maxResults) { return complete(false) } } } return complete(true) } } export function allFuzzyParts(value: string, includeDelimeters: boolean): string[] { const buf: string[] = [] let start = 0 let end = 0 while (end < value.length) { if (end > start) { buf.push(value.slice(start, end)) } while (end < value.length && isDelimeter(value[end])) { if (includeDelimeters) { buf.push(value[end]) } end++ } start = end end = nextFuzzyPart(value, end + 1) } if (start < value.length && end > start) { buf.push(value.slice(start, end)) } return buf } function isDigit(value: string): boolean { return value >= '0' && value <= '9' } function isLowercaseCharacter(value: string): boolean { return isLowercaseOrDigit(value) && !isDelimeter(value) } function isLowercaseOrDigit(value: string): boolean { return isDigit(value) || (value.toLowerCase() === value && value !== value.toUpperCase()) } function isUppercaseCharacter(value: string): boolean { return isUppercase(value) && !isDelimeter(value) } function isUppercase(value: string): boolean { return value.toUpperCase() === value && value !== value.toLowerCase() } function isDelimeterOrUppercase(character: string): boolean { return isDelimeter(character) || isUppercase(character) } function isDelimeter(character: string): boolean { switch (character) { case '/': case '_': case '-': case '.': case ' ': return true default: return false } } function fuzzyMatches(queries: string[], value: string): RangePosition[] { const result: RangePosition[] = [] const matcher = new FuzzyMatcher(queries, value) while (!matcher.isDone()) { const isCurrentQueryDelimeter = matcher.isQueryDelimeter() while (!matcher.isQueryDelimeter() && matcher.isStartDelimeter()) { matcher.start++ } if (matcher.matchesFromStart()) { result.push(matcher.rangePositionFromStart()) matcher.queryIndex++ } matcher.start = matcher.nextStart(isCurrentQueryDelimeter) } return matcher.queryIndex >= queries.length ? result : [] } class FuzzyMatcher { public queryIndex = 0 public start = 0 private lowercaseValue: string constructor(private readonly queries: string[], private readonly value: string) { this.lowercaseValue = value.toLowerCase() } public nextStart(isCurrentQueryDelimeter: boolean): number { const offset = isCurrentQueryDelimeter ? this.start : this.start + 1 let end = this.isQueryDelimeter() ? this.indexOfDelimeter(this.query(), offset) : nextFuzzyPart(this.value, offset) while (end < this.value.length && !this.isQueryDelimeter() && isDelimeter(this.value[end])) { end++ } return end } public rangePositionFromStart(): RangePosition { const end = this.start + this.query().length return { startOffset: this.start, endOffset: end, isExact: end >= this.value.length || startsNewWord(this.value, end), } } public matchesFromStart(): boolean { const caseInsensitive = this.isCaseInsensitive() const compareValue = caseInsensitive ? this.lowercaseValue : this.value return ( compareValue.startsWith(this.query(), this.start) && (!caseInsensitive || isCapitalizedPart(this.value, this.start, this.query())) ) } public isStartDelimeter(): boolean { return isDelimeter(this.value[this.start]) } public isDone(): boolean { return this.queryIndex >= this.queries.length || this.start >= this.value.length } public query(): string { return this.queries[this.queryIndex] } public isCaseInsensitive(): boolean { return isLowercaseOrDigit(this.query()) } public isQueryDelimeter(): boolean { return isDelimeter(this.query()) } public indexOfDelimeter(delim: string, start: number): number { const index = this.value.indexOf(delim, start) return index < 0 ? this.value.length : index } } function startsNewWord(value: string, index: number): boolean { return ( isDelimeterOrUppercase(value[index]) || (isLowercaseCharacter(value[index]) && !isLowercaseCharacter(value[index - 1])) ) } /** * Returns true if value.substring(start, start + query.length) is "properly capitalized". * * The string is properly capitalized as long it contains no lowercase character * that is followed by an uppercase character. For example: * * - Not properly capitalized: "InnerClasses" "innerClasses" * - Properly capitalized: "Innerclasses" "INnerclasses" */ function isCapitalizedPart(value: string, start: number, query: string): boolean { let previousIsLowercase = false for (let index = start; index < value.length && index - start < query.length; index++) { const nextIsLowercase = isLowercaseOrDigit(value[index]) if (previousIsLowercase && !nextIsLowercase) { return false } previousIsLowercase = nextIsLowercase } return true } function nextFuzzyPart(value: string, start: number): number { let end = start while (end < value.length && !isDelimeterOrUppercase(value[end])) { end++ } return end } function populateBloomFilter(values: SearchValue[]): BloomFilter { const hashes = new BloomFilter(DEFAULT_BLOOM_FILTER_SIZE, DEFAULT_BLOOM_FILTER_HASH_FUNCTION_COUNT) for (const value of values) { if (value.text.length < MAX_VALUE_LENGTH) { updateHashParts(value.text, hashes) } } return hashes } function allQueryHashParts(query: string): number[] { const fuzzyParts = allFuzzyParts(query, false) const result: number[] = [] const hasher = new Hasher() for (const part of fuzzyParts) { hasher.reset() for (const character of part) { hasher.update(character) result.push(hasher.digest()) } } return result } function updateHashParts(value: string, buf: BloomFilter): void { const words = new Hasher() const lowercaseWords = new Hasher() for (let index = 0; index < value.length; index++) { const character = value[index] if (isDelimeterOrUppercase(character)) { words.reset() lowercaseWords.reset() if (isUppercaseCharacter(character) && (index === 0 || !isUppercaseCharacter(value[index - 1]))) { let uppercaseWordIndex = index const upper = [] while (uppercaseWordIndex < value.length && isUppercaseCharacter(value[uppercaseWordIndex])) { upper.push(value[uppercaseWordIndex]) lowercaseWords.update(value[uppercaseWordIndex].toLowerCase()) buf.add(lowercaseWords.digest()) uppercaseWordIndex++ } lowercaseWords.reset() } } if (isDelimeter(character)) { continue } words.update(character) lowercaseWords.update(character.toLowerCase()) buf.add(words.digest()) if (words.digest() !== lowercaseWords.digest()) { buf.add(lowercaseWords.digest()) } } } interface BucketResult { skipped: boolean value: HighlightedLinkProps[] } class Bucket { constructor( public readonly files: SearchValue[], public readonly filter: BloomFilter, public readonly id: number ) {} public static fromSearchValues(files: SearchValue[]): Bucket { files.sort((a, b) => a.text.length - b.text.length) return new Bucket(files, populateBloomFilter(files), Math.random()) } private matchesMaybe(hashParts: number[]): boolean { for (const part of hashParts) { if (!this.filter.test(part)) { return false } } return true } public matches(query: FuzzySearchParameters, queryParts: string[], hashParts: number[]): BucketResult { const matchesMaybe = this.matchesMaybe(hashParts) if (!matchesMaybe) { return { skipped: true, value: [] } } const result: HighlightedLinkProps[] = [] for (const file of this.files) { const positions = fuzzyMatches(queryParts, file.text) if (positions.length > 0) { result.push({ text: file.text, positions, url: query.createUrl ? query.createUrl(file.text) : undefined, onClick: query.onClick, }) } } return { skipped: false, value: result } } } class Indexer { private buffer: SearchValue[] = [] private buckets: Bucket[] = [] private index = 0 constructor(private readonly files: SearchValue[], private readonly bucketSize: number) { this.files.sort((a, b) => a.text.length - b.text.length) } public complete(): WordSensitiveFuzzySearch { return new WordSensitiveFuzzySearch(this.buckets) } public isDone(): boolean { return this.index >= this.files.length } public totalFileCount(): number { return this.files.length } public indexedFileCount(): number { return this.index } public processBuckets(fileCount: number): void { let bucketCount = fileCount / this.bucketSize while (bucketCount > 0 && !this.isDone()) { const endIndex = Math.min(this.files.length, this.index + this.bucketSize) while (this.index < endIndex) { this.buffer.push(this.files[this.index]) this.index++ } if (this.buffer) { this.buckets.push(Bucket.fromSearchValues(this.buffer)) this.buffer = [] } bucketCount-- } } }
the_stack
import _ from 'lodash'; import moment from 'moment'; import angular from 'angular'; import * as dateMath from 'app/core/utils/datemath'; import appEvents from 'app/core/app_events'; import TableModel from 'app/core/table_model'; System.config({ meta: { 'https://apis.google.com/js/api.js': { exports: 'gapi', format: 'global' } } }); export default class GoogleStackdriverDatasource { type: string; name: string; id: string; access: string; clientId: string; defaultProjectId: string; maxAvailableToken: number; token: number; provideTokenInterval: number; tokenTimer: any; scopes: any; discoveryDocs: any; initialized: boolean; gapi: any; /** @ngInject */ constructor(instanceSettings, private $q, private templateSrv, private timeSrv, private backendSrv) { this.type = instanceSettings.type; this.name = instanceSettings.name; this.id = instanceSettings.id; this.access = instanceSettings.jsonData.access; this.clientId = instanceSettings.jsonData.clientId; this.defaultProjectId = instanceSettings.jsonData.defaultProjectId; this.maxAvailableToken = ((instanceSettings.jsonData.quota && instanceSettings.jsonData.quota.requestsPerMinutePerUser) || 6000) / 60; this.token = this.maxAvailableToken; this.provideTokenInterval = 1000 / this.maxAvailableToken; this.tokenTimer = null; this.scopes = [ //'https://www.googleapis.com/auth/cloud-platform', //'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read' ].join(' '); this.discoveryDocs = ["https://monitoring.googleapis.com/$discovery/rest?version=v3"]; this.initialized = false; } query(options) { return this.initialize().then(() => { return Promise.all(options.targets .filter(target => !target.hide) .map(target => { target = angular.copy(target); let filter = 'metric.type = "' + this.templateSrv.replace(target.metricType, options.scopedVars || {}) + '"'; if (target.filter) { filter += ' AND ' + this.templateSrv.replace(target.filter, options.scopedVars || {}); } target.filter = filter; return this.performTimeSeriesQuery(target, options).then(response => { appEvents.emit('ds-request-response', response); response.timeSeries.forEach(series => { series.target = target; }); return this.filterSeries(target, response); }); })).then((responses: any) => { let timeSeries = _.flatten(responses.filter(response => { return !!response.timeSeries; }).map(response => { return response.timeSeries; })); if (options.targets[0].format === 'table') { return this.transformMetricDataToTable(timeSeries); } else { return this.transformMetricData(timeSeries); } }, err => { console.log(err); err = JSON.parse(err.body); appEvents.emit('ds-request-error', err); throw err.error; }); }); } provideToken() { if (this.token < this.maxAvailableToken) { let tokenCount = 1; if (this.provideTokenInterval < 10) { // setInterval's minumum interval is 10 tokenCount = Math.floor(10 / this.provideTokenInterval); } this.token += tokenCount; if (this.token === this.maxAvailableToken) { clearInterval(this.tokenTimer); this.tokenTimer = null; } } } delay(func, retryCount, wait) { return new Promise((resolve, reject) => { setTimeout(() => { func(retryCount).then(resolve, reject); }, wait); }); } retryable(retryCount, func) { let promise = Promise.reject({}).catch(() => func(retryCount)); for (let i = 0; i < retryCount; i++) { ((i) => { promise = promise.catch(err => func(i + 1)); })(i); } return promise; } calculateRetryWait(initialWait, retryCount) { return initialWait * Math.min(10, Math.pow(2, retryCount)) + Math.floor(Math.random() * 1000); } transformMetricData(timeSeries) { return { data: timeSeries.map(series => { let aliasPattern = series.target.alias; let valueKey = series.valueType.toLowerCase() + 'Value'; if (valueKey !== 'distributionValue') { let datapoints = []; let metricLabel = this.getMetricLabel(aliasPattern, series); for (let point of series.points) { let value = point.value[valueKey]; if (_.isUndefined(value)) { continue; } switch (valueKey) { case 'boolValue': value = value ? 1 : 0; // convert bool value to int break; } datapoints.push([parseFloat(value), Date.parse(point.interval.endTime).valueOf()]); } // Stackdriver API returns series in reverse chronological order. datapoints.reverse(); return [{ target: metricLabel, datapoints: datapoints }]; } else { let buckets = []; for (let point of series.points) { if (!point.value.distributionValue.bucketCounts) { continue; } for (let i = 0; i < point.value.distributionValue.bucketCounts.length; i++) { let value = parseInt(point.value.distributionValue.bucketCounts[i], 10); if (!buckets[i]) { // set lower bounds // https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries#Distribution let bucketBound = this.calcBucketBound(point.value.distributionValue.bucketOptions, i); buckets[i] = { target: this.getMetricLabel(aliasPattern, _.extend(series, { bucket: bucketBound })), datapoints: [] }; } buckets[i].datapoints.push([value, Date.parse(point.interval.endTime).valueOf()]); } // fill empty bucket let n = _.max(_.keys(buckets)); for (let i = 0; i < n; i++) { if (!buckets[i]) { let bucketBound = this.calcBucketBound(point.value.distributionValue.bucketOptions, i); buckets[i] = { target: this.getMetricLabel(aliasPattern, _.extend(series, { bucket: bucketBound })), datapoints: [] }; } } } return buckets; } }).flatten().filter(series => { return series.datapoints.length > 0; }) }; } transformMetricDataToTable(md) { var table = new TableModel(); var i, j; var metricLabels = {}; if (md.length === 0) { return table; } // Collect all labels across all metrics metricLabels['metric.type'] = 1; metricLabels['resource.type'] = 1; [ 'metric.labels', 'resource.labels', 'metadata.systemLabels', 'metadata.userLabels', ].forEach(path => { _.each(md, _.property(path)).forEach(labels => { if (labels) { _.keys(labels).forEach(k => { let label = path + '.' + k; if (!metricLabels.hasOwnProperty(label)) { metricLabels[label] = 1; } }); } }); }); // Sort metric labels, create columns for them and record their index var sortedLabels = _.keys(metricLabels).sort(); table.columns.push({ text: 'Time', type: 'time' }); _.each(sortedLabels, function (label, labelIndex) { metricLabels[label] = labelIndex + 1; table.columns.push({ text: label }); }); table.columns.push({ text: 'Value' }); // Populate rows, set value to empty string when label not present. _.each(md, function (series) { if (series.points) { for (i = 0; i < series.points.length; i++) { var point = series.points[i]; var reordered: any = [Date.parse(point.interval.endTime).valueOf()]; for (j = 0; j < sortedLabels.length; j++) { var label = sortedLabels[j]; reordered.push(_.get(series, label) || ''); } reordered.push(point.value[_.keys(point.value)[0]]); table.rows.push(reordered); } } }); return { data: [table] }; } metricFindQuery(query) { return this.initialize().then(() => { let metricsQuery = query.match(/^metrics\((([^,]+), *)?(.*)\)/); if (metricsQuery) { let projectId = metricsQuery[2] || this.defaultProjectId; let filter = metricsQuery[3]; let params = { projectId: this.templateSrv.replace(projectId), filter: this.templateSrv.replace(filter) }; return this.performMetricDescriptorsQuery(params, {}).then(response => { return this.$q.when(response.metricDescriptors.map(d => { return { text: d.type }; })); }); } let labelQuery = query.match(/^label_values\((([^,]+), *)?([^,]+), *(.*)\)/); if (labelQuery) { let projectId = labelQuery[2] || this.defaultProjectId; let targetProperty = labelQuery[3]; let filter = labelQuery[4]; let params = { projectId: this.templateSrv.replace(projectId), filter: this.templateSrv.replace(filter), view: 'HEADERS' }; return this.performTimeSeriesQuery(params, { range: this.timeSrv.timeRange() }).then(response => { let valuePicker = _.property(targetProperty); return this.$q.when(response.timeSeries.map(d => { return { text: valuePicker(d) }; })); }, err => { console.log(err); err = JSON.parse(err.body); throw err.error; }); } let groupsQuery = query.match(/^groups\(([^,]+)?\)/); if (groupsQuery) { let projectId = groupsQuery[1] || this.defaultProjectId; let params = { projectId: this.templateSrv.replace(projectId) }; return this.performGroupsQuery(params, {}).then(response => { return this.$q.when(response.group.map(d => { return { //text: d.displayName text: d.name.split('/')[3] }; })); }, err => { console.log(err); err = JSON.parse(err.body); throw err.error; }); } let groupMembersQuery = query.match(/^group_members\((([^,]+), *)?([^,]+), *([^,]+), *(.*)\)/); if (groupMembersQuery) { let projectId = groupMembersQuery[2] || this.defaultProjectId; let groupId = groupMembersQuery[3]; let targetProperty = groupMembersQuery[4]; let filter = groupMembersQuery[5]; let params = { projectId: this.templateSrv.replace(projectId), groupId: this.templateSrv.replace(groupId), filter: this.templateSrv.replace(filter) }; return this.performGroupsMembersQuery(params, { range: this.timeSrv.timeRange() }).then(response => { let valuePicker = _.property(targetProperty); return this.$q.when(response.members.map(d => { return { text: valuePicker(d) }; })); }, err => { console.log(err); err = JSON.parse(err.body); throw err.error; }); } return Promise.reject(new Error('Invalid query, use one of: metrics(), label_values(), groups(), group_members()')); }); } testDatasource() { return this.initialize().then(() => { if (this.access === 'proxy' && this.defaultProjectId) { let params = { projectId: this.defaultProjectId, filter: '' }; return this.performMetricDescriptorsQuery(params, {}).then(response => { return { status: 'success', message: 'Data source is working', title: 'Success' }; }); } else { return { status: 'success', message: 'Data source is working', title: 'Success' }; } }).catch(err => { console.log(err); return { status: "error", message: err.message, title: "Error" }; }); } load() { let deferred = this.$q.defer(); System.import('https://apis.google.com/js/api.js').then((gapi) => { this.gapi = gapi; this.gapi.load('client:auth2', () => { return deferred.resolve(); }); }); return deferred.promise; } initialize() { if (this.access === 'proxy') { return Promise.resolve([]); } if (this.initialized) { return Promise.resolve(this.gapi.auth2.getAuthInstance().currentUser.get()); } return this.load().then(() => { return this.gapi.client.init({ clientId: this.clientId, scope: this.scopes, discoveryDocs: this.discoveryDocs }).then(() => { let authInstance = this.gapi.auth2.getAuthInstance(); if (!authInstance) { throw { message: 'failed to initialize' }; } let isSignedIn = authInstance.isSignedIn.get(); if (isSignedIn) { this.initialized = true; return authInstance.currentUser.get(); } return authInstance.signIn().then(user => { this.initialized = true; return user; }); }, err => { console.log(err); throw { message: 'failed to initialize' }; }); }); } backendPluginRawRequest(params) { return this.backendSrv.datasourceRequest(params).then(response => { return { result: response.data.results[""].meta }; }).catch(err => { throw { body: JSON.stringify({ error: { message: err.data.results[""].error } }) }; }); } performTimeSeriesQuery(target, options) { if (this.token === 0) { return this.delay((retryCount) => { return this.performTimeSeriesQuery(target, options); }, 0, Math.ceil(this.provideTokenInterval)); } target = angular.copy(target); let params: any = {}; params.name = this.templateSrv.replace('projects/' + (target.projectId || this.defaultProjectId), options.scopedVars || {}); params.filter = this.templateSrv.replace(target.filter, options.scopedVars || {}); if (target.aggregation) { for (let key of Object.keys(target.aggregation)) { if (_.isArray(target.aggregation[key])) { params['aggregation.' + key] = target.aggregation[key].map(aggregation => { return this.templateSrv.replace(aggregation, options.scopedVars || {}); }); } else if (target.aggregation[key] !== '') { params['aggregation.' + key] = this.templateSrv.replace(target.aggregation[key], options.scopedVars || {}); } } // auto period if (params['aggregation.perSeriesAligner'] !== 'ALIGN_NONE' && !params['aggregation.alignmentPeriod']) { params['aggregation.alignmentPeriod'] = Math.max((options.intervalMs / 1000), 60) + 's'; } } if (target.view) { params.view = target.view; } if (target.pageToken) { params.pageToken = target.pageToken; } params['interval.startTime'] = this.convertTime(options.range.from, false); params['interval.endTime'] = this.convertTime(options.range.to, true); this.token--; if (this.tokenTimer === null) { this.tokenTimer = setInterval(() => { this.provideToken(); }, Math.max(10, Math.ceil(this.provideTokenInterval))); } return ((params) => { if (this.access !== 'proxy') { return this.gapi.client.monitoring.projects.timeSeries.list(params); } else { return this.backendPluginRawRequest({ url: '/api/tsdb/query', method: 'POST', data: { from: options.range.from.valueOf().toString(), to: options.range.to.valueOf().toString(), queries: [ _.extend({ queryType: 'raw', api: 'monitoring.projects.timeSeries.list', refId: target.refId, datasourceId: this.id }, params) ], } }); } })(params).then(response => { response = response.result; if (!response.timeSeries) { return { timeSeries: [] }; } if (!response.nextPageToken) { return response; } target.pageToken = response.nextPageToken; return this.performTimeSeriesQuery(target, options).then(nextResponse => { response.timeSeries = response.timeSeries.concat(nextResponse.timeSeries); return response; }); }, err => { let e = JSON.parse(err.body); if (e.error.message.indexOf('The query rate is too high.') >= 0) { this.token = 0; return this.retryable(3, (retryCount) => { return this.delay((retryCount) => { return this.performTimeSeriesQuery(target, options); }, retryCount, this.calculateRetryWait(1000, retryCount)); }); } throw err; }); } performMetricDescriptorsQuery(target, options) { target = angular.copy(target); let params: any = {}; params.name = this.templateSrv.replace('projects/' + (target.projectId || this.defaultProjectId), options.scopedVars || {}); params.filter = this.templateSrv.replace(target.filter, options.scopedVars || {}); if (target.pageToken) { params.pageToken = target.pageToken; } return ((params) => { if (this.access !== 'proxy') { return this.gapi.client.monitoring.projects.metricDescriptors.list(params); } else { return this.backendPluginRawRequest({ url: '/api/tsdb/query', method: 'POST', data: { queries: [ _.extend({ queryType: 'raw', api: 'monitoring.projects.metricDescriptors.list', refId: '', datasourceId: this.id }, params) ], } }); } })(params).then(response => { response = response.result; if (!response.metricDescriptors) { return { metricDescriptors: [] }; } if (!response.nextPageToken) { return response; } target.pageToken = response.nextPageToken; return this.performMetricDescriptorsQuery(target, options).then(nextResponse => { response = response.metricDescriptors.concat(nextResponse.metricDescriptors); return response; }); }); } performGroupsQuery(target, options) { target = angular.copy(target); let params: any = {}; params.name = this.templateSrv.replace('projects/' + (target.projectId || this.defaultProjectId), options.scopedVars || {}); if (target.pageToken) { params.pageToken = target.pageToken; } return ((params) => { if (this.access !== 'proxy') { return this.gapi.client.monitoring.projects.groups.list(params); } else { return this.backendPluginRawRequest({ url: '/api/tsdb/query', method: 'POST', data: { queries: [ _.extend({ queryType: 'raw', api: 'monitoring.projects.groups.list', refId: '', datasourceId: this.id }, params) ], } }); } })(params).then(response => { response = response.result; if (!response.group) { return { group: [] }; } if (!response.nextPageToken) { return response; } target.pageToken = response.nextPageToken; return this.performGroupsQuery(target, options).then(nextResponse => { response = response.group.concat(nextResponse.group); return response; }); }); } performGroupsMembersQuery(target, options) { target = angular.copy(target); let params: any = {}; params.name = this.templateSrv.replace('projects/' + (target.projectId || this.defaultProjectId) + '/groups/' + target.groupId, options.scopedVars || {}); params.filter = this.templateSrv.replace(target.filter, options.scopedVars || {}); if (target.pageToken) { params.pageToken = target.pageToken; } params['interval.startTime'] = this.convertTime(options.range.from, false); params['interval.endTime'] = this.convertTime(options.range.to, true); return ((params) => { if (this.access !== 'proxy') { return this.gapi.client.monitoring.projects.groups.members.list(params); } else { return this.backendPluginRawRequest({ url: '/api/tsdb/query', method: 'POST', data: { from: options.range.from.valueOf().toString(), to: options.range.to.valueOf().toString(), queries: [ _.extend({ queryType: 'raw', api: 'monitoring.projects.groups.members.list', refId: '', datasourceId: this.id }, params) ], } }); } })(params).then(response => { response = response.result; if (!response.members) { return { members: [] }; } if (!response.nextPageToken) { return response; } target.pageToken = response.nextPageToken; return this.performGroupsMembersQuery(target, options).then(nextResponse => { response = response.members.concat(nextResponse.members); return response; }); }); } filterSeries(target, response) { if (!_.has(target, 'seriesFilter') || target.seriesFilter.mode === 'NONE' || target.seriesFilter.type === 'NONE' || target.seriesFilter.param === '') { return response; } let param = _.toNumber(target.seriesFilter.param); if (_.isNaN(param)) { return response; } response.timeSeries.forEach(series => { series['filterValue'] = this.getSeriesFilterValue(target, series); }); switch (target.seriesFilter.mode) { case 'TOP': response.timeSeries.sort(function (a, b) { return b.filterValue - a.filterValue; }); response.timeSeries = response.timeSeries.slice(0, param); return response; case 'BOTTOM': response.timeSeries.sort(function (a, b) { return a.filterValue - b.filterValue; }); response.timeSeries = response.timeSeries.slice(0, param); return response; case 'BELOW': response.timeSeries = response.timeSeries.filter(function (elem) { return elem.filterValue < param; }); return response; case 'ABOVE': response.timeSeries = response.timeSeries.filter(function (elem) { return elem.filterValue > param; }); return response; default: console.log(`Unknown series filter mode: ${target.seriesFilter.mode}`); return response; } } getSeriesFilterValue(target, series) { // For empty timeseries return filter value that will push them out first. if (series.points.length === 0) { if (target.seriesFilter.mode === 'BOTTOM' || target.seriesFilter.mode === 'BELOW') { return Number.MAX_VALUE; } else { return Number.MIN_VALUE; } } let valueKey = series.valueType.toLowerCase() + 'Value'; switch (target.seriesFilter.type) { case 'MAX': return series.points.reduce(function (acc, elem) { return Math.max(acc, elem.value[valueKey]); }, Number.MIN_VALUE); case 'MIN': return series.points.reduce(function (acc, elem) { return Math.min(acc, elem.value[valueKey]); }, Number.MAX_VALUE); case 'AVERAGE': return series.points.reduce(function (acc, elem) { return acc + elem.value[valueKey]; }, 0) / series.points.length; case 'CURRENT': return series.points[0].value[valueKey]; default: console.log(`Unknown series filter type: ${target.seriesFilter.type}`); return 0; } } getMetricLabel(alias, series) { let aliasData = { metric: series.metric, resource: series.resource }; if (!_.isUndefined(series.bucket)) { aliasData['bucket'] = series.bucket; } if (alias === '') { return JSON.stringify(aliasData); } let aliasRegex = /\{\{(.+?)\}\}/g; alias = alias.replace(aliasRegex, (match, g1) => { let matchedValue = _.property(g1)(aliasData); if (!_.isUndefined(matchedValue)) { if (typeof matchedValue === 'object') { return JSON.stringify(matchedValue); } else { return matchedValue; } } return g1; }); let aliasSubRegex = /sub\(([^,]+), "([^"]+)", "([^"]+)"\)/g; alias = alias.replace(aliasSubRegex, (match, g1, g2, g3) => { try { let matchedValue = _.property(g1)(aliasData); let labelRegex = new RegExp(g2); if (!_.isUndefined(matchedValue)) { return matchedValue.replace(labelRegex, g3); } } catch (e) { // if regexp compilation fails, we'll return original string below } return `sub(${g1}, "${g2}", "${g3}")`; }); return alias; } calcBucketBound(bucketOptions, n) { let bucketBound = 0; if (n === 0) { return bucketBound; } if (bucketOptions.linearBuckets) { bucketBound = bucketOptions.linearBuckets.offset + (bucketOptions.linearBuckets.width * (n - 1)); } else if (bucketOptions.exponentialBuckets) { bucketBound = bucketOptions.exponentialBuckets.scale * (Math.pow(bucketOptions.exponentialBuckets.growthFactor, (n - 1))); } else if (bucketOptions.explicitBuckets) { bucketBound = bucketOptions.explicitBuckets.bounds[(n - 1)]; } return bucketBound; } convertTime(date, roundUp) { if (_.isString(date)) { date = dateMath.parse(date, roundUp); } return date.toISOString(); } }
the_stack
import { $TSAny, $TSContext, $TSObject, pathManager, readCFNTemplate, stateManager, writeCFNTemplate } from 'amplify-cli-core'; import { printer, prompter } from 'amplify-prompts'; import _ from 'lodash'; import * as path from 'path'; import { v4 as uuid } from 'uuid'; import { categoryName, functionCategoryName } from '../../constants'; import { FunctionServiceNameLambdaFunction, providerName } from './provider-constants'; export async function removeTrigger(context: $TSContext, resourceName: string, triggerFunctionName: string) { // Update Cloudformtion file const projectRoot = pathManager.findProjectRoot(); const resourceDirPath = pathManager.getResourceDirectoryPath(projectRoot, categoryName, resourceName); const storageCFNFilePath = path.join(resourceDirPath, 's3-cloudformation-template.json'); const { cfnTemplate: storageCFNFile }: { cfnTemplate: $TSAny } = readCFNTemplate(storageCFNFilePath); const bucketParameters = stateManager.getResourceParametersJson(projectRoot, categoryName, resourceName); const adminTrigger = bucketParameters.adminTriggerFunction; delete storageCFNFile.Parameters[`function${triggerFunctionName}Arn`]; delete storageCFNFile.Parameters[`function${triggerFunctionName}Name`]; delete storageCFNFile.Parameters[`function${triggerFunctionName}LambdaExecutionRole`]; delete storageCFNFile.Resources.TriggerPermissions; if (!adminTrigger) { // Remove reference for old triggerFunctionName delete storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration; delete storageCFNFile.Resources.S3TriggerBucketPolicy; delete storageCFNFile.Resources.S3Bucket.DependsOn; } else { const lambdaConfigurations: $TSAny = []; storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration.LambdaConfigurations.forEach((triggers: $TSAny) => { if ( triggers.Filter && typeof triggers.Filter.S3Key.Rules[0].Value === 'string' && triggers.Filter.S3Key.Rules[0].Value.includes('index-faces') ) { lambdaConfigurations.push(triggers); } }); storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration.LambdaConfigurations = lambdaConfigurations; const index = storageCFNFile.Resources.S3Bucket.DependsOn.indexOf('TriggerPermissions'); if (index > -1) { storageCFNFile.Resources.S3Bucket.DependsOn.splice(index, 1); } const roles: $TSAny[] = []; storageCFNFile.Resources.S3TriggerBucketPolicy.Properties.Roles.forEach((role: $TSAny) => { if (!role.Ref.includes(triggerFunctionName)) { roles.push(role); } }); storageCFNFile.Resources.S3TriggerBucketPolicy.Properties.Roles = roles; } await writeCFNTemplate(storageCFNFile, storageCFNFilePath); const meta = stateManager.getMeta(projectRoot); const s3DependsOnResources = meta.storage[resourceName].dependsOn; const s3Resources: $TSAny[] = []; s3DependsOnResources.forEach((resource: $TSAny) => { if (resource.resourceName !== triggerFunctionName) { s3Resources.push(resource); } }); context.amplify.updateamplifyMetaAfterResourceUpdate(categoryName, resourceName, 'dependsOn', s3Resources); } /* * When updating, remove the old trigger before adding a new one * This function has a side effect of updating the dependsOn array */ export async function addTrigger( context: $TSContext, resourceName: string, triggerFunction: $TSAny, adminTriggerFunction: $TSAny, options: { dependsOn?: $TSAny[]; headlessTrigger?: { name: string; mode: 'new' | 'existing' } }, ) { const triggerTypeChoices = ['Choose an existing function from the project', 'Create a new function']; const [shortId] = uuid().split('-'); let functionName = `S3Trigger${shortId}`; let useExistingFunction: boolean; if (options?.headlessTrigger) { functionName = options.headlessTrigger.name; useExistingFunction = options.headlessTrigger.mode === 'existing'; } else { const triggerTypeQuestion = { message: 'Select from the following options', choices: triggerTypeChoices, }; useExistingFunction = (await prompter.pick(triggerTypeQuestion.message, triggerTypeQuestion.choices)) === triggerTypeChoices[0]; if (useExistingFunction) { let lambdaResources = await getLambdaFunctions(context); if (triggerFunction) { lambdaResources = lambdaResources.filter((lambdaResource: $TSAny) => lambdaResource !== triggerFunction); } if (lambdaResources.length === 0) { throw new Error("No functions were found in the project. Use 'amplify add function' to add a new function."); } const triggerOptionQuestion = { message: 'Select from the following options', choices: lambdaResources, }; functionName = await prompter.pick(triggerOptionQuestion.message, triggerOptionQuestion.choices); } } // Update Lambda CFN const functionCFNFilePath = path.join( pathManager.getResourceDirectoryPath(undefined, functionCategoryName, functionName), `${functionName}-cloudformation-template.json`, ); if (useExistingFunction) { const { cfnTemplate: functionCFNFile }: { cfnTemplate: $TSAny } = readCFNTemplate(functionCFNFilePath); functionCFNFile.Outputs.LambdaExecutionRole = { Value: { Ref: 'LambdaExecutionRole', }, }; // Update the function resource's CFN template await writeCFNTemplate(functionCFNFile, functionCFNFilePath); printer.success(`Successfully updated resource ${functionName} locally`); } else { // Create a new lambda trigger const targetDir = pathManager.getBackendDirPath(); const pluginDir = __dirname; const defaults = { functionName, roleName: `${functionName}LambdaRole${shortId}`, }; const copyJobs = [ { dir: pluginDir, template: path.join('..', '..', '..', 'resources', 'triggers', 's3', 'lambda-cloudformation-template.json.ejs'), target: path.join(targetDir, functionCategoryName, functionName, `${functionName}-cloudformation-template.json`), }, { dir: pluginDir, template: path.join('..', '..', '..', 'resources', 'triggers', 's3', 'event.json'), target: path.join(targetDir, functionCategoryName, functionName, 'src', 'event.json'), }, { dir: pluginDir, template: path.join('..', '..', '..', 'resources', 'triggers', 's3', 'index.js'), target: path.join(targetDir, functionCategoryName, functionName, 'src', 'index.js'), }, { dir: pluginDir, template: path.join('..', '..', '..', 'resources', 'triggers', 's3', 'package.json.ejs'), target: path.join(targetDir, functionCategoryName, functionName, 'src', 'package.json'), }, ]; // copy over the files await context.amplify.copyBatch(context, copyJobs, defaults, !!options?.headlessTrigger); // Update amplify-meta and backend-config const backendConfigs = { service: FunctionServiceNameLambdaFunction, providerPlugin: providerName, build: true, }; await context.amplify.updateamplifyMetaAfterResourceAdd(functionCategoryName, functionName, backendConfigs); printer.success(`Successfully added resource ${functionName} locally`); if ( !options?.headlessTrigger && (await context.amplify.confirmPrompt(`Do you want to edit the local ${functionName} lambda function now?`)) ) { await context.amplify.openEditor(context, path.join(targetDir, functionCategoryName, functionName, 'src', 'index.js')); } } // If updating an already existing S3 resource if (resourceName) { // Update Cloudformtion file const projectBackendDirPath = pathManager.getBackendDirPath(); const storageCFNFilePath = path.join(projectBackendDirPath, categoryName, resourceName, 's3-cloudformation-template.json'); const { cfnTemplate: storageCFNFile }: { cfnTemplate: $TSAny } = readCFNTemplate(storageCFNFilePath); const amplifyMetaFile = stateManager.getMeta(); // Remove reference for old triggerFunction if (triggerFunction) { delete storageCFNFile.Parameters[`function${triggerFunction}Arn`]; delete storageCFNFile.Parameters[`function${triggerFunction}Name`]; delete storageCFNFile.Parameters[`function${triggerFunction}LambdaExecutionRole`]; } // Add reference for the new triggerFunction storageCFNFile.Parameters[`function${functionName}Arn`] = { Type: 'String', Default: `function${functionName}Arn`, }; storageCFNFile.Parameters[`function${functionName}Name`] = { Type: 'String', Default: `function${functionName}Name`, }; storageCFNFile.Parameters[`function${functionName}LambdaExecutionRole`] = { Type: 'String', Default: `function${functionName}LambdaExecutionRole`, }; storageCFNFile.Parameters.triggerFunction = { Type: 'String', }; if (adminTriggerFunction && !triggerFunction) { storageCFNFile.Resources.S3Bucket.DependsOn.push('TriggerPermissions'); storageCFNFile.Resources.S3TriggerBucketPolicy.Properties.Roles.push({ Ref: `function${functionName}LambdaExecutionRole`, }); // eslint-disable-next-line max-len let lambdaConf = storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration.LambdaConfigurations; lambdaConf = lambdaConf.concat( getTriggersForLambdaConfiguration('private', functionName), getTriggersForLambdaConfiguration('protected', functionName), getTriggersForLambdaConfiguration('public', functionName), ); // eslint-disable-next-line max-len storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration.LambdaConfigurations = lambdaConf; const dependsOnResources = amplifyMetaFile.storage[resourceName].dependsOn; dependsOnResources.push({ category: functionCategoryName, resourceName: functionName, attributes: ['Name', 'Arn', 'LambdaExecutionRole'], }); context.amplify.updateamplifyMetaAfterResourceUpdate(categoryName, resourceName, 'dependsOn', dependsOnResources); } else if (adminTriggerFunction && triggerFunction !== 'NONE') { storageCFNFile.Resources.S3TriggerBucketPolicy.Properties.Roles.forEach((role: $TSAny) => { if (role.Ref.includes(triggerFunction)) { role.Ref = `function${functionName}LambdaExecutionRole`; } }); storageCFNFile.Resources.TriggerPermissions.Properties.FunctionName.Ref = `function${functionName}Name`; // eslint-disable-next-line max-len storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration.LambdaConfigurations.forEach((lambdaConf: $TSAny) => { if ( !(typeof lambdaConf.Filter.S3Key.Rules[0].Value === 'string' && lambdaConf.Filter.S3Key.Rules[0].Value.includes('index-faces')) ) { lambdaConf.Function.Ref = `function${functionName}Arn`; } }); const dependsOnResources = amplifyMetaFile.storage[resourceName].dependsOn; dependsOnResources.forEach((resource: $TSAny) => { if (resource.resourceName === triggerFunction) { resource.resourceName = functionName; } }); context.amplify.updateamplifyMetaAfterResourceUpdate(categoryName, resourceName, 'dependsOn', dependsOnResources); } else { storageCFNFile.Resources.S3Bucket.Properties.NotificationConfiguration = { LambdaConfigurations: [ { Event: 's3:ObjectCreated:*', Function: { Ref: `function${functionName}Arn`, }, }, { Event: 's3:ObjectRemoved:*', Function: { Ref: `function${functionName}Arn`, }, }, ], }; storageCFNFile.Resources.S3Bucket.DependsOn = ['TriggerPermissions']; storageCFNFile.Resources.S3TriggerBucketPolicy = { Type: 'AWS::IAM::Policy', DependsOn: ['S3Bucket'], Properties: { PolicyName: 's3-trigger-lambda-execution-policy', Roles: [ { Ref: `function${functionName}LambdaExecutionRole`, }, ], PolicyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: ['s3:PutObject', 's3:GetObject', 's3:DeleteObject'], Resource: [ { 'Fn::Join': [ '', [ 'arn:aws:s3:::', { Ref: 'S3Bucket', }, '/*', ], ], }, ], }, { Effect: 'Allow', Action: 's3:ListBucket', Resource: [ { 'Fn::Join': [ '', [ 'arn:aws:s3:::', { Ref: 'S3Bucket', }, ], ], }, ], }, ], }, }, }; // Update DependsOn const dependsOnResources = options.dependsOn || amplifyMetaFile.storage[resourceName].dependsOn || []; dependsOnResources.filter((resource: $TSAny) => resource.resourceName !== triggerFunction); dependsOnResources.push({ category: functionCategoryName, resourceName: functionName, attributes: ['Name', 'Arn', 'LambdaExecutionRole'], }); context.amplify.updateamplifyMetaAfterResourceUpdate(categoryName, resourceName, 'dependsOn', dependsOnResources); } storageCFNFile.Resources.TriggerPermissions = { Type: 'AWS::Lambda::Permission', Properties: { Action: 'lambda:InvokeFunction', FunctionName: { Ref: `function${functionName}Name`, }, Principal: 's3.amazonaws.com', SourceAccount: { Ref: 'AWS::AccountId', }, SourceArn: { 'Fn::Join': [ '', [ 'arn:aws:s3:::', { 'Fn::If': [ 'ShouldNotCreateEnvResources', { Ref: 'bucketName', }, { 'Fn::Join': [ '', [ { Ref: 'bucketName', }, { 'Fn::Select': [ 3, { 'Fn::Split': [ '-', { Ref: 'AWS::StackName', }, ], }, ], }, '-', { Ref: 'env', }, ], ], }, ], }, ], ], }, }, }; await writeCFNTemplate(storageCFNFile, storageCFNFilePath); } else { // New resource if (!options.dependsOn) { options.dependsOn = []; } options.dependsOn.push({ category: functionCategoryName, resourceName: functionName, attributes: ['Name', 'Arn', 'LambdaExecutionRole'], }); } return functionName; } function getTriggersForLambdaConfiguration(protectionLevel: string, functionName: string) { const triggers = [ { Event: 's3:ObjectCreated:*', Filter: { S3Key: { Rules: [ { Name: 'prefix', Value: { 'Fn::Join': [ '', [ `${protectionLevel}/`, { Ref: 'AWS::Region', }, ], ], }, }, ], }, }, Function: { Ref: `function${functionName}Arn`, }, }, { Event: 's3:ObjectRemoved:*', Filter: { S3Key: { Rules: [ { Name: 'prefix', Value: { 'Fn::Join': [ '', [ `${protectionLevel}/`, { Ref: 'AWS::Region', }, ], ], }, }, ], }, }, Function: { Ref: `function${functionName}Arn`, }, }, ]; return triggers; } async function getLambdaFunctions(context: $TSContext) { const { allResources } = await context.amplify.getResourceStatus(); const lambdaResources = allResources .filter((resource: $TSObject) => resource.service === FunctionServiceNameLambdaFunction) .map((resource: $TSObject) => resource.resourceName); return lambdaResources; }
the_stack
import React, { useCallback, useMemo, useState } from "react" import { observer } from "mobx-react-lite" import { useHistory, useParams } from "react-router" import { cloneDeep, snakeCase, uniqueId } from "lodash" // @Types import { CommonSourcePageProps } from "ui/pages/SourcesPage/SourcesPage" import { SourceConnector as CatalogSourceConnector } from "@jitsu/catalog/sources/types" // @Store import { sourcesStore } from "stores/sources" // @Catalog import { allSources as sourcesCatalog } from "@jitsu/catalog/sources/lib" // @Components import { sourcesPageRoutes } from "ui/pages/SourcesPage/SourcesPage.routes" import { createInitialSourceData, sourceEditorUtils } from "./SourceEditor.utils" import { sourcePageUtils, TestConnectionResponse } from "ui/pages/SourcesPage/SourcePage.utils" import { firstToLower } from "lib/commons/utils" import { actionNotification } from "ui/components/ActionNotification/ActionNotification" import { SourceEditorView } from "./SourceEditorView" import { ErrorDetailed } from "lib/commons/errors" import { connectionsHelper } from "stores/helpers" import { projectRoute } from "lib/components/ProjectLink/ProjectLink" import { flowResult } from "mobx" // @Utils /** Accumulated state of all forms that is transformed and sent to backend on source save */ export type SourceEditorState = { /** * Source configuration step/tab */ configuration: ConfigurationState /** * Source streams step/tab */ streams: StreamsState /** * Source connected destinations step/tab */ connections: ConnectionsState /** * Whether user made any changes */ stateChanged: boolean } export type SetSourceEditorState = React.Dispatch<React.SetStateAction<SourceEditorState>> /** Initial source data used to render the forms */ export type SourceEditorInitialSourceData = Optional<Partial<SourceData>> export type SetSourceEditorInitialSourceData = React.Dispatch<React.SetStateAction<SourceEditorInitialSourceData>> /** Set of source editor disabled tabs */ export type SourceEditorDisabledTabs = Set<string> export type SetSourceEditorDisabledTabs = (tabKeys: string[], action: "enable" | "disable") => void /** Method for saving the configured source */ export type HandleSaveSource = (config?: HandleSaveSourceConfig) => Promise<void> type HandleSaveSourceConfig = { /** Errors names to skip when saving the source */ ignoreErrors?: string[] } /** Method for validating and testing connection of the configured source */ export type HandleValidateTestConnection = (config?: HandleValidateTestConnectionConfig) => Promise<void> type HandleValidateTestConnectionConfig = { /** Errors names to skip when testing the source connection */ ignoreErrors?: string[] } type ConfigurationState = { config: SourceConfigurationData validateGetErrorsCount: () => Promise<number> errorsCount: number } type StreamsState = { /** @deprecated use `selectedStreams` instead */ streams?: SourceStreamsData selectedStreams: SourceSelectedStreams validateGetErrorsCount: () => Promise<number> forceReloadStreamsList: VoidFunction | AsyncVoidFunction errorsCount: number } type ConnectionsState = { connections: SourceConnectionsData errorsCount: number } export type SourceConfigurationData = { [key: string]: PlainObjectWithPrimitiveValues } export type SourceStreamsData = { [pathToStreamsInSourceData: string]: StreamData[] } export type SourceSelectedStreams = { [pathToSelectedStreamsInSourceData: string]: StreamConfig[] } export type SourceConnectionsData = { [pathToConnectionsInSourceData: string]: string[] } export type UpdateConfigurationFields = (newFileds: Partial<SourceConfigurationData>) => void const initialState: SourceEditorState = { configuration: { config: {}, validateGetErrorsCount: async () => 0, errorsCount: 0, }, streams: { streams: {}, selectedStreams: {}, validateGetErrorsCount: async () => 0, forceReloadStreamsList: () => {}, errorsCount: 0, }, connections: { connections: {}, errorsCount: 0, }, stateChanged: false, } const disableControlsRequestsRegistry = new Map<string, { tooltipMessage?: string }>() const SourceEditor: React.FC<CommonSourcePageProps> = ({ editorMode }) => { const history = useHistory() const allSourcesList = sourcesStore.list const { source, sourceId } = useParams<{ source?: string; sourceId?: string }>() const sourceDataFromCatalog = useMemo<CatalogSourceConnector>(() => { let sourceType = source ? source : sourceId ? sourcesStore.list.find(src => src.sourceId === sourceId)?.sourceProtoType : undefined return sourceType ? sourcesCatalog.find((source: CatalogSourceConnector) => snakeCase(source.id) === snakeCase(sourceType)) : undefined }, [sourceId, allSourcesList]) const [initialSourceData, setInitialSourceData] = useState<SourceEditorInitialSourceData>( () => sourceEditorUtils.reformatCatalogIntoSelectedStreams(allSourcesList.find(src => src.sourceId === sourceId)) ?? createInitialSourceData(sourceDataFromCatalog) ) const [state, setState] = useState<SourceEditorState>(initialState) const [controlsDisabled, setControlsDisabled] = useState<boolean | string>(false) const [tabsDisabled, setTabsDisabled] = useState<SourceEditorDisabledTabs>(null) const [showDocumentation, setShowDocumentation] = useState<boolean>(false) const handleSetControlsDisabled = useCallback((disabled: boolean | string, disableRequestId: string): void => { const tooltipMessage: string | undefined = typeof disabled === "string" ? disabled : undefined if (disabled) { setControlsDisabled(disabled) disableControlsRequestsRegistry.set(disableRequestId, { tooltipMessage }) } else { disableControlsRequestsRegistry.delete(disableRequestId) // enable back only if controls are not disabled by any other callers if (disableControlsRequestsRegistry.size === 0) { setControlsDisabled(disabled) } else { // set the tooltip message by a last `disable` caller let disabled: boolean | string = true disableControlsRequestsRegistry.forEach(({ tooltipMessage }) => { if (tooltipMessage) disabled = tooltipMessage }) setControlsDisabled(disabled) } } }, []) const handleSetTabsDisabled = useCallback<SetSourceEditorDisabledTabs>((tabKeys, action) => { setTabsDisabled(state => { const newState = new Set(state) tabKeys.forEach(key => (action === "disable" ? newState.add(key) : newState.delete(key))) return newState }) }, []) const handleBringSourceData = () => { let sourceEditorState = state setState(state => { sourceEditorState = state return state }) return sourceEditorUtils.getSourceDataFromState(sourceEditorState, sourceDataFromCatalog, initialSourceData) } const validateCountErrors = async (): Promise<number> => { const configurationErrorsCount = await state.configuration.validateGetErrorsCount() const streamsErrorsCount = await state.streams.validateGetErrorsCount() setState(state => { const newState = cloneDeep(state) newState.configuration.errorsCount = configurationErrorsCount newState.streams.errorsCount = streamsErrorsCount return newState }) return configurationErrorsCount + streamsErrorsCount } const validateAllForms = async () => { const someFieldsErrored = !!(await validateCountErrors()) if (someFieldsErrored) throw new Error("some values are invalid") } const getTestConnectionResponse = async (): Promise<TestConnectionResponse> => { const sourceData = handleBringSourceData() const testResult = await sourcePageUtils.testConnection(sourceData, true) return testResult } const assertCanConnect = async (config?: { testConnectionResponse?: TestConnectionResponse ignoreErrors?: string[] }): Promise<void> => { const response = config?.testConnectionResponse ?? (await getTestConnectionResponse()) if (!response.connected && !config?.ignoreErrors?.includes(response.connectedErrorType)) throw new ErrorDetailed({ message: response.connectedErrorMessage, name: response.connectedErrorType, payload: response.connectedErrorPayload, }) } const handleValidateAndTestConnection: HandleValidateTestConnection = async (methodConfig): Promise<void> => { await validateAllForms() const controlsDisableRequestId = uniqueId("validateAndTest-") handleSetControlsDisabled("Validating source configuration", controlsDisableRequestId) try { await assertCanConnect({ ignoreErrors: methodConfig?.ignoreErrors }) } finally { handleSetControlsDisabled(false, controlsDisableRequestId) } } const handleSave = useCallback<HandleSaveSource>( async methodConfig => { let sourceEditorState = null setState(state => { sourceEditorState = state // hack for getting the most recent state in the async function return { ...state, stateChanged: false } }) if (editorMode === "edit") await validateAllForms() const sourceData = handleBringSourceData() const testConnectionResults = await sourcePageUtils.testConnection(sourceData, true) await assertCanConnect({ testConnectionResponse: testConnectionResults, ignoreErrors: methodConfig?.ignoreErrors, }) let sourceDataToSave: SourceData = { ...sourceData, ...testConnectionResults, } let savedSourceData: SourceData = sourceDataToSave if (editorMode === "add") { savedSourceData = await flowResult(sourcesStore.add(sourceDataToSave)) } if (editorMode === "edit") { await flowResult(sourcesStore.replace(sourceDataToSave)) } await connectionsHelper.updateDestinationsConnectionsToSource( savedSourceData.sourceId, savedSourceData.destinations ) handleLeaveEditor({ goToSourcesList: true }) if (savedSourceData.connected) { actionNotification.success(editorMode === "add" ? "New source has been added!" : "Source has been saved") } else { actionNotification.warn( `Source has been saved, but test has failed with '${firstToLower( savedSourceData.connectedErrorMessage )}'. Data from this source will not be available` ) } }, [editorMode, state] ) const handleLeaveEditor = useCallback<(options?: { goToSourcesList?: boolean }) => void>(options => { options.goToSourcesList ? history.push(projectRoute(sourcesPageRoutes.root)) : history.goBack() }, []) const handleValidateStreams = async (): Promise<void> => { const streamsErrorsCount = await state.streams.validateGetErrorsCount() if (streamsErrorsCount) throw new Error("some streams settings are invalid") } return ( <SourceEditorView state={state} controlsDisabled={controlsDisabled} tabsDisabled={tabsDisabled} editorMode={editorMode} showDocumentationDrawer={showDocumentation} initialSourceData={initialSourceData} sourceDataFromCatalog={sourceDataFromCatalog} setSourceEditorState={setState} handleSetControlsDisabled={handleSetControlsDisabled} handleSetTabsDisabled={handleSetTabsDisabled} setShowDocumentationDrawer={setShowDocumentation} handleBringSourceData={handleBringSourceData} handleSave={handleSave} setInitialSourceData={setInitialSourceData} handleLeaveEditor={handleLeaveEditor} handleValidateAndTestConnection={handleValidateAndTestConnection} handleValidateStreams={handleValidateStreams} handleReloadStreams={state.streams.forceReloadStreamsList} /> ) } const Wrapped = observer(SourceEditor) Wrapped.displayName = "SourceEditor" export { Wrapped as SourceEditor }
the_stack
/// <reference types="jquery" /> declare namespace JQueryTooltipster { /** * Tooltipster options @see http://iamceege.github.io/tooltipster/ */ export interface ITooltipsterOptions { /** * Determines how the tooltip will animate in and out. In addition to the built-in transitions, * you may also create custom transitions in your CSS files. In IE9 and lower, all animations * default to a JavaScript generated, fade animation. * @default 'fade' */ animation?: 'fade' | 'grow' | 'swing' | 'slide' | 'fall'; /** * Sets the duration of the animation, in milliseconds. If you wish to provide different durations * for the opening and closing animations, provide an array of two different values. * @default 350 */ animationDuration?: number | number[]; /** * Add a "speech bubble" arrow to the tooltip. * @default true */ arrow?: boolean; /** * If set, this will override the content of the tooltip. If you provide something else than a string * or jQuery-wrapped HTML element, you will need to use the 'functionFormat' option to format your * content for display. * @default null */ content?: string | JQuery | any; /** * If the content of the tooltip is provided as a string, it is displayed as plain text by default. * If this content should actually be interpreted as HTML, set this option to true. * @default false */ contentAsHTML?: boolean; /** * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object * that should actually be used. * @default false */ contentCloning?: boolean; /** * Tooltipster logs hints and notices into the console when you're doing something you ideally shouldn't * be doing. Set to false to disable logging. * @default true */ debug?: boolean; /** * Upon mouse interaction, this is the delay before the tooltip starts its opening and closing animations * when the 'hover' trigger is used (*). If you wish to specify different delays for opening and closing, * you may provide an array of two different values. * @default 300 */ delay?: number | number[]; /** * Upon touch interaction, this is the delay before the tooltip starts its opening and closing animations * when the 'hover' trigger is used (*). If you wish to specify different delays for opening and closing, * you may provide an array of two different values. * @default [300, 500] */ delayTouch?: number | number[]; /** * The distance between the origin and the tooltip, in pixels. The value may be an integer or an array of * integers (in the usual CSS syntax) if you wish to specify a different distance for each side. * @default 6 */ distance?: number | number[]; /** * A custom function to be fired only once at instantiation. * @default null */ functionInit?: TooltipsterStandardCallbackFunction; /** * A custom function to be fired before the tooltip is opened. This function may prevent the opening if it * returns false. * @default null */ functionBefore?: TooltipsterStandardCallbackFunction; /** * A custom function to be fired when the tooltip and its contents have been added to the DOM. * @default null */ functionReady?: TooltipsterStandardCallbackFunction; /** * A custom function to be fired once the tooltip has been closed and removed from the DOM. * @default null */ functionAfter?: TooltipsterStandardCallbackFunction; /** * A custom function that does not modify the content but that can format it for display. It gets the two * first usual arguments and also the content as third argument. It must return the value that will be * displayed in the tooltip, either a string or a jQuery-wrapped HTML element (see the formatting section). * @default null */ functionFormat?: (instance: ITooltipsterInstance, helper: ITooltipsterHelper, content: any) => string | JQuery; /** * A custom function fired when the tooltip is repositioned. It gives you the ability to slightly or * completely modify the position that Tooltipster is about to give to the tooltip. It gets the proposed * set of placement values as third argument. The function must return the set of placement values, which * you may have edited (see the positioning section). * @default null */ functionPosition?: (instance: ITooltipsterInstance, helper: ITooltipsterHelper, position: ITooltipPosition) => ITooltipPosition; /** * The minimum version of Internet Explorer to run on. * @default 6 */ IEmin?: number; /** * Give users the possibility to interact with the content of the tooltip. If you want them to be able to * make clicks, fill forms or do other interactions inside the tooltip, you have to set this option to * true. When the 'hover' close trigger is used, the user has to move the cursor to the tooltip before it * starts closing (this lapse of time has its duration set by the 'delay' option). * @default false */ interactive?: boolean; /** * Set a maximum width for the tooltip. * @default null (no max width) */ maxWidth?: number; /** * Corresponds to the minimum distance to enforce between the center of the arrow and the edges of the * tooltip. Mainly used to create an arrow bigger than those of the default themes. * @default 16 */ minIntersection?: number; /** * Set a minimum width for the tooltip. * @default 0 (auto width) */ minWidth?: number; /** * Allows you to put several tooltips on a single element (see the multiple section). * @default false */ multiple?: boolean; /** * The names of plugins to be used by Tooltipster. * @default ['sideTip'] */ plugins?: string[]; /** * Several plugins may have options of the same name. To resolve the conflict, wrap the options of plugins * under a property with their full name. */ [pluginName: string]: any; /** * Repositions the tooltip if it goes out of the viewport when the user scrolls the page, in order to * keep it visible as long as possible. * @default false */ repositionOnScroll?: boolean; /** * Specifies if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' * method. This attribute may be omitted, or be restored with the value that existed before Tooltipster * was initialized, or be restored with the stringified value of the current content. Note: in case of * multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. * * @default 'none' */ restoration?: 'none' | 'previous' | 'current'; /** * Sets if the tooltip should self-destruct after a few seconds when its origin is removed from the DOM. * This prevents memory leaks. * @default true */ selfDestruction?: boolean; /** * Sets the side of the tooltip. The value may one of the following: 'top', 'bottom', 'left', 'right'. * It may also be an array containing one or more of these values. When using an array, the order of * values is taken into account as order of fallbacks and the absence of a side disables it (see the * sides section). Default: ['top', 'bottom', 'right', 'left'] */ side?: TooltipPositioningSide | TooltipPositioningSide[]; /** * How long (in ms) the tooltip should live before closing. * @default 0 (disabled) */ timer?: number; /** * Set a theme that will override the default tooltip appearance. You may provide an array of strings * to apply several themes at once (see the themes section). * @default: [] */ theme?: string | string[]; /** * Sets how often the tracker should run (see trackOrigin and trackTooltip), in milliseconds. The tracker * runs even if trackOrigin and trackTooltip are false to check if the origin has not been removed while * the tooltip was open, so you shouldn't set too high or too low values unless you need to. * @default 500 */ trackerInterval?: number; trackOrigin?: boolean; trackTooltip?: boolean; /** * Set how tooltips should be activated and closed. * Possible values: hover, click or custom. */ trigger?: string; /** * When 'trigger' is set to 'custom', all built-in close triggers are disabled by default. This option * allows you to reactivate the triggers of your choice to create a customized behavior. Only applies * if 'trigger' is set to 'custom'. See http://iamceege.github.io/tooltipster/#triggers. */ triggerClose?: { /** * When a mouse click happens anywhere in the page. However, if the interactive option is set to true, * a click happening inside the tooltip will not close it. */ click?: boolean; /** * When the mouse goes away from the origin. The delay option is taken into account as the delay before * closing. */ mouseleave?: boolean; /** * When the origin is clicked by a mouse. This mimics a behavior that browsers usually have and is meant * to be used with the mouseenter open trigger. */ originClick?: boolean; /** * When scrolling happens in the window or in a scrollable area which is a parent of the origin. */ scroll?: boolean; /** * When the finger taps (ie presses and releases) anywhere in the touch screen. */ tap?: boolean; /** * When the finger is removed from the touch screen or if the interaction was stopped by the device. The * delayTouch option is taken into account as the delay before closing. */ touchleave?: boolean; }; /** * When 'trigger' is set to 'custom', all built-in open triggers are disabled by default. This option * allows you to reactivate the triggers of your choice to create a customized behavior. Only applies * if 'trigger' is set to 'custom'. See http://iamceege.github.io/tooltipster/#triggers. */ triggerOpen?: { /** * When the origin is clicked by a mouse. */ click?: boolean; /** * When a mouse comes over the origin. The delay option is taken into account as the delay before * opening. */ mouseenter?: boolean; /** * When the origin is pressed on a touch screen. The delayTouch option is taken into account as the * delay before opening. */ touchstart?: boolean; /** * When the origin is tapped (ie pressed and then released) on a touch screen. */ tap?: boolean; }; /** * Plays a subtle animation when the content of the tooltip is updated (if the tooltip is open). You * may create custom animations in your CSS files. Set to null to disable the animation. * @default 'rotate' */ updateAnimation?: 'fade' | 'rotate' | 'scale' | null; /** * Tries to place the tooltip in such a way that it will be entirely visible on screen when it's opened. * If the tooltip is to be opened while its origin is off screen (using a method call), you may want to * set this option to false. * @default true */ viewportAware?: boolean; /** * Set the z-index of the tooltip. * @default 9999999 */ zIndex?: number; } type TooltipsterStandardCallbackFunction = (instance: ITooltipsterInstance, helper: ITooltipsterHelper) => void; interface ITooltipsterHelper { origin: HTMLElement; /** provided on functionReady and open callbacks */ tooltip?: HTMLElement | undefined; /** provided on functionBefore and functionAfter callbacks */ event?: MouseEvent | TouchEvent | null | undefined; /** provided on position callback */ mode?: 'natural' | 'constrained'; /** provided on position callback */ tooltipClone?: HTMLElement; /** provided on position callback */ geo?: ITooltipsterGeoHelper; } interface ITooltipsterGeoHelper { document: { size: { height: number; width: number; }; }; window: { scroll: { left: number; top: number; }; size: { height: number; width: number; } }; origin: { /** the origin has a fixed lineage if itself or one of its ancestors has a fixed position */ fixedLineage: boolean; offset: { /** this is the distance between the bottom side of the origin and the top of the document */ bottom: number; left: number; /** this is the distance between the right side of the origin and the left of the document */ right: number; top: number; }; size: { height: number; width: number }; /** if the origin is a map area, this will hold the associated image element */ usemapImage: HTMLImageElement | null; windowOffset: { /** this is the distance between the bottom side of the origin and the top of the viewport */ bottom: number; left: number; /** this is the distance between the right side of the origin and the left of the viewport */ right: number; top: number } } } /** see http://iamceege.github.io/tooltipster/#positioning */ interface ITooltipPosition { /** determines the position of the tooltip and are relative to the viewport */ coord: { left: number; top: number; }; /** the offset that will be applied between the origin and the tooltip */ distance: number; /** is the side Tooltipster has judged best for your tooltip, according to your requirements */ side: TooltipPositioningSide; /** * the size that your tooltip will have. It is either the natural size of the tooltip, or a size that has been * set by Tooltipster to fit best on screen according to your requirements */ size: { height: number; width: number; }; /** * the location Tooltipster thinks the tooltip should ideally be centered on, and the arrow aiming at. It is * given as the distance from the relevant edge of the viewport (left edge if the side is "top" or "bottom", * top edge if the side is "left" or "right"). The target is usually the middle of the origin, but can be * somewhere else when the origin is actually a portion of text split in several lines. Editing this value * will change the location the arrow is aiming at but will not change the position of the tooltip itself * (use coord for that). */ target: number; } type TooltipPositioningSide = 'top' | 'bottom' | 'left' | 'right'; type TooltipEventName = 'init' | 'before' | 'ready' | 'after' | 'format' | 'position' | 'close' | 'closing' | 'created' | 'destroy' | 'destroyed' | 'dismissable' | 'geometry' | 'positionTest' | 'positionTested' | 'reposition' | 'repositioned' | 'scroll' | 'start' | 'startcancel' | 'startend' | 'state' | 'updated'; /** * Tooltipster tooltip instance object. */ export interface ITooltipsterInstance { /** * Closes the tooltip. When the animation is over, its HTML element is destroyed (definitely removed from the * DOM). The `callback` function argument is optional. */ close(callback?: TooltipsterStandardCallbackFunction): void; /** * Returns a tooltip's current content. If the selector matches multiple origins, only the value of the first * will be returned. */ content(): any; /** * Updates the tooltip's content. * @param value the new content of the tooltip */ content(value: any): ITooltipsterInstance; /** * Closes and destroys the tooltip functionality. */ destroy(): void; /** * Temporarily disables a tooltip from being able to open. */ disable(): void; /** * Returns the HTML element which has been tooltipped. */ elementOrigin(): HTMLElement; /** * Returns the HTML root element of the tooltip if it is open, `null` if it is closed. */ elementTooltip(): HTMLElement | null; /** * If a tooltip was disabled, restores its previous functionality. */ enable(): void; /** * Returns the instance of Tooltipster associated to the tooltip. If the selector matches multiple origins, * only the instance of the first will be returned. */ instance(): ITooltipsterInstance; /** * Handle Tooltipster's `on` event coming from any instance. See http://iamceege.github.io/tooltipster/#events * for a complete description of available events. */ on(eventName: string, callback: (e: JQueryEventObject) => void): ITooltipsterInstance; /** * Handle Tooltipster's `one` event coming from any instance. */ one(eventName: string, callback: (e: JQueryEventObject) => void): ITooltipsterInstance; /** * Handle Tooltipster's `off` event coming from any instance. */ off(eventName: string): ITooltipsterInstance; /** * Trigger a Tooltipster's event coming from any instance. */ triggerHandler(eventName: string): ITooltipsterInstance; /** * Opens the tooltip. The `callback` function argument is optional (see its input signature) and, if provided, * is called when the opening animation has ended */ open(callback?: TooltipsterStandardCallbackFunction): ITooltipsterInstance; /** * Returns the value of an option. */ option(optionName: string): any; /** * Sets the value of an option (for advanced users only; we do not provide support on unexpected results). */ option(optionName: string, optionValue: any): ITooltipsterInstance; /** * Resizes and repositions the tooltip. */ reposition(): ITooltipsterInstance; /** * Returns various information about the tooltip, like whether it is open or not. See * http://iamceege.github.io/tooltipster/#status */ status(): ITooltipStatus; /** * Several plugins may have methods of the same name. To resolve the conflict, use the instance object of the * tooltip and specify the full name of the desired plugin in your calls. */ [pluginName: string]: any; } /** * Tooltipster methods available on a JQuery object */ export interface ITooltipsterJQuery { /** Activates Tooltipster */ (options?: ITooltipsterOptions): JQuery; /** * Closes the tooltip. When the animation is over, its HTML element is destroyed (definitely removed from the * DOM). The `callback` function argument is optional. */ (method: 'close', callback?: TooltipsterStandardCallbackFunction): JQuery; /** * Returns a tooltip's current content. If the selector matches multiple origins, only the value of the first * will be returned. */ (method: 'content'): any; /** * Updates the tooltip's content. * @param value the new content of the tooltip */ (method: 'content', value: string): JQuery; /** * Closes and destroys the tooltip functionality. */ (method: 'destroy'): JQuery; /** * Temporarily disables a tooltip from being able to open. */ (method: 'disable'): JQuery; /** * Returns the HTML element which has been tooltipped. */ (method: 'elementOrigin'): HTMLElement; /** * Returns the HTML root element of the tooltip if it is open, `null` if it is closed. */ (method: 'elementTooltip'): HTMLElement | null; /** * If a tooltip was disabled, restores its previous functionality. */ (method: 'enable'): JQuery; /** * Returns the instance of Tooltipster associated to the tooltip. If the selector matches multiple origins, * only the instance of the first will be returned. */ (method: 'instance'): ITooltipsterInstance; /** * Handle Tooltipster's `on` event coming from any instance. See http://iamceege.github.io/tooltipster/#events * for a complete description of available events. */ (method: 'on', eventName: string, callback: (e: JQueryEventObject) => void): JQuery; /** * Handle Tooltipster's `one` event coming from any instance. */ (method: 'one', eventName: string, callback: (e: JQueryEventObject) => void): JQuery; /** * Handle Tooltipster's `off` event coming from any instance. */ (method: 'off', eventName: string): JQuery; /** * Trigger a Tooltipster's event coming from any instance. */ (method: 'triggerHandler', eventName: string): JQuery; /** * Opens the tooltip. The `callback` function argument is optional (see its input signature) and, if provided, * is called when the opening animation has ended */ (method: 'open', callback?: TooltipsterStandardCallbackFunction): JQuery; /** * Returns the value of an option. */ (method: 'option', optionName: string): any; /** * Sets the value of an option (for advanced users only; we do not provide support on unexpected results). */ (method: 'option', optionName: string, optionValue: any): JQuery; /** * Resizes and repositions the tooltip. */ (method: 'reposition'): JQuery; /** * Returns various information about the tooltip, like whether it is open or not. See * http://iamceege.github.io/tooltipster/#status */ (method: 'status'): ITooltipStatus; } interface ITooltipsterStatic { /** * all instances of all tooltips present in the page are returned */ instances(): ITooltipsterInstance[]; /** * Returns the instances of Tooltipster of all tooltips set on the element(s) matched by the argument. */ instances(selector: string | JQuery): ITooltipsterInstance[]; /** * Returns the instances of Tooltipster of all tooltips set on the element(s) matched by the argument. */ instances(element: HTMLElement): ITooltipsterInstance[]; /** * Returns the instances of Tooltipster which were generated during the last initializing call. */ instancesLatest(): ITooltipsterInstance[]; /** * Handle Tooltipster's `on` event coming from any instance. See http://iamceege.github.io/tooltipster/#events * for a complete description of available events. */ on(eventName: string, callback: (e: ITooltipEvent) => void): ITooltipsterStatic; /** * Handle Tooltipster's `one` event coming from any instance. */ one(eventName: string, callback: (e: ITooltipEvent) => void): ITooltipsterStatic; /** * Handle Tooltipster's `off` event coming from any instance. */ off(eventName: string): ITooltipsterStatic; /** * Trigger a Tooltipster's event coming from any instance. */ triggerHandler(eventName: string): ITooltipsterStatic; /** * Returns an array of all HTML elements in the page which have one or several tooltips initialized. If a selector * is passed, the results will be limited to the descendants of the matched elements. */ origins(selector?: string | JQuery): HTMLElement[]; /** * Changes the default options that will apply to any tooltips created from now on. */ setDefaults(options: ITooltipsterOptions): void; } interface ITooltipEvent { instance: ITooltipsterInstance; origin: HTMLElement; event: JQueryEventObject; } interface ITooltipStatus { /** if the tooltip has been destroyed */ destroyed: boolean, /** if the tooltip is scheduled for destruction (which means that the tooltip is currently closing and may not be reopened) */ destroying: boolean, /** if the tooltip is enabled */ enabled: boolean, /** if the tooltip is open (either appearing, stable or disappearing) */ open: boolean, /** the state equals one of these four values: */ state: 'appearing' | 'stable' | 'disappearing' | 'closed' } } interface JQuery { tooltipster: JQueryTooltipster.ITooltipsterJQuery; } interface JQueryStatic { tooltipster: JQueryTooltipster.ITooltipsterStatic; }
the_stack
import { BotFrameworkAdapter, TurnContext } from 'botbuilder'; import { Choice, ChoicePrompt, ComponentDialog, DialogTurnResult, DialogTurnStatus, FoundChoice, OAuthPrompt, PromptValidatorContext, WaterfallDialog, WaterfallStep, WaterfallStepContext, OAuthPromptSettings, Dialog } from 'botbuilder-dialogs'; import { TokenStatus } from 'botframework-connector'; import { ActionTypes, Activity, ActivityTypes, TokenResponse } from 'botframework-schema'; import { IOAuthConnection } from '../authentication'; import { ResponseManager } from '../responses'; import { TokenEvents } from '../tokenEvents'; import { AuthenticationResponses } from './authenticationResponses'; import { OAuthProviderExtensions } from './oAuthProviderExtensions'; import { IProviderTokenResponse } from './providerTokenResponse'; import { AppCredentials } from 'botframework-connector'; enum DialogIds { providerPrompt = 'ProviderPrompt', firstStepPrompt = 'FirstStep', authPrompt = 'AuthPrompt', } /** * Provides the ability to prompt for which Authentication provider the user wishes to use. */ export class MultiProviderAuthDialog extends ComponentDialog { private static readonly acceptedLocales: string[] = ['en', 'de', 'es', 'fr', 'it', 'zh']; private selectedAuthType: string = ''; private authenticationConnections: IOAuthConnection[]; private responseManager: ResponseManager; private oauthCredentials: AppCredentials | undefined; public constructor( authenticationConnections: IOAuthConnection[], locale: string, promptSettings: OAuthPromptSettings[], oauthCredentials?: AppCredentials ) { super(MultiProviderAuthDialog.name); if (authenticationConnections === undefined) { throw new Error('The value of authenticationConnections cannot be undefined'); } this.authenticationConnections = authenticationConnections; this.oauthCredentials = oauthCredentials; this.responseManager = new ResponseManager( MultiProviderAuthDialog.acceptedLocales, [AuthenticationResponses] ); const firstStep: WaterfallStep[] = [ this.firstStep.bind(this) ]; const authSteps: WaterfallStep[] = [ this.promptForProvider.bind(this), this.promptForAuth.bind(this), this.handleTokenResponse.bind(this) ]; this.addDialog(new WaterfallDialog(DialogIds.firstStepPrompt, firstStep)); if (this.authenticationConnections !== undefined && this.authenticationConnections.length > 0 && this.authenticationConnections.some((c: IOAuthConnection): boolean => c.name !== undefined && c.name.trim().length > 0)) { for (var i = 0; i < this.authenticationConnections.length; ++i) { let connection = this.authenticationConnections[i]; MultiProviderAuthDialog.acceptedLocales.forEach((locale): void => { this.addDialog(this.getLocalizedDialog(locale, connection.name, promptSettings[i])); }); }; this.addDialog(new WaterfallDialog(DialogIds.authPrompt, authSteps)); this.addDialog(new ChoicePrompt(DialogIds.providerPrompt)); } else { throw new Error('There is no authenticationConnections value'); } } private getLocalizedDialog(locale: string, connectionName: string, settings: OAuthPromptSettings): Dialog { const loginButtonActivity: string = this.responseManager.getLocalizedResponse(AuthenticationResponses.loginButton, locale).text; const loginPromptActivity: string = this.responseManager.getLocalizedResponse(AuthenticationResponses.loginPrompt, locale, new Map<string, string>([['authType', connectionName]])).text; settings = settings || { connectionName: connectionName, title: loginButtonActivity, text: loginPromptActivity }; return new OAuthPrompt( connectionName + '_' + locale, settings, this.authPromptValidator.bind(this) ); } // Validators protected async tokenResponseValidator(pc: PromptValidatorContext<Activity>): Promise<boolean> { const activity: Activity | undefined = pc.recognized.value; if (activity !== undefined && ((activity.type === ActivityTypes.Event && activity.name === TokenEvents.tokenResponseEventName) || (activity.type === ActivityTypes.Invoke && activity.name === 'signin/verifyState'))) { return Promise.resolve(true); } return Promise.resolve(false); } private async firstStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> { return await stepContext.beginDialog(DialogIds.authPrompt); } private async promptForProvider(stepContext: WaterfallStepContext): Promise<DialogTurnResult> { if (this.authenticationConnections.length === 1) { const result: string = this.authenticationConnections[0].name + '_' + stepContext.context.activity.locale.split('-')[0]; return await stepContext.next(result); } //PENDING: adapter could not be parsed to IExtendedUserTokenProvider as C# does const adapter: BotFrameworkAdapter = stepContext.context.adapter as BotFrameworkAdapter; if (adapter !== undefined) { const tokenStatusCollection: TokenStatus[] = await adapter.getTokenStatus( stepContext.context, stepContext.context.activity.from.id, undefined, this.oauthCredentials); const matchingProviders: TokenStatus[] = tokenStatusCollection.filter((p: TokenStatus): boolean => { return (p.hasToken || false) && this.authenticationConnections.some((t: IOAuthConnection): boolean => { return t.name === p.connectionName; }); }); if (matchingProviders.length === 1) { const authType: string|undefined = matchingProviders[0].connectionName; return stepContext.next(authType); } if (matchingProviders.length > 1) { const choices: Choice[] = matchingProviders.map((connection: TokenStatus): Choice => { const value: string = connection.connectionName || ''; return { action: { type: ActionTypes.ImBack, title: value, value: value }, value: value }; }); return stepContext.prompt(DialogIds.providerPrompt, { prompt: this.responseManager.getResponse(AuthenticationResponses.configuredAuthProvidersPrompt, stepContext.context.activity.locale as string), choices: choices }); } else { const choices: Choice[] = this.authenticationConnections.map((connection: IOAuthConnection): Choice => { return { action: { type: ActionTypes.ImBack, title: connection.name, value: connection.name }, value: connection.name }; }); return stepContext.prompt(DialogIds.providerPrompt, { prompt: this.responseManager.getResponse(AuthenticationResponses.authProvidersPrompt, stepContext.context.activity.locale as string), choices: choices }); } } throw new Error('The adapter doesn\'t support Token Handling.'); } private async promptForAuth(stepContext: WaterfallStepContext): Promise<DialogTurnResult> { if (typeof stepContext.result === 'string') { this.selectedAuthType = stepContext.result; } else { const choice: FoundChoice = stepContext.result as FoundChoice; if (choice !== undefined) { this.selectedAuthType = choice.value; } } return await stepContext.prompt(this.selectedAuthType, {}); } private async handleTokenResponse(stepContext: WaterfallStepContext): Promise<DialogTurnResult> { const tokenResponse: TokenResponse = stepContext.result as TokenResponse; if (tokenResponse !== undefined && tokenResponse.token) { const result: IProviderTokenResponse = await this.createProviderTokenResponse(stepContext.context, tokenResponse); return await stepContext.endDialog(result); } this.telemetryClient.trackEvent({ name: 'TokenRetrievalFailure' }); return { status: DialogTurnStatus.cancelled }; } private async createProviderTokenResponse(context: TurnContext, tokenResponse: TokenResponse): Promise<IProviderTokenResponse> { const tokens: TokenStatus[] = await this.getTokenStatus(context, context.activity.from.id); const match: TokenStatus|undefined = tokens.find((t: TokenStatus): boolean => t.connectionName === tokenResponse.connectionName); if (!match) { throw new Error('Token not found'); } const response: IProviderTokenResponse = { authenticationProvider: OAuthProviderExtensions.getAuthenticationProvider(match.serviceProviderDisplayName || ''), tokenResponse: tokenResponse }; return Promise.resolve(response); } private async getTokenStatus(context: TurnContext, userId: string, includeFilter?: string): Promise<TokenStatus[]> { if (context === undefined) { throw new Error('"context" undefined'); } if (userId === undefined || userId.trim().length === 0) { throw new Error('"userId" undefined'); } //PENDING: adapter could not be parsed to IExtendedUserTokenProvider as C# does const tokenProvider: BotFrameworkAdapter = context.adapter as BotFrameworkAdapter; if (tokenProvider !== undefined) { return await tokenProvider.getTokenStatus(context, userId, includeFilter, this.oauthCredentials); } else { throw new Error('Adapter does not support IExtendedUserTokenProvider'); } } private async authPromptValidator(promptContext: PromptValidatorContext<TokenResponse>): Promise<boolean> { const token: TokenResponse|undefined = promptContext.recognized.value; if (token !== undefined && token.token !== undefined && token.token.trim().length > 0) { return Promise.resolve(true); } const eventActivity: Activity = promptContext.context.activity; if (eventActivity !== undefined && eventActivity.name === TokenEvents.tokenResponseEventName) { promptContext.recognized.value = eventActivity.value as TokenResponse; return Promise.resolve(true); } this.telemetryClient.trackEvent({ name: 'AuthPromptValidatorAsyncFailure' }); return Promise.resolve(false); } }
the_stack
import { hasScrollbars, mixInto } from '../../util/Utils'; import EventObject from '../event/EventObject'; import InternalEvent from '../event/InternalEvent'; import PanningHandler from './PanningHandler'; import { Graph } from '../Graph'; import Cell from '../cell/datatypes/Cell'; import Rectangle from '../geometry/Rectangle'; import Point from '../geometry/Point'; import SelectionCellsHandler from '../selection/SelectionCellsHandler'; declare module '../Graph' { interface Graph { shiftPreview1: HTMLElement | null; shiftPreview2: HTMLElement | null; useScrollbarsForPanning: boolean; timerAutoScroll: boolean; allowAutoPanning: boolean; panDx: number; panDy: number; isUseScrollbarsForPanning: () => boolean; isTimerAutoScroll: () => boolean; isAllowAutoPanning: () => boolean; getPanDx: () => number; setPanDx: (dx: number) => void; getPanDy: () => number; setPanDy: (dy: number) => void; panGraph: (dx: number, dy: number) => void; scrollCellToVisible: (cell: Cell, center?: boolean) => void; scrollRectToVisible: (rect: Rectangle) => boolean; setPanning: (enabled: boolean) => void; } } type PartialGraph = Pick<Graph, 'getContainer' | 'getView' | 'getPlugin' | 'fireEvent'>; type PartialPanning = Pick< Graph, | 'shiftPreview1' | 'shiftPreview2' | 'useScrollbarsForPanning' | 'timerAutoScroll' | 'allowAutoPanning' | 'panDx' | 'panDy' | 'isUseScrollbarsForPanning' | 'isTimerAutoScroll' | 'isAllowAutoPanning' | 'getPanDx' | 'setPanDx' | 'getPanDy' | 'setPanDy' | 'panGraph' | 'scrollCellToVisible' | 'scrollRectToVisible' | 'setPanning' >; type PartialType = PartialGraph & PartialPanning; // @ts-expect-error The properties of PartialGraph are defined elsewhere. const GraphPanningMixin: PartialType = { shiftPreview1: null, shiftPreview2: null, /** * Specifies if scrollbars should be used for panning in {@link panGraph} if * any scrollbars are available. If scrollbars are enabled in CSS, but no * scrollbars appear because the graph is smaller than the container size, * then no panning occurs if this is `true`. * @default true */ useScrollbarsForPanning: true, isUseScrollbarsForPanning() { return this.useScrollbarsForPanning; }, /** * Specifies if autoscrolling should be carried out via mxPanningManager even * if the container has scrollbars. This disables {@link scrollPointToVisible} and * uses {@link PanningManager} instead. If this is true then {@link autoExtend} is * disabled. It should only be used with a scroll buffer or when scollbars * are visible and scrollable in all directions. * @default false */ timerAutoScroll: false, isTimerAutoScroll() { return this.timerAutoScroll; }, /** * Specifies if panning via {@link panGraph} should be allowed to implement autoscroll * if no scrollbars are available in {@link scrollPointToVisible}. To enable panning * inside the container, near the edge, set {@link PanningManager.border} to a * positive value. * @default false */ allowAutoPanning: false, isAllowAutoPanning() { return this.allowAutoPanning; }, /** * Current horizontal panning value. * @default 0 */ panDx: 0, getPanDx() { return this.panDx; }, setPanDx(dx) { this.panDx = dx; }, /** * Current vertical panning value. * @default 0 */ panDy: 0, getPanDy() { return this.panDy; }, setPanDy(dy) { this.panDy = dy; }, /** * Shifts the graph display by the given amount. This is used to preview * panning operations, use {@link GraphView.setTranslate} to set a persistent * translation of the view. Fires {@link InternalEvent.PAN}. * * @param dx Amount to shift the graph along the x-axis. * @param dy Amount to shift the graph along the y-axis. */ panGraph(dx, dy) { const container = this.getContainer(); if (this.useScrollbarsForPanning && hasScrollbars(container)) { container.scrollLeft = -dx; container.scrollTop = -dy; } else { const canvas = this.getView().getCanvas(); // Puts everything inside the container in a DIV so that it // can be moved without changing the state of the container if (dx === 0 && dy === 0) { canvas.removeAttribute('transform'); if (this.shiftPreview1) { let child = this.shiftPreview1.firstChild; while (child) { const next = child.nextSibling; container.appendChild(child); child = next; } if (this.shiftPreview1.parentNode) { this.shiftPreview1.parentNode.removeChild(this.shiftPreview1); } this.shiftPreview1 = null; container.appendChild(<Node>canvas.parentNode); const shiftPreview2 = <HTMLElement>this.shiftPreview2; child = shiftPreview2.firstChild; while (child) { const next = child.nextSibling; container.appendChild(child); child = next; } if (shiftPreview2.parentNode) { shiftPreview2.parentNode.removeChild(shiftPreview2); } this.shiftPreview2 = null; } } else { canvas.setAttribute('transform', `translate(${dx},${dy})`); if (!this.shiftPreview1) { // Needs two divs for stuff before and after the SVG element this.shiftPreview1 = document.createElement('div'); this.shiftPreview1.style.position = 'absolute'; this.shiftPreview1.style.overflow = 'visible'; this.shiftPreview2 = document.createElement('div'); this.shiftPreview2.style.position = 'absolute'; this.shiftPreview2.style.overflow = 'visible'; let current = this.shiftPreview1; let child = container.firstChild; while (child) { const next = child.nextSibling; // SVG element is moved via transform attribute // @ts-ignore if (child !== canvas.parentNode) { current.appendChild(child); } else { current = this.shiftPreview2; } child = next; } // Inserts elements only if not empty if (this.shiftPreview1.firstChild) { container.insertBefore(this.shiftPreview1, canvas.parentNode); } if (this.shiftPreview2.firstChild) { container.appendChild(this.shiftPreview2); } } this.shiftPreview1.style.left = `${dx}px`; this.shiftPreview1.style.top = `${dy}px`; if (this.shiftPreview2) { this.shiftPreview2.style.left = `${dx}px`; this.shiftPreview2.style.top = `${dy}px`; } } this.panDx = dx; this.panDy = dy; this.fireEvent(new EventObject(InternalEvent.PAN)); } }, /** * Pans the graph so that it shows the given cell. Optionally the cell may * be centered in the container. * * To center a given graph if the {@link container} has no scrollbars, use the following code. * * [code] * var bounds = graph.getGraphBounds(); * graph.view.setTranslate(-bounds.x - (bounds.width - container.clientWidth) / 2, * -bounds.y - (bounds.height - container.clientHeight) / 2); * [/code] * * @param cell {@link mxCell} to be made visible. * @param center Optional boolean flag. Default is `false`. */ scrollCellToVisible(cell, center = false) { const x = -this.getView().translate.x; const y = -this.getView().translate.y; const state = this.getView().getState(cell); if (state) { const bounds = new Rectangle(x + state.x, y + state.y, state.width, state.height); if (center && this.getContainer()) { const w = this.getContainer().clientWidth; const h = this.getContainer().clientHeight; bounds.x = bounds.getCenterX() - w / 2; bounds.width = w; bounds.y = bounds.getCenterY() - h / 2; bounds.height = h; } const tr = new Point(this.getView().translate.x, this.getView().translate.y); if (this.scrollRectToVisible(bounds)) { // Triggers an update via the view's event source const tr2 = new Point(this.getView().translate.x, this.getView().translate.y); this.getView().translate.x = tr.x; this.getView().translate.y = tr.y; this.getView().setTranslate(tr2.x, tr2.y); } } }, /** * Pans the graph so that it shows the given rectangle. * * @param rect {@link mxRectangle} to be made visible. */ scrollRectToVisible(rect) { let isChanged = false; const container = <HTMLElement>this.getContainer(); const w = container.offsetWidth; const h = container.offsetHeight; const widthLimit = Math.min(w, rect.width); const heightLimit = Math.min(h, rect.height); if (hasScrollbars(container)) { rect.x += this.getView().translate.x; rect.y += this.getView().translate.y; let dx = container.scrollLeft - rect.x; const ddx = Math.max(dx - container.scrollLeft, 0); if (dx > 0) { container.scrollLeft -= dx + 2; } else { dx = rect.x + widthLimit - container.scrollLeft - container.clientWidth; if (dx > 0) { container.scrollLeft += dx + 2; } } let dy = container.scrollTop - rect.y; const ddy = Math.max(0, dy - container.scrollTop); if (dy > 0) { container.scrollTop -= dy + 2; } else { dy = rect.y + heightLimit - container.scrollTop - container.clientHeight; if (dy > 0) { container.scrollTop += dy + 2; } } if (!this.useScrollbarsForPanning && (ddx != 0 || ddy != 0)) { this.getView().setTranslate(ddx, ddy); } } else { const x = -this.getView().translate.x; const y = -this.getView().translate.y; const s = this.getView().scale; if (rect.x + widthLimit > x + w) { this.getView().translate.x -= (rect.x + widthLimit - w - x) / s; isChanged = true; } if (rect.y + heightLimit > y + h) { this.getView().translate.y -= (rect.y + heightLimit - h - y) / s; isChanged = true; } if (rect.x < x) { this.getView().translate.x += (x - rect.x) / s; isChanged = true; } if (rect.y < y) { this.getView().translate.y += (y - rect.y) / s; isChanged = true; } if (isChanged) { this.getView().refresh(); const selectionCellsHandler = this.getPlugin( 'SelectionCellsHandler' ) as SelectionCellsHandler; // Repaints selection marker (ticket 18) if (selectionCellsHandler) { selectionCellsHandler.refresh(); } } } return isChanged; }, /***************************************************************************** * Group: Graph behaviour *****************************************************************************/ /** * Specifies if panning should be enabled. This implementation updates * {@link PanningHandler.panningEnabled} in {@link panningHandler}. * * @param enabled Boolean indicating if panning should be enabled. */ setPanning(enabled) { const panningHandler = this.getPlugin('PanningHandler') as PanningHandler; if (panningHandler) panningHandler.panningEnabled = enabled; }, }; mixInto(Graph)(GraphPanningMixin);
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormMailbox_Information { interface tab_MailboxStatusTab_Sections { MailboxStatusTab_section_1: DevKit.Controls.Section; } interface tab_tab_4_Sections { tab_4_section_1: DevKit.Controls.Section; } interface tab_MailboxStatusTab extends DevKit.Controls.ITab { Section: tab_MailboxStatusTab_Sections; } interface tab_tab_4 extends DevKit.Controls.ITab { Section: tab_tab_4_Sections; } interface Tabs { MailboxStatusTab: tab_MailboxStatusTab; tab_4: tab_tab_4; } interface Body { Tab: Tabs; /** Choose the delivery method for the mailbox for appointments, contacts, and tasks. */ ACTDeliveryMethod: DevKit.Controls.OptionSet; /** Status of the Appointments, Contacts, and Tasks. */ ACTStatus: DevKit.Controls.OptionSet; /** Choose whether to allow the email connector to use credentials. */ AllowEmailConnectorToUseCredentials: DevKit.Controls.Boolean; /** Type the email address of the mailbox. */ EmailAddress: DevKit.Controls.String; /** Select the email server profile of the mailbox. */ EmailServerProfile: DevKit.Controls.Lookup; /** Select how incoming email will be delivered to the mailbox. */ IncomingEmailDeliveryMethod: DevKit.Controls.OptionSet; /** Select the status that will be assigned to incoming email messages. */ IncomingEmailStatus: DevKit.Controls.OptionSet; /** Shows the status of approval of the email address by O365 Admin. */ IsEmailAddressApprovedByO365Admin: DevKit.Controls.Boolean; /** Select whether the mailbox is a forward mailbox. */ IsForwardMailbox: DevKit.Controls.Boolean; /** Type the name of the mailbox. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Type the Oauth access token for the mailbox. */ OauthAccessToken: DevKit.Controls.String; /** Select how outgoing email will be sent from the mailbox. */ OutgoingEmailDeliveryMethod: DevKit.Controls.OptionSet; /** Select the status of outgoing email messages. */ OutgoingEmailStatus: DevKit.Controls.OptionSet; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Type the password for the mailbox. */ Password: DevKit.Controls.String; /** Select whether to delete emails from the mailbox after processing. */ ProcessAndDeleteEmails: DevKit.Controls.Boolean; /** Choose the user associated to the mailbox. */ RegardingObjectId: DevKit.Controls.Lookup; /** Date and time when the last email configuration test was completed for a mailbox record. */ TestMailboxAccessCompletedOn: DevKit.Controls.DateTime; /** Type a user name used for mailbox authentication. */ Username: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Shows whether the mailbox is active or inactive. */ StateCode: DevKit.Controls.OptionSet; } } class FormMailbox_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Mailbox_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 Mailbox_Information */ Body: DevKit.FormMailbox_Information.Body; /** The Footer section of form Mailbox_Information */ Footer: DevKit.FormMailbox_Information.Footer; } class MailboxApi { /** * DynamicsCrm.DevKit MailboxApi * @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; /** Choose the delivery method for the mailbox for appointments, contacts, and tasks. */ ACTDeliveryMethod: DevKit.WebApi.OptionSetValue; /** Status of the Appointments, Contacts, and Tasks. */ ACTStatus: DevKit.WebApi.OptionSetValue; /** Choose whether to allow the email connector to use credentials. */ AllowEmailConnectorToUseCredentials: DevKit.WebApi.BooleanValue; /** Mailbox Total Duration in Average */ AverageTotalDuration: DevKit.WebApi.IntegerValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the email address of the mailbox. */ EmailAddress: DevKit.WebApi.StringValue; /** Shows the status of the email address. */ EmailRouterAccessApproval: DevKit.WebApi.OptionSetValue; /** Select the email server profile of the mailbox. */ EmailServerProfile: DevKit.WebApi.LookupValue; /** Indicates whether the mailbox is enabled for Appointments, Contacts, and Tasks. */ EnabledForACT: DevKit.WebApi.BooleanValue; /** Choose whether the mailbox is enabled for receiving email. */ EnabledForIncomingEmail: DevKit.WebApi.BooleanValue; /** Choose whether the mailbox is enabled for sending email. */ EnabledForOutgoingEmail: DevKit.WebApi.BooleanValue; /** The default image for the entity. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Exchange web services endpoint URL for the mailbox. */ EWSURL: DevKit.WebApi.StringValue; /** Date and time when the exchange contacts import was last completed for a mailbox record. */ ExchangeContactsImportCompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Indicates the exchange contacts import status for a mailbox record. */ ExchangeContactsImportStatus: DevKit.WebApi.OptionSetValue; /** Contains the exchange synchronization state in XML format. */ ExchangeSyncStateXml: DevKit.WebApi.StringValue; ExchangeSyncStateXmlFileRef_Name: DevKit.WebApi.StringValueReadonly; /** Holds the hierarchy of folders under inbox in XML format. */ FolderHierarchy: DevKit.WebApi.StringValue; /** For internal use only */ ForcedUnlockCount: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the async host that is processing this mailbox. */ HostId: DevKit.WebApi.StringValueReadonly; /** Select how incoming email will be delivered to the mailbox. */ IncomingEmailDeliveryMethod: DevKit.WebApi.OptionSetValue; /** Select the status that will be assigned to incoming email messages. */ IncomingEmailStatus: DevKit.WebApi.OptionSetValue; /** Set the current organization as the synchronization organization. */ IsACTSyncOrgFlagSet: DevKit.WebApi.BooleanValue; /** Shows the status of approval of the email address by O365 Admin. */ IsEmailAddressApprovedByO365Admin: DevKit.WebApi.BooleanValue; /** Is Exchange Contacts Import Scheduled. */ IsExchangeContactsImportScheduled: DevKit.WebApi.BooleanValueReadonly; /** Select whether the mailbox is a forward mailbox. */ IsForwardMailbox: DevKit.WebApi.BooleanValueReadonly; IsOauthAccessTokenSet: DevKit.WebApi.BooleanValueReadonly; IsOauthRefreshTokenSet: DevKit.WebApi.BooleanValueReadonly; IsPasswordSet: DevKit.WebApi.BooleanValueReadonly; /** Select whether the mailbox corresponds to one for the service account. */ IsServiceAccount: DevKit.WebApi.BooleanValueReadonly; /** For internal use only. */ ItemsFailedForLastSync: DevKit.WebApi.IntegerValue; /** For internal use only. */ ItemsProcessedForLastSync: DevKit.WebApi.IntegerValue; /** For internal use only. */ LastActiveOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows the date and time when the Exchange web services URL was last discovered using the AutoDiscover service. */ LastAutoDiscoveredOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Last Duration for the mailbox */ LastDuration: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ LastMailboxForcedUnlockOccurredOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the last message. */ LastMessageId: DevKit.WebApi.StringValueReadonly; /** Last Successful Sync Time */ LastSuccessfulSyncCompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ LastSyncError: DevKit.WebApi.StringValue; /** For internal use only. */ LastSyncErrorCode: DevKit.WebApi.IntegerValue; /** For internal use only */ LastSyncErrorCount: DevKit.WebApi.IntegerValue; /** For internal use only. */ LastSyncErrorMachineName: DevKit.WebApi.StringValue; /** For internal use only. */ LastSyncErrorOccurredOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Last Sync Start Time */ LastSyncStartedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Identifies the last MessageId that has been processed for tagging in the remote system. */ LastTaggedMessageId: DevKit.WebApi.StringValue; /** Unique identifier of the mailbox. */ MailboxId: DevKit.WebApi.GuidValue; /** For internal use only. */ MailboxProcessingContext: DevKit.WebApi.IntegerValue; /** Last Sync Status for Outgoing, Incoming and ACT as a whole. */ MailboxStatus: DevKit.WebApi.OptionSetValueReadonly; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the name of the mailbox. */ Name: DevKit.WebApi.StringValue; /** The next scheduled ACT sync delay, in seconds, to apply to the mailbox. */ NextScheduledACTSyncInSeconds: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ NoACTCount: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ NoEmailCount: DevKit.WebApi.IntegerValueReadonly; /** Type the Oauth access token for the mailbox. */ OauthAccessToken: DevKit.WebApi.StringValue; /** Type the Oauth refresh token for the mailbox. */ OauthRefreshToken: DevKit.WebApi.StringValue; /** Date and time when the Oauth token will expire */ OauthTokenExpiresOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Date and time when the last office apps deployment was completed for a mailbox record. */ OfficeAppsDeploymentCompleteOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** The Office Apps deployment error. */ OfficeAppsDeploymentError: DevKit.WebApi.StringValueReadonly; /** Indicates if the office apps deployment has been scheduled for a mailbox record. */ OfficeAppsDeploymentScheduled: DevKit.WebApi.BooleanValue; /** Indicates the office apps deployment type for a mailbox record. */ OfficeAppsDeploymentStatus: DevKit.WebApi.OptionSetValue; /** Unique identifier of the organization associated with the record. */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Indicates if the crm org is to be marked as primary syncing org for the mailbox record. */ OrgMarkedAsPrimaryForExchangeSync: DevKit.WebApi.BooleanValue; /** Select how outgoing email will be sent from the mailbox. */ OutgoingEmailDeliveryMethod: DevKit.WebApi.OptionSetValue; /** Select the status of outgoing email messages. */ OutgoingEmailStatus: DevKit.WebApi.OptionSetValue; /** 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; /** Select 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; /** Type the password for the mailbox. */ Password: DevKit.WebApi.StringValue; /** Shows the date and time when processing will begin on this mailbox. */ PostponeMailboxProcessingUntil_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the date and time when the next outlook mail app install will be run for a mailbox record. */ PostponeOfficeAppsDeploymentUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the date and time when the mailbox can start sending emails. */ PostponeSendingUntil_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the date and time when the next email configuration test will be run for a mailbox record. */ PostponeTestEmailConfigurationUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Select whether to delete emails from the mailbox after processing. */ ProcessAndDeleteEmails: DevKit.WebApi.BooleanValue; /** The number of times mailbox has processed */ ProcessedTimes: DevKit.WebApi.IntegerValueReadonly; /** Shows the date and time to start processing email received by the mailbox. */ ProcessEmailReceivedAfter_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Date and time when the processing of the mailbox was last attempted. */ ProcessingLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Information that indicates whether email will be processed for this mailbox */ ProcessingStateCode: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ ReceivingPostponedUntil_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** For internal use only. */ ReceivingPostponedUntilForACT_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** Choose the user associated to the mailbox. */ regardingobjectid_queue: DevKit.WebApi.LookupValueReadonly; /** Choose the user associated to the mailbox. */ regardingobjectid: DevKit.WebApi.LookupValueReadonly; /** Shows whether the mailbox is active or inactive. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the mailbox's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Identifies the timestamp after for which emails should be tagged in the remote system. */ TagEmailsAfter_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the number of times an email configuration test has been performed. */ TestEmailConfigurationRetryCount: DevKit.WebApi.IntegerValue; /** Indicates if the email configuration test has been scheduled for a mailbox record. */ TestEmailConfigurationScheduled: DevKit.WebApi.BooleanValue; /** Date and time when the last email configuration test was completed for a mailbox record. */ TestMailboxAccessCompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Concatenation of transient failure counts of all mailbox operations. */ TransientFailureCount: DevKit.WebApi.IntegerValueReadonly; /** Shows the ID of the Undeliverable folder in the mailbox managed by Microsoft Exchange. */ UndeliverableFolder: DevKit.WebApi.StringValue; /** Type a user name used for mailbox authentication. */ Username: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Indicates if verbose tracing needs to be enabled for this mailbox. */ VerboseLoggingEnabled: DevKit.WebApi.IntegerValue; /** Version number of the mailbox. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Mailbox { enum ACTDeliveryMethod { /** 0 */ Microsoft_Dynamics_365_for_Outlook, /** 2 */ None, /** 1 */ Server_Side_Synchronization } enum ACTStatus { /** 2 */ Failure, /** 0 */ Not_Run, /** 1 */ Success } enum EmailRouterAccessApproval { /** 1 */ Approved, /** 0 */ Empty, /** 2 */ Pending_Approval, /** 3 */ Rejected } enum ExchangeContactsImportStatus { /** 1 */ Imported, /** 2 */ ImportFailed, /** 0 */ NotImported } enum IncomingEmailDeliveryMethod { /** 3 */ Forward_Mailbox, /** 1 */ Microsoft_Dynamics_365_for_Outlook, /** 0 */ None, /** 2 */ Server_Side_Synchronization_or_Email_Router } enum IncomingEmailStatus { /** 2 */ Failure, /** 0 */ Not_Run, /** 1 */ Success } enum MailboxStatus { /** 2 */ Failure, /** 0 */ Not_Run, /** 1 */ Success } enum OfficeAppsDeploymentStatus { /** 1 */ Installed, /** 2 */ InstallFailed, /** 0 */ NotInstalled, /** 3 */ UninstallFailed, /** 4 */ UpgradeRequired } enum OutgoingEmailDeliveryMethod { /** 1 */ Microsoft_Dynamics_365_for_Outlook, /** 0 */ None, /** 2 */ Server_Side_Synchronization_or_Email_Router } enum OutgoingEmailStatus { /** 2 */ Failure, /** 0 */ Not_Run, /** 1 */ Success } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_quotebookingsetup_Information { interface Tabs { } interface Body { /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } } class Formmsdyn_quotebookingsetup_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_quotebookingsetup_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_quotebookingsetup_Information */ Body: DevKit.Formmsdyn_quotebookingsetup_Information.Body; } class msdyn_quotebookingsetupApi { /** * DynamicsCrm.DevKit msdyn_quotebookingsetupApi * @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; /** 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; /** Enable if the system should automatically generate Order Bookings for the Booking Dates of this Booking Setup */ msdyn_autogeneratebooking: DevKit.WebApi.BooleanValue; /** Enable if the system should automatically generate Work Orders for the Booking Dates of this Booking Setup */ msdyn_autogenerateworkorder: DevKit.WebApi.BooleanValue; /** Type a description of this booking setup. */ msdyn_description: DevKit.WebApi.StringValue; msdyn_EstimatedCost: DevKit.WebApi.MoneyValue; /** Value of the Estimated Cost in base currency. */ msdyn_estimatedcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the duration of the booking. */ msdyn_estimatedduration: DevKit.WebApi.IntegerValue; /** The estimated margin for this Quote Booking Setup */ msdyn_EstimatedMargin: DevKit.WebApi.DecimalValue; msdyn_EstimatedMarginPerWO: DevKit.WebApi.DecimalValue; /** Estimated Costs of all Products that are associated to this Quote Booking Setup */ msdyn_EstimatedProductCost: DevKit.WebApi.MoneyValue; /** Value of the EstimatedProductCost in base currency. */ msdyn_estimatedproductcost_Base: DevKit.WebApi.MoneyValueReadonly; /** The sum of estimated revenue of all products that are associated to this quote booking setup */ msdyn_EstimatedProductRevenue: DevKit.WebApi.MoneyValue; /** Value of the EstimatedProductRevenue in base currency. */ msdyn_estimatedproductrevenue_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstimatedRevenue: DevKit.WebApi.MoneyValue; /** Value of the Estimated Revenue in base currency. */ msdyn_estimatedrevenue_Base: DevKit.WebApi.MoneyValueReadonly; /** The Estimated Revenue per Work Order */ msdyn_EstimatedRevenuePerWO: DevKit.WebApi.MoneyValue; /** Value of the EstimatedRevenuePerWO in base currency. */ msdyn_estimatedrevenueperwo_Base: DevKit.WebApi.MoneyValueReadonly; /** The sum of the estimated costs of all quote booking services that are associated to this quote booking setup */ msdyn_EstimatedServiceCost: DevKit.WebApi.MoneyValue; /** Value of the EstimatedServiceCost in base currency. */ msdyn_estimatedservicecost_Base: DevKit.WebApi.MoneyValueReadonly; /** The sum of estimated revenue of all services that are associated to this quote booking setup */ msdyn_EstimatedServiceRevenue: DevKit.WebApi.MoneyValue; /** Value of the EstimatedServiceRevenue in base currency. */ msdyn_estimatedservicerevenue_Base: DevKit.WebApi.MoneyValueReadonly; /** Specify how many days in advance of the Booking Date the system should automatically generate a Work Order */ msdyn_generateworkorderdaysinadvance: DevKit.WebApi.IntegerValue; /** For internal use only. */ msdyn_Internalflags: DevKit.WebApi.StringValue; /** Only used when Work Location is a Facility. Latitude is used when trying to locate nearby facilities. */ msdyn_Latitude: DevKit.WebApi.DoubleValue; /** Only used when Work Location is a Facility. Longitude is used when trying to locate nearby facilities. */ msdyn_Longitude: DevKit.WebApi.DoubleValue; msdyn_Margin: DevKit.WebApi.DecimalValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; msdyn_NumberOfWO: DevKit.WebApi.IntegerValue; /** Shows the flexibility of days after the booking date. */ msdyn_postbookingflexibility: DevKit.WebApi.IntegerValue; /** Shows the date until which Work Order generation can be postponed. Intended for internal use. Manipulating values in this field is not supported and can lead to unexpected system behavior. */ msdyn_postponegenerationuntil_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue; /** Shows the flexibility of days prior to the booking date. */ msdyn_prebookingflexibility: DevKit.WebApi.IntegerValue; /** Preferred Resource to booked */ msdyn_preferredresource: DevKit.WebApi.LookupValue; /** Shows the preferred time to booking. */ msdyn_preferredstarttime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Booking Priority */ msdyn_priority: DevKit.WebApi.LookupValue; /** Quote this Booking Setup relates to */ msdyn_quote: DevKit.WebApi.LookupValue; /** Unique identifier for entity instances */ msdyn_quotebookingsetupId: DevKit.WebApi.GuidValue; /** Relationship between Quote Detail and Quote Booking Setup */ msdyn_quotedetail: DevKit.WebApi.LookupValue; msdyn_QuoteDetailId: DevKit.WebApi.StringValue; /** Stores the booking recurrence settings. */ msdyn_recurrencesettings: DevKit.WebApi.StringValue; /** For internal use only. */ msdyn_revision: DevKit.WebApi.IntegerValue; /** Shows the time window up until when this can be booked. */ msdyn_timewindowend_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the time window from when this can be booked. */ msdyn_timewindowstart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_WorkLocation: DevKit.WebApi.OptionSetValue; /** Shows the work order summary to be set on the work orders generated. */ msdyn_workordersummary: DevKit.WebApi.StringValue; /** Work Order Type to be used on generated Work Orders */ msdyn_workordertype: 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 Quote Booking Setup */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Quote Booking Setup */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** 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_quotebookingsetup { enum msdyn_WorkLocation { /** 690970001 */ Facility, /** 690970002 */ Location_Agnostic, /** 690970000 */ Onsite } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { CrochetValue, ForeignInterface } from "../../../build/crochet"; export default (ffi: ForeignInterface) => { const known_tags = ["h1", "h2", "p", "header", "section", "strong", "em"]; //#region Selections const references = new WeakMap<CrochetValue, string>(); const refered_elements = new WeakMap< CrochetValue, { value: CrochetValue; element: HTMLElement }[] >(); function make_id() { const id = new Uint8Array(16); crypto.getRandomValues(id); return Array.from(id) .map((x) => x.toString(16).padStart(2, "0")) .join(""); } function get_reference(value: CrochetValue) { const ref = references.get(value); if (ref != null) { return ref; } else { const id = make_id(); references.set(value, id); return id; } } function set_reference( ref: CrochetValue, element: HTMLElement, value: CrochetValue ) { element.setAttribute("data-reference", get_reference(ref)); const elements = refered_elements.get(ref) ?? []; elements.push({ value, element }); refered_elements.set(ref, elements); } //#region Utilities interface Deferred<T> { promise: Promise<T>; resolve: (_: T) => void; reject: (_: any) => void; } function defer<T>() { const result: Deferred<T> = { promise: null!, resolve: null!, reject: null!, }; result.promise = new Promise((resolve, reject) => { result.resolve = resolve; result.reject = reject; }); return result; } function sleep(ms: number) { return new Promise<void>((resolve) => { setTimeout(() => resolve(), ms); }); } function role_to_tag(x: string) { if (known_tags.includes(x)) { return x; } else { return "span"; } } //#region Measuring class Rect { constructor( readonly left: number, readonly top: number, readonly width: number, readonly height: number ) {} static from_element_offset(x: HTMLElement) { return new Rect(x.offsetLeft, x.offsetTop, x.offsetWidth, x.offsetHeight); } get bottom() { return this.top + this.height; } get right() { return this.left + this.width; } } function measure(canvas: Canvas, x: HTMLElement) { const old_visibility = x.style.visibility; const old_animation = x.style.animation; x.style.visibility = "hidden"; x.style.animation = "none"; canvas.root.appendChild(x); const dimensions = Rect.from_element_offset(x); canvas.root.removeChild(x); x.style.animation = old_animation; x.style.visibility = old_visibility; return dimensions; } function scroll_to( container: HTMLElement, element: HTMLElement, time: number ) { const deferred = defer<void>(); const st = container.scrollTop; const ot = element.offsetTop; const diff = ot - st; let start: number | null = null; const style: any = container.style; const old_scroll_snap = style.scrollSnapType; style.scrollSnapType = "none"; function step(ts: number) { if (start == null) { start = ts; } const elapsed = ts - start; const done = elapsed / time; const scroll = Math.min(ot, st + diff * done); container.scrollTop = scroll; if (done < 1) { requestAnimationFrame(step); } else { style.scrollSnapType = old_scroll_snap; deferred.resolve(); } } requestAnimationFrame(step); return deferred.promise; } //#region Rendering enum PageStatus { NEW_PAGE, PAGE_RENDERING, OLD_PAGE, } class Canvas { public mark: HTMLElement | null = null; public new_page = PageStatus.NEW_PAGE; constructor(readonly root: HTMLElement) {} } function is_interactive(x: HTMLElement) { if (x.getAttribute("data-interactive") === "true") { return true; } for (const child of x.children) { if (child instanceof HTMLElement && is_interactive(child)) { return true; } } return false; } async function click_to_continue(canvas: Canvas, mark: HTMLElement | null) { const deferred = defer<void>(); canvas.root.setAttribute("data-wait", "true"); canvas.root.addEventListener( "click", (ev) => { ev.stopPropagation(); ev.preventDefault(); canvas.root.removeAttribute("data-wait"); if (mark != null) { canvas.mark = mark; } else { const children = canvas.root.children; canvas.mark = (children.item(children.length - 1) as HTMLElement) ?? null; } deferred.resolve(); }, { once: true } ); return deferred.promise; } async function wait_mark(canvas: Canvas, mark: HTMLElement) { if (canvas.mark == null) { canvas.mark = mark; return; } const dimensions = measure(canvas, mark); if (dimensions.bottom - mark.offsetTop > canvas.root.clientHeight) { await click_to_continue(canvas, mark); } if (is_interactive(mark)) { canvas.mark = null; } } async function animate(x: HTMLElement, frames: Keyframe[], time: number) { const deferred = defer<void>(); const animation = x.animate(frames, time); animation.addEventListener("finish", () => deferred.resolve()); animation.addEventListener("cancel", () => deferred.resolve()); await deferred.promise; } async function animate_appear(x: HTMLElement, time: number) { x.style.opacity = "0"; x.style.top = "-1em"; x.style.position = "relative"; const appear = [ { opacity: 0, top: "-1em" }, { opacity: 1, top: "0px" }, ]; await animate(x, appear, time); x.style.opacity = "1"; x.style.top = "0px"; x.style.position = "relative"; } function get_canvas(x0: CrochetValue) { const x = ffi.unbox(x0); if (x instanceof Canvas) { return x; } else { throw ffi.panic("invalid-type", `Expected a canvas`); } } //#region Foreign functions ffi.defun("html.empty", () => { const element = document.createElement("span"); element.className = "novella-element novella-empty"; return ffi.box(element); }); ffi.defun("html.element", (attrs0, children0) => { const attrs = ffi.record_to_map(attrs0); const children = ffi.list_to_array(children0); const element = document.createElement("span"); for (const [k, v] of attrs.entries()) { element.setAttribute(k, ffi.text_to_string(v)); } for (const x of children) { element.appendChild(ffi.unbox(x) as HTMLElement); } element.classList.add("novella-element"); return ffi.box(element); }); ffi.defun("html.text", (x) => { const element = document.createElement("span"); element.appendChild(document.createTextNode(ffi.text_to_string(x))); element.className = "novella-text"; return ffi.box(element); }); ffi.defun("html.role", (role0, child) => { const role = ffi.text_to_string(role0); const tag = role_to_tag(role); const element = document.createElement(tag); element.setAttribute("data-role", role); element.className = "novella-element"; element.appendChild(ffi.unbox(child) as HTMLElement); return ffi.box(element); }); ffi.defmachine("html.show", function* (canvas0, element0) { const canvas = get_canvas(canvas0); const element = ffi.unbox(element0) as HTMLElement; if (canvas.new_page === PageStatus.NEW_PAGE) { canvas.new_page = PageStatus.PAGE_RENDERING; canvas.mark = element; const old_opacity = element.style.opacity; element.style.opacity = "0"; canvas.root.appendChild(element); yield ffi.await( scroll_to(canvas.root, element, 300).then((_) => ffi.nothing) ); element.style.opacity = old_opacity; element.classList.add("novella-appear"); } else { canvas.root.appendChild(element); element.classList.add("novella-appear"); } return ffi.nothing; }); ffi.defmachine("html.wait", function* (canvas0) { const canvas = get_canvas(canvas0); yield ffi.await(click_to_continue(canvas, null).then((_) => ffi.nothing)); canvas.new_page = PageStatus.NEW_PAGE; return ffi.nothing; }); ffi.defun("html.make-canvas", (element) => { return ffi.box(new Canvas(ffi.unbox(element) as HTMLElement)); }); ffi.defun("html.button", (element0, ref, value) => { const element = ffi.unbox(element0) as HTMLElement; const button = document.createElement("button"); button.className = "novella-element novella-button"; button.setAttribute("data-interactive", "true"); button.appendChild(element); set_reference(ref, button, value); return ffi.box(button); }); ffi.defmachine("html.wait-selection", function* (canvas0, ref) { const canvas = get_canvas(canvas0); const deferred = defer<CrochetValue>(); const elements = refered_elements.get(ref); if (elements == null) { throw ffi.panic( "no-refered-elements", `The reference ${ffi.to_debug_string( ref )} does not have any associated novella elements.` ); } let listeners: { element: HTMLElement; listener: (_: MouseEvent) => void; }[] = []; for (const { value, element } of elements) { const listener = async (ev: MouseEvent) => { ev.preventDefault(); ev.stopPropagation(); for (const x of elements) { if (x.element !== element) { x.element.setAttribute("data-selected", "false"); } } for (const { element, listener } of listeners) { element.removeEventListener("click", listener); } element.setAttribute("data-selected", "true"); await sleep(300); deferred.resolve(value); }; listeners.push({ element, listener }); element.addEventListener("click", listener, { once: true }); } const result = yield ffi.await(deferred.promise); canvas.new_page = PageStatus.NEW_PAGE; return result; }); };
the_stack
import { FASTElement } from "@microsoft/fast-element"; import { RenderCommand } from "./commands.js"; import { RouterConfiguration } from "./configuration.js"; import { NavigationContributor } from "./contributors.js"; import { LinkHandler } from "./links.js"; import { NavigationMessage, NavigationQueue } from "./navigation.js"; import { NavigationPhase } from "./phases.js"; import { RecognizedRoute } from "./recognizer.js"; import { childRouteParameter } from "./routes.js"; import { Layout, RouterExecutionContext, RouteView, Transition } from "./view.js"; /** * @alpha */ export interface RenderOperation { commit(): Promise<void>; rollback(): Promise<void>; } /** * @alpha */ export interface Router<TSettings = any> { readonly level: number; readonly parent: Router | null; readonly route: RecognizedRoute | null; config: RouterConfiguration | null; connect(): void; disconnect(): void; shouldRender(route: RecognizedRoute<TSettings>): boolean; beginRender( route: RecognizedRoute<TSettings>, command: RenderCommand ): Promise<RenderOperation>; addContributor(contributor: NavigationContributor): void; removeContributor(contributor: NavigationContributor): void; } const routerProperty = "$router"; // TODO: remove this from here and from fast-foundation // TODO: move this to fast-element so router and foundation can both use it function composedParent<T extends HTMLElement>(element: T): HTMLElement | null { const parentNode = element.parentElement; if (parentNode) { return parentNode; } else { const rootNode = element.getRootNode(); if ((rootNode as ShadowRoot).host instanceof HTMLElement) { // this is shadow-root return (rootNode as ShadowRoot).host as HTMLElement; } } return null; } function findParentRouterForElement(element: HTMLElement) { let parent: HTMLElement | null = element; while ((parent = composedParent(parent))) { if (routerProperty in parent) { return parent[routerProperty]; } } return null; } /** * @alpha */ export interface RouterElement extends HTMLElement { readonly [routerProperty]: Router; config: RouterConfiguration | null; connectedCallback(); disconnectedCallback(); } /** * @alpha */ export const Router = Object.freeze({ getOrCreateFor(element: HTMLElement) { const router: Router = element[routerProperty]; if (router !== void 0) { return router; } return (element[routerProperty] = new DefaultRouter(element)); }, find(element: HTMLElement): Router | null { return element[routerProperty] || findParentRouterForElement(element); }, from<TBase extends typeof HTMLElement>( BaseType: TBase ): { new (): InstanceType<TBase> & RouterElement } { class RouterBase extends (BaseType as any) { public readonly [routerProperty]!: Router; public get config(): RouterConfiguration { return this[routerProperty].config!; } public set config(value: RouterConfiguration) { this[routerProperty].config = value; } constructor() { super(); Router.getOrCreateFor(this as any); } } const proto = RouterBase.prototype; if ("connectedCallback" in proto) { const original = proto.connectedCallback; proto.connectedCallback = function () { original.call(this); this[routerProperty].connect(); }; } else { proto.connectedCallback = function () { this[routerProperty].connect(); }; } if ("disconnectedCallback" in proto) { const original = proto.disconnectedCallback; proto.disconnectedCallback = function () { original.call(this); this[routerProperty].disconnect(); }; } else { proto.disconnectedCallback = function () { this[routerProperty].disconnect(); }; } return RouterBase as any; }, }); /** * @alpha */ export function isFASTElementHost(host: HTMLElement): host is HTMLElement & FASTElement { return host instanceof FASTElement; } /** * @alpha */ export class DefaultRouter implements Router { private parentRouter: Router | null | undefined = void 0; private contributors = new Set<NavigationContributor>(); private navigationQueue: NavigationQueue | null = null; private linkHandler: LinkHandler | null = null; private newView: RouteView | null = null; private newRoute: RecognizedRoute | null = null; private childCommandContributor: NavigationContributor | null = null; private childRoute: RecognizedRoute | null = null; private isConnected = false; private routerConfig: RouterConfiguration | null = null; private view: RouteView | null = null; public route: RecognizedRoute | null = null; public constructor(public readonly host: HTMLElement) { host[routerProperty] = this; } public get config(): RouterConfiguration | null { return this.routerConfig; } public set config(value: RouterConfiguration | null) { this.routerConfig = value; this.tryConnect(); } public get parent() { if (this.parentRouter === void 0) { if (!this.isConnected) { return null; } this.parentRouter = findParentRouterForElement(this.host); } return this.parentRouter || null; } public get level() { if (this.parent === null) { return 0; } return this.parent.level + 1; } public shouldRender(route: RecognizedRoute): boolean { if (this.route && this.route.endpoint.path === route.endpoint.path) { const newParams = route?.allParams; const oldParams = this.route?.allParams; if (JSON.stringify(oldParams) === JSON.stringify(newParams)) { return false; } } return true; } public async beginRender(route: RecognizedRoute, command: RenderCommand) { this.newRoute = route; this.newView = await command.createView(); this.newView.bind(route.allTypedParams, RouterExecutionContext.create(this)); this.newView.appendTo(this.host); await command.transition.begin(this.host, this.view, this.newView); return { commit: this.renderOperationCommit.bind( this, command.layout, command.transition ), rollback: this.renderOperationRollback.bind(this, command.transition), }; } public connect() { this.isConnected = true; this.tryConnect(); } public disconnect() { if (this.parent === null) { if (this.navigationQueue !== null) { this.navigationQueue.disconnect(); this.navigationQueue = null; } if (this.linkHandler !== null) { this.linkHandler.disconnect(); this.linkHandler = null; } } else { this.parent!.removeContributor(this as any); } this.isConnected = false; this.parentRouter = void 0; } public addContributor(contributor: NavigationContributor): void { this.contributors.add(contributor); } public removeContributor(contributor: NavigationContributor): void { this.contributors.delete(contributor); } private tryConnect() { if (this.config === null || !this.isConnected) { return; } if (this.parent === null) { if (this.navigationQueue !== null) { this.navigationQueue.disconnect(); } this.navigationQueue = this.config!.createNavigationQueue(); this.navigationQueue.connect(); this.navigationQueue.receive().then(this.onNavigationMessage); if (this.linkHandler !== null) { this.linkHandler.disconnect(); } this.linkHandler = this.config!.createLinkHandler(); this.linkHandler.connect(); } else { this.config.parent = this.parent.config; this.parent!.addContributor(this as any); } } private onNavigationMessage = async (message: NavigationMessage) => { const process = this.config!.createNavigationProcess(); await process.run(this, message); this.navigationQueue!.receive().then(this.onNavigationMessage); }; private async renderOperationCommit(layout: Layout, transition: Transition) { await layout.beforeCommit(this.host); await transition.commit(this.host, this.view, this.newView!); await layout.afterCommit(this.host); if (this.view !== null) { this.view.dispose(); } this.route = this.newRoute; this.view = this.newView; this.newRoute = null; this.newView = null; } private async renderOperationRollback(transition: Transition) { if (this.newView !== null) { await transition.rollback(this.host, this.view, this.newView); this.newView.dispose(); this.newRoute = null; this.newView = null; } } private async navigate(phase: NavigationPhase) { await this.tunnel(phase); } private async leave(phase: NavigationPhase) { await this.tunnel(phase); if (!phase.canceled) { const contributors = this.contributors; this.contributors = new Set(); phase.onCancel(() => (this.contributors = contributors)); } } private async construct(phase: NavigationPhase) { if (this.parent !== null) { const rest = phase.route.allParams[childRouteParameter] || ""; const match = await this.config!.recognizeRoute(rest); if (match === null) { const events = this.config!.createEventSink(); events.onUnhandledNavigationMessage(this, new NavigationMessage(rest)); phase.cancel(); return; } this.childRoute = match.route; this.childCommandContributor = await match.command.createContributor( this, match.route ); } await this.tunnel(phase); } private async enter(phase: NavigationPhase) { await this.tunnel(phase); } private async commit(phase: NavigationPhase) { await this.tunnel(phase); } private async tunnel(phase: NavigationPhase) { const route = this.childRoute; const contributor = this.childCommandContributor; if (route && contributor) { await phase.evaluateContributor(contributor, route, this); } if (phase.canceled) { return; } const potentialContributors = [ ...this.config!.findContributors(phase.name), ...Array.from(this.contributors), ]; for (const potential of potentialContributors) { await phase.evaluateContributor(potential, void 0, this); if (phase.canceled) { return; } } } }
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { XTreeComponent } from './tree.component'; import { Component, DebugElement, Injectable, ChangeDetectorRef, ViewChild } from '@angular/core'; import { By } from '@angular/platform-browser'; import { XTreeModule } from '@ng-nest/ui/tree'; import { XTreePrefix, XTreeNode, XTreeAction } from './tree.property'; import { XLayoutModule } from '@ng-nest/ui/layout'; import { Observable } from 'rxjs'; import { XButtonModule } from '@ng-nest/ui/button'; import { XLinkModule } from '@ng-nest/ui/link'; import { XFormModule, XFormRow } from '@ng-nest/ui/form'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormGroup } from '@angular/forms'; import { XRepositoryService, XHttpService, guid } from '@ng-nest/ui/core'; import { map } from 'rxjs/operators'; import { XMessageModule, XMessageService } from '@ng-nest/ui/message'; import { XThemeModule } from '@ng-nest/ui/theme'; describe(XTreePrefix, () => { beforeEach((() => { TestBed.configureTestingModule({ imports: [ BrowserAnimationsModule, XThemeModule, XTreeModule, XLayoutModule, XButtonModule, XLinkModule, XFormModule, XLinkModule, XMessageModule ], declarations: [ TestXTreeComponent, TestXTreeLazyComponent, TestXTreeCheckedComponent, TestXTreeDiabledComponent, TestXTreeCustomComponent, TestXTreeEventComponent, TestXTreeOperationComponent ] }).compileComponents(); })); describe(`default.`, () => { let fixture: ComponentFixture<TestXTreeComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); describe(`lazy.`, () => { let fixture: ComponentFixture<TestXTreeLazyComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeLazyComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); describe(`checked.`, () => { let fixture: ComponentFixture<TestXTreeCheckedComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeCheckedComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); describe(`disabled.`, () => { let fixture: ComponentFixture<TestXTreeDiabledComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeDiabledComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); describe(`custom.`, () => { let fixture: ComponentFixture<TestXTreeCustomComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeCustomComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); describe(`event.`, () => { let fixture: ComponentFixture<TestXTreeEventComponent>; let tree: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestXTreeEventComponent); fixture.detectChanges(); tree = fixture.debugElement.query(By.directive(XTreeComponent)); }); it('should create.', () => { expect(tree).toBeDefined(); }); }); // describe(`operation.`, () => { // let fixture: ComponentFixture<TestXTreeOperationComponent>; // let tree: DebugElement; // beforeEach(() => { // fixture = TestBed.createComponent(TestXTreeOperationComponent); // fixture.detectChanges(); // tree = fixture.debugElement.query(By.directive(XTreeComponent)); // }); // it('should create.', () => { // expect(tree).toBeDefined(); // }); // }); }); @Injectable() class TreeServiceTest { data: XTreeNode[] = [ { id: 1, label: '一级 1', nowrap: false, alignItems: 'start' }, { id: 2, label: '一级 2', height: 3 }, { id: 3, label: '一级 3' }, { id: 5, label: '二级 1-1', pid: 1 }, { id: 6, label: '二级 1-2', pid: 1 }, { id: 7, label: '二级 1-3', pid: 1 }, { id: 8, label: '二级 1-4', pid: 1, disabled: true }, { id: 9, label: '二级 2-1', pid: 2 }, { id: 10, label: '二级 2-2', pid: 2 }, { id: 11, label: '二级 2-3', pid: 2 }, { id: 12, label: '二级 2-4', pid: 2 }, { id: 13, label: '二级 3-1', pid: 3 }, { id: 14, label: '二级 3-2', pid: 3 }, { id: 15, label: '二级 3-3', pid: 3, disabled: true }, { id: 16, label: '二级 3-4', pid: 3 }, { id: 21, label: '三级 1-1-1', pid: 5 }, { id: 22, label: '三级 1-1-2', pid: 5 }, { id: 23, label: '三级 1-1-3', pid: 5 }, { id: 24, label: '三级 1-1-4', pid: 5 } ]; getTreeList = (pid = undefined): Observable<XTreeNode[]> => { return new Observable((x) => { let result = this.data .filter((y) => y.pid === pid) .map((x) => { x.leaf = this.data.find((y) => y.pid === x.id) ? true : false; return x; }); setTimeout(() => { x.next(result); x.complete(); }, 500); }); }; } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <x-tree [data]="service.data"> </x-tree> </x-col> <x-col span="8"> <x-tree [data]="service.data" nodeOpen> </x-tree> </x-col> <x-col span="8"> <x-tree [data]="service.data" checkbox> </x-tree> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeComponent { constructor(public service: TreeServiceTest) {} } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <x-tree [data]="service.getTreeList" lazy> </x-tree> </x-col> <x-col span="8"> <x-tree [data]="service.getTreeList" checkbox lazy> </x-tree> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeLazyComponent { constructor(public service: TreeServiceTest) {} } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <x-tree [data]="service.data" [expanded]="[1, 3]" [checked]="[8, 15, 18]" checkbox> </x-tree> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeCheckedComponent { constructor(public service: TreeServiceTest) {} } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <x-tree [data]="service.data" [expanded]="[1, 3]" [checked]="[8, 15, 18]" checkbox> </x-tree> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeDiabledComponent { constructor(public service: TreeServiceTest) {} } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="12"> <x-tree [data]="service.data" checkbox [labelTpl]="labelTpl"> </x-tree> <ng-template #labelTpl let-node="$node"> <div class="custom-label"> <span>{{ node.label }}</span> <span class="custom-links"> <x-link type="primary">新增</x-link> <x-link type="primary">修改</x-link> <x-link type="primary">删除</x-link> </span> </div> </ng-template> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } .custom-label { display: flex; align-items: center; } .custom-links { margin-left: 1rem; } .custom-links x-link:not(:first-child) { margin-left: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeCustomComponent { constructor(public service: TreeServiceTest) {} } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <ul class="operations"> <li>当前激活的节点:{{ activatedNode?.label }}</li> <li><x-button (click)="setCheckedKeys([9, 11, 21, 23])">通过 Key 值设置选中的节点</x-button></li> <li><x-button (click)="getCheckedKeys()">获取选中的节点的 Key 值</x-button></li> <li> <x-button (click)="setExpandedAll()">{{ expandedAll ? '全部收起' : '全部展开' }}</x-button> </li> <li>{{ content | json }}</li> </ul> </x-col> <x-col span="8"> <x-tree #treeCom checkbox [data]="service.data" [checked]="[15, 8]" (activatedChange)="activatedChange($event)" [expandedAll]="expandedAll" > </x-tree> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } .operations > li:not(:first-child) { margin-top: 1rem; } ` ], providers: [TreeServiceTest] }) class TestXTreeEventComponent { @ViewChild('treeCom', { static: true }) treeCom!: XTreeComponent; activatedNode!: XTreeNode; selectedNodes: XTreeNode[] = []; expandedAll: boolean = true; content: any; constructor(public service: TreeServiceTest, private cdr: ChangeDetectorRef) {} activatedChange(node: XTreeNode) { this.activatedNode = node; this.cdr.detectChanges(); } getCheckedKeys() { this.content = this.treeCom.getCheckedKeys(); this.cdr.detectChanges(); } setCheckedKeys(keys = []) { this.treeCom.setCheckedKeys(keys); } setExpandedAll() { this.expandedAll = !this.expandedAll; this.cdr.detectChanges(); } } @Injectable() class OrganizationService extends XRepositoryService<Organization> { constructor(public override http: XHttpService) { super(http, { api: 'http://localhost:3000/', controller: { name: 'organization' } }); } } interface Organization extends XTreeNode { label?: string; type?: string; icon?: string; pid?: string; path?: string; } @Component({ template: ` <x-theme showDark></x-theme> <x-row space="1"> <x-col span="8"> <x-button (click)="action('add-root', selected)">添加根节点</x-button> <x-tree #treeCom [data]="data" expandedLevel="0" [activatedId]="activatedId" [nodeHeight]="1.875" [actions]="actions" (activatedChange)="action('info', $event)" > </x-tree> </x-col> <x-col span="8"> <x-form [formGroup]="formGroup" [controls]="controls" [disabled]="disabled" direction="row" labelSuffix=":" labelWidth="6rem" width="20rem" labelAlign="end" span="24" space="2" ></x-form> <div [style.margin-top.rem]="2" [style.padding-left]="'6rem'"> <x-buttons [space]="1"> <x-button type="primary" (click)="!formGroup.invalid && !disabled && action('save', selected)" [disabled]="formGroup.invalid || disabled" > 确 认 </x-button> <x-button (click)="action('cancel', selected)">取 消</x-button> </x-buttons> </div> </x-col> </x-row> `, styles: [ ` :host { background-color: var(--x-background); padding: 1rem; border: 0.0625rem solid var(--x-border); } .row:not(:first-child) { margin-top: 1rem; } .operations > li:not(:first-child) { margin-top: 1rem; } ` ], providers: [OrganizationService] }) class TestXTreeOperationComponent { @ViewChild('treeCom') treeCom!: XTreeComponent; formGroup = new FormGroup({}); get disabled() { return !['edit', 'add', 'add-root'].includes(this.type); } type = 'info'; selected!: Organization; activatedId!: string; data = () => this.service.getList(1, Number.MAX_SAFE_INTEGER).pipe(map((x) => x.list)); actions: XTreeAction[] = [ { id: 'add', label: '新增', icon: 'fto-plus-square', handler: (node: Organization) => { this.action('add', node); } }, { id: 'edit', label: '修改', icon: 'fto-edit', handler: (node: Organization) => { this.action('edit', node); } }, { id: 'delete', label: '删除', icon: 'fto-trash-2', handler: (node: Organization) => { this.action('delete', node); } } ]; controls: XFormRow[] = [ { controls: [ { control: 'input', id: 'label', label: '名称', required: true }, { control: 'input', id: 'icon', label: '图标' }, { control: 'select', id: 'type', label: '类型', data: [ { id: 'group', label: '事业部' }, { id: 'subsidiary', label: '子公司' }, { id: 'department', label: '部门' } ], value: 'department' } ] }, { hidden: true, controls: [ { control: 'input', id: 'id' }, { control: 'input', id: 'pid' } ] } ]; constructor(private service: OrganizationService, private message: XMessageService, private cdr: ChangeDetectorRef) {} action(type: string, node: Organization) { switch (type) { case 'info': this.type = type; this.selected = node; this.service.get(node?.id).subscribe((x) => { this.formGroup.patchValue(x); this.cdr.detectChanges(); }); break; case 'add': this.type = type; this.selected = node; this.formGroup.reset(); this.formGroup.patchValue({ id: guid(), pid: node.id, type: 'department' }); this.cdr.detectChanges(); break; case 'add-root': this.type = type; this.formGroup.reset(); this.formGroup.patchValue({ id: guid(), pid: null, type: '' }); this.cdr.detectChanges(); break; case 'edit': this.type = type; this.service.get(node?.id).subscribe((x) => { this.formGroup.patchValue(x); this.cdr.detectChanges(); }); break; case 'delete': this.service.delete(node.id).subscribe(() => { this.treeCom.removeNode(node); this.formGroup.reset(); this.message.success('删除成功!'); }); break; case 'save': if (this.type === 'add' || this.type === 'add-root') { this.service.post(this.formGroup.value).subscribe((x) => { this.type = 'info'; this.treeCom.addNode(x); this.cdr.detectChanges(); this.message.success('新增成功!'); }); } else if (this.type === 'edit') { this.service.put(this.formGroup.value).subscribe(() => { this.type = 'info'; this.treeCom.updateNode(node, this.formGroup.value); this.cdr.detectChanges(); this.message.success('修改成功!'); }); } break; case 'cancel': break; } } }
the_stack
import { Side, Snapshot } from '../Snapshot'; import { Change, ChangeType, placeFromStablePlace, StablePlace, StableRange, validateStablePlace, validateStableRange, } from '../default-edits'; import { assert, assertNotUndefined, fail } from '../Common'; import { EditValidationResult } from '../Checkout'; import { NodeId } from '../Identifiers'; import { ReconciliationPath } from '../ReconciliationPath'; import { AnchoredChange, NodeAnchor, PlaceAnchor, PlaceAnchorSemanticsChoice, RangeAnchor, RelativePlaceAnchor, } from './PersistedTypes'; /** * A change and the snapshots that precede and succeed it. */ export interface EvaluatedChange<TChange> { readonly change: TChange; /** * The snapshot before the change was applied. */ readonly before: Snapshot; /** * The snapshot after the change was applied. */ readonly after: Snapshot; } /** * Object that includes a function for resolving node anchors. */ export interface HasNodeResolver { nodeResolver: (node: NodeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange>) => NodeId | undefined; } /** * Object that includes a function for resolving place anchors. */ export interface HasPlaceResolver { placeResolver: ( range: PlaceAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange> ) => StablePlace | undefined; } /** * Object that includes a function for resolving range anchors. */ export interface HasRangeResolver { rangeResolver: ( range: RangeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange> ) => StableRange | undefined; } /** * Object that includes a function for validating places. */ export interface HasPlaceValidator { placeValidator: (snapshot: Snapshot, place: StablePlace) => EditValidationResult; } /** * Reconciliates a given `change` in the face of concurrent edits described in a `ReconciliationPath`. * @param change - The anchor to reconciliate. * @param before - The state to which the `change` would be applied to. * @param path - The reconciliation path for the `change`. * @returns A `Change` that satisfies the same semantics of the given `change` but whose tree locations are valid in the `before` snapshot. * Undefined if no such change can be produced. * @internal */ export function resolveChangeAnchors( change: AnchoredChange, before: Snapshot, path: ReconciliationPath<AnchoredChange> ): Change | undefined; /** * For testing purposes only. * @internal */ export function resolveChangeAnchors( change: AnchoredChange, before: Snapshot, path: ReconciliationPath<AnchoredChange>, dependencies?: HasNodeResolver & HasPlaceResolver & HasRangeResolver ): Change | undefined; export function resolveChangeAnchors( change: AnchoredChange, before: Snapshot, path: ReconciliationPath<AnchoredChange>, { nodeResolver, placeResolver, rangeResolver }: HasNodeResolver & HasPlaceResolver & HasRangeResolver = { nodeResolver: resolveNodeAnchor, placeResolver: resolvePlaceAnchor, rangeResolver: resolveRangeAnchor, } ): Change | undefined { switch (change.type) { case ChangeType.Build: return change; case ChangeType.Insert: { const destination = placeResolver(change.destination, before, path); return destination !== undefined ? { ...change, destination } : undefined; } case ChangeType.Detach: { const source = rangeResolver(change.source, before, path); return source !== undefined ? { ...change, source } : undefined; } case ChangeType.Constraint: { const toConstrain = rangeResolver(change.toConstrain, before, path); return toConstrain !== undefined ? { ...change, toConstrain } : undefined; } case ChangeType.SetValue: { const nodeToModify = nodeResolver(change.nodeToModify, before, path); return nodeToModify !== undefined ? { ...change, nodeToModify } : undefined; } default: return fail('Attempted to reconciliate unsupported change'); } } /** * Resolves a given `node` anchor in the face of a `ReconciliationPath`. * @param node - The anchor to resolve. * @param before - The state to which the change that the `node` anchor should be applied to. * @param path - The reconciliation path for the change that the `node` is part of. * @returns A matching `NodeId` that is valid in the snapshot at the end of the `path`. Undefined if no such node exists. * @internal */ export function resolveNodeAnchor( node: NodeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange> ): NodeId | undefined { return before.hasNode(node) ? node : undefined; } /** * Resolves a given `range` anchor in the face of a `ReconciliationPath`. * @param range - The anchor to resolve. * @param before - The state to which the change that the `range` anchor should be applied to. * @param path - The reconciliation path for the change that the `range` is part of. * @returns A matching `StableRange` that is valid in the snapshot at the end of the `path`. Undefined if no such valid range exists. * @internal */ export function resolveRangeAnchor( range: RangeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange> ): StableRange | undefined; /** * For testing purposes only. * @internal */ export function resolveRangeAnchor( range: RangeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange>, dependencies?: HasPlaceResolver & { rangeValidator: (snapshot: Snapshot, range: StableRange) => EditValidationResult; } ): StableRange | undefined; export function resolveRangeAnchor( range: RangeAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange>, { placeResolver, rangeValidator, }: HasPlaceResolver & { rangeValidator: (snapshot: Snapshot, range: StableRange) => EditValidationResult; } = { placeResolver: resolvePlaceAnchor, rangeValidator: validateStableRange, } ): StableRange | undefined { const start = placeResolver(range.start, before, path); if (start !== undefined) { const end = placeResolver(range.end, before, path); if (end !== undefined) { const resolvedRange = { start, end, }; return rangeValidator(before, resolvedRange) === EditValidationResult.Valid ? resolvedRange : undefined; } } return undefined; } /** * Resolves a given `place` anchor in the face of a `ReconciliationPath`. * @param place - The anchor to resolve. * @param before - The state to which the change that the `place` anchor should be applied to. * @param path - The reconciliation path for the change that the `place` is part of. * @returns A matching `StablePlace` that is valid in the snapshot at the end of the `path`. Undefined if no such valid place exists. * @internal */ export function resolvePlaceAnchor( place: PlaceAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange> ): StablePlace | undefined; /** * For testing purposes only. * @internal */ export function resolvePlaceAnchor( place: PlaceAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange>, dependencies?: HasPlaceValidator & { placeUpdatorForPath: ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ) => PlaceAnchor | undefined; } ): StablePlace | undefined; export function resolvePlaceAnchor( place: PlaceAnchor, before: Snapshot, path: ReconciliationPath<AnchoredChange>, { placeValidator, placeUpdatorForPath, }: HasPlaceValidator & { placeUpdatorForPath: ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ) => PlaceAnchor | undefined; } = { placeValidator: validateStablePlace, placeUpdatorForPath: updateRelativePlaceAnchorForPath, } ): StablePlace | undefined { let newPlace: PlaceAnchor | undefined = place; while (newPlace !== undefined && placeValidator(before, newPlace) !== EditValidationResult.Valid) { switch (newPlace.semantics) { case PlaceAnchorSemanticsChoice.RelativeToNode: { newPlace = placeUpdatorForPath(newPlace as RelativePlaceAnchor, path); break; } case PlaceAnchorSemanticsChoice.BoundToNode: case undefined: // There's nothing we can do to fix this place newPlace = undefined; break; default: fail('Unsupported choice of PlaceAnchorSemanticsChoice'); } } return newPlace; } /** * Updates a given `place` anchor in the face of a `ReconciliationPath` that violates its semantics. * @param place - The anchor to update. Assumed to be invalid after the latest change. * @param path - The sequence of edits that violates the anchor's semantics. * @returns A place anchor whose semantics are inline with the given `place`, and valid after the most recent change that made it invalid. * Undefined if those semantics cannot be preserved. * @internal */ export function updateRelativePlaceAnchorForPath( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ): PlaceAnchor | undefined; /** * For testing purposes only. * @internal */ export function updateRelativePlaceAnchorForPath( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange>, dependencies?: { lastOffendingChangeFinder: ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ) => EvaluatedChange<AnchoredChange> | undefined; placeUpdatorForChange: ( place: RelativePlaceAnchor, change: EvaluatedChange<AnchoredChange> ) => PlaceAnchor | undefined; } ): PlaceAnchor | undefined; export function updateRelativePlaceAnchorForPath( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange>, { lastOffendingChangeFinder, placeUpdatorForChange, }: { lastOffendingChangeFinder: ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ) => EvaluatedChange<AnchoredChange> | undefined; placeUpdatorForChange: ( place: RelativePlaceAnchor, change: EvaluatedChange<AnchoredChange> ) => PlaceAnchor | undefined; } = { lastOffendingChangeFinder: findLastOffendingChange, placeUpdatorForChange: updateRelativePlaceAnchorForChange, } ): PlaceAnchor | undefined { if (place.referenceSibling === undefined) { // Start and end places cannot be updated. return undefined; } const lastOffendingChange = lastOffendingChangeFinder(place, path); return lastOffendingChange === undefined ? undefined : placeUpdatorForChange(place, lastOffendingChange); } /** * Finds the latest change in the given `path` that last made the given `place` invalid. * @param place - A anchor that is invalid in the last snapshot on the path. * @param path - The sequence of edits that violates the anchor's semantics. * @returns The change that last made the given `place` invalid and the snapshots before and after it. Undefined if `place` was never valid. * @internal */ export function findLastOffendingChange( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ): EvaluatedChange<AnchoredChange> | undefined; /** * For testing purposes only. * @internal */ export function findLastOffendingChange( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange>, dependencies?: HasPlaceValidator ): EvaluatedChange<AnchoredChange> | undefined; export function findLastOffendingChange( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange>, { placeValidator }: HasPlaceValidator = { placeValidator: validateStablePlace, } ): EvaluatedChange<AnchoredChange> | undefined { let followingChange: { change: AnchoredChange; after: Snapshot } | undefined; for (let editIndex = path.length - 1; editIndex >= 0; --editIndex) { const edit = path[editIndex]; for (let changeIndex = edit.length - 1; changeIndex >= 0; --changeIndex) { const change = edit[changeIndex]; const placeStatusAfterChange = placeValidator(change.after, place); if (placeStatusAfterChange === EditValidationResult.Valid) { return { before: change.after, ...assertNotUndefined(followingChange, 'The last change should not make the place valid'), }; } followingChange = { change: change.resolvedChange, after: change.after, }; } } return path.length > 0 && placeValidator(path[0].before, place) === EditValidationResult.Valid ? { before: path[0].before, ...assertNotUndefined(followingChange, 'The last change should not make the place valid'), } : // The place was never valid undefined; } /** * Updates a given `place` anchor in the face of a change that violates its semantics. * @param place - The anchor to update. * @param change - The change that violates the anchor's semantics. * @returns A place anchor that is valid after the given `change` and in line with the original `place`'s semantics. * Undefined if those semantics cannot be preserved. * @internal */ export function updateRelativePlaceAnchorForChange( place: RelativePlaceAnchor, change: EvaluatedChange<AnchoredChange> ): PlaceAnchor | undefined; export function updateRelativePlaceAnchorForChange( place: RelativePlaceAnchor, { change, before }: EvaluatedChange<AnchoredChange> ): PlaceAnchor | undefined { if (place.referenceSibling === undefined) { // A start or end place cannot be further updated return undefined; } assert(change.type === ChangeType.Detach, 'A PlaceAnchor can only be made invalid by a detach change'); const targetPlace = placeFromStablePlace(before, place); const startPlace = placeFromStablePlace(before, change.source.start); const endPlace = placeFromStablePlace(before, change.source.end); if (targetPlace.trait.parent !== startPlace.trait.parent) { // The target place was detached indirectly by detaching its parent. // The anchor cannot recover. return undefined; } let newIndex; if (targetPlace.side === Side.After) { newIndex = before.findIndexWithinTrait(startPlace) - 1; } if (targetPlace.side === Side.Before) { newIndex = before.findIndexWithinTrait(endPlace); } const referenceTrait = targetPlace.trait; const parentNode = before.getSnapshotNode(referenceTrait.parent); const traits = new Map(parentNode.traits); const trait = assertNotUndefined( traits.get(referenceTrait.label), 'The trait must have been populated before the deletion' ); const referenceSibling = trait[newIndex]; if (referenceSibling === undefined) { return { referenceTrait, side: place.side, semantics: place.semantics }; } return { referenceSibling, side: place.side, semantics: place.semantics }; }
the_stack
import Adapt, { AdaptMountedElement, AdaptMountedPrimitiveElement, BuiltinProps, ChangeType, childrenToArray, DomError, Group, handle, isElement, PluginOptions, rule, Style, Waiting, } from "@adpt/core"; import * as ld from "lodash"; import should from "should"; import { createMockLogger, k8sutils, MockLogger } from "@adpt/testutils"; import { sleep } from "@adpt/utils"; import * as abs from "../../src"; import { ActionPlugin, createActionPlugin } from "../../src/action"; import { ClusterInfo, ConfigMap, Container, K8sContainer, Kubeconfig, Pod, podResourceInfo, resourceElementToName, ResourcePod, Secret, ServiceAccount } from "../../src/k8s"; import { labelKey } from "../../src/k8s/manifest_support"; import { mkInstance } from "../run_minikube"; import { act, checkNoActions, doBuild, randomName } from "../testlib"; import { forceK8sObserverSchemaLoad, K8sTestStatusType } from "./testlib"; const { deleteAll, getAll } = k8sutils; // tslint:disable-next-line: no-object-literal-type-assertion const dummyConfig = {} as ClusterInfo; describe("k8s Pod Component Tests", () => { it("Should Instantiate Pod", () => { const pod = <Pod key="test" config={dummyConfig}> <K8sContainer name="onlyContainer" image="node:latest" /> </Pod>; should(pod).not.Undefined(); }); it("Should enforce unique container names", async () => { const pod = <Pod key="test" config={dummyConfig}> <K8sContainer name="container" image="node:latest" /> <K8sContainer name="dupContainer" image="node:latest" /> <K8sContainer name="dupContainer" image="node:latest" /> </Pod>; should(pod).not.Undefined(); const { contents: dom } = await Adapt.build(pod, null); if (dom == null) { should(dom).not.Null(); return; } const kids = childrenToArray(dom.props.children); const err = ld.find(kids, (child) => { if (!isElement(child)) return false; if (child.componentType === DomError) return true; return false; }); should(err).not.Undefined(); if (!isElement(err)) { should(isElement(err)).True(); return; } should(err.props.children).match(/dupContainer/); }); it("Should translate from abstract to k8s", async () => { const absDom = <abs.Compute> <abs.Container name="one" dockerHost="" image="alpine" /> <abs.Container name="two" dockerHost="" image="alpine" /> </abs.Compute>; const style = <Style> {abs.Container} {rule<abs.ContainerProps>(({ handle: hand, ...props }) => ( <Container {...props} /> ))} {abs.Compute} {rule<abs.ComputeProps>((props) => ( <Pod config={dummyConfig}> {props.children} </Pod> ))} </Style>; const result = await Adapt.build(absDom, style); const dom = result.contents; if (dom == null) { should(dom).not.be.Null(); return; } should(result.messages).have.length(0); const domXml = Adapt.serializeDom(dom); const expected = `<Adapt> <Resource kind="Pod"> <__props__> <prop name="config">{}</prop> <prop name="isTemplate">false</prop> <prop name="key">"Compute-Pod"</prop> <prop name="metadata">{}</prop> <prop name="spec">{ dnsPolicy: "ClusterFirst", enableServiceLinks: true, hostIPC: false, hostPID: false, restartPolicy: "Always", securityContext: {}, shareProcessNamespace: false, terminationGracePeriodSeconds: 30, containers: [ { imagePullPolicy: "IfNotPresent", name: "one", image: "alpine", }, { imagePullPolicy: "IfNotPresent", name: "two", image: "alpine", }, ], volumes: undefined, }</prop> </__props__> </Resource> </Adapt> `; should(domXml).eql(expected); }); it("Should translate volumes correctly", async () => { const secHandle = handle(); const mapHandle = handle(); const podHandle = handle(); const items = [ { key: "foo", path: "foo"} ]; const orig = <Group> <Secret handle={secHandle} config={dummyConfig} stringData={{ foo: "bar" }} /> <ConfigMap handle={mapHandle} config={dummyConfig} data={{ foo: "bar" }} /> <Pod key="test" handle={podHandle} config={dummyConfig} volumes={[ { name: "s0", secret: { secretName: "foo", items} }, { name: "c1", configMap: { name: "foo", items } }, { name: "s2", secret: { secretName: secHandle, items }}, { name: "c3", configMap: { name: mapHandle, items }} ]} > <K8sContainer name="container" image="node:latest" /> </Pod> </Group>; should(orig).not.Undefined(); const deployID = "foo"; const { contents: dom } = await Adapt.build(orig, null, { deployID }); if (dom == null) throw should(dom).not.Null(); const podTarget = podHandle.target; const secTarget = secHandle.target; const mapTarget = mapHandle.target; if (podTarget == undefined) throw should(podTarget).not.Undefined(); if (secTarget == undefined) throw should(secTarget).not.Undefined(); if (mapTarget == undefined) throw should(mapTarget).not.Undefined(); const props = podTarget.props as ResourcePod & BuiltinProps; should(props.kind).equal("Pod"); const podSpec = props.spec; should(podSpec).not.Undefined(); const volumes = podSpec.volumes; if (volumes === undefined) throw should(volumes).not.Undefined(); should(volumes).length(4); should(volumes.map((v) => v.name)).eql(["s0", "c1", "s2", "c3"]); const v0secret = volumes[0].secret; if (v0secret === undefined) throw should(v0secret).not.Undefined(); should(v0secret.secretName).equal("foo"); should(v0secret.items).eql(items); const v1map = volumes[1].configMap; if (v1map === undefined) throw should(v1map).not.Undefined(); should(v1map.name).equal("foo"); should(v1map.items).eql(items); const v2secret = volumes[2].secret; if (v2secret === undefined) throw should(v2secret).not.Undefined(); should(v2secret.secretName).equal(resourceElementToName(secTarget, deployID)); should(v2secret.items).eql(items); const v3map = volumes[3].configMap; if (v3map === undefined) throw should(v3map).not.Undefined(); should(v3map.name).equal(resourceElementToName(mapTarget, deployID)); should(v3map.items).eql(items); }); it("Should translate volumeMounts correctly", async () => { const podHandle = handle(); const orig = <Pod key="test" handle={podHandle} config={dummyConfig} volumes={[ { name: "s0", secret: { secretName: "foo" } }, ]} > <K8sContainer name="container" image="node:latest" volumeMounts={[ { name: "s0", mountPath: "/secret0" } ]} /> </Pod>; should(orig).not.Undefined(); const deployID = "foo"; const { contents: dom } = await Adapt.build(orig, null, { deployID }); if (dom == null) throw should(dom).not.Null(); const podTarget = podHandle.target; if (podTarget == undefined) throw should(podTarget).not.Undefined(); const props = podTarget.props as ResourcePod & BuiltinProps; should(props.kind).equal("Pod"); const podSpec = props.spec; should(podSpec).not.Undefined(); const containers = podSpec.containers; should(containers).length(1); const volumeMounts = containers[0].volumeMounts; if (volumeMounts === undefined) throw should(volumeMounts).not.Undefined(); should(volumeMounts).length(1); should(volumeMounts[0].name).equal("s0"); should(volumeMounts[0].mountPath).equal("/secret0"); }); it("Should resolve serviceAccount correctly", async () => { const podHandle = handle(); const serviceAccountHandle = handle(); const orig = <Group> <ServiceAccount handle={serviceAccountHandle} config={dummyConfig} /> <Pod key="test" handle={podHandle} config={dummyConfig} serviceAccountName={serviceAccountHandle} > <K8sContainer name="container" image="node:latest" /> </Pod> </Group>; should(orig).not.Undefined(); const deployID = "foo"; const { contents: dom } = await Adapt.build(orig, null, { deployID }); if (dom == null) throw should(dom).not.Null(); const podTarget = podHandle.target; if (podTarget == undefined) throw should(podTarget).not.Undefined(); const serviceAccountTarget = serviceAccountHandle.target; if (serviceAccountTarget == undefined) throw should(serviceAccountTarget).not.Undefined(); const props = podTarget.props as ResourcePod & BuiltinProps; should(props.kind).equal("Pod"); const podSpec = props.spec; should(podSpec).not.Undefined(); should(podSpec.serviceAccountName).equal(resourceElementToName(serviceAccountTarget, deployID)); }); }); async function waitForDeployed(mountedOrig: AdaptMountedElement, dom: AdaptMountedElement, deployID: string) { let deployed: boolean | Waiting = false; do { const status = await mountedOrig.status<K8sTestStatusType>(); should(status.kind).equal("Pod"); should(status.metadata.name).equal(resourceElementToName(dom, deployID)); should(status.metadata.annotations).containEql({ [labelKey("name")]: dom.id }); deployed = podResourceInfo.deployedWhen(status); if (deployed !== true) await sleep(1000); else return status; } while (1); } describe("k8s Pod Operation Tests", function () { this.timeout(60 * 1000); let plugin: ActionPlugin; let logger: MockLogger; let options: PluginOptions; let kubeClusterInfo: ClusterInfo; let client: k8sutils.KubeClient; let deployID: string | undefined; before(async function () { this.timeout(mkInstance.setupTimeoutMs); this.slow(20 * 1000); kubeClusterInfo = { kubeconfig: await mkInstance.kubeconfig as Kubeconfig }; client = await mkInstance.client; forceK8sObserverSchemaLoad(); }); beforeEach(async () => { plugin = createActionPlugin(); logger = createMockLogger(); deployID = randomName("cloud-pod-op"); options = { dataDir: "/fake/datadir", deployID, logger, log: logger.info, }; }); afterEach(async function () { this.timeout(40 * 1000); if (client) { await deleteAll("pods", { client, deployID }); await deleteAll("services", { client, deployID }); } }); async function createPod(name: string): Promise<AdaptMountedPrimitiveElement | null> { const pod = <Pod key={name} config={kubeClusterInfo} terminationGracePeriodSeconds={0}> <K8sContainer name="container" image="alpine:3.8" command={["sleep", "3s"]} /> </Pod>; const { mountedOrig, dom } = await doBuild(pod, { deployID }); await plugin.start(options); const obs = await plugin.observe(null, dom); const actions = plugin.analyze(null, dom, obs); should(actions).length(1); should(actions[0].type).equal(ChangeType.create); should(actions[0].detail).startWith("Creating Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.create); should(actions[0].changes[0].detail).startWith("Creating Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal(name); if (!deployID) throw new Error(`Missing deployID?`); await act(actions); await waitForDeployed(mountedOrig, dom, deployID); const pods = await getAll("pods", { client, deployID }); should(pods).length(1); should(pods[0].metadata.name) .equal(resourceElementToName(dom, deployID)); if (mountedOrig === null) throw should(mountedOrig).not.Null(); const status = await mountedOrig.status<K8sTestStatusType>(); should(status.kind).equal("Pod"); should(status.metadata.name).equal(resourceElementToName(dom, options.deployID)); should(status.metadata.annotations).containEql({ [labelKey("name")]: dom.id }); await plugin.finish(); return dom; } it("Should create pod", async () => { await createPod("test"); }); it("Should modify pod", async () => { const oldDom = await createPod("test"); //5s sleep diff to cause modify vs. 3s sleep in createPod const command = ["sleep", "5s"]; const pod = <Pod key="test" config={kubeClusterInfo} terminationGracePeriodSeconds={0}> <K8sContainer name="container" image="alpine:3.8" command={command} /> </Pod>; const { dom } = await doBuild(pod, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions).length(1); should(actions[0].type).equal(ChangeType.modify); should(actions[0].detail).startWith("Replacing Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.modify); should(actions[0].changes[0].detail).startWith("Replacing Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); if (!deployID) throw new Error(`Missing deployID?`); await act(actions); const pods = await getAll("pods", { client, deployID }); should(pods).length(1); should(pods[0].metadata.name) .equal(resourceElementToName(dom, deployID)); should(pods[0].spec.containers).length(1); should(pods[0].spec.containers[0].command).eql(command); await plugin.finish(); }); it("Should leave pod alone", async () => { const oldDom = await createPod("test"); //No diff const command = ["sleep", "3s"]; const pod = <Pod key="test" config={kubeClusterInfo} terminationGracePeriodSeconds={0}> <K8sContainer name="container" image="alpine:3.8" command={command} /> </Pod>; const { dom } = await doBuild(pod, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); checkNoActions(actions, dom); await plugin.finish(); }); it("Should delete pod", async () => { const oldDom = await createPod("test"); const { dom } = await doBuild(<Group />, { deployID }); await plugin.start(options); const obs = await plugin.observe(oldDom, dom); const actions = plugin.analyze(oldDom, dom, obs); should(actions.length).equal(1); should(actions[0].type).equal(ChangeType.delete); should(actions[0].detail).startWith("Deleting Pod"); should(actions[0].changes).have.length(1); should(actions[0].changes[0].type).equal(ChangeType.delete); should(actions[0].changes[0].detail).startWith("Deleting Pod"); should(actions[0].changes[0].element.componentName).equal("Resource"); should(actions[0].changes[0].element.props.key).equal("test"); if (!deployID) throw new Error(`Missing deployID?`); await act(actions); await sleep(6); // Sleep longer than termination grace period const pods = await getAll("pods", { client, deployID }); if (pods.length !== 0) { should(pods.length).equal(1); should(pods[0].metadata.deletionGracePeriod).not.Undefined(); } await plugin.finish(); }); });
the_stack
import ZRText from 'zrender/src/graphic/Text'; import { LabelLayoutOption } from '../util/types'; import { BoundingRect, OrientedBoundingRect, Polyline } from '../util/graphic'; import type Element from 'zrender/src/Element'; interface LabelLayoutListPrepareInput { label: ZRText labelLine?: Polyline computedLayoutOption?: LabelLayoutOption priority: number defaultAttr: { ignore: boolean labelGuideIgnore?: boolean } } export interface LabelLayoutInfo { label: ZRText labelLine: Polyline priority: number rect: BoundingRect // Global rect localRect: BoundingRect obb?: OrientedBoundingRect // Only available when axisAligned is true axisAligned: boolean layoutOption: LabelLayoutOption defaultAttr: { ignore: boolean labelGuideIgnore?: boolean } transform: number[] } export function prepareLayoutList(input: LabelLayoutListPrepareInput[]): LabelLayoutInfo[] { const list: LabelLayoutInfo[] = []; for (let i = 0; i < input.length; i++) { const rawItem = input[i]; if (rawItem.defaultAttr.ignore) { continue; } const label = rawItem.label; const transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el. const localRect = label.getBoundingRect(); const isAxisAligned = !transform || (transform[1] < 1e-5 && transform[2] < 1e-5); const minMargin = label.style.margin || 0; const globalRect = localRect.clone(); globalRect.applyTransform(transform); globalRect.x -= minMargin / 2; globalRect.y -= minMargin / 2; globalRect.width += minMargin; globalRect.height += minMargin; const obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null; list.push({ label, labelLine: rawItem.labelLine, rect: globalRect, localRect, obb, priority: rawItem.priority, defaultAttr: rawItem.defaultAttr, layoutOption: rawItem.computedLayoutOption, axisAligned: isAxisAligned, transform }); } return list; } function shiftLayout( list: Pick<LabelLayoutInfo, 'rect' | 'label'>[], xyDim: 'x' | 'y', sizeDim: 'width' | 'height', minBound: number, maxBound: number, balanceShift: boolean ) { const len = list.length; if (len < 2) { return; } list.sort(function (a, b) { return a.rect[xyDim] - b.rect[xyDim]; }); let lastPos = 0; let delta; let adjusted = false; const shifts = []; let totalShifts = 0; for (let i = 0; i < len; i++) { const item = list[i]; const rect = item.rect; delta = rect[xyDim] - lastPos; if (delta < 0) { // shiftForward(i, len, -delta); rect[xyDim] -= delta; item.label[xyDim] -= delta; adjusted = true; } const shift = Math.max(-delta, 0); shifts.push(shift); totalShifts += shift; lastPos = rect[xyDim] + rect[sizeDim]; } if (totalShifts > 0 && balanceShift) { // Shift back to make the distribution more equally. shiftList(-totalShifts / len, 0, len); } // TODO bleedMargin? const first = list[0]; const last = list[len - 1]; let minGap: number; let maxGap: number; updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds. minGap < 0 && squeezeGaps(-minGap, 0.8); maxGap < 0 && squeezeGaps(maxGap, 0.8); updateMinMaxGap(); takeBoundsGap(minGap, maxGap, 1); takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space. updateMinMaxGap(); if (minGap < 0) { squeezeWhenBailout(-minGap); } if (maxGap < 0) { squeezeWhenBailout(maxGap); } function updateMinMaxGap() { minGap = first.rect[xyDim] - minBound; maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim]; } function takeBoundsGap(gapThisBound: number, gapOtherBound: number, moveDir: 1 | -1) { if (gapThisBound < 0) { // Move from other gap if can. const moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound); if (moveFromMaxGap > 0) { shiftList(moveFromMaxGap * moveDir, 0, len); const remained = moveFromMaxGap + gapThisBound; if (remained < 0) { squeezeGaps(-remained * moveDir, 1); } } else { squeezeGaps(-gapThisBound * moveDir, 1); } } } function shiftList(delta: number, start: number, end: number) { if (delta !== 0) { adjusted = true; } for (let i = start; i < end; i++) { const item = list[i]; const rect = item.rect; rect[xyDim] += delta; item.label[xyDim] += delta; } } // Squeeze gaps if the labels exceed margin. function squeezeGaps(delta: number, maxSqeezePercent: number) { const gaps: number[] = []; let totalGaps = 0; for (let i = 1; i < len; i++) { const prevItemRect = list[i - 1].rect; const gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0); gaps.push(gap); totalGaps += gap; } if (!totalGaps) { return; } const squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent); if (delta > 0) { for (let i = 0; i < len - 1; i++) { // Distribute the shift delta to all gaps. const movement = gaps[i] * squeezePercent; // Forward shiftList(movement, 0, i + 1); } } else { // Backward for (let i = len - 1; i > 0; i--) { // Distribute the shift delta to all gaps. const movement = gaps[i - 1] * squeezePercent; shiftList(-movement, i, len); } } } /** * Squeeze to allow overlap if there is no more space available. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds. */ function squeezeWhenBailout(delta: number) { const dir = delta < 0 ? -1 : 1; delta = Math.abs(delta); const moveForEachLabel = Math.ceil(delta / (len - 1)); for (let i = 0; i < len - 1; i++) { if (dir > 0) { // Forward shiftList(moveForEachLabel, 0, i + 1); } else { // Backward shiftList(-moveForEachLabel, len - i - 1, len); } delta -= moveForEachLabel; if (delta <= 0) { return; } } } return adjusted; } /** * Adjust labels on x direction to avoid overlap. */ export function shiftLayoutOnX( list: Pick<LabelLayoutInfo, 'rect' | 'label'>[], leftBound: number, rightBound: number, // If average the shifts on all labels and add them to 0 // TODO: Not sure if should enable it. // Pros: The angle of lines will distribute more equally // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly. balanceShift?: boolean ): boolean { return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift); } /** * Adjust labels on y direction to avoid overlap. */ export function shiftLayoutOnY( list: Pick<LabelLayoutInfo, 'rect' | 'label'>[], topBound: number, bottomBound: number, // If average the shifts on all labels and add them to 0 balanceShift?: boolean ): boolean { return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift); } export function hideOverlap(labelList: LabelLayoutInfo[]) { const displayedLabels: LabelLayoutInfo[] = []; // TODO, render overflow visible first, put in the displayedLabels. labelList.sort(function (a, b) { return b.priority - a.priority; }); const globalRect = new BoundingRect(0, 0, 0, 0); function hideEl(el: Element) { if (!el.ignore) { // Show on emphasis. const emphasisState = el.ensureState('emphasis'); if (emphasisState.ignore == null) { emphasisState.ignore = false; } } el.ignore = true; } for (let i = 0; i < labelList.length; i++) { const labelItem = labelList[i]; const isAxisAligned = labelItem.axisAligned; const localRect = labelItem.localRect; const transform = labelItem.transform; const label = labelItem.label; const labelLine = labelItem.labelLine; globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely. globalRect.width -= 0.1; globalRect.height -= 0.1; globalRect.x += 0.05; globalRect.y += 0.05; let obb = labelItem.obb; let overlapped = false; for (let j = 0; j < displayedLabels.length; j++) { const existsTextCfg = displayedLabels[j]; // Fast rejection. if (!globalRect.intersect(existsTextCfg.rect)) { continue; } if (isAxisAligned && existsTextCfg.axisAligned) { // Is overlapped overlapped = true; break; } if (!existsTextCfg.obb) { // If self is not axis aligned. But other is. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform); } if (!obb) { // If self is axis aligned. But other is not. obb = new OrientedBoundingRect(localRect, transform); } if (obb.intersect(existsTextCfg.obb)) { overlapped = true; break; } } // TODO Callback to determine if this overlap should be handled? if (overlapped) { hideEl(label); labelLine && hideEl(labelLine); } else { label.attr('ignore', labelItem.defaultAttr.ignore); labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore); displayedLabels.push(labelItem); } } }
the_stack
import { MockHistory, MockInstruction } from './shared'; import { History } from 'aurelia-history'; import { Container } from 'aurelia-dependency-injection'; import { Router, NavModel, RouteConfig, PipelineProvider, AppRouter, NavigationInstruction } from '../src/aurelia-router'; let absoluteRoot = 'http://aurelia.io/docs/'; describe('the router', () => { let router: Router; let history: History; beforeEach(() => { history = new MockHistory(); history.getAbsoluteRoot = () => absoluteRoot; router = new AppRouter( new Container(), history, new PipelineProvider(new Container()), null ); }); describe('addRoute', () => { it('should register named routes', () => { const child = router.createChild(new Container()); router.addRoute({ name: 'parent', route: 'parent', moduleId: 'parent' }); child.addRoute({ name: 'child', route: 'child', moduleId: 'child' }); expect(child.hasRoute('child')).toBe(true); expect(child.hasRoute('parent')).toBe(true); expect(child.hasOwnRoute('child')).toBe(true); expect(child.hasOwnRoute('parent')).toBe(false); expect(router.hasRoute('child')).toBe(false); expect(router.hasRoute('parent')).toBe(true); expect(router.hasOwnRoute('child')).toBe(false); expect(router.hasOwnRoute('parent')).toBe(true); }); it('should add a route to navigation if it has a nav=true', () => { const config = { route: 'test', moduleId: 'test', title: 'Resume', nav: true }; const navModel = router.createNavModel(config); router.addRoute(config, navModel); expect(router.navigation).toContain(navModel); }); it('should not add a route to navigation if it has a nav=false', () => { let testRoute: NavModel = {} as any; router.addRoute({ route: 'test', moduleId: 'test', title: 'Resume', nav: false }, testRoute); expect(router.navigation).not.toContain(testRoute); }); it('should reject dynamic routes specifying nav=true with no href', () => { expect(() => router.addRoute({ route: 'test/:id', href: 'test', moduleId: 'test', nav: true })).not.toThrow(); expect(() => router.addRoute({ route: 'test/:id', moduleId: 'test', nav: true })).toThrow(); }); it('should add a route with multiple view ports', () => { expect(() => router.addRoute({ route: 'multiple/viewports', viewPorts: { 'default': { moduleId: 'test1' }, 'number2': { moduleId: 'test2' } } })).not.toThrow(); }); it('should map a routeconfig with an array of routes to multiple routeconfigs with one route each', () => { router.addRoute({ route: ['test1', 'test2'], moduleId: 'test', nav: true }); expect(router.routes[0].route).toEqual('test1'); expect(router.routes[1].route).toEqual('test2'); }); }); describe('generate', () => { it('should generate route URIs', (done) => { const child = router.createChild(new Container()); child.baseUrl = 'child-router'; Promise.all([ router.configure(config => config.map({ name: 'parent', route: 'parent', moduleId: './test' })), child.configure(config => config.map({ name: 'child', route: 'child', moduleId: './test' })) ]).then(() => { expect(router.generate('parent')).toBe('#/parent'); expect(child.generate('parent')).toBe('#/parent'); expect(child.generate('child')).toBe('#/child-router/child'); router.history._hasPushState = true; expect(router.generate('parent')).toBe('/parent'); expect(child.generate('parent')).toBe('/parent'); expect(child.generate('child')).toBe('/child-router/child'); done(); }); }); it('should delegate to parent when not configured', (done) => { const child = router.createChild(new Container()); router.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) .then(() => { expect(child.generate('test', { id: 1 })).toBe('#/test/1'); done(); }); }); it('should delegate to parent when generating unknown route', (done) => { const child = router.createChild(new Container()); Promise .all([ router.configure(config => config.map({ name: 'parent', route: 'parent/:id', moduleId: './test' })), child.configure(config => config.map({ name: 'child', route: 'child/:id', moduleId: './test' })) ]).then(() => { expect(child.generate('child', { id: 1 })).toBe('#/child/1'); expect(child.generate('parent', { id: 1 })).toBe('#/parent/1'); done(); }); }); it('should return a fully-qualified URL when options.absolute is true', (done) => { const child = router.createChild(new Container()); let options = { absolute: true }; Promise .all([ router.configure(config => config.map({ name: 'parent', route: 'parent/:id', moduleId: './test' })), child.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) ]) .then(() => { expect(child.generate('test', { id: 1 }, options)).toBe(`${absoluteRoot}#/test/1`); expect(child.generate('parent', { id: 2 }, options)).toBe(`${absoluteRoot}#/parent/2`); router.history._hasPushState = true; expect(child.generate('test', { id: 1 }, options)).toBe(`${absoluteRoot}test/1`); expect(child.generate('parent', { id: 2 }, options)).toBe(`${absoluteRoot}parent/2`); done(); }); }); }); describe('navigate', () => { it('should navigate to absolute paths', (done) => { const options = {}; spyOn(history, 'navigate'); const child = router.createChild(new Container()); child.baseUrl = 'child-router'; Promise.all([ router.configure(config => { config.map([ { name: 'parent', route: 'parent/:id', moduleId: './test' }, { name: 'parent-empty', route: '', moduleId: './parent-empty' } ]); return config; }), child.configure(config => { config.map([ { name: 'child', route: 'child/:id', moduleId: './test' }, { name: 'empty', route: '', moduleId: './empty' } ]); return config; }) ]).then(() => { router.navigate('', options); expect(history.navigate).toHaveBeenCalledWith('#/', options); (history.navigate as jasmine.Spy).calls.reset(); router.navigate('#/test1', options); expect(history.navigate).toHaveBeenCalledWith('#/test1', options); (history.navigate as jasmine.Spy).calls.reset(); router.navigate('/test2', options); expect(history.navigate).toHaveBeenCalledWith('#/test2', options); (history.navigate as jasmine.Spy).calls.reset(); router.navigate('test3', options); expect(history.navigate).toHaveBeenCalledWith('#/test3', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('#/test4', options); expect(history.navigate).toHaveBeenCalledWith('#/test4', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('/test5', options); expect(history.navigate).toHaveBeenCalledWith('#/test5', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('test6', options); expect(history.navigate).toHaveBeenCalledWith('#/child-router/test6', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('#/child-router/test7', options); expect(history.navigate).toHaveBeenCalledWith('#/child-router/test7', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('/child-router/test8', options); expect(history.navigate).toHaveBeenCalledWith('#/child-router/test8', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('child-router/test9', options); expect(history.navigate).toHaveBeenCalledWith('#/child-router/child-router/test9', options); (history.navigate as jasmine.Spy).calls.reset(); child.navigate('', options); expect(history.navigate).toHaveBeenCalledWith('#/child-router/', options); (history.navigate as jasmine.Spy).calls.reset(); done(); }); }); it('should navigate to named routes', (done) => { const options = {}; spyOn(history, 'navigate'); router.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) .then(() => { router.navigateToRoute('test', { id: 123 }, options); expect(history.navigate).toHaveBeenCalledWith('#/test/123', options); done(); }); }); }); describe('_createNavigationInstruction', () => { it('should reject when router not configured', (done) => { router._createNavigationInstruction() .then(x => expect(true).toBeFalsy('should have rejected')) .catch(reason => expect(reason).toBeTruthy()) .then(done); }); it('should reject when route not found', (done) => { router.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) .then(() => router._createNavigationInstruction('test')) .then(() => expect(true).toBeFalsy('should have rejected')) .catch(reason => expect(reason).toBeTruthy()) .then(done); }); it('should resolve matching routes', (done) => { router.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) .then(() => router._createNavigationInstruction('test/123?foo=456')) .then(x => expect(x as Required<NavigationInstruction>) .toEqual(jasmine.objectContaining({ fragment: 'test/123', queryString: 'foo=456' } as Required<NavigationInstruction>)) ) .catch(reason => fail(reason)) .then(done); }); describe('should match routes with same pattern based on href', () => { it('', (done) => { router.configure(config => config.map([ { name: 'a', route: 'test/:p', moduleId: './test', href: '/test/a' }, { name: 'b', route: 'test/:p', moduleId: './test', href: '/test/b' } ])) .then(() => router._createNavigationInstruction('test/b?foo=456')) .then(i => { expect(i.fragment).toEqual('test/b'); expect(i.queryString).toEqual('foo=456'); expect(i.params.p).toEqual('b'); expect(i.config.name).toEqual('b'); }) .catch(reason => fail(reason)) .then(done); }); it('when fragment matches the child router', (done) => { const childRouter = router.createChild(new Container()); router.configure(config => config.map([ { name: 'a', route: 'parent/:p', moduleId: './parent', href: '/parent/a' }, { name: 'b', route: 'parent/:p', moduleId: './parent', href: '/parent/b' } ])) .then(() => childRouter.configure(config => config.map([ { name: 'c', route: 'child/:p', moduleId: './child', href: '/child/c' }, { name: 'd', route: 'child/:p', moduleId: './child', href: '/child/d' } ]))) .then(() => router._createNavigationInstruction('parent/b/child/c?foo=456')) .then(i => { expect(i.fragment).toEqual('parent/b/child/c'); expect(i.queryString).toEqual('foo=456'); expect(i.params.p).toEqual('b'); expect(i.config.name).toEqual('b'); }) .then(() => childRouter._createNavigationInstruction('child/c?foo=456')) .then(i => { // This failing test needs to be implemented. // expect(i.fragment).toEqual('child/c'); // expect(i.queryString).toEqual('foo=456'); // expect(i.params.p).toEqual('c'); // expect(i.config.name).toEqual('c'); }) .catch(reason => fail(reason)) .then(done); }); }); it('should be case insensitive by default', (done) => { router.configure(config => config.map({ name: 'test', route: 'test/:id', moduleId: './test' })) .then(() => router._createNavigationInstruction('TeSt/123?foo=456')) .then(x => expect(x as Required<NavigationInstruction>) .toEqual(jasmine.objectContaining({ fragment: 'TeSt/123', queryString: 'foo=456' } as Required<NavigationInstruction>)) ) .catch(reason => fail(reason)) .then(done); }); it('should reject when route is case sensitive', (done) => { router.configure(config => config.map({ name: 'test', route: 'Test/:id', moduleId: './test', caseSensitive: true })) .then(() => router._createNavigationInstruction('test/123')) .then(() => expect(true).toBeFalsy('should have rejected')) .catch(reason => expect(reason).toBeTruthy()) .then(done); }); describe('catchAllHandler', () => { it('should use a parent routers catchAllHandler if one exists', (done) => { const child = router.createChild(new Container()); child.baseUrl = 'empty'; Promise.all([ router.configure(config => { config.unknownRouteConfig = 'test'; config.mapRoute({ route: 'foo', moduleId: './empty' }); return config; }), child.configure(config => { config.mapRoute({ route: '', moduleId: './child-empty' }); return config; }) ]) .then(() => router._createNavigationInstruction('foo/bar/123?bar=456')) .then(parentInstruction => { expect(parentInstruction.config.moduleId).toEqual('./empty'); return child._createNavigationInstruction('bar/123?bar=456', parentInstruction); }) .then(childInstruction => expect(childInstruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should use string moduleId handler', (done) => { router .configure(config => { config.unknownRouteConfig = 'test'; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(instruction => expect(instruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should use route config handler', (done) => { router .configure(config => { config.unknownRouteConfig = { moduleId: 'test' } as RouteConfig as any; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(instruction => expect(instruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should use function handler', (done) => { router .configure(config => { config.unknownRouteConfig = instruction => ({ moduleId: 'test' } as RouteConfig) as any; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(instruction => expect(instruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should use async function handler', (done) => { router .configure(config => { config.unknownRouteConfig = instruction => Promise.resolve({ moduleId: 'test' } as RouteConfig) as any; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(instruction => expect(instruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should pass instruction to function handler', (done) => { router .configure(config => { config.unknownRouteConfig = ((instruction: NavigationInstruction) => { expect(instruction.fragment).toBe('foo/123'); expect(instruction.queryString).toBe('bar=456'); expect(instruction.config).toBe(null); return { moduleId: 'test' } as RouteConfig; }) as any; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(instruction => expect(instruction.config.moduleId).toEqual('test')) .catch(fail) .then(done); }); it('should throw on invalid handlers', () => { expect(() => { router.handleUnknownRoutes(null); }).toThrow(); }); it('should reject invalid configs', (done) => { router .configure(config => { config.unknownRouteConfig = instruction => null; return config; }) .then(() => router._createNavigationInstruction('foo/123?bar=456')) .then(() => fail('should have rejected')) .catch(() => done()); }); }); }); describe('configure', () => { it('notifies when configured', (done) => { expect(router.isConfigured).toBe(false); router.ensureConfigured().then(() => { expect(router.isConfigured).toBe(true); done(); }); router.configure(config => config.map({ route: '', moduleId: './test' })); }); it('notifies when already configured', (done) => { expect(router.isConfigured).toBe(false); router.configure(config => config.map({ route: '', moduleId: './test' })) .then(() => { expect(router.isConfigured).toBe(true); router.ensureConfigured().then(() => { expect(router.isConfigured).toBe(true); done(); }); }); }); it('waits for async callbacks', (done) => { let resolve: (val?: any) => any; let promise = new Promise(r => resolve = r); expect(router.isConfigured).toBe(false); router.configure(config => { // This conflicts with type definition so much // what should be fixed ??? return promise.then(x => { config.map({ route: '', moduleId: './test' }); }) as any; }); expect(router.isConfigured).toBe(true); expect(router.routes.length).toBe(0); router.ensureConfigured().then(() => { expect(router.routes.length).toBe(1); done(); }); resolve(); }); }); describe('refreshNavigation', () => { let staticHref: string; beforeEach((done) => { staticHref = '#/a/static/href'; router.baseUrl = 'initial-root'; router.configure(config => config.map([ { name: 'dynamic', route: 'dynamic', moduleId: 'dynamic', nav: true }, { name: 'static', route: 'static', moduleId: 'static', href: staticHref, nav: true }])).then(() => { router.refreshNavigation(); done(); }); }); it('updates a dynamic href ', () => { router.baseUrl = 'updated-root'; router.refreshNavigation(); expect(router.navigation[0].href).toEqual('#/updated-root/dynamic'); }); it('respects a static href ', () => { router.baseUrl = 'updated-root'; router.refreshNavigation(); expect(router.navigation[1].href).toEqual(staticHref); }); }); });
the_stack
import AWS = require('aws-sdk'); import type * as iam from '@aws-cdk/aws-iam'; import type * as lambda from '@aws-cdk/aws-lambda'; import type * as cdk from '@aws-cdk/core'; import { Json } from '@punchcard/shape-json'; import { any, AnyShape, Mapper, MapperFactory, NothingShape, Pointer, Shape, Value } from '@punchcard/shape'; import { DataSourceType, VExpression } from '../appsync'; import { call } from '../appsync/lang/statement'; import { VTL } from '../appsync/lang/vtl'; import { VObject } from '../appsync/lang/vtl-object'; import { Assembly } from '../core/assembly'; import { Build } from '../core/build'; import { Cache } from '../core/cache'; import { CDK } from '../core/cdk'; import { Client } from '../core/client'; import { Code } from '../core/code'; import { Scope } from '../core/construct'; import { Dependency } from '../core/dependency'; import { Duration } from '../core/duration'; import { Entrypoint, entrypoint } from '../core/entrypoint'; import { Global } from '../core/global'; import { Resource } from '../core/resource'; import { Run } from '../core/run'; import { ENTRYPOINT_ENV_KEY, IS_RUNTIME_ENV_KEY } from '../util/constants'; /** * Overridable subset of @aws-cdk/aws-lambda.FunctionProps */ export interface FunctionOverrideProps extends Omit<Partial<lambda.FunctionProps>, 'code' | 'functionName' | 'handler' | 'runtime' | 'memorySize'> {} export interface HandlerProps<T extends Shape = AnyShape, U extends Shape = AnyShape, D extends Dependency<any> | undefined = undefined> { /** * Type of the request * * @default any */ request?: Pointer<T>; /** * Type of the response * * @default any */ response?: Pointer<U>; /** * Factory for a `Mapper` to serialize shapes to/from a `string`. * * @default Json */ mapper?: MapperFactory<Json.Of<T>>; /** * Dependency resources which this Function needs clients for. * * Each client will have a chance to grant permissions to the function and environment variables. */ depends?: D | ((it?: undefined) => D); } export interface FunctionProps<T extends Shape = AnyShape, U extends Shape = AnyShape, D extends Dependency<any> | undefined = undefined> extends HandlerProps<T, U, D> { /** * A name for the function. * * @default - AWS CloudFormation generates a unique physical ID and uses that * ID for the function's name. For more information, see Name Type. */ functionName?: string; /** * A description of the function. * * @default - No description. */ description?: string; /** * The amount of memory, in MB, that is allocated to your Lambda function. * Lambda uses this value to proportionally allocate the amount of CPU * power. For more information, see Resource Model in the AWS Lambda * Developer Guide. * * @default 128 */ memorySize?: number; /** * The function execution time (in seconds) after which Lambda terminates * the function. Because the execution time affects cost, set this value * based on the function's expected execution time. * * @default Duration.seconds(3) */ timeout?: Duration; /** * Extra Lambda Function Props. */ functionProps?: Build<FunctionOverrideProps> } /** * Runs a function `T => U` in AWS Lambda with some runtime dependencies, `D`. * * @typeparam T input type * @typeparam U return type * @typeparam D runtime dependencies */ export class Function<T extends Shape = AnyShape, U extends Shape = AnyShape, D extends Dependency<any> | undefined = any> implements Entrypoint, Resource<lambda.Function> { public readonly [entrypoint] = true; public readonly filePath: string; /** * The Lambda Function CDK Construct. */ public readonly resource: Build<lambda.Function>; /** * Entrypoint handler function. */ public readonly entrypoint: Run<Promise<(event: any, context: any) => Promise<any>>>; /** * Function to handle the event of type `T`, given initialized client instances `Clients<D>`. * * @param event the parsed request * @param clients initialized clients to dependency resources */ public readonly handle: (event: Value.Of<T>, clients: Client<D>, context: any) => Promise<Value.Of<U>>; public readonly request: Pointer<T>; public readonly response: Pointer<U>; private readonly depends?: D | ((it?: undefined) => D); private readonly mapperFactory: MapperFactory<Json.Of<T>>; private _dependencies: D; private get dependencies(): D { if (this._dependencies === undefined && this.depends !== undefined) { this._dependencies = (this.depends as any).install ? this.depends as D : (this.depends as () => D)(); } return this._dependencies; } constructor( scope: Scope, id: string, props: FunctionProps<T, U, D>, handle: (event: Value.Of<T>, run: Client<D>, context: any) => Promise<U extends NothingShape ? void : Value.Of<U>> ) { this.request = (props.request || any) as any; this.response = (props.request || any) as any; this.handle = handle as any; const entrypointId = Global.addEntrypoint(this); // default to JSON serialization this.mapperFactory = (props.mapper || Json.mapper) as MapperFactory<Json.Of<T>>; this.depends = props.depends; this.resource = CDK.chain(({lambda}) => Scope.resolve(scope).chain(scope => (props.functionProps || Build.empty).map(functionProps => { const lambdaFunction: lambda.Function = new lambda.Function(scope, id, { code: Code.tryGetCode(scope) || Code.mock(), runtime: lambda.Runtime.NODEJS_10_X, handler: 'index.handler', functionName: props.functionName, memorySize: props.memorySize, description: props.description, timeout: props.timeout?.toCDKDuration(), ...functionProps, }); lambdaFunction.addEnvironment(IS_RUNTIME_ENV_KEY, 'true'); lambdaFunction.addEnvironment(ENTRYPOINT_ENV_KEY, entrypointId); const assembly = new Assembly(); if (this.dependencies) { Build.resolve(this.dependencies.install)(assembly, lambdaFunction); } for (const [name, p] of Object.entries(assembly.properties)) { lambdaFunction.addEnvironment(name, p); } return lambdaFunction; }))); this.entrypoint = Run.lazy(async () => { const requestMapper = this.mapperFactory(Pointer.resolve(props.request) || any); const responseMapper = this.mapperFactory(Pointer.resolve(props.response) || any); const bag: {[name: string]: string} = {}; for (const [env, value] of Object.entries(process.env)) { if (env.startsWith('punchcard') && value !== undefined) { bag[env] = value; } } let client: Client<D> = undefined as any; if (this.dependencies) { const cache = new Cache(); const runtimeProperties = new Assembly(bag); client = await (Run.resolve(this.dependencies!.bootstrap))(runtimeProperties, cache); } return (async (event: any, context: any) => { const parsed = requestMapper.read(event); try { const result = await this.handle(parsed as any, client, context); return responseMapper.write(result as any); } catch (err) { console.error(err); throw err; } }); }); } /** * Invoke this function from within an AWS AppSync Resolver. * * ```ts * class A extends Record({ * key: string * }) {} * * const myFunction: Lambda.Function<typeof A, StringShape>; * const obj: VObject.Of<typeof A>; * * // option 1 - pass a VObject that represents a reference to an A * const response: VString = yield* myFunction.invoke(obj) * * // option 2 - pass in an object that is the same structure * const id = yield* $util.autoId(); * const response: VString = yield* myFunction.invoke({ * key: id * }); * ``` * * @param request VTL object for the request * @param props optional props to customize the Lambda data source. */ public invoke(request: VObject.Like<T>, props?: Function.DataSourceProps): VTL<VObject.Of<U>> { const requestShape: T = Pointer.resolve(this.request); const responseShape: U = Pointer.resolve(this.response); const requestObject = VObject.fromExpr(requestShape, VExpression.json({ version: '2017-02-28', operation: 'Invoke', payload: VObject.isObject(request) ? VExpression.concat( VExpression.text('$util.toJson('), VObject.getExpr(request), VExpression.text(')') ) : VExpression.json(request), })); const dataSourceProps = Build.concat( CDK, this.resource, props?.serviceRole || Build.of(undefined) ).map(([cdk, fn, serviceRole]) => (scope: cdk.Construct, id: string) => { const role = serviceRole || new cdk.iam.Role(scope, `${id}:Role`, { assumedBy: new cdk.iam.ServicePrincipal('appsync') }); fn.grantInvoke(role); return { type: DataSourceType.AWS_LAMBDA, lambdaConfig: { lambdaFunctionArn: fn.functionArn }, description: props?.description, serviceRoleArn: role.roleArn, }; }); return call(dataSourceProps, requestObject, responseShape) ; } /** * Depend on invoking this Function. */ public invokeAccess(): Dependency<Function.Client<Value.Of<T>, Value.Of<U>>> { return { install: this.resource.map(fn => (ns, g) => { fn.grantInvoke(g); ns.set('functionArn', fn.functionArn); }), bootstrap: Run.of(async (ns, cache) => { const requestMapper = this.mapperFactory(Pointer.resolve(this.request)) || any; const responseMapper = this.mapperFactory(Pointer.resolve(this.response)) || any; return new Function.Client( cache.getOrCreate('aws:lambda', () => new AWS.Lambda()), ns.get('functionArn'), Json.asString(requestMapper), Json.asString(responseMapper) ) as any; }) }; } } export namespace Function { export interface DataSourceProps { description?: string; serviceRole?: Build<iam.IRole> } /** * Client for invoking a Lambda Function */ export class Client<T, U> { constructor( private readonly client: AWS.Lambda, private readonly functionArn: string, private readonly requestMapper: Mapper<T, string>, private readonly responseMapper: Mapper<U, string>) {} /** * Invoke the function synchronously and return the result. * @return Promise of the result */ public async invoke(request: T): Promise<U> { const response = await this.client.invoke({ FunctionName: this.functionArn, InvocationType: 'RequestResponse', Payload: this.requestMapper.write(request) }).promise(); if (response.StatusCode === 200) { if (typeof response.Payload === 'string') { return this.responseMapper.read(response.Payload); } else if (Buffer.isBuffer(response.Payload)) { return this.responseMapper.read(response.Payload.toString('utf8')); } else { throw new Error(`Unknown response payload type: ${typeof response.Payload}`); } } else { throw new Error(`Function returned non-200 status code, '${response.StatusCode}' with error, '${response.FunctionError}'`); } } /** * Invoke the function asynchronously. */ public async invokeAsync(request: T): Promise<void> { await this.client.invoke({ FunctionName: this.functionArn, InvocationType: 'Event', Payload: this.requestMapper.write(request) }).promise(); } } }
the_stack
'use strict'; import nls = require('vs/nls'); import { TPromise } from 'vs/base/common/winjs.base'; import { Builder, $ } from 'vs/base/browser/builder'; import URI from 'vs/base/common/uri'; import { ThrottledDelayer } from 'vs/base/common/async'; import errors = require('vs/base/common/errors'); import paths = require('vs/base/common/paths'); import { Action, IActionRunner, IAction } from 'vs/base/common/actions'; import { prepareActions } from 'vs/workbench/browser/actionBarRegistry'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { IResolveFileOptions, FileChangeType, FileChangesEvent, IFileChange, IFileService } from 'vs/platform/files/common/files'; import { RefreshViewExplorerAction, CleanRosNodeAction } from 'vs/workbench/parts/files/browser/fileActions'; import { FileDataSource } from 'vs/workbench/parts/files/browser/views/explorerViewer'; import { FileRenderer, FileController, ActionProvider, FileAccessibilityProvider, FileFilter } from 'vs/workbench/parts/files/browser/views/rosNodeViewer'; import * as DOM from 'vs/base/browser/dom'; import { CollapseAction, CollapsibleViewletView } from 'vs/workbench/browser/viewlet'; import { FileStat } from 'vs/workbench/parts/files/common/explorerViewModel'; import { IListService } from 'vs/platform/list/browser/listService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { IWorkspaceContextService, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IMessageService, Severity } from 'vs/platform/message/common/message'; import { RawContextKey, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ResourceContextKey } from 'vs/workbench/common/resourceContextKey'; import { IWorkbenchThemeService, IFileIconTheme } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { attachListStyler } from 'vs/platform/theme/common/styler'; export class RosNodeView extends CollapsibleViewletView { private static EXPLORER_FILE_CHANGES_REACT_DELAY = 500; // delay in ms to react to file changes to give our internal events a chance to react first private static EXPLORER_FILE_CHANGES_REFRESH_DELAY = 100; // delay in ms to refresh the explorer from disk file changes private workspace: IWorkspace; private rosNodeViewer: ITree; private filter: FileFilter; private explorerRefreshDelayer: ThrottledDelayer<void>; private resourceContext: ResourceContextKey; private folderContext: IContextKey<boolean>; private shouldRefresh: boolean; private autoReveal: boolean; private settings: any; private rootPath: string; private changeRoot: boolean; constructor( actionRunner: IActionRunner, settings: any, headerSize: number, @IMessageService messageService: IMessageService, @IContextMenuService contextMenuService: IContextMenuService, @IInstantiationService private instantiationService: IInstantiationService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IProgressService private progressService: IProgressService, @IListService private listService: IListService, @IFileService private fileService: IFileService, @IPartService private partService: IPartService, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService private configurationService: IConfigurationService, @IWorkbenchThemeService private themeService: IWorkbenchThemeService ) { super(actionRunner, false, nls.localize('rosNodeSection', "ROS Node Section"), messageService, keybindingService, contextMenuService, headerSize); this.workspace = contextService.getWorkspace(); this.settings = settings; this.actionRunner = actionRunner; this.autoReveal = true; this.rootPath = 'devel/lib'; this.changeRoot = false; this.explorerRefreshDelayer = new ThrottledDelayer<void>(RosNodeView.EXPLORER_FILE_CHANGES_REFRESH_DELAY); this.resourceContext = instantiationService.createInstance(ResourceContextKey); this.folderContext = new RawContextKey<boolean>('explorerResourceIsFolder', undefined).bindTo(contextKeyService); } public renderHeader(container: HTMLElement): void { const titleDiv = $('div.title').appendTo(container); $('span').text(nls.localize('node', "Node")).appendTo(titleDiv); super.renderHeader(container); } public renderBody(container: HTMLElement): void { this.treeContainer = super.renderViewTree(container); DOM.addClass(this.treeContainer, 'explorer-folders-view'); DOM.addClass(this.treeContainer, 'show-file-icons'); this.tree = this.createViewer($(this.treeContainer)); if (this.toolBar) { this.toolBar.setActions(prepareActions(this.getActions()), [])(); } const onFileIconThemeChange = (fileIconTheme: IFileIconTheme) => { DOM.toggleClass(this.treeContainer, 'align-icons-and-twisties', fileIconTheme.hasFileIcons && !fileIconTheme.hasFolderIcons); }; this.themeService.onDidFileIconThemeChange(onFileIconThemeChange); onFileIconThemeChange(this.themeService.getFileIconTheme()); } public getActions(): IAction[] { const actions: Action[] = []; actions.push(this.instantiationService.createInstance(CleanRosNodeAction, this, 'explorer-action clean-rosnode')); actions.push(this.instantiationService.createInstance(RefreshViewExplorerAction, this, 'explorer-action refresh-explorer')); actions.push(this.instantiationService.createInstance(CollapseAction, this.getViewer(), true, 'explorer-action collapse-explorer')); // Set Order for (let i = 0; i < actions.length; i++) { const action = actions[i]; action.order = 10 * (i + 1); } return actions; } public create(): TPromise<void> { // Load and Fill Viewer return this.doRefresh(); } public focusBody(): void { // Make sure the current selected element is revealed if (this.rosNodeViewer) { if (this.autoReveal) { const selection = this.rosNodeViewer.getSelection(); if (selection.length > 0) { this.reveal(selection[0], 0.5).done(null, errors.onUnexpectedError); } } // Pass Focus to Viewer this.rosNodeViewer.DOMFocus(); } } public setVisible(visible: boolean): TPromise<void> { return super.setVisible(visible).then(() => { // Show if (visible) { // If a refresh was requested and we are now visible, run it let refreshPromise = TPromise.as<void>(null); if (this.shouldRefresh) { refreshPromise = this.doRefresh(); this.shouldRefresh = false; // Reset flag } if (!this.autoReveal) { return refreshPromise; // do not react to setVisible call if autoReveal === false } // Return now if the workbench has not yet been created - in this case the workbench takes care of restoring last used editors if (!this.partService.isCreated()) { return TPromise.as(null); } // Otherwise restore last used file: By Explorer selection return refreshPromise; } return undefined; }); } public getRootPath(): string { return this.rootPath; } public setRootPath(rootPath: string): TPromise<void> { if (this.rootPath === rootPath) { return null; } this.rootPath = rootPath; this.changeRoot = true; return this.refresh(); } private get root(): FileStat { return this.rosNodeViewer ? (<FileStat>this.rosNodeViewer.getInput()) : null; } public createViewer(container: Builder): ITree { const dataSource = this.instantiationService.createInstance(FileDataSource); const actionProvider = this.instantiationService.createInstance(ActionProvider); const renderer = this.instantiationService.createInstance(FileRenderer); const controller = this.instantiationService.createInstance(FileController, actionProvider); this.filter = this.instantiationService.createInstance(FileFilter); const accessibilityProvider = this.instantiationService.createInstance(FileAccessibilityProvider); this.rosNodeViewer = new Tree(container.getHTMLElement(), { dataSource, renderer, controller, filter: this.filter, accessibilityProvider }, { autoExpandSingleChildren: true, ariaLabel: nls.localize('treeAriaLabel', "Nodes Explorer"), twistiePixels: 12, showTwistie: false, keyboardSupport: false }); // Theme styler this.toDispose.push(attachListStyler(this.rosNodeViewer, this.themeService)); // Update Viewer based on File Change Events this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); // Update resource context based on focused element this.toDispose.push(this.rosNodeViewer.addListener('focus', (e: { focus: FileStat }) => { this.resourceContext.set(e.focus && e.focus.resource); this.folderContext.set(e.focus && e.focus.isDirectory); })); // Open when selecting via keyboard this.toDispose.push(this.rosNodeViewer.addListener('selection', event => { if (event && event.payload && event.payload.origin === 'keyboard') { const element = this.tree.getSelection(); if (Array.isArray(element) && element[0] instanceof FileStat) { if (element[0].isDirectory) { this.rosNodeViewer.toggleExpansion(element[0]); } } } })); return this.rosNodeViewer; } public getOptimalWidth(): number { const parentNode = this.rosNodeViewer.getHTMLElement(); const childNodes = [].slice.call(parentNode.querySelectorAll('.explorer-item > a')); return DOM.getLargestChildWidth(parentNode, childNodes); } private onFileChanges(e: FileChangesEvent): void { // Check if an explorer refresh is necessary (delayed to give internal events a chance to react first) // Note: there is no guarantee when the internal events are fired vs real ones. Code has to deal with the fact that one might // be fired first over the other or not at all. setTimeout(() => { if (!this.shouldRefresh && this.shouldRefreshFromEvent(e)) { this.refreshFromEvent(); } }, RosNodeView.EXPLORER_FILE_CHANGES_REACT_DELAY); } private shouldRefreshFromEvent(e: FileChangesEvent): boolean { // Filter to the ones we care e = this.filterToAddRemovedOnWorkspacePath(e, (event, segments) => { if (segments[0] !== '.git') { return true; // we like all things outside .git } return segments.length === 1; // we only care about the .git folder itself }); // We only ever refresh from files/folders that got added or deleted if (e.gotAdded() || e.gotDeleted()) { const added = e.getAdded(); const deleted = e.getDeleted(); if (!this.root) { return false; } // Check added: Refresh if added file/folder is not part of resolved root and parent is part of it const ignoredPaths: { [fsPath: string]: boolean } = <{ [fsPath: string]: boolean }>{}; for (let i = 0; i < added.length; i++) { const change = added[i]; if (!this.contextService.isInsideWorkspace(change.resource)) { continue; // out of workspace file } // Find parent const parent = paths.dirname(change.resource.fsPath); // Continue if parent was already determined as to be ignored if (ignoredPaths[parent]) { continue; } // Compute if parent is visible and added file not yet part of it const parentStat = this.root.find(URI.file(parent)); if (parentStat && parentStat.isDirectoryResolved && !this.root.find(change.resource)) { return true; } // Keep track of path that can be ignored for faster lookup if (!parentStat || !parentStat.isDirectoryResolved) { ignoredPaths[parent] = true; } } // Check deleted: Refresh if deleted file/folder part of resolved root for (let j = 0; j < deleted.length; j++) { const del = deleted[j]; if (!this.contextService.isInsideWorkspace(del.resource)) { continue; // out of workspace file } if (this.root.find(del.resource)) { return true; } } } return false; } private filterToAddRemovedOnWorkspacePath(e: FileChangesEvent, fn: (change: IFileChange, workspacePathSegments: string[]) => boolean): FileChangesEvent { return new FileChangesEvent(e.changes.filter(change => { if (change.type === FileChangeType.UPDATED) { return false; // we only want added / removed } const workspacePath = this.contextService.toWorkspaceRelativePath(change.resource); if (!workspacePath) { return false; // not inside workspace } const segments = workspacePath.split(/\//); return fn(change, segments); })); } private refreshFromEvent(): void { if (this.isVisible) { this.explorerRefreshDelayer.trigger(() => { if (!this.rosNodeViewer.getHighlight()) { return this.doRefresh(); } return TPromise.as(null); }).done(null, errors.onUnexpectedError); } else { this.shouldRefresh = true; } } /** * Refresh the contents of the explorer to get up to date data from the disk about the file structure. */ public refresh(): TPromise<void> { if (!this.rosNodeViewer || this.rosNodeViewer.getHighlight()) { return TPromise.as(null); } // Focus this.rosNodeViewer.DOMFocus(); return this.doRefresh(); } private doRefresh(): TPromise<void> { const root = this.changeRoot ? null : this.root; const targetsToResolve: URI[] = []; let targetsToExpand: URI[] = []; this.changeRoot = false; // First time refresh: Receive target through active editor input or selection and also include settings from previous session if (!root) { if (targetsToExpand.length) { targetsToResolve.push(...targetsToExpand); } } // Subsequent refresh: Receive targets through expanded folders in tree else { this.getResolvedDirectories(root, targetsToResolve); } // Load Root Stat with given target path configured const options: IResolveFileOptions = { resolveTo: targetsToResolve }; const absRootPath: URI = URI.file(paths.join(this.workspace.resource.fsPath, this.rootPath)); const promise = this.fileService.resolveFile(absRootPath, options).then(stat => { let explorerPromise: TPromise<void>; // Convert to model const modelStat = FileStat.create(stat, options.resolveTo); // First time refresh: The stat becomes the input of the viewer if (!root) { explorerPromise = this.rosNodeViewer.setInput(modelStat).then(() => { // Make sure to expand all folders that where expanded in the previous session if (targetsToExpand) { return this.rosNodeViewer.expandAll(targetsToExpand.map(expand => this.root.find(expand))); } return TPromise.as(null); }); } // Subsequent refresh: Merge stat into our local model and refresh tree else { FileStat.mergeLocalWithDisk(modelStat, root); explorerPromise = this.rosNodeViewer.refresh(root); } return explorerPromise; }, (e: any) => TPromise.wrapError(e)); this.progressService.showWhile(promise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */); return promise; } /** * Given a stat, fills an array of path that make all folders below the stat that are resolved directories. */ private getResolvedDirectories(stat: FileStat, resolvedDirectories: URI[]): void { if (stat.isDirectoryResolved) { if (stat.resource.toString() !== this.workspace.resource.toString()) { // Drop those path which are parents of the current one for (let i = resolvedDirectories.length - 1; i >= 0; i--) { const resource = resolvedDirectories[i]; if (stat.resource.toString().indexOf(resource.toString()) === 0) { resolvedDirectories.splice(i); } } // Add to the list of path to resolve resolvedDirectories.push(stat.resource); } // Recurse into children for (let i = 0; i < stat.children.length; i++) { const child = stat.children[i]; this.getResolvedDirectories(child, resolvedDirectories); } } } /** * Selects and reveal the file element provided by the given resource if its found in the explorer. Will try to * resolve the path from the disk in case the explorer is not yet expanded to the file yet. */ public select(resource: URI, reveal: boolean = this.autoReveal): TPromise<void> { // Require valid path if (!resource || resource.toString() === this.workspace.resource.toString()) { return TPromise.as(null); } // If path already selected, just reveal and return const selection = this.hasSelection(resource); if (selection) { return reveal ? this.reveal(selection, 0.5) : TPromise.as(null); } // First try to get the stat object from the input to avoid a roundtrip const root = this.root; if (!root) { return TPromise.as(null); } const fileStat = root.find(resource); if (fileStat) { return this.doSelect(fileStat, reveal); } // Stat needs to be resolved first and then revealed const options: IResolveFileOptions = { resolveTo: [resource] }; return this.fileService.resolveFile(this.workspace.resource, options).then(stat => { // Convert to model const modelStat = FileStat.create(stat, options.resolveTo); // Update Input with disk Stat FileStat.mergeLocalWithDisk(modelStat, root); // Select and Reveal return this.rosNodeViewer.refresh(root).then(() => this.doSelect(root.find(resource), reveal)); }, (e: any) => this.messageService.show(Severity.Error, e)); } private hasSelection(resource: URI): FileStat { const currentSelection: FileStat[] = this.rosNodeViewer.getSelection(); for (let i = 0; i < currentSelection.length; i++) { if (currentSelection[i].resource.toString() === resource.toString()) { return currentSelection[i]; } } return null; } private doSelect(fileStat: FileStat, reveal: boolean): TPromise<void> { if (!fileStat) { return TPromise.as(null); } // Special case: we are asked to reveal and select an element that is not visible // In this case we take the parent element so that we are at least close to it. if (!this.filter.isVisible(this.tree, fileStat)) { fileStat = fileStat.parent; if (!fileStat) { return TPromise.as(null); } } // Reveal depending on flag let revealPromise: TPromise<void>; if (reveal) { revealPromise = this.reveal(fileStat, 0.5); } else { revealPromise = TPromise.as(null); } return revealPromise.then(() => { if (!fileStat.isDirectory) { this.rosNodeViewer.setSelection([fileStat]); // Since folders can not be opened, only select files } this.rosNodeViewer.setFocus(fileStat); }); } public dispose(): void { if (this.toolBar) { this.toolBar.dispose(); } super.dispose(); } }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojSwitch extends editableValue<boolean, ojSwitchSettableProperties> { disabled: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; readonly: boolean; value: boolean; translations: { switchOff?: string; switchOn?: string; }; addEventListener<T extends keyof ojSwitchEventMap>(type: T, listener: (this: HTMLElement, ev: ojSwitchEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojSwitchSettableProperties>(property: T): ojSwitch[T]; getProperty(property: string): any; setProperty<T extends keyof ojSwitchSettableProperties>(property: T, value: ojSwitchSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSwitchSettableProperties>): void; setProperties(properties: ojSwitchSettablePropertiesLenient): void; } export namespace ojSwitch { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojSwitch["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojSwitch["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojSwitch["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged = JetElementCustomEvent<ojSwitch["readonly"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojSwitch["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<boolean, ojSwitchSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojSwitchEventMap extends editableValueEventMap<boolean, ojSwitchSettableProperties> { 'ojAnimateEnd': ojSwitch.ojAnimateEnd; 'ojAnimateStart': ojSwitch.ojAnimateStart; 'disabledChanged': JetElementCustomEvent<ojSwitch["disabled"]>; 'displayOptionsChanged': JetElementCustomEvent<ojSwitch["displayOptions"]>; 'labelledByChanged': JetElementCustomEvent<ojSwitch["labelledBy"]>; 'readonlyChanged': JetElementCustomEvent<ojSwitch["readonly"]>; 'valueChanged': JetElementCustomEvent<ojSwitch["value"]>; 'describedByChanged': JetElementCustomEvent<ojSwitch["describedBy"]>; 'helpChanged': JetElementCustomEvent<ojSwitch["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojSwitch["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojSwitch["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojSwitch["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<ojSwitch["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojSwitch["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojSwitch["valid"]>; } export interface ojSwitchSettableProperties extends editableValueSettableProperties<boolean> { disabled: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; readonly: boolean; value: boolean; translations: { switchOff?: string; switchOn?: string; }; } export interface ojSwitchSettablePropertiesLenient extends Partial<ojSwitchSettableProperties> { [key: string]: any; } export type SwitchElement = ojSwitch; export namespace SwitchElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojSwitch["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojSwitch["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojSwitch["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged = JetElementCustomEvent<ojSwitch["readonly"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojSwitch["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<boolean, ojSwitchSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<boolean, ojSwitchSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface SwitchIntrinsicProps extends Partial<Readonly<ojSwitchSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojSwitchEventMap['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojSwitchEventMap['ojAnimateStart']) => void; ondisabledChanged?: (value: ojSwitchEventMap['disabledChanged']) => void; ondisplayOptionsChanged?: (value: ojSwitchEventMap['displayOptionsChanged']) => void; onlabelledByChanged?: (value: ojSwitchEventMap['labelledByChanged']) => void; onreadonlyChanged?: (value: ojSwitchEventMap['readonlyChanged']) => void; onvalueChanged?: (value: ojSwitchEventMap['valueChanged']) => void; ondescribedByChanged?: (value: ojSwitchEventMap['describedByChanged']) => void; onhelpChanged?: (value: ojSwitchEventMap['helpChanged']) => void; onhelpHintsChanged?: (value: ojSwitchEventMap['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojSwitchEventMap['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojSwitchEventMap['labelHintChanged']) => void; onmessagesCustomChanged?: (value: ojSwitchEventMap['messagesCustomChanged']) => void; onuserAssistanceDensityChanged?: (value: ojSwitchEventMap['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojSwitchEventMap['validChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-switch": SwitchIntrinsicProps; } } }
the_stack
import './mock_browser_for_node'; import canvas from 'canvas'; import path, {dirname} from 'path'; import fs from 'fs'; import {PNG} from 'pngjs'; import pixelmatch from 'pixelmatch'; import {fileURLToPath} from 'url'; import glob from 'glob'; import nise from 'nise'; import {createRequire} from 'module'; import rtlText from '@mapbox/mapbox-gl-rtl-text'; import localizeURLs from '../lib/localize-urls'; import maplibregl from '../../../src/index'; import browser from '../../../src/util/browser'; import * as rtlTextPluginModule from '../../../src/source/rtl_text_plugin'; import CanvasSource from '../../../src/source/canvas_source'; import customLayerImplementations from './custom_layer_implementations'; import type Map from '../../../src/ui/map'; import type {StyleSpecification} from '../../../src/style-spec/types.g'; import type {PointLike} from '../../../src/ui/camera'; const {fakeServer} = nise; const {plugin: rtlTextPlugin} = rtlTextPluginModule; const {registerFont} = canvas; // @ts-ignore const __dirname = dirname(fileURLToPath(import.meta.url)); // @ts-ignore const require = createRequire(import.meta.url); registerFont('./node_modules/npm-font-open-sans/fonts/Bold/OpenSans-Bold.ttf', {family: 'Open Sans', weight: 'bold'}); rtlTextPlugin['applyArabicShaping'] = rtlText.applyArabicShaping; rtlTextPlugin['processBidirectionalText'] = rtlText.processBidirectionalText; rtlTextPlugin['processStyledBidirectionalText'] = rtlText.processStyledBidirectionalText; let now = 0; type TestData = { id: string; width: number; height: number; pixelRatio: number; recycleMap: boolean; allowed: number; ok: boolean; difference: number; timeout: number; addFakeCanvas: { id: string; image: string; }; axonometric: boolean; skew: [number, number]; fadeDuration: number; debug: boolean; showOverdrawInspector: boolean; showPadding: boolean; collisionDebug: boolean; localIdeographFontFamily: string; crossSourceCollisions: boolean; operations: any[]; queryGeometry: PointLike; queryOptions: any; error: Error; maxPitch: number; // base64-encoded content of the PNG results actual: string; diff: string; expected: string; } type RenderOptions = { tests: any[]; recycleMap: boolean; report: boolean; seed: string; } type StyleWithTestData = StyleSpecification & { metadata : { test: TestData; }; } // https://stackoverflow.com/a/1349426/229714 function makeHash(): string { const array = []; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 10; ++i) array.push(possible.charAt(Math.floor(Math.random() * possible.length))); // join array elements without commas. return array.join(''); } function checkParameter(options: RenderOptions, param: string): boolean { const index = options.tests.indexOf(param); if (index === -1) return false; options.tests.splice(index, 1); return true; } function checkValueParameter(options: RenderOptions, defaultValue: any, param: string) { const index = options.tests.findIndex((elem) => { return String(elem).startsWith(param); }); if (index === -1) return defaultValue; const split = String(options.tests.splice(index, 1)).split('='); if (split.length !== 2) return defaultValue; return split[1]; } /** * Compares the Unit8Array that was created to the expected file in the file system. * It updates testData with the results. * * @param directory The base directory of the data * @param testData The test data * @param data The actual image data to compare the expected to * @returns nothing as it updates the testData object */ function compareRenderResults(directory: string, testData: TestData, data: Uint8Array) { let stats; const dir = path.join(directory, testData.id); try { // @ts-ignore stats = fs.statSync(dir, fs.R_OK | fs.W_OK); if (!stats.isDirectory()) throw new Error(); } catch (e) { fs.mkdirSync(dir); } const expectedPath = path.join(dir, 'expected.png'); const actualPath = path.join(dir, 'actual.png'); const diffPath = path.join(dir, 'diff.png'); const width = Math.floor(testData.width * testData.pixelRatio); const height = Math.floor(testData.height * testData.pixelRatio); const actualImg = new PNG({width, height}); // PNG data must be unassociated (not premultiplied) for (let i = 0; i < data.length; i++) { const a = data[i * 4 + 3] / 255; if (a !== 0) { data[i * 4 + 0] /= a; data[i * 4 + 1] /= a; data[i * 4 + 2] /= a; } } actualImg.data = data as any; // there may be multiple expected images, covering different platforms const expectedPaths = glob.sync(path.join(dir, 'expected*.png')); if (!process.env.UPDATE && expectedPaths.length === 0) { throw new Error('No expected*.png files found; did you mean to run tests with UPDATE=true?'); } if (process.env.UPDATE) { fs.writeFileSync(expectedPath, PNG.sync.write(actualImg)); return; } // if we have multiple expected images, we'll compare against each one and pick the one with // the least amount of difference; this is useful for covering features that render differently // depending on platform, i.e. heatmaps use half-float textures for improved rendering where supported let minDiff = Infinity; let minDiffImg: PNG; let minExpectedBuf: Buffer; for (const path of expectedPaths) { const expectedBuf = fs.readFileSync(path); const expectedImg = PNG.sync.read(expectedBuf); const diffImg = new PNG({width, height}); const diff = pixelmatch( actualImg.data, expectedImg.data, diffImg.data, width, height, {threshold: 0.1285}) / (width * height); if (diff < minDiff) { minDiff = diff; minDiffImg = diffImg; minExpectedBuf = expectedBuf; } } const diffBuf = PNG.sync.write(minDiffImg, {filterType: 4}); const actualBuf = PNG.sync.write(actualImg, {filterType: 4}); fs.writeFileSync(diffPath, diffBuf); fs.writeFileSync(actualPath, actualBuf); testData.difference = minDiff; testData.ok = minDiff <= testData.allowed; testData.actual = actualBuf.toString('base64'); testData.expected = minExpectedBuf.toString('base64'); testData.diff = diffBuf.toString('base64'); } /** * Mocks XHR request and simply pulls file from the file system. */ function mockXhr() { const server = fakeServer.create(); global.XMLHttpRequest = (server as any).xhr; // @ts-ignore XMLHttpRequest.onCreate = (req: any) => { setTimeout(() => { const relativePath = req.url.replace(/^http:\/\/localhost:(\d+)\//, '').replace(/\?.*/, ''); let body: Buffer = null; try { if (relativePath.startsWith('mapbox-gl-styles')) { body = fs.readFileSync(path.join(path.dirname(require.resolve('mapbox-gl-styles')), '..', relativePath)); } else if (relativePath.startsWith('mvt-fixtures')) { body = fs.readFileSync(path.join(path.dirname(require.resolve('@mapbox/mvt-fixtures')), '..', relativePath)); } else { body = fs.readFileSync(path.join(__dirname, '../assets', relativePath)); } if (req.responseType !== 'arraybuffer') { req.response = body.toString('utf8'); } else { req.response = body; } req.setStatus(200); req.onload(); } catch (ex) { req.setStatus(404); // file not found req.onload(); } }, 0); }; } /** * Gets all the tests from the file system looking for style.json files. * * @param options The options * @param directory The base directory * @returns The tests data structure and the styles that were loaded */ function getTestStyles(options: RenderOptions, directory: string): StyleWithTestData[] { const tests = options.tests || []; const sequence = glob.sync('**/style.json', {cwd: directory}) .map(fixture => { const id = path.dirname(fixture); const style = JSON.parse(fs.readFileSync(path.join(directory, fixture), 'utf8')) as StyleWithTestData; style.metadata = style.metadata || {} as any; style.metadata.test = Object.assign({ id, width: 512, height: 512, pixelRatio: 1, recycleMap: options.recycleMap || false, allowed: 0.00025 }, style.metadata.test); return style; }) .filter(style => { const test = style.metadata.test; if (tests.length !== 0 && !tests.some(t => test.id.indexOf(t) !== -1)) { return false; } if (process.env.BUILDTYPE !== 'Debug' && test.id.match(/^debug\//)) { console.log(`* skipped ${test.id}`); return false; } localizeURLs(style, 2900, path.join(__dirname, '../'), require); return true; }); return sequence; } // replacing the browser method of get image in order to avoid usage of context and canvas 2d with Image object... // @ts-ignore browser.getImageData = (img, padding = 0) => { // @ts-ignore if (!img.data) { return {width: 1, height: 1, data: new Uint8Array(1)}; } const width = img.width as number; const height = img.height as number; // @ts-ignore const data = img.data; const source = new Uint8Array(data); const dest = new Uint8Array((2 * padding + width) * (2 * padding + height) * 4); const offset = (2 * padding + width) * padding + padding; for (let i = 0; i < height; i++) { dest.set(source.slice(i * width * 4, (i + 1) * width * 4), 4 * (offset + (width + 2 * padding) * i)); } return {width: width + 2 * padding, height: height + 2 * padding, data: dest}; }; function createFakeCanvas(document: Document, id: string, imagePath: string): HTMLCanvasElement { const fakeCanvas = document.createElement('canvas'); const image = PNG.sync.read(fs.readFileSync(path.join(__dirname, '../assets', imagePath))); fakeCanvas.id = id; (fakeCanvas as any).data = image.data; fakeCanvas.width = image.width; fakeCanvas.height = image.height; return fakeCanvas; } function updateFakeCanvas(document: Document, id: string, imagePath: string) { const fakeCanvas = document.getElementById(id); const image = PNG.sync.read(fs.readFileSync(path.join(__dirname, '../assets', imagePath))); (fakeCanvas as any).data = image.data; } /** * Executes the operations in the test data * * @param testData The test data to operate upon * @param map The Map * @param operations The operations * @param callback The callback to use when all the operations are executed */ function applyOperations(testData: TestData, map: Map & { _render: () => void}, operations: any[], callback: Function) { const operation = operations && operations[0]; if (!operations || operations.length === 0) { callback(); } else if (operation[0] === 'wait') { if (operation.length > 1) { now += operation[1]; map._render(); applyOperations(testData, map, operations.slice(1), callback); } else { const wait = function() { if (map.loaded()) { applyOperations(testData, map, operations.slice(1), callback); } else { map.once('render', wait); } }; wait(); } } else if (operation[0] === 'sleep') { // Prefer "wait", which renders until the map is loaded // Use "sleep" when you need to test something that sidesteps the "loaded" logic setTimeout(() => { applyOperations(testData, map, operations.slice(1), callback); }, operation[1]); } else if (operation[0] === 'addImage') { const {data, width, height} = PNG.sync.read(fs.readFileSync(path.join(__dirname, '../assets', operation[2]))); map.addImage(operation[1], {width, height, data: new Uint8Array(data)}, operation[3] || {}); applyOperations(testData, map, operations.slice(1), callback); } else if (operation[0] === 'addCustomLayer') { map.addLayer(new customLayerImplementations[operation[1]](), operation[2]); map._render(); applyOperations(testData, map, operations.slice(1), callback); } else if (operation[0] === 'updateFakeCanvas') { const canvasSource = map.getSource(operation[1]) as CanvasSource; canvasSource.play(); // update before pause should be rendered updateFakeCanvas(window.document, testData.addFakeCanvas.id, operation[2]); canvasSource.pause(); // update after pause should not be rendered updateFakeCanvas(window.document, testData.addFakeCanvas.id, operation[3]); map._render(); applyOperations(testData, map, operations.slice(1), callback); } else if (operation[0] === 'setStyle') { // Disable local ideograph generation (enabled by default) for // consistent local ideograph rendering using fixtures in all runs of the test suite. map.setStyle(operation[1], {localIdeographFontFamily: false as any}); applyOperations(testData, map, operations.slice(1), callback); } else if (operation[0] === 'pauseSource') { map.style.sourceCaches[operation[1]].pause(); applyOperations(testData, map, operations.slice(1), callback); } else { if (typeof map[operation[0]] === 'function') { map[operation[0]](...operation.slice(1)); } applyOperations(testData, map, operations.slice(1), callback); } } /** * It creates the map and applies the operations to create an image * and returns it as a Uint8Array * * @param style The style to use * @returns an image byte array promise */ function getImageFromStyle(style: StyleWithTestData): Promise<Uint8Array> { return new Promise((resolve, reject) => { const options = style.metadata.test; setTimeout(() => { reject(new Error('Test timed out')); }, options.timeout || 20000); if (options.addFakeCanvas) { const fakeCanvas = createFakeCanvas(window.document, options.addFakeCanvas.id, options.addFakeCanvas.image); window.document.body.appendChild(fakeCanvas); } const container = window.document.createElement('div'); Object.defineProperty(container, 'clientWidth', {value: options.width}); Object.defineProperty(container, 'clientHeight', {value: options.height}); const map = new maplibregl.Map({ container, style, // @ts-ignore classes: options.classes, interactive: false, attributionControl: false, maxPitch: options.maxPitch, pixelRatio: options.pixelRatio, preserveDrawingBuffer: true, axonometric: options.axonometric || false, skew: options.skew || [0, 0], fadeDuration: options.fadeDuration || 0, localIdeographFontFamily: options.localIdeographFontFamily || false as any, crossSourceCollisions: typeof options.crossSourceCollisions === 'undefined' ? true : options.crossSourceCollisions }); // Configure the map to never stop the render loop map.repaint = true; now = 0; browser.now = () => { return now; }; if (options.debug) map.showTileBoundaries = true; if (options.showOverdrawInspector) map.showOverdrawInspector = true; if (options.showPadding) map.showPadding = true; const gl = map.painter.context.gl; map.once('load', () => { if (options.collisionDebug) { map.showCollisionBoxes = true; if (options.operations) { options.operations.push(['wait']); } else { options.operations = [['wait']]; } } applyOperations(options, map as any, options.operations, () => { const viewport = gl.getParameter(gl.VIEWPORT); const w = viewport[2]; const h = viewport[3]; const data = new Uint8Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data); // Flip the scanlines. const stride = w * 4; const tmp = new Uint8Array(stride); for (let i = 0, j = h - 1; i < j; i++, j--) { const start = i * stride; const end = j * stride; tmp.set(data.slice(start, start + stride), 0); data.set(data.slice(end, end + stride), start); data.set(tmp, end); } map.remove(); gl.getExtension('STACKGL_destroy_context').destroy(); delete map.painter.context.gl; if (options.addFakeCanvas) { const fakeCanvas = window.document.getElementById(options.addFakeCanvas.id); fakeCanvas.parentNode.removeChild(fakeCanvas); } resolve(data); }); }); }); } /** * Prints the progress to the console * * @param test The current test * @param total The total number of tests * @param index The current test index */ function printProgress(test: TestData, total: number, index: number) { if (test.error) { console.log(`${index}/${total}: errored ${test.id} ${test.error.message}`); } else if (!test.ok) { console.log(`${index}/${total}: failed ${test.id} ${test.difference}`); } else { console.log(`${index}/${total}: passed ${test.id}`); } } type TestStats = { total: number; errored: TestData[]; failed: TestData[]; passed: TestData[]; }; /** * Prints the summary at the end of the run * * @param tests all the tests with their resutls * @returns */ function printStatistics(stats: TestStats): boolean { const erroredCount = stats.errored.length; const failedCount = stats.failed.length; const passedCount = stats.passed.length; function printStat(status: string, statusCount: number) { if (statusCount > 0) { console.log(`${statusCount} ${status} (${(100 * statusCount / stats.total).toFixed(1)}%)`); } } printStat('passed', passedCount); printStat('failed', failedCount); printStat('errored', erroredCount); return (failedCount + erroredCount) === 0; } /** * Run the render test suite, compute differences to expected values (making exceptions based on * implementation vagaries), print results to standard output, write test artifacts to the * filesystem (optionally updating expected results), and exit the process with a success or * failure code. * * If all the tests are successful, this function exits the process with exit code 0. Otherwise * it exits with 1. */ const options: RenderOptions = { tests: [], recycleMap: false, report: false, seed: makeHash() }; if (process.argv.length > 2) { options.tests = process.argv.slice(2).filter((value, index, self) => { return self.indexOf(value) === index; }) || []; options.recycleMap = checkParameter(options, '--recycle-map'); options.report = checkParameter(options, '--report'); options.seed = checkValueParameter(options, options.seed, '--seed'); } mockXhr(); const directory = path.join(__dirname); const testStyles = getTestStyles(options, directory); let index = 0; for (const style of testStyles) { try { //@ts-ignore const data = await getImageFromStyle(style); compareRenderResults(directory, style.metadata.test, data); } catch (ex) { style.metadata.test.error = ex; } printProgress(style.metadata.test, testStyles.length, ++index); } const tests = testStyles.map(s => s.metadata.test).filter(t => !!t); const testStats: TestStats = { total: tests.length, errored: tests.filter(t => t.error), failed: tests.filter(t => !t.error && !t.ok), passed: tests.filter(t => !t.error && t.ok) }; if (process.env.UPDATE) { console.log(`Updated ${testStyles.length} tests.`); process.exit(0); } const success = printStatistics(testStats); function getReportItem(test: TestData) { let status: 'errored' | 'failed'; if (test.error) { status = 'errored'; } else { status = 'failed'; } return `<div class="test"> <h2>${test.id}</h2> ${status !== 'errored' ? ` <img width="${test.width}" height="${test.height}" src="data:image/png;base64,${test.actual}" data-alt-src="data:image/png;base64,${test.expected}"> <img style="width: ${test.width}; height: ${test.height}" src="data:image/png;base64,${test.diff}">` : '' } ${test.error ? `<p style="color: red"><strong>Error:</strong> ${test.error.message}</p>` : ''} ${test.difference ? `<p class="diff"><strong>Diff:</strong> ${test.difference}</p>` : ''} </div>`; } if (options.report) { const erroredItems = testStats.errored.map(t => getReportItem(t)); const failedItems = testStats.failed.map(t => getReportItem(t)); let resultData: string; if (erroredItems.length || failedItems.length) { resultData = ` <div class="tests failed"> <h1 style="color: red"><button id="toggle-failed">Toggle</button> Failed Tests (${failedItems.length})</h1> ${failedItems.join('\n')} </div> <div class="tests errored"> <h1 style="color: black"><button id="toggle-errored">Toggle</button> Errored Tests (${erroredItems.length})</h1> ${erroredItems.join('\n')} </div> <script> document.addEventListener('mouseover', handleHover); document.addEventListener('mouseout', handleHover); function handleHover(e) { var el = e.target; if (el.tagName === 'IMG' && el.dataset.altSrc) { var tmp = el.src; el.src = el.dataset.altSrc; el.dataset.altSrc = tmp; } } document.getElementById('toggle-failed').addEventListener('click', function (e) { for (const row of document.querySelectorAll('.tests.failed .test')) { row.classList.toggle('hide'); } }); document.getElementById('toggle-errored').addEventListener('click', function (e) { for (const row of document.querySelectorAll('.tests.errored .test.')) { row.classList.toggle('hide'); } }); </script>`; } else { resultData = '<h1 style="color: green">All tests passed!</h1>'; } const resultsContent = ` <!doctype html> <html lang="en"> <head> <title>Render Test Results</title> <style> body { font: 18px/1.2 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 10px; } h1 { font-size: 32px; margin-bottom: 0; } button { vertical-align: middle; } h2 { font-size: 24px; font-weight: normal; margin: 10px 0 10px; line-height: 1; } img { margin: 0 10px 10px 0; border: 1px dotted #ccc; } .stats { margin-top: 10px; } .test { border-bottom: 1px dotted #bbb; padding-bottom: 5px; } .tests { border-top: 1px dotted #bbb; margin-top: 10px; } .diff { color: #777; } .test p, .test pre { margin: 0 0 10px; } .test pre { font-size: 14px; } .label { color: white; font-size: 18px; padding: 2px 6px 3px; border-radius: 3px; margin-right: 3px; vertical-align: bottom; display: inline-block; } .hide { display: none; } </style> </head> <body> ${resultData} </body> </html> `; const p = path.join(__dirname, options.recycleMap ? 'results-recycle-map.html' : 'results.html'); fs.writeFileSync(p, resultsContent, 'utf8'); console.log(`Results logged to '${p}'`); } process.exit(success ? 0 : 1);
the_stack
import * as expect from "expect"; import * as simple from "simple-mock"; import { ConsoleLogger, DeviceKeyAlgorithm, EncryptedFile, LogService, MatrixClient, RoomEncryptionAlgorithm, } from "../../src"; import { createTestClient, TEST_DEVICE_ID } from "../MatrixClientTest"; import { InternalOlmMachineFactory } from "../../src/e2ee/InternalOlmMachineFactory"; import { OlmMachine, Signatures } from "@turt2live/matrix-sdk-crypto-nodejs"; describe('CryptoClient', () => { afterEach(() => { InternalOlmMachineFactory.FACTORY_OVERRIDE = null; }); it('should not have a device ID or be ready until prepared', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); client.getWhoAmI = () => Promise.resolve({ user_id: userId, device_id: TEST_DEVICE_ID }); expect(client.crypto).toBeDefined(); expect(client.crypto.clientDeviceId).toBeFalsy(); expect(client.crypto.isReady).toEqual(false); await client.crypto.prepare([]); expect(client.crypto.clientDeviceId).toEqual(TEST_DEVICE_ID); expect(client.crypto.isReady).toEqual(true); }); describe('prepare', () => { it('should prepare the room tracker', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const roomIds = ["!a:example.org", "!b:example.org"]; const { client } = createTestClient(null, userId, true); client.getWhoAmI = () => Promise.resolve({ user_id: userId, device_id: TEST_DEVICE_ID }); const prepareSpy = simple.stub().callFn((rids: string[]) => { expect(rids).toBe(roomIds); return Promise.resolve(); }); (<any>client.crypto).roomTracker.prepare = prepareSpy; // private member access await client.crypto.prepare(roomIds); expect(prepareSpy.callCount).toEqual(1); }); it('should use a stored device ID', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); const whoamiSpy = simple.stub().callFn(() => Promise.resolve({ user_id: userId, device_id: "wrong" })); client.getWhoAmI = whoamiSpy; await client.crypto.prepare([]); expect(whoamiSpy.callCount).toEqual(0); expect(client.crypto.clientDeviceId).toEqual(TEST_DEVICE_ID); }); }); describe('isRoomEncrypted', () => { it('should fail when the crypto has not been prepared', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // await client.crypto.prepare([]); // deliberately commented try { await client.crypto.isRoomEncrypted("!new:example.org"); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); it('should return false for unknown rooms', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); client.getRoomStateEvent = () => Promise.reject("return value not used"); await client.crypto.prepare([]); const result = await client.crypto.isRoomEncrypted("!new:example.org"); expect(result).toEqual(false); }); it('should return false for unencrypted rooms', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); client.getRoomStateEvent = () => Promise.reject("implying 404"); await client.crypto.prepare([]); const result = await client.crypto.isRoomEncrypted("!new:example.org"); expect(result).toEqual(false); }); it('should return true for encrypted rooms (redacted state)', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); client.getRoomStateEvent = () => Promise.resolve({}); await client.crypto.prepare([]); const result = await client.crypto.isRoomEncrypted("!new:example.org"); expect(result).toEqual(true); }); it('should return true for encrypted rooms', async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const userId = "@alice:example.org"; const { client } = createTestClient(null, userId, true); await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); client.getRoomStateEvent = () => Promise.resolve({ algorithm: RoomEncryptionAlgorithm.MegolmV1AesSha2 }); await client.crypto.prepare([]); const result = await client.crypto.isRoomEncrypted("!new:example.org"); expect(result).toEqual(true); }); }); describe('sign', () => { const userId = "@alice:example.org"; let client: MatrixClient; beforeEach(async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), sign: async (_) => ({ [userId]: { [DeviceKeyAlgorithm.Ed25519 + ":" + TEST_DEVICE_ID]: "SIGNATURE_GOES_HERE", }, } as Signatures), } as OlmMachine); const { client: mclient } = createTestClient(null, userId, true); client = mclient; await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // client crypto not prepared for the one test which wants that state }); it('should fail when the crypto has not been prepared', async () => { try { await client.crypto.sign({ doesnt: "matter" }); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); it('should sign the object while retaining signatures without mutation', async () => { await client.crypto.prepare([]); const obj = { sign: "me", signatures: { "@another:example.org": { "ed25519:DEVICE": "signature goes here", }, }, unsigned: { not: "included", }, }; const signatures = await client.crypto.sign(obj); expect(signatures).toMatchObject({ [userId]: { [`ed25519:${TEST_DEVICE_ID}`]: expect.any(String), }, ...obj.signatures, }); expect(obj['signatures']).toBeDefined(); expect(obj['unsigned']).toBeDefined(); }); }); describe('encryptRoomEvent', () => { const userId = "@alice:example.org"; let client: MatrixClient; beforeEach(async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const { client: mclient } = createTestClient(null, userId, true); client = mclient; await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // client crypto not prepared for the one test which wants that state }); it('should fail when the crypto has not been prepared', async () => { try { await client.crypto.encryptRoomEvent("!room:example.org", "org.example", {}); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); it('should fail in unencrypted rooms', async () => { await client.crypto.prepare([]); // Force unencrypted rooms client.crypto.isRoomEncrypted = async () => false; try { await client.crypto.encryptRoomEvent("!room:example.org", "type", {}); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("Room is not encrypted"); } }); it.skip('should get devices for invited members', async () => { // TODO: Support invited members, if history visibility would allow. }); }); describe('decryptRoomEvent', () => { const userId = "@alice:example.org"; let client: MatrixClient; beforeEach(async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const { client: mclient } = createTestClient(null, userId, true); client = mclient; await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // client crypto not prepared for the one test which wants that state }); afterEach(async () => { LogService.setLogger(new ConsoleLogger()); }); it('should fail when the crypto has not been prepared', async () => { try { await client.crypto.decryptRoomEvent(null, null); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); }); describe('encryptMedia', () => { const userId = "@alice:example.org"; let client: MatrixClient; beforeEach(async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const { client: mclient } = createTestClient(null, userId, true); client = mclient; await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // client crypto not prepared for the one test which wants that state }); afterEach(async () => { LogService.setLogger(new ConsoleLogger()); }); it('should fail when the crypto has not been prepared', async () => { try { await client.crypto.encryptMedia(null); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); it('should encrypt media', async () => { await client.crypto.prepare([]); const inputBuffer = Buffer.from("test"); const inputStr = inputBuffer.join(''); const result = await client.crypto.encryptMedia(inputBuffer); expect(result).toBeDefined(); expect(result.buffer).toBeDefined(); expect(result.buffer.join('')).not.toEqual(inputStr); expect(result.file).toBeDefined(); expect(result.file.hashes).toBeDefined(); expect(result.file.hashes.sha256).not.toEqual("n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg"); expect(result.file).toMatchObject({ hashes: { sha256: expect.any(String), }, key: { alg: "A256CTR", ext: true, key_ops: ['encrypt', 'decrypt'], kty: "oct", k: expect.any(String), }, iv: expect.any(String), v: "v2", }); }); }); describe('decryptMedia', () => { const userId = "@alice:example.org"; let client: MatrixClient; // Created from Element Web const testFileContents = "THIS IS A TEST FILE."; const mediaFileContents = Buffer.from("eB15hJlkw8WwgYxwY2mu8vS250s=", "base64"); const testFile: EncryptedFile = { v: "v2", key: { alg: "A256CTR", ext: true, k: "l3OtQ3IJzfJa85j2WMsqNu7J--C-I1hzPxFvinR48mM", key_ops: [ "encrypt", "decrypt" ], kty: "oct" }, iv: "KJQOebQS1wwAAAAAAAAAAA", hashes: { sha256: "Qe4YzmVoPaEcLQeZwFZ4iMp/dlgeFph6mi5DmCaCOzg" }, url: "mxc://localhost/uiWuISEVWixompuiiYyUoGrx", }; function copyOfTestFile(): EncryptedFile { return JSON.parse(JSON.stringify(testFile)); } beforeEach(async () => { InternalOlmMachineFactory.FACTORY_OVERRIDE = () => ({ identityKeys: {}, runEngineUntilComplete: () => Promise.resolve(), } as OlmMachine); const { client: mclient } = createTestClient(null, userId, true); client = mclient; await client.cryptoStore.setDeviceId(TEST_DEVICE_ID); // client crypto not prepared for the one test which wants that state }); afterEach(async () => { LogService.setLogger(new ConsoleLogger()); }); it('should fail when the crypto has not been prepared', async () => { try { await client.crypto.encryptMedia(null); // noinspection ExceptionCaughtLocallyJS throw new Error("Failed to fail"); } catch (e) { expect(e.message).toEqual("End-to-end encryption has not initialized"); } }); it('should be symmetrical', async () => { await client.crypto.prepare([]); const mxc = "mxc://example.org/test"; const inputBuffer = Buffer.from("test"); const encrypted = await client.crypto.encryptMedia(inputBuffer); const downloadSpy = simple.stub().callFn(async (u) => { expect(u).toEqual(mxc); return {data: encrypted.buffer, contentType: "application/octet-stream"}; }); client.downloadContent = downloadSpy; const result = await client.crypto.decryptMedia({ url: mxc, ...encrypted.file, }); expect(result.join('')).toEqual(inputBuffer.join('')); expect(downloadSpy.callCount).toBe(1); }); it('should decrypt', async () => { await client.crypto.prepare([]); const downloadSpy = simple.stub().callFn(async (u) => { expect(u).toEqual(testFile.url); return {data: Buffer.from(mediaFileContents), contentType: "application/octet-stream"}; }); client.downloadContent = downloadSpy; const f = copyOfTestFile(); const result = await client.crypto.decryptMedia(f); expect(result.toString()).toEqual(testFileContents); expect(downloadSpy.callCount).toBe(1); }); }); });
the_stack
import {Component, Input, SimpleChange, HostListener, ViewChild, ElementRef} from '@angular/core'; import { Subject } from "rxjs"; export interface planCount { nodesCnt: number, levelsCnt: number } @Component({ selector: 'plan-viewer', templateUrl: 'plan-viewer.component.html', styleUrls: ['plan-viewer.component.scss'], }) export class PlanViewerComponent { @Input() planFormat: any; @Input() plan: any; @Input() planName: any; @Input() jsonPlan: any; plan_: any; jsonVisible = false; detailed: boolean = false; nodesArr: any[]; nodeIdsArr: any[] = []; ids: any[] = []; edgesArr: any[]; //search variables flatJSONGraph: any = {}; searchRegex: string = ""; searchMatches: any[] = []; matchesFound: boolean = false; matchIdx: number = 0; //variables for ngx-graph zoomToFit$: Subject<boolean> = new Subject(); center$: Subject<boolean> = new Subject(); update$: Subject<boolean> = new Subject(); panToNode$: Subject<any> = new Subject(); //drop down variables planOrientation = "BT"; selectedNode = "n11"; previousNodeId: any; previouseOccurrenceArrayIdx: number; selectedVariableOccurrences: any; selectedVariableOccurrencesArray: any[]; occurrenceArrayIdx: number = 0; nodeIdx = 0; orientations: any[] = [ { label: "Bottom to Top", value: "BT" }, { label: "Top to Bottom", value: "TB" } /* Left to Right or Right to Left do not look right yet { label: "Left to Right", value: "LR" }, { label: "Right to Left", value: "RL" } */ ]; colors = [ "#00ff00", "#0000ff", "#ffff00", "#8b008b", "#ffa500", "#ee82ee", "#ff0000", "#9acd32", "#20b2aa", "#00fa9a", "#db7093", "#eee8aa", "#6495ed", "#ff1493", "#ffa07a", "#2f4f4f", "#8b4513", "#006400", "#808000", "#483d8b", "#000080" ] coloredNodes: any = {}; variablesOccurrences: any = {}; variablesDeclarations: any = {}; variables: any[]; constructor() {} ngOnInit() {} ngAfterViewInit() { } ngOnChanges() { this.plan_ = this.plan; /* If plan format is JSON analyze and augment for visualization */ if (this.planFormat === 'JSON') { //clear previous plans results this.nodesArr = []; this.edgesArr = []; this.nodeIdsArr = []; this.ids = []; this.selectedNode = 'n11'; this.previousNodeId = undefined; this.previouseOccurrenceArrayIdx = undefined; this.selectedVariableOccurrences = undefined; this.selectedVariableOccurrencesArray = undefined; this.occurrenceArrayIdx = 0; this.nodeIdx = 0; this.coloredNodes = {}; this.variablesOccurrences = {}; this.variablesDeclarations = {}; this.variables = undefined; this.searchRegex = ""; this.searchMatches = []; this.matchesFound = false; this.matchIdx = 0; let nodesSet = new Set(); let edgesSet = new Set(); let recurseResults = this.createLinksEdgesArray(this.plan_, this.nodesArr, this.edgesArr, nodesSet, edgesSet); this.nodesArr = recurseResults[0]; this.edgesArr = recurseResults[1]; this.variables = Object.keys(this.variablesOccurrences); //get declarations from variableOccurrences for (let variable of this.variables) { //extract first occurrence of variable (last because we parse from bottom->down) this.variablesDeclarations[variable] = this.variablesOccurrences[variable][this.variablesOccurrences[variable].length-1]; } this.jsonVisible = false; } else { this.jsonVisible = true; } } /* Function that makes the entire graph to fit the view */ fitGraph() { this.zoomToFit$.next(true); this.center$.next(true); } /* * Create links array and edges array for NgxGraphModule */ createLinksEdgesArray(plan, nodesArr, edgesArr, nodesSet, edgesSet) { let nodes = {}; nodes = plan; let nodeToAdd = {}; if (nodes) { if (!nodesSet.has(nodes['operatorId'])) { nodesSet.add(nodes['operatorId']); nodeToAdd['id'] = "n" + nodes['operatorId']; nodeToAdd['id'] = nodeToAdd['id'].replace(/\./g, ''); //read variables and expressions from node and add to this.nodeOccurrences this.storeVariablesExpressions(nodes, nodeToAdd['id']); this.flatJSONGraph[nodeToAdd['id']] = ""; //logic for label nodeToAdd['label'] = nodes['operatorId'] + " : " + nodes['operator']; nodeToAdd['detailed_label'] = nodes['operatorId'] + " : " + nodes['operator']; nodeToAdd['physical_operator'] = nodes['physical-operator']; nodeToAdd['execution_mode'] = "[" + nodes['execution-mode'] + "]" nodeToAdd["details"] = {}; nodeToAdd['selected'] = false; nodeToAdd['operator'] = nodes['operator']; //case for having both expressions and variables if (nodes['expressions'] && nodes['variables']) { nodeToAdd['detailed_label'] += `${this.variableExpressionStringify(nodes['expressions'])} <- ${this.variableExpressionStringify(nodes['variables'])}`; } //case for having only expressions if (nodes['expressions'] && nodes['variables'] == undefined) { nodeToAdd['detailed_label'] += this.variableExpressionStringify(nodes['expressions']); } //case for having only variables if (nodes['variables'] && nodes['expressions'] == undefined) { //if data scan, different if (nodes['data-source']) { nodeToAdd['details']['data-scan'] = `[]<-${this.variableExpressionStringify(nodes['variables'])}<-${nodes['data-source']}`; } //else else nodeToAdd['detailed_label'] += `(${this.variableExpressionStringify(nodes['variables'])})`; } //limit value if (nodes['value']) { nodeToAdd['detailed_label'] += ` ${nodes['value']}`; } //group by operator group-by list if (nodes['group-by-list']) nodeToAdd['details']['group_by_list'] = `group by ([${this.groupByListStringify(nodes['group-by-list'])}])`; //group by operator decor-list if (nodes['decor-list']) nodeToAdd['details']['decor_list'] = `decor ([${this.groupByListStringify(nodes['decor-list'])}])`; //join operator condition if (nodes['condition']) { nodeToAdd['details']['condition'] = `join condition (${nodes['condition']})`; } let nodeDropDown = {}; nodeDropDown['label'] = nodeToAdd['label']; nodeDropDown['value'] = nodeToAdd['id']; this.nodeIdsArr.push(nodeDropDown); for (let val of Object.values(nodeToAdd)) { this.flatJSONGraph[nodeToAdd['id']] += String(val).toLowerCase() + " "; } //Dynamic node coloring if (nodeToAdd['operator'] in this.coloredNodes) { nodeToAdd['color'] = this.coloredNodes[nodeToAdd['operator']]; } else { if (this.colors.length > 1) { let nodeColor = this.colors[0]; this.colors.splice(0, 1); nodeToAdd['color'] = nodeColor; this.coloredNodes[nodeToAdd['operator']] = nodeColor; } else { let nodeColor = "#ffffff"; nodeToAdd['color'] = nodeColor; this.coloredNodes[nodeToAdd['operator']] = nodeColor; } } this.ids.push(nodeToAdd['id']); nodesArr.push(nodeToAdd); } if (nodes['inputs']) { for (let i = 0; i < nodes['inputs'].length; i++) { let edge = nodes['operatorId'].slice() + "to" + nodes['inputs'][i]['operatorId'].slice(); edge = edge.replace(/\./g, ''); if (!edgesSet.has(edge)) { edgesSet.add(edge); //create the edge let edgeToAdd = {}; edgeToAdd['id'] = "e" + edge; edgeToAdd['source'] = "n" + nodes['inputs'][i]['operatorId']; edgeToAdd['source'] = edgeToAdd['source'].replace(/\./g, ''); edgeToAdd['target'] = "n" + nodes['operatorId']; edgeToAdd['target'] = edgeToAdd['target'].replace(/\./g, ''); edgesArr.push(Object.assign(edgeToAdd, {})); } let recurseResult = this.createLinksEdgesArray(nodes['inputs'][i], nodesArr, edgesArr, nodesSet, edgesSet); nodesArr = recurseResult[0]; edgesArr = recurseResult[1]; nodesSet = recurseResult[2]; edgesSet = recurseResult[3]; } } } return [nodesArr, edgesArr, nodesSet, edgesSet]; } /* * Extracts variables and expressions and stores occurences in this.variablesOccurrences */ storeVariablesExpressions(node, id) { if (node['expressions']) { if (node['operator'] == 'assign') { for (let expression of node['expressions']) { let matches = expression.match(/\$\$.*?(?=,|\])/g) if (matches) { for (let match of matches) { this.addVariableExpression(match, id); } } } } else { for (let expression of node['expressions']) { this.addVariableExpression(expression, id); } } } if (node['variables']) { for (let variable of node['variables']) { this.addVariableExpression(variable, id); } } if (node['group-by-list']) { for (let item of node['group-by-list']) { this.addVariableExpression(item.variable, id); this.addVariableExpression(item.expression, id); } } if (node['decor-list']) { for (let item of node['decor-list']) { this.addVariableExpression(item.variable, id); this.addVariableExpression(item.expression, id); } } if (node['condition'] || node['operator'] == 'exchange') { //does this for joins or exchanges (HASH_PARTITION_EXCHANGE contains variables/expressions) //regex extracts variables / expressions ($$ match until a ',' ']', or '(' let matches = node['physical-operator'].match(/\$\$.*?(?=,|\]|\()/g) if (matches) { for (let match of matches) { this.addVariableExpression(match, id); } } } } /* * Helper function that creates a set if var/exp not in this.variableOccurrences, then stores the id of the node */ addVariableExpression(varExp, id) { if (!(varExp in this.variablesOccurrences)) { this.variablesOccurrences[varExp] = []; } if (!(this.variablesOccurrences[varExp].includes(varExp))) this.variablesOccurrences[varExp].push(id); } /* * Conducts the string match in query plan viewer */ onClickSearch() { if (this.searchRegex != "") { this.searchMatches = []; for (let searchId in this.flatJSONGraph) { if (this.flatJSONGraph[searchId].includes(String(this.searchRegex).toLowerCase())) { this.searchMatches.push(searchId); } } if (this.searchMatches.length > 0) { //matches found this.matchesFound = true; this.matchIdx = 0; let currentIdx = this.ids.indexOf(this.selectedNode); let nextIdx = this.ids.indexOf(this.searchMatches[this.matchIdx]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; } } } /* * Function that resets all the navigation variables */ clearSelections() { //clear main selection variables this.nodeIdx = 0; this.selectedNode = "n11"; //clear variable occurrences variables this.selectedVariableOccurrences = undefined; this.selectedVariableOccurrencesArray = []; this.occurrenceArrayIdx = 0; //clear search variables this.searchRegex = ""; this.searchMatches = []; this.matchesFound = false; this.matchIdx = 0; for (let node of this.nodesArr) { node['selected'] = false; } this.panToNode(this.selectedNode); } /* * Select variable from variable occurrences drop down */ setSelectedVariableOccurrences(variable) { this.selectedVariableOccurrences = variable; //set the array this.selectedVariableOccurrencesArray = this.variablesOccurrences[this.selectedVariableOccurrences]; //set the selected node to the first in the array this.panToNode(this.selectedVariableOccurrencesArray[0]); this.occurrenceArrayIdx = 0; } /* * Jumps to selected variable's declaration (first occurrence in a DFS) */ jumpToDeclaration() { this.previousNodeId = this.selectedNode; this.previouseOccurrenceArrayIdx = this.occurrenceArrayIdx; this.panToNode(this.variablesDeclarations[this.selectedVariableOccurrences]) this.occurrenceArrayIdx = this.selectedVariableOccurrencesArray.length - 1; } /* * Jump back to previous node after a call to jumpToDeclaration() */ jumpBack() { this.panToNode(this.previousNodeId); this.occurrenceArrayIdx = this.previouseOccurrenceArrayIdx; this.previousNodeId = undefined; this.previouseOccurrenceArrayIdx = undefined; } /* * Sets the orientation of the graph (top to bottom, left to right, etc.) */ setOrientation(orientation: string): void { this.planOrientation = orientation; this.update$.next(true); } setDetail(checked: boolean) { this.detailed = checked; this.update$.next(true); } /* * Pans to node in the graph. Jumps to specified node and updates selection variables */ panToNode(id: any) { this.selectedNode = id; this.nodesArr[this.nodeIdx]['selected'] = false; let nodeIdx = this.nodesArr.map(function(e) { return e.id}).indexOf(id); this.nodeIdx = nodeIdx; this.nodesArr[nodeIdx]['selected'] = true; this.panToNode$.next(id); this.update$.next(true); } /* * Increments current node in graph (going "down" the graph in a DFS) */ incrementNode() { let currentIdx = this.ids.indexOf(this.selectedNode); if (currentIdx + 1 < this.nodesArr.length) { this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[currentIdx + 1]['selected'] = true; this.panToNode(this.ids[currentIdx + 1]); this.nodeIdx = currentIdx + 1; } } /* * Decrements current node in graph (going "up" the graph in a DFS) */ decrementNode() { let currentIdx = this.ids.indexOf(this.selectedNode); if (currentIdx - 1 >= 0) { this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[currentIdx-1]['selected'] = true; this.panToNode(this.ids[currentIdx - 1]); this.nodeIdx = currentIdx - 1; } } /* * Increments current node but in occurrence (Jumping to the next occurrence of the selected variable) */ incrementOccurrence() { let currentIdx = this.ids.indexOf(this.selectedNode); if (this.occurrenceArrayIdx + 1 < this.selectedVariableOccurrencesArray.length) { let nextIdx = this.ids.indexOf(this.selectedVariableOccurrencesArray[this.occurrenceArrayIdx + 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.occurrenceArrayIdx += 1; } else { //wrap around to first item let nextIdx = this.ids.indexOf(this.selectedVariableOccurrencesArray[0]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.occurrenceArrayIdx = 0; } } /* * Decrements current node but in occurrence (Jumping to the previous occurrence of the selected variable) */ decrementOccurrence() { let currentIdx = this.ids.indexOf(this.selectedNode); if (this.occurrenceArrayIdx - 1 >= 0) { let nextIdx = this.ids.indexOf(this.selectedVariableOccurrencesArray[this.occurrenceArrayIdx - 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.occurrenceArrayIdx -= 1; } else { //wrap around to last item let nextIdx = this.ids.indexOf(this.selectedVariableOccurrencesArray[this.selectedVariableOccurrencesArray.length - 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.occurrenceArrayIdx = this.selectedVariableOccurrencesArray.length - 1; } } /* * Increments current node but in search match (Jumping to the next occurrence of the search results) */ incrementMatch() { let currentIdx = this.ids.indexOf(this.selectedNode); if (this.matchIdx + 1 < this.searchMatches.length) { let nextIdx = this.ids.indexOf(this.searchMatches[this.matchIdx + 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.matchIdx += 1; } else { //wrap around to first item let nextIdx = this.ids.indexOf(this.searchMatches[0]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.matchIdx = 0; } } /* * Decrements current node but in search match (Jumping to the previous occurrence of the search results) */ decrementMatch() { let currentIdx = this.ids.indexOf(this.selectedNode); if (this.matchIdx - 1 >= 0) { let nextIdx = this.ids.indexOf(this.searchMatches[this.matchIdx - 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.matchIdx -= 1; } else { //wrap around to last item let nextIdx = this.ids.indexOf(this.searchMatches[this.searchMatches.length - 1]); this.nodesArr[currentIdx]['selected'] = false; this.nodesArr[nextIdx]['selected'] = true; this.panToNode(this.ids[nextIdx]); this.nodeIdx = nextIdx; this.matchIdx = this.searchMatches.length - 1; } } /* * Function takes in array of objects and stringifies */ groupByListStringify(variables: any[]) { let buildString = ""; let listSize = variables.length; let counter = 0; for (let variable of variables) { if (counter < listSize - 1) { buildString += variable['variable'] + " := " + variable['expression'] + "; "; } else { buildString += variable['variable'] + " := " + variable['expression']; } counter++; } return buildString; } /* * Function that stringifys variables / objects array */ variableExpressionStringify(arr: any[]) { if (arr.length == 1) { return "[" + arr[0] + "]"; } else { return "[" + arr.toString() + "]"; } } }
the_stack
import { bit, byte, memory } from '../types'; import { base64_decode, base64_encode } from '../base64'; import { bytify, debug, toHex } from '../util'; import { NibbleDisk, ENCODING_NIBBLE } from './types'; /** * DOS 3.3 Physical sector order (index is physical sector, value is DOS sector). */ export const DO = [ 0x0, 0x7, 0xE, 0x6, 0xD, 0x5, 0xC, 0x4, 0xB, 0x3, 0xA, 0x2, 0x9, 0x1, 0x8, 0xF ] as const; /** * DOS 3.3 Logical sector order (index is DOS sector, value is physical sector). */ export const _DO = [ 0x0, 0xD, 0xB, 0x9, 0x7, 0x5, 0x3, 0x1, 0xE, 0xC, 0xA, 0x8, 0x6, 0x4, 0x2, 0xF ] as const; /** * ProDOS Physical sector order (index is physical sector, value is ProDOS sector). */ export const PO = [ 0x0, 0x8, 0x1, 0x9, 0x2, 0xa, 0x3, 0xb, 0x4, 0xc, 0x5, 0xd, 0x6, 0xe, 0x7, 0xf ] as const; /** * ProDOS Logical sector order (index is ProDOS sector, value is physical sector). */ export const _PO = [ 0x0, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, 0x1, 0x3, 0x5, 0x7, 0x9, 0xb, 0xd, 0xf ] as const; /** * DOS 13-sector disk physical sector order (index is disk sector, value is * physical sector). */ export const D13O = [ 0x0, 0xa, 0x7, 0x4, 0x1, 0xb, 0x8, 0x5, 0x2, 0xc, 0x9, 0x6, 0x3 ] as const; export const _D13O = [ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc ] as const; const _trans53 = [ 0xab, 0xad, 0xae, 0xaf, 0xb5, 0xb6, 0xb7, 0xba, 0xbb, 0xbd, 0xbe, 0xbf, 0xd6, 0xd7, 0xda, 0xdb, 0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xed, 0xee, 0xef, 0xf5, 0xf6, 0xf7, 0xfa, 0xfb, 0xfd, 0xfe, 0xff ] as const; const _trans62 = [ 0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6, 0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3, 0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ] as const; export const detrans62 = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x03, 0x00, 0x04, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0x00, 0x00, 0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x00, 0x00, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x00, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x1C, 0x1D, 0x1E, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x20, 0x21, 0x00, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x2A, 0x2B, 0x00, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x00, 0x00, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x00, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F ] as const; /** * Converts a byte into its 4x4 encoded representation * * @param val byte to encode. * @returns A two byte array of representing the 4x4 encoding. */ export function fourXfour(val: byte): [xx: byte, yy: byte] { let xx = val & 0xaa; let yy = val & 0x55; xx >>= 1; xx |= 0xaa; yy |= 0xaa; return [xx, yy]; } /** * Converts 2 4x4 encoded bytes into a byte value * * @param xx First encoded byte. * @param yy Second encoded byte. * @returns The decoded value. */ export function defourXfour(xx: byte, yy: byte): byte { return ((xx << 1) | 0x01) & yy; } /** * Converts a raw sector into a nibblized representation to be combined into a * nibblized 16 sector track. * * @param volume volume number * @param track track number * @param sector sector number * @param data sector data * @returns a nibblized representation of the sector data */ export function explodeSector16(volume: byte, track: byte, sector: byte, data: memory): byte[] { let buf = []; let gap; /* * Gap 1/3 (40/0x28 bytes) */ if (sector === 0) // Gap 1 gap = 0x80; else { // Gap 3 gap = track === 0 ? 0x28 : 0x26; } for (let idx = 0; idx < gap; idx++) { buf.push(0xff); } /* * Address Field */ const checksum = volume ^ track ^ sector; buf = buf.concat([0xd5, 0xaa, 0x96]); // Address Prolog D5 AA 96 buf = buf.concat(fourXfour(volume)); buf = buf.concat(fourXfour(track)); buf = buf.concat(fourXfour(sector)); buf = buf.concat(fourXfour(checksum)); buf = buf.concat([0xde, 0xaa, 0xeb]); // Epilog DE AA EB /* * Gap 2 (5 bytes) */ for (let idx = 0; idx < 0x05; idx++) { buf.push(0xff); } /* * Data Field */ buf = buf.concat([0xd5, 0xaa, 0xad]); // Data Prolog D5 AA AD const nibbles: byte[] = []; const ptr2 = 0; const ptr6 = 0x56; for (let idx = 0; idx < 0x156; idx++) { nibbles[idx] = 0; } let idx2 = 0x55; for (let idx6 = 0x101; idx6 >= 0; idx6--) { let val6 = data[idx6 % 0x100]; let val2: byte = nibbles[ptr2 + idx2]; val2 = (val2 << 1) | (val6 & 1); val6 >>= 1; val2 = (val2 << 1) | (val6 & 1); val6 >>= 1; nibbles[ptr6 + idx6] = val6; nibbles[ptr2 + idx2] = val2; if (--idx2 < 0) idx2 = 0x55; } let last = 0; for (let idx = 0; idx < 0x156; idx++) { const val = nibbles[idx]; buf.push(_trans62[last ^ val]); last = val; } buf.push(_trans62[last]); buf = buf.concat([0xde, 0xaa, 0xeb]); // Epilog DE AA EB /* * Gap 3 */ buf.push(0xff); return buf; } /** * Converts a raw sector into a nibblized representation to be combined into * a nibblized 13 sector track. * * @param volume volume number * @param track track number * @param sector sector number * @param data sector data * @returns a nibblized representation of the sector data */ export function explodeSector13(volume: byte, track: byte, sector: byte, data: memory): byte[] { let buf = []; let gap; /* * Gap 1/3 (40/0x28 bytes) */ if (sector === 0) // Gap 1 gap = 0x80; else { // Gap 3 gap = track === 0 ? 0x28 : 0x26; } for (let idx = 0; idx < gap; idx++) { buf.push(0xff); } /* * Address Field */ const checksum = volume ^ track ^ sector; buf = buf.concat([0xd5, 0xaa, 0xb5]); // Address Prolog D5 AA B5 buf = buf.concat(fourXfour(volume)); buf = buf.concat(fourXfour(track)); buf = buf.concat(fourXfour(sector)); buf = buf.concat(fourXfour(checksum)); buf = buf.concat([0xde, 0xaa, 0xeb]); // Epilog DE AA EB /* * Gap 2 (5 bytes) */ for (let idx = 0; idx < 0x05; idx++) { buf.push(0xff); } /* * Data Field */ buf = buf.concat([0xd5, 0xaa, 0xad]); // Data Prolog D5 AA AD const nibbles = []; let jdx = 0; for (let idx = 0x32; idx >= 0; idx--) { const a5 = data[jdx] >> 3; const a3 = data[jdx] & 0x07; jdx++; const b5 = data[jdx] >> 3; const b3 = data[jdx] & 0x07; jdx++; const c5 = data[jdx] >> 3; const c3 = data[jdx] & 0x07; jdx++; const d5 = data[jdx] >> 3; const d3 = data[jdx] & 0x07; jdx++; const e5 = data[jdx] >> 3; const e3 = data[jdx] & 0x07; jdx++; nibbles[idx + 0x00] = a5; nibbles[idx + 0x33] = b5; nibbles[idx + 0x66] = c5; nibbles[idx + 0x99] = d5; nibbles[idx + 0xcc] = e5; nibbles[idx + 0x100] = a3 << 2 | (d3 & 0x4) >> 1 | (e3 & 0x4) >> 2; nibbles[idx + 0x133] = b3 << 2 | (d3 & 0x2) | (e3 & 0x2) >> 1; nibbles[idx + 0x166] = c3 << 2 | (d3 & 0x1) << 1 | (e3 & 0x1); } nibbles[0xff] = data[jdx] >> 3; nibbles[0x199] = data[jdx] & 0x07; let last = 0; for (let idx = 0x199; idx >= 0x100; idx--) { const val = nibbles[idx]; buf.push(_trans53[last ^ val]); last = val; } for (let idx = 0x0; idx < 0x100; idx++) { const val = nibbles[idx]; buf.push(_trans53[last ^ val]); last = val; } buf.push(_trans53[last]); buf = buf.concat([0xde, 0xaa, 0xeb]); // Epilog DE AA EB /* * Gap 3 */ buf.push(0xff); return buf; } /** * Reads a sector of data from a nibblized disk * * TODO(flan): Does not work on WOZ disks * * @param disk Nibble disk * @param track track number to read * @param sector sector number to read * @returns An array of sector data bytes. */ export function readSector(disk: NibbleDisk, track: byte, sector: byte): memory { const _sector = disk.format == 'po' ? _PO[sector] : _DO[sector]; let val, state = 0; let idx = 0; let retry = 0; const cur = disk.tracks[track]; function _readNext() { const result = cur[idx++]; if (idx >= cur.length) { idx = 0; retry++; } return result; } function _skipBytes(count: number) { idx += count; if (idx >= cur.length) { idx %= cur.length; retry++; } } let t = 0, s = 0, v = 0, checkSum; const data = new Uint8Array(256); while (retry < 4) { switch (state) { case 0: val = _readNext(); state = (val === 0xd5) ? 1 : 0; break; case 1: val = _readNext(); state = (val === 0xaa) ? 2 : 0; break; case 2: val = _readNext(); state = (val === 0x96) ? 3 : (val === 0xad ? 4 : 0); break; case 3: // Address v = defourXfour(_readNext(), _readNext()); // Volume t = defourXfour(_readNext(), _readNext()); s = defourXfour(_readNext(), _readNext()); checkSum = defourXfour(_readNext(), _readNext()); if (checkSum != (v ^ t ^ s)) { debug('Invalid header checksum:', toHex(v), toHex(t), toHex(s), toHex(checkSum)); } _skipBytes(3); // Skip footer state = 0; break; case 4: // Data if (s === _sector && t === track) { const data2 = []; let last = 0; for (let jdx = 0x55; jdx >= 0; jdx--) { val = detrans62[_readNext() - 0x80] ^ last; data2[jdx] = val; last = val; } for (let jdx = 0; jdx < 0x100; jdx++) { val = detrans62[_readNext() - 0x80] ^ last; data[jdx] = val; last = val; } checkSum = detrans62[_readNext() - 0x80] ^ last; if (checkSum) { debug('Invalid data checksum:', toHex(v), toHex(t), toHex(s), toHex(checkSum)); } for (let kdx = 0, jdx = 0x55; kdx < 0x100; kdx++) { data[kdx] <<= 1; if ((data2[jdx] & 0x01) !== 0) { data[kdx] |= 0x01; } data2[jdx] >>= 1; data[kdx] <<= 1; if ((data2[jdx] & 0x01) !== 0) { data[kdx] |= 0x01; } data2[jdx] >>= 1; if (--jdx < 0) jdx = 0x55; } return data; } else _skipBytes(0x159); // Skip data, checksum and footer state = 0; break; default: break; } } return new Uint8Array(); } /** * Convert a nibblized disk into a JSON string for storage. * * @param disk Nibblized disk * @param pretty Whether to format the output string * @returns A JSON string representing the disk */ export function jsonEncode(disk: NibbleDisk, pretty: boolean): string { // For 'nib', tracks are encoded as strings. For all other formats, // tracks are arrays of sectors which are encoded as strings. const data: string[] | string[][] = []; let format = 'dsk'; for (let t = 0; t < disk.tracks.length; t++) { data[t] = []; if (disk.format === 'nib') { format = 'nib'; data[t] = base64_encode(disk.tracks[t]); } else { for (let s = 0; s < 0x10; s++) { (data[t] as string[])[s] = base64_encode(readSector(disk, t, s)); } } } return JSON.stringify({ 'type': format, 'encoding': 'base64', 'volume': disk.volume, 'data': data, 'readOnly': disk.readOnly, }, undefined, pretty ? ' ' : undefined); } /** * Convert a JSON string into a nibblized disk. * * @param data JSON string representing a disk image, created by [jsonEncode]. * @returns A nibblized disk */ export function jsonDecode(data: string): NibbleDisk { const tracks: memory[] = []; const json = JSON.parse(data); const v = json.volume; const readOnly = json.readOnly; for (let t = 0; t < json.data.length; t++) { let track: byte[] = []; for (let s = 0; s < json.data[t].length; s++) { const _s = json.type == 'po' ? PO[s] : DO[s]; const sector: string = json.data[t][_s]; const d = base64_decode(sector); track = track.concat(explodeSector16(v, t, s, d)); } tracks[t] = bytify(track); } const disk: NibbleDisk = { volume: v, format: json.type, encoding: ENCODING_NIBBLE, name: json.name, tracks, readOnly, }; return disk; } /** * Debugging method that displays the logical sector ordering of a nibblized disk * * @param disk */ export function analyseDisk(disk: NibbleDisk) { for (let track = 0; track < 35; track++) { let outStr = `${toHex(track)}: `; let val, state = 0; let idx = 0; const cur = disk.tracks[track]; const _readNext = () => { const result = cur[idx++]; return result; }; const _skipBytes = (count: number) => { idx += count; }; let t = 0, s = 0, v = 0, checkSum; while (idx < cur.length) { switch (state) { case 0: val = _readNext(); state = (val === 0xd5) ? 1 : 0; break; case 1: val = _readNext(); state = (val === 0xaa) ? 2 : 0; break; case 2: val = _readNext(); state = (val === 0x96) ? 3 : (val === 0xad ? 4 : 0); break; case 3: // Address v = defourXfour(_readNext(), _readNext()); // Volume t = defourXfour(_readNext(), _readNext()); s = defourXfour(_readNext(), _readNext()); checkSum = defourXfour(_readNext(), _readNext()); if (checkSum != (v ^ t ^ s)) { debug('Invalid header checksum:', toHex(v), toHex(t), toHex(s), toHex(checkSum)); } else { outStr += toHex(s, 1); } _skipBytes(3); // Skip footer state = 0; break; case 4: // Valid header _skipBytes(0x159); // Skip data, checksum and footer state = 0; break; default: break; } } debug(outStr); } } /** * Debugging utility to convert a bitstream into a nibble. Does not wrap. * * @param bits Bitstream containing nibbles * @param offset Offset into bitstream to start nibblizing * @returns nibble, the next nibble in the bitstream, * and offset, the end of that nibble in the bitstream */ export function grabNibble(bits: bit[], offset: number) { let nibble = 0; let waitForOne = true; while (offset < bits.length) { const bit = bits[offset]; if (bit) { nibble = (nibble << 1) | 0x01; waitForOne = false; } else { if (!waitForOne) { nibble = nibble << 1; } } if (nibble & 0x80) { // nibble complete return it break; } offset += 1; } return { nibble: nibble, offset: offset }; }
the_stack
import operationGroup from '@/bkdata-ui/components/operationGroup/operationGroup.vue'; import { showMsg } from '@/common/js/util'; import utils from '@/pages/DataGraph/Common/utils.js'; import DataTable from '@/pages/datamart/common/components/DataTable.vue'; import { BKHttpResponse } from '@/common/js/BKHttpResponse'; import { Component, Inject, Ref, Watch } from 'vue-property-decorator'; import { calculationAtomDetail, confirmModelIndicators, deleteCalculationAtom, deleteIndicator, getCalculationAtoms, getIndicatorList, } from '../../Api/index'; import { ICalculationAtomDetail, ICalculationAtomDetailData, ICalculationAtomsData, ICalculationAtomsResults, IIndicatorDetail, } from '../../Interface/indexDesign'; import { IndexTree } from '../Common/index'; import AddCaliber from './ChildNodes/AddCaliber'; import DataDetailFold from './ChildNodes/DataDetailFold.vue'; import { DataModelManage } from './IStepsManage'; /** * 获取指标类型节点树数据 * @param nodes * @param calculationFormula */ const getChildNodes = (nodes: any[] = [], calculationFormula: string) => { const resNodes: any[] = []; nodes.forEach(child => { Object.assign(child, { displayName: `${child.indicatorName}(${child.indicatorAlias})` }); const { indicatorAlias, indicatorName } = child; Object.assign(child, { calculationFormula }); const nodeName = `${indicatorAlias}(${indicatorName})`; const grandSonNode = { name: indicatorName, displayName: nodeName, alias: indicatorAlias, // type为indicator类型 type: child.type, children: [], icon: 'icon-quota', id: `indicatorId-${child.indicatorId}`, sourceData: child, count: child.indicatorCount, }; if (child.subIndicators && child.subIndicators.length) { grandSonNode.children = getChildNodes(child.subIndicators, calculationFormula); } resNodes.push(grandSonNode); }); return resNodes; }; @Component({ components: { operationGroup, AddCaliber, DataTable, AddIndicator: () => import('./ChildNodes/AddIndicator.vue'), DataDetailFold, IndexTree, }, }) export default class IndexDesign extends DataModelManage.IStepsManage { @Ref() public readonly indexTree!: IndexTree; @Ref() public readonly detailsFold!: DataDetailFold; public appHeight: number = window.innerHeight; // 窗口类型 public windowTypeMap = { scroll: $t('滚动窗口'), accumulate: $t('累加窗口'), slide: $t('滑动窗口'), accumulate_by_hour: $t('按小时累加窗口'), fixed: $t('固定窗口'), }; // 统计口径详情请求loading public isAllLoading = false; // 统计口径的添加方式 public addMethod = 'quote'; // 是否增加指标 public isAddIndicator = false; // 当前模型的相关信息 @Inject('activeTabItem') public activeTabItem!: function; public searchText = ''; public isLoading = false; public isIndexLoading = false; public calculationAtomsInfo = { step_id: 1, results: [], }; public indexDetailNameIcons = { master_table: 'icon-fact-model', fact_table: 'icon-fact-model', dimension_table: 'icon-dimension-model', calculation_atom: 'icon-statistic-caliber', indicator: 'icon-quota', }; public treeData: any[] = []; public activeNode: any = null; public indexInfo = { step_id: 1, results: [], }; // 操作弹框相关信息 public dialogInfo = { isShow: false, buttonText: '', title: '', data: '', buttonLoading: false, }; // 统计口径相关信息 public calculationAtomDetailData: ICalculationAtomDetailData = {}; // 单位map public unitMap = { s: $t('秒'), min: $t('分钟'), h: $t('小时'), d: $t('天'), w: $t('周'), m: $t('月'), }; // 表格头部的信息会依赖此数据变化,每次只要更改这个数据值来改变表格头部信息 public tableInfoValueMap = { type: '', name: '', }; public headerTop = 0; public calculationAtomProp = {}; public isOpen = false; public detailsFoldHeight = 0; @Watch('tableInfoValueMap.type') public handleTypeChange(value: string | undefined, old: string | undefined) { if (value === 'indicator' && value !== old) { this.getFoldHeight(); } } @Watch('isOpen') public handleOpenChange() { if (this.tableInfoValueMap.type === 'indicator') { this.getFoldHeight(); } } /** * 获取 table maxHeight */ get maxHeight() { if (this.tableInfoValueMap.type === 'indicator') { const occupyHeight = 421; return this.appHeight - occupyHeight - this.detailsFoldHeight; } return this.appHeight - 451; } get tableInfoData() { const { data = {} } = this.activeNode || {}; return { displayName: data.displayName, data: data.sourceData, }; } /** * 统计口径列表 */ get calculationAtomTableData() { if (this.tableInfoValueMap.type !== 'master_table') { return this.calculationAtomsInfo.results; } return this.calculationAtomsInfo.results.filter(item => { return ( item.calculationAtomName.includes(this.searchText) || item.calculationAtomAlias.includes(this.searchText) || item.calculationFormulaStrippedComment.includes(this.searchText) || item.updatedBy.includes(this.searchText) ); }); } /** * 指标列表 */ get indexTableData() { return this.indexInfo.results.filter(item => { return ( item.indicatorName.includes(this.searchText) || item.indicatorAlias.includes(this.searchText) || item.aggregationFieldsStr.includes(this.searchText) || item.filterFormulaStrippedComment.includes(this.searchText) || item.updatedBy.includes(this.searchText) ); }); } /** * 添加按钮的文本 */ get addButtonText() { if (this.tableInfoValueMap.type === 'master_table') { return $t('指标统计口径'); } else { return $t('指标'); } } get isCalculationDelete() { if (this.tableInfoValueMap.type === 'calculation_atom') { return !this.tableInfoData.data.deletable; } return false; } get isIndicatorDelete() { if (this.tableInfoValueMap.type === 'indicator') { return !this.tableInfoData.data.deletable; } return false; } /** * 某个模型下所有的聚合逻辑列表 */ get aggregationLogicList() { return this.calculationAtomTableData.length ? this.calculationAtomTableData.map((item: ICalculationAtomsResults) => item.calculationFormula) : []; } /** * 获取删除 tips */ get getTableInfoDeleTips() { if (this.tableInfoValueMap.type === 'calculation_atom') { return this.getCalculationAtomsTips(this.tableInfoData.data); } if (this.tableInfoValueMap.type === 'indicator' && !this.tableInfoData.data.deletable) { return this.$t('父指标无法被删除'); } return { disabled: true, }; } /** * 获取编辑 tips */ get getTableInfoEditTips() { if (this.tableInfoValueMap.type === 'calculation_atom' && !this.tableInfoData.data.editable) { return { content: $t('该指标统计口径引用自数据集市'), disabled: false, }; } return { disabled: true, }; } get searchPlaceholder() { return this.tableInfoValueMap.type === 'master_table' ? this.$t('请输入指标统计口径名称、聚合逻辑、更新人') : this.$t('请输入指标名称、聚合字段、过滤条件、更新人'); } /** * 获取指标详情内容高度 */ public getFoldHeight() { this.$nextTick(() => { const el = this.detailsFold.$el; const style = window.getComputedStyle(el, null); const height = parseInt(style.getPropertyValue('height')); const marginTop = parseInt(style.getPropertyValue('margin-top')); this.detailsFoldHeight = height + marginTop; }); } /** * 获取指标删除 tips * @param row */ public handleDeleteIndicatorTips(row) { if (!row.deletable) { return this.$t('父指标无法被删除'); } return { disabled: true, }; } /** * 获取内容展示 icon * @param type */ public getIcon(type: string) { if (type === 'master_table') { const modeType = this.activeModelTabItem?.modelType || 'master_table'; return this.indexDetailNameIcons[modeType]; } return this.indexDetailNameIcons[type]; } /** * 控制折叠状态 * @param status */ public handleChangeStatus(status: boolean) { this.isOpen = status; } /** * 重新设置内容 height */ public handleResetHeight() { this.appHeight = window.innerHeight; if (this.tableInfoValueMap.type === 'indicator') { this.getFoldHeight(); } } public async created() { window.addEventListener('resize', this.handleResetHeight); // 初始化根节点 const { name, displayName } = this.activeTabItem(); const showName = `${displayName}(${name})`; this.tableInfoValueMap = { type: 'master_table', name, }; const rootNode = { name, displayName: showName, alias: displayName, count: 0, type: 'master_table', icon: this.indexDetailNameIcons[this.activeModelTabItem?.modelType] || 'icon-fact-model', id: `model_id_${this.modelId}`, children: [], }; this.treeData = [rootNode]; this.initPreNextManage(); await this.getCalculationAtoms(); const timer = setTimeout(() => { // 查看态跳转打开对应编辑侧栏 const { open } = this.routeParams; if (open) { const { name, row } = open; if (name && row) { const editFn = name === 'calculationAtom' ? this.calculationAtomDetail : this.editIndicator; editFn(row); this.appendRouter(Object.assign(this.routeParams, { open: undefined })); } } clearTimeout(timer); }, 200); } public beforeDestroy() { window.removeEventListener('resize', this.handleResetHeight); } /** * 获取单位第一个字母 * @param unit */ public getUnitFirstWord(unit: string) { return unit.split('')[0].toLowerCase(); } /** * 控制滑动事件 * @param e */ public scrollEvent(e) { this.headerTop = e.target.scrollTop; } /** * 统计口径表格的编辑按钮tips * @param content */ public getCalculationAtomsEditTips(content: string) { return { content, disabled: !content, }; } /** * 获取统计口径列表删除按钮的tips * @param data */ public getCalculationAtomsTips(data) { function getParams(content = '') { return { content, disabled: !content, }; } if (data.isAppliedByIndicators && data.isQuotedByOtherModels) { return getParams($t('统计口径同时被指标和其他统计口径引用!')); } if (data.isAppliedByIndicators) { return getParams($t('统计口径正在被指标应用!')); } if (data.isQuotedByOtherModels) { return getParams($t('统计口径正在被其他统计口径引用!')); } return getParams(); } /** * 创建指标之后需要刷新tree和指标列表 */ public updateIndexInfo({ name, isChildIndicator }) { this.getCalculationAtoms(); this.getIndicatorList(name, isChildIndicator); } /** * 编辑操作 */ public editOption() { if (this.tableInfoValueMap.type === 'calculation_atom') { this.calculationAtomDetail(this.tableInfoData.data); } else if (this.tableInfoValueMap.type === 'indicator') { this.editIndicator(this.tableInfoData.data); } } /** * 表格上方搜索框来搜索指标或统计口径 */ public searchTextChange() { if (this.tableInfoValueMap.type === 'master_table') { this.calculationAtomsInfo.results.filter((item: ICalculationAtomsResults) => { return ( item.calculationAtomName.includes(this.searchText) || item.calculationAtomAlias.includes(this.searchText) ); }); } } /** * 查看统计口径下的指标列表 * @param data */ public handleIndexDetail(data: ICalculationAtomsResults) { this.tableInfoValueMap = { type: 'calculation_atom', name: data.calculationAtomName, }; this.indexTree.handleSetTreeSelected(data.calculationAtomName); this.getIndicatorList(data.calculationAtomName); } /** * 重置弹窗信息 */ public reSetDialogInfo() { this.dialogInfo = { isShow: false, buttonText: '', title: '', data: '', buttonLoading: false, }; } /** * 节点树触发统计口径/指标编辑 * @param data */ public changeIndexType(data: object) { this.tableInfoValueMap = { type: data.type, name: data.name, }; this.indexTree.handleSetTreeSelected(data.id); if (this.tableInfoValueMap.type === 'master_table') { this.openAddCaliber(); } else { this.calculationAtomProp = this.tableInfoData.data; this.getIndicatorList(data.name, this.tableInfoValueMap.type === 'indicator'); this.openAddIndicatorSlide(); } } /** * 表头新增指标按钮方法 */ public addIncatior() { this.calculationAtomProp = this.tableInfoData.data; this.openAddIndicatorSlide(); } /** * 新增指标 * @param calculationAtomProp */ public addIndex(calculationAtomProp) { this.calculationAtomProp = calculationAtomProp; this.openAddIndicatorSlide(); } /** * 打开统计口径侧边栏 */ public openAddCaliber() { this.addMethod = 'quote'; this.$refs.addCaliber.isShow = true; this.sendUserActionData({ name: '添加【指标统计口径】' }); } /** * 打开创建指标侧边栏 */ public openAddIndicatorSlide() { this.sendUserActionData({ name: '添加【指标】' }); this.$nextTick(() => { this.$refs.addIndicator.init(); }); } /** * 展示指标详情 * @param indicatorName */ public goToIndexDetail(indicatorName: string) { this.tableInfoValueMap.type = 'indicator'; this.tableInfoValueMap.name = indicatorName; this.indexTree.handleSetTreeSelected(indicatorName); } /** * 展示统计口径详情 * @param calculationAtomName */ public goToCalculationAtomDetail(calculationAtomName: string) { this.tableInfoValueMap.type = 'calculation_atom'; this.tableInfoValueMap.name = calculationAtomName; this.indexTree.handleSetTreeSelected(calculationAtomName); // 获取统计口径下指标列表 this.getIndicatorList(calculationAtomName); } /** * 处理节点点击事件 * @param node */ public handleNodeClick(node: any) { const { data = {} } = node; this.tableInfoValueMap = { type: data.type, name: data.name, }; this.activeNode = node; this.isOpen = false; if (data.type === 'calculation_atom') { // 根据统计口径名称获取指标列表,在二级树形 this.getIndicatorList(data.sourceData.calculationAtomName); } else if (data.type === 'master_table') { // 一级树形 !this.calculationAtomsInfo.results.length && this.getCalculationAtoms(); } else if (data.type === 'indicator') { this.calculationAtomProp = data; this.getIndicatorList(data.name, true); } } /** * 获取字表详情信息 */ get indicatorDetailData() { const aggregationFieldsStr = this.getAggregationFieldsStr({ aggregationFieldsAlias: this.tableInfoData.data.aggregationFieldsAlias, aggregationFields: this.tableInfoData.data.aggregationFields, }); const { calculationAtomAlias, calculationAtomName, calculationFormula, filterFormulaStrippedComment } = this.tableInfoData.data; const { schedulingContent } = this.tableInfoData.data.schedulingContent; const commonParams = [ { label: $t('指标统计口径'), value: `${calculationAtomAlias}(${calculationAtomName})`, }, { label: $t('口径聚合逻辑'), value: calculationFormula || '--', }, { label: $t('聚合字段'), value: aggregationFieldsStr || '--', }, { label: $t('过滤条件'), value: filterFormulaStrippedComment || '--', }, { groupDataList: [ { label: $t('计算类型'), value: this.tableInfoData.data.schedulingType === 'stream' ? $t('实时计算') : $t('离线计算'), }, { label: $t('窗口类型'), value: this.windowTypeMap[schedulingContent.windowType], }, ], }, ]; let params1 = []; if (['scroll', 'slide', 'accumulate'].includes(schedulingContent.windowType)) { // 滚动窗口、滑动窗口、累加窗口共用参数 params1 = [ { groupDataList: [ { label: $t('统计频率'), value: schedulingContent.countFreq + $t('秒'), }, { label: $t('窗口长度'), value: schedulingContent.windowTime + $t('分钟'), isHidden: schedulingContent.windowType === 'scroll', }, { label: $t('等待时间'), value: schedulingContent.waitingTime + $t('秒'), }, ], }, { groupDataList: [ { label: $t('依赖计算延迟数据'), value: schedulingContent.windowLateness.allowedLateness ? $t('是') : $t('否'), }, { label: $t('延迟时间'), value: schedulingContent.windowLateness.latenessTime + $t('小时'), isHidden: !schedulingContent.windowLateness.allowedLateness, }, { label: $t('统计频率'), value: schedulingContent.windowLateness.latenessCountFreq + $t('秒'), isHidden: !schedulingContent.windowLateness.allowedLateness, }, ], }, ]; } else { // 固定窗口、按小时累加窗口共用参数 const dependencyRule = { no_failed: $t('无失败'), all_finished: $t('全部成功'), at_least_one_finished: $t('一次成功'), }; let dataStartList: Array<{ id: number; name: string; }> = []; let dataEndList: Array<{ id: number; name: string; }> = []; if (schedulingContent.windowType === 'accumulate_by_hour') { dataStartList = utils.getTimeList(); dataEndList = utils.getTimeList('59'); } params1 = [ { groupDataList: [ { label: $t('统计频率'), value: schedulingContent.countFreq + this.unitMap[this.getUnitFirstWord(schedulingContent.schedulePeriod)], }, { label: $t('统计延迟'), value: schedulingContent.windowType === 'fixed' ? schedulingContent.fixedDelay + $t('小时') : schedulingContent.delay + $t('小时'), }, { label: $t('窗口长度'), value: schedulingContent.formatWindowSize + this.unitMap[schedulingContent.formatWindowSizeUnit], isHidden: schedulingContent.windowType !== 'fixed', }, { label: $t('窗口起点'), value: dataStartList.find(child => child.id === schedulingContent.dataStart) ?.name, isHidden: schedulingContent.windowType === 'fixed', }, { label: $t('窗口终点'), value: dataEndList.find(child => child.id === schedulingContent.dataEnd)?.name, isHidden: schedulingContent.windowType === 'fixed', }, ], }, { label: $t('依赖策略'), value: dependencyRule[schedulingContent?.unifiedConfig?.dependencyRule], }, { groupDataList: [ { label: $t('调度失败重试'), value: schedulingContent.advanced.recoveryEnable ? $t('是') : $t('否'), }, { label: $t('重试次数'), value: schedulingContent.advanced.recoveryTimes + $t('小时'), isHidden: !schedulingContent.advanced.recoveryEnable, }, { label: $t('调度间隔'), value: parseInt(schedulingContent.advanced.recoveryInterval) + $t('分钟'), isHidden: !schedulingContent.advanced.recoveryEnable, }, ], }, ]; } return [ ...commonParams, ...params1, { groupDataList: [ { label: $t('更新人'), value: this.tableInfoData.data.updatedBy, }, { label: $t('更新时间'), value: this.tableInfoData.data.updatedAt, }, ], }, ]; } /** * 表格上方删除指标功能 */ public deleteIndex() { if (this.tableInfoValueMap.type === 'calculation_atom') { if (this.isCalculationDelete) { return; } this.handleDelete(this.tableInfoValueMap.type, this.tableInfoData.data.calculationAtomName); } else if (this.tableInfoValueMap.type === 'indicator') { if (this.isIndicatorDelete) { return; } this.handleDelete(this.tableInfoValueMap.type, this.tableInfoData.data.indicatorName); } } /** * 弹框确认方法 */ public confirm() { if (this.dialogInfo.type === 'indicator') { this.deleteIndicator(this.dialogInfo.data); } else { this.deleteCalculationAtom(this.dialogInfo.data); } } /** * 删除指标 * @param indicatorName * @param deletable */ public handleDeleteIndicator(indicatorName: string, deletable = true) { if (!deletable) { return; } this.handleDelete('indicator', indicatorName); } /** * 删除统计口径 * @param calculationAtomName * @param deletable */ public handleDeleteCalculation(calculationAtomName: string, deletable = true) { this.handleDelete('calculation_atom', calculationAtomName, deletable); } /** * 打开删除提示弹窗 * @param type * @param data * @param deletable */ public handleDelete(type: string, data: string, deletable = true) { if (!deletable) { return; } const deleteInfoMap = { master_table: $t('确认删除该统计口径?'), calculation_atom: $t('确认删除该统计口径?'), indicator: $t('确认删除该指标?'), }; const deleteApi = type === 'indicator' ? this.deleteIndicator : this.deleteCalculationAtom; this.$bkInfo({ title: deleteInfoMap[type], subTitle: this.$t('删除操作无法撤回'), extCls: 'bk-dialog-sub-header-center', closeIcon: true, confirmLoading: true, confirmFn: async () => { await deleteApi(data); }, }); } /** * 编辑指标 * @param data */ public editIndicator(data) { this.calculationAtomProp = data; this.$refs.addIndicator && this.$refs.addIndicator.getIndicatorDetail(data.indicatorName); } /** * 删除指标 * @param indicator_name */ public deleteIndicator(indicator_name: string) { this.dialogInfo.buttonLoading = true; deleteIndicator(indicator_name, Number(this.modelId)) .then(res => { if (res.validateResult()) { showMsg(this.$t('删除该指标成功!'), 'success', { delay: 1500 }); this.getCalculationAtoms(); if (this.dialogInfo.type === 'calculation_atom') { this.getIndicatorList(this.tableInfoData.data.calculationAtomName); } else { const { name } = this.activeTabItem(); this.tableInfoValueMap = { type: 'master_table', name, }; this.indexTree.handleSetTreeSelected(this.treeData[0].id); } // 刷新可以引用的统计口径列表 this.$refs.addCaliber.getCalculationAtoms(); this.reSetDialogInfo(); this.handleUpdatePublishStatus(res.data.publish_status); } }) ['finally'](() => { this.dialogInfo.buttonLoading = false; }); } /** * 获取指标列表 * @param name * @param isChildIndicator */ public getIndicatorList(name: string | undefined, isChildIndicator = false) { let calculationAtomName; let parentIndicatorName; isChildIndicator ? (parentIndicatorName = name) : (calculationAtomName = name); this.isIndexLoading = true; this.addMethod = 'quote'; getIndicatorList(calculationAtomName, this.$route.params.modelId, parentIndicatorName) .then(res => { const instance = new BKHttpResponse<IIndicatorDetail>(res); instance.setData(this, 'indexInfo'); this.indexInfo.results.forEach(item => { this.$set(item, 'displayName', `${item.indicatorName}(${item.indicatorAlias})`); }); this.indexInfo.results.length && this.indexInfo.results.forEach(item => { this.$set(item, 'aggregationFieldsStr', this.getAggregationFieldsStr(item)); }); }) ['finally'](() => { this.isIndexLoading = false; }); } /** * 获取聚合字段信息 * @param item */ public getAggregationFieldsStr(item) { // 聚合字段(aggregationFieldsStr),首先用aggregationFieldsAlias,不存在用aggregationFields let str = ''; let arr: any[]; if (item.aggregationFieldsAlias?.length) { arr = item.aggregationFieldsAlias; } else if (item.aggregationFields?.length) { arr = item.aggregationFields; } if (arr?.length) { arr.forEach(child => { str += child + ','; }); } return str.slice(0, str.length - 1) || '--'; } /** * 删除统计口径 * @param calculation_atom_name */ public deleteCalculationAtom(calculation_atom_name: string) { this.dialogInfo.buttonLoading = true; return deleteCalculationAtom(calculation_atom_name, this.$route.params.modelId) .then(res => { if (res.validateResult()) { showMsg(this.$t('删除该统计口径成功!'), 'success', { delay: 1500 }); this.getCalculationAtoms(); this.reSetDialogInfo(); const { name } = this.activeTabItem(); this.tableInfoValueMap = { type: 'master_table', name, }; this.indexTree.handleSetTreeSelected(this.treeData[0].id); this.handleUpdatePublishStatus(res.data.publish_status); } }) ['finally'](() => { this.dialogInfo.buttonLoading = false; }); } /** * 获取统计口径详情 * @param data */ public calculationAtomDetail(data) { if (!data.editable) { return; } this.isAllLoading = true; // 打开统计口径侧边栏 this.openAddCaliber(); calculationAtomDetail(data.calculationAtomName) .then(res => { if (res.validateResult()) { const instance = new BKHttpResponse<ICalculationAtomDetail>(res, false); instance.setData(this, 'calculationAtomDetailData'); this.addMethod = data.calculationAtomType; this.$refs.addCaliber.mode = 'edit'; } }) ['finally'](() => { this.isAllLoading = false; }); } /** * 获取统计口径列表 */ public getCalculationAtoms() { this.isLoading = true; getCalculationAtoms(this.$route.params.modelId, true) .then(res => { if (res.validateResult()) { // 事实表没有统计口径不允许下一步 if (this.activeModelTabItem?.modelType === 'fact_table') { this.$parent.nextBtnDisabled = !res.data.results.length; } this.treeData[0].children = []; const instance = new BKHttpResponse<ICalculationAtomsData>(res); instance.setData(this, 'calculationAtomsInfo'); this.calculationAtomsInfo.results.forEach(item => { this.$set(item, 'displayName', `${item.calculationAtomName}(${item.calculationAtomAlias})`); }); // 总指标数 let totalCount = 0; this.calculationAtomsInfo.results.forEach(item => { const { calculationAtomName, calculationAtomAlias, type, indicatorCount } = item; totalCount += indicatorCount; const nodeName = `${calculationAtomAlias}(${calculationAtomName})`; const childNode = { name: calculationAtomName, displayName: nodeName, alias: calculationAtomAlias, type, count: indicatorCount, sourceData: item, icon: 'icon-statistic-caliber', id: calculationAtomName, children: [], }; if (item.indicators && item.indicators.length) { const linkNodes = getChildNodes(item.indicators, item.calculationFormulaStrippedComment); childNode.children.push(...linkNodes); } this.treeData[0].count = totalCount; this.treeData[0].children.push(childNode); }); // 更新激活节点信息 const timer = setTimeout(() => { const nodeId = this.activeNode && this.activeNode.id; if (nodeId) { const newNode = this.indexTree.handleGetNodeById(nodeId); this.activeNode = newNode; } clearTimeout(timer); }, 300); } }) ['finally'](() => { this.isLoading = false; }); } /** * 点击下一步方法 */ public nextStepClick() { confirmModelIndicators(this.modelId).then(res => { if (res.validateResult(null, null, false)) { const activeTabItem = this.DataModelTabManage.getActiveItem()[0]; activeTabItem.lastStep = res.data.step_id; this.DataModelTabManage.updateTabItem(activeTabItem); this.DataModelTabManage.dispatchEvent('updateModel', [ { model_id: this.modelId, step_id: res.data.step_id, }, ]); } }); } /** * 更新模型发布状态 * @param status */ public handleUpdatePublishStatus(status: string) { const activeTabItem = this.DataModelTabManage.getActiveItem()[0]; activeTabItem.publishStatus = status; this.DataModelTabManage.updateTabItem(activeTabItem); this.DataModelTabManage.dispatchEvent('updateModel', [ { model_id: this.modelId, publish_status: status, }, ]); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a node pool in a Google Kubernetes Engine (GKE) cluster separately from * the cluster control plane. For more information see [the official documentation](https://cloud.google.com/container-engine/docs/node-pools) * and [the API reference](https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1beta1/projects.locations.clusters.nodePools). * * ## Example Usage * ### Using A Separately Managed Node Pool (Recommended) * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const _default = new gcp.serviceaccount.Account("default", { * accountId: "service-account-id", * displayName: "Service Account", * }); * const primary = new gcp.container.Cluster("primary", { * location: "us-central1", * removeDefaultNodePool: true, * initialNodeCount: 1, * }); * const primaryPreemptibleNodes = new gcp.container.NodePool("primaryPreemptibleNodes", { * cluster: primary.id, * nodeCount: 1, * nodeConfig: { * preemptible: true, * machineType: "e2-medium", * serviceAccount: _default.email, * oauthScopes: ["https://www.googleapis.com/auth/cloud-platform"], * }, * }); * ``` * ### 2 Node Pools, 1 Separately Managed + The Default Node Pool * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const _default = new gcp.serviceaccount.Account("default", { * accountId: "service-account-id", * displayName: "Service Account", * }); * const primary = new gcp.container.Cluster("primary", { * location: "us-central1-a", * initialNodeCount: 3, * nodeLocations: ["us-central1-c"], * nodeConfig: { * serviceAccount: _default.email, * oauthScopes: ["https://www.googleapis.com/auth/cloud-platform"], * guestAccelerators: [{ * type: "nvidia-tesla-k80", * count: 1, * }], * }, * }); * const np = new gcp.container.NodePool("np", { * cluster: primary.id, * nodeConfig: { * machineType: "e2-medium", * serviceAccount: _default.email, * oauthScopes: ["https://www.googleapis.com/auth/cloud-platform"], * }, * timeouts: [{ * create: "30m", * update: "20m", * }], * }); * ``` * * ## Import * * Node pools can be imported using the `project`, `location`, `cluster` and `name`. If the project is omitted, the project value in the provider configuration will be used. Examples * * ```sh * $ pulumi import gcp:container/nodePool:NodePool mainpool my-gcp-project/us-east1-a/my-cluster/main-pool * ``` * * ```sh * $ pulumi import gcp:container/nodePool:NodePool mainpool us-east1/my-cluster/main-pool * ``` */ export class NodePool extends pulumi.CustomResource { /** * Get an existing NodePool resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: NodePoolState, opts?: pulumi.CustomResourceOptions): NodePool { return new NodePool(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:container/nodePool:NodePool'; /** * Returns true if the given object is an instance of NodePool. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is NodePool { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === NodePool.__pulumiType; } /** * Configuration required by cluster autoscaler to adjust * the size of the node pool to the current cluster usage. Structure is documented below. */ public readonly autoscaling!: pulumi.Output<outputs.container.NodePoolAutoscaling | undefined>; /** * The cluster to create the node pool for. Cluster must be present in `location` provided for clusters. May be specified in the format `projects/{{project}}/locations/{{location}}/clusters/{{cluster}}` or as just the name of the cluster. */ public readonly cluster!: pulumi.Output<string>; /** * The initial number of nodes for the pool. In * regional or multi-zonal clusters, this is the number of nodes per zone. Changing * this will force recreation of the resource. WARNING: Resizing your node pool manually * may change this value in your existing cluster, which will trigger destruction * and recreation on the next provider run (to rectify the discrepancy). If you don't * need this value, don't set it. If you do need it, you can use a lifecycle block to * ignore subsqeuent changes to this field. */ public readonly initialNodeCount!: pulumi.Output<number>; /** * The resource URLs of the managed instance groups associated with this node pool. */ public /*out*/ readonly instanceGroupUrls!: pulumi.Output<string[]>; /** * The location (region or zone) of the cluster. */ public readonly location!: pulumi.Output<string>; /** * List of instance group URLs which have been assigned to this node pool. */ public /*out*/ readonly managedInstanceGroupUrls!: pulumi.Output<string[]>; /** * Node management configuration, wherein auto-repair and * auto-upgrade is configured. Structure is documented below. */ public readonly management!: pulumi.Output<outputs.container.NodePoolManagement>; /** * The maximum number of pods per node in this node pool. * Note that this does not work on node pools which are "route-based" - that is, node * pools belonging to clusters that do not have IP Aliasing enabled. * See the [official documentation](https://cloud.google.com/kubernetes-engine/docs/how-to/flexible-pod-cidr) * for more information. */ public readonly maxPodsPerNode!: pulumi.Output<number>; /** * The name of the node pool. If left blank, the provider will * auto-generate a unique name. */ public readonly name!: pulumi.Output<string>; /** * Creates a unique name for the node pool beginning * with the specified prefix. Conflicts with `name`. */ public readonly namePrefix!: pulumi.Output<string>; /** * The network configuration of the pool. See * gcp.container.Cluster for schema. */ public readonly networkConfig!: pulumi.Output<outputs.container.NodePoolNetworkConfig>; /** * Parameters used in creating the node pool. See * gcp.container.Cluster for schema. */ public readonly nodeConfig!: pulumi.Output<outputs.container.NodePoolNodeConfig>; /** * The number of nodes per instance group. This field can be used to * update the number of nodes per instance group but should not be used alongside `autoscaling`. */ public readonly nodeCount!: pulumi.Output<number>; /** * The list of zones in which the node pool's nodes should be located. Nodes must * be in the region of their regional cluster or in the same region as their * cluster's zone for zonal clusters. If unspecified, the cluster-level * `nodeLocations` will be used. */ public readonly nodeLocations!: pulumi.Output<string[]>; public /*out*/ readonly operation!: pulumi.Output<string>; /** * The ID of the project in which to create the node pool. If blank, * the provider-configured project will be used. */ public readonly project!: pulumi.Output<string>; /** * Specify node upgrade settings to change how many nodes GKE attempts to * upgrade at once. The number of nodes upgraded simultaneously is the sum of `maxSurge` and `maxUnavailable`. * The maximum number of nodes upgraded simultaneously is limited to 20. Structure is documented below. */ public readonly upgradeSettings!: pulumi.Output<outputs.container.NodePoolUpgradeSettings>; /** * The Kubernetes version for the nodes in this pool. Note that if this field * and `autoUpgrade` are both specified, they will fight each other for what the node version should * be, so setting both is highly discouraged. While a fuzzy version can be specified, it's * recommended that you specify explicit versions as the provider will see spurious diffs * when fuzzy versions are used. See the `gcp.container.getEngineVersions` data source's * `versionPrefix` field to approximate fuzzy versions in a provider-compatible way. */ public readonly version!: pulumi.Output<string>; /** * Create a NodePool resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: NodePoolArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: NodePoolArgs | NodePoolState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as NodePoolState | undefined; inputs["autoscaling"] = state ? state.autoscaling : undefined; inputs["cluster"] = state ? state.cluster : undefined; inputs["initialNodeCount"] = state ? state.initialNodeCount : undefined; inputs["instanceGroupUrls"] = state ? state.instanceGroupUrls : undefined; inputs["location"] = state ? state.location : undefined; inputs["managedInstanceGroupUrls"] = state ? state.managedInstanceGroupUrls : undefined; inputs["management"] = state ? state.management : undefined; inputs["maxPodsPerNode"] = state ? state.maxPodsPerNode : undefined; inputs["name"] = state ? state.name : undefined; inputs["namePrefix"] = state ? state.namePrefix : undefined; inputs["networkConfig"] = state ? state.networkConfig : undefined; inputs["nodeConfig"] = state ? state.nodeConfig : undefined; inputs["nodeCount"] = state ? state.nodeCount : undefined; inputs["nodeLocations"] = state ? state.nodeLocations : undefined; inputs["operation"] = state ? state.operation : undefined; inputs["project"] = state ? state.project : undefined; inputs["upgradeSettings"] = state ? state.upgradeSettings : undefined; inputs["version"] = state ? state.version : undefined; } else { const args = argsOrState as NodePoolArgs | undefined; if ((!args || args.cluster === undefined) && !opts.urn) { throw new Error("Missing required property 'cluster'"); } inputs["autoscaling"] = args ? args.autoscaling : undefined; inputs["cluster"] = args ? args.cluster : undefined; inputs["initialNodeCount"] = args ? args.initialNodeCount : undefined; inputs["location"] = args ? args.location : undefined; inputs["management"] = args ? args.management : undefined; inputs["maxPodsPerNode"] = args ? args.maxPodsPerNode : undefined; inputs["name"] = args ? args.name : undefined; inputs["namePrefix"] = args ? args.namePrefix : undefined; inputs["networkConfig"] = args ? args.networkConfig : undefined; inputs["nodeConfig"] = args ? args.nodeConfig : undefined; inputs["nodeCount"] = args ? args.nodeCount : undefined; inputs["nodeLocations"] = args ? args.nodeLocations : undefined; inputs["project"] = args ? args.project : undefined; inputs["upgradeSettings"] = args ? args.upgradeSettings : undefined; inputs["version"] = args ? args.version : undefined; inputs["instanceGroupUrls"] = undefined /*out*/; inputs["managedInstanceGroupUrls"] = undefined /*out*/; inputs["operation"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(NodePool.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering NodePool resources. */ export interface NodePoolState { /** * Configuration required by cluster autoscaler to adjust * the size of the node pool to the current cluster usage. Structure is documented below. */ autoscaling?: pulumi.Input<inputs.container.NodePoolAutoscaling>; /** * The cluster to create the node pool for. Cluster must be present in `location` provided for clusters. May be specified in the format `projects/{{project}}/locations/{{location}}/clusters/{{cluster}}` or as just the name of the cluster. */ cluster?: pulumi.Input<string>; /** * The initial number of nodes for the pool. In * regional or multi-zonal clusters, this is the number of nodes per zone. Changing * this will force recreation of the resource. WARNING: Resizing your node pool manually * may change this value in your existing cluster, which will trigger destruction * and recreation on the next provider run (to rectify the discrepancy). If you don't * need this value, don't set it. If you do need it, you can use a lifecycle block to * ignore subsqeuent changes to this field. */ initialNodeCount?: pulumi.Input<number>; /** * The resource URLs of the managed instance groups associated with this node pool. */ instanceGroupUrls?: pulumi.Input<pulumi.Input<string>[]>; /** * The location (region or zone) of the cluster. */ location?: pulumi.Input<string>; /** * List of instance group URLs which have been assigned to this node pool. */ managedInstanceGroupUrls?: pulumi.Input<pulumi.Input<string>[]>; /** * Node management configuration, wherein auto-repair and * auto-upgrade is configured. Structure is documented below. */ management?: pulumi.Input<inputs.container.NodePoolManagement>; /** * The maximum number of pods per node in this node pool. * Note that this does not work on node pools which are "route-based" - that is, node * pools belonging to clusters that do not have IP Aliasing enabled. * See the [official documentation](https://cloud.google.com/kubernetes-engine/docs/how-to/flexible-pod-cidr) * for more information. */ maxPodsPerNode?: pulumi.Input<number>; /** * The name of the node pool. If left blank, the provider will * auto-generate a unique name. */ name?: pulumi.Input<string>; /** * Creates a unique name for the node pool beginning * with the specified prefix. Conflicts with `name`. */ namePrefix?: pulumi.Input<string>; /** * The network configuration of the pool. See * gcp.container.Cluster for schema. */ networkConfig?: pulumi.Input<inputs.container.NodePoolNetworkConfig>; /** * Parameters used in creating the node pool. See * gcp.container.Cluster for schema. */ nodeConfig?: pulumi.Input<inputs.container.NodePoolNodeConfig>; /** * The number of nodes per instance group. This field can be used to * update the number of nodes per instance group but should not be used alongside `autoscaling`. */ nodeCount?: pulumi.Input<number>; /** * The list of zones in which the node pool's nodes should be located. Nodes must * be in the region of their regional cluster or in the same region as their * cluster's zone for zonal clusters. If unspecified, the cluster-level * `nodeLocations` will be used. */ nodeLocations?: pulumi.Input<pulumi.Input<string>[]>; operation?: pulumi.Input<string>; /** * The ID of the project in which to create the node pool. If blank, * the provider-configured project will be used. */ project?: pulumi.Input<string>; /** * Specify node upgrade settings to change how many nodes GKE attempts to * upgrade at once. The number of nodes upgraded simultaneously is the sum of `maxSurge` and `maxUnavailable`. * The maximum number of nodes upgraded simultaneously is limited to 20. Structure is documented below. */ upgradeSettings?: pulumi.Input<inputs.container.NodePoolUpgradeSettings>; /** * The Kubernetes version for the nodes in this pool. Note that if this field * and `autoUpgrade` are both specified, they will fight each other for what the node version should * be, so setting both is highly discouraged. While a fuzzy version can be specified, it's * recommended that you specify explicit versions as the provider will see spurious diffs * when fuzzy versions are used. See the `gcp.container.getEngineVersions` data source's * `versionPrefix` field to approximate fuzzy versions in a provider-compatible way. */ version?: pulumi.Input<string>; } /** * The set of arguments for constructing a NodePool resource. */ export interface NodePoolArgs { /** * Configuration required by cluster autoscaler to adjust * the size of the node pool to the current cluster usage. Structure is documented below. */ autoscaling?: pulumi.Input<inputs.container.NodePoolAutoscaling>; /** * The cluster to create the node pool for. Cluster must be present in `location` provided for clusters. May be specified in the format `projects/{{project}}/locations/{{location}}/clusters/{{cluster}}` or as just the name of the cluster. */ cluster: pulumi.Input<string>; /** * The initial number of nodes for the pool. In * regional or multi-zonal clusters, this is the number of nodes per zone. Changing * this will force recreation of the resource. WARNING: Resizing your node pool manually * may change this value in your existing cluster, which will trigger destruction * and recreation on the next provider run (to rectify the discrepancy). If you don't * need this value, don't set it. If you do need it, you can use a lifecycle block to * ignore subsqeuent changes to this field. */ initialNodeCount?: pulumi.Input<number>; /** * The location (region or zone) of the cluster. */ location?: pulumi.Input<string>; /** * Node management configuration, wherein auto-repair and * auto-upgrade is configured. Structure is documented below. */ management?: pulumi.Input<inputs.container.NodePoolManagement>; /** * The maximum number of pods per node in this node pool. * Note that this does not work on node pools which are "route-based" - that is, node * pools belonging to clusters that do not have IP Aliasing enabled. * See the [official documentation](https://cloud.google.com/kubernetes-engine/docs/how-to/flexible-pod-cidr) * for more information. */ maxPodsPerNode?: pulumi.Input<number>; /** * The name of the node pool. If left blank, the provider will * auto-generate a unique name. */ name?: pulumi.Input<string>; /** * Creates a unique name for the node pool beginning * with the specified prefix. Conflicts with `name`. */ namePrefix?: pulumi.Input<string>; /** * The network configuration of the pool. See * gcp.container.Cluster for schema. */ networkConfig?: pulumi.Input<inputs.container.NodePoolNetworkConfig>; /** * Parameters used in creating the node pool. See * gcp.container.Cluster for schema. */ nodeConfig?: pulumi.Input<inputs.container.NodePoolNodeConfig>; /** * The number of nodes per instance group. This field can be used to * update the number of nodes per instance group but should not be used alongside `autoscaling`. */ nodeCount?: pulumi.Input<number>; /** * The list of zones in which the node pool's nodes should be located. Nodes must * be in the region of their regional cluster or in the same region as their * cluster's zone for zonal clusters. If unspecified, the cluster-level * `nodeLocations` will be used. */ nodeLocations?: pulumi.Input<pulumi.Input<string>[]>; /** * The ID of the project in which to create the node pool. If blank, * the provider-configured project will be used. */ project?: pulumi.Input<string>; /** * Specify node upgrade settings to change how many nodes GKE attempts to * upgrade at once. The number of nodes upgraded simultaneously is the sum of `maxSurge` and `maxUnavailable`. * The maximum number of nodes upgraded simultaneously is limited to 20. Structure is documented below. */ upgradeSettings?: pulumi.Input<inputs.container.NodePoolUpgradeSettings>; /** * The Kubernetes version for the nodes in this pool. Note that if this field * and `autoUpgrade` are both specified, they will fight each other for what the node version should * be, so setting both is highly discouraged. While a fuzzy version can be specified, it's * recommended that you specify explicit versions as the provider will see spurious diffs * when fuzzy versions are used. See the `gcp.container.getEngineVersions` data source's * `versionPrefix` field to approximate fuzzy versions in a provider-compatible way. */ version?: pulumi.Input<string>; }
the_stack
import Context from './../../src/lib/context'; import util from './../../src' import { getData } from './data'; const { deepClone } = util.data; describe('@idraw/board: src/lib/context', () => { const options = { width: 600, height: 400, contextWidth: 1000, contextHeight: 900, devicePixelRatio: 2 } test('Context', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const data = getData(); ctx.clearRect(0, 0, opts.contextWidth, opts.contextHeight); ctx.setFillStyle('#ffffff'); ctx.fillRect(0, 0, opts.contextWidth, opts.contextHeight); data.elements.forEach(ele => { ctx.setFillStyle(ele.desc.color); ctx.fillRect(ele.x, ele.y, ele.w, ele.h); }); // @ts-ignore; const calls = ctx2d.__getDrawCalls(); expect(calls).toMatchSnapshot(); }); test('Context.getSize', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); expect(ctx.getSize()).toStrictEqual(opts); }) test('Context.resetSize', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const newOpts = { width: 601, height: 401, contextWidth: 1001, contextHeight: 901, devicePixelRatio: 3, } const ctx = new Context(ctx2d, opts); ctx.resetSize(newOpts); expect(ctx.getSize()).toStrictEqual(newOpts); }); test('Context.calcDeviceNum', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const num = 100; expect(ctx.calcDeviceNum(num)).toStrictEqual(opts.devicePixelRatio * num); }); test('Context.calcScreenNum', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const num = 100; expect(ctx.calcScreenNum(num)).toStrictEqual(num / opts.devicePixelRatio); }); test('Context.setTransform', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const transform = { scale: 2, scrollX: 100, scrollY: -200, }; ctx.setTransform(deepClone(transform)) expect(ctx.getTransform()).toStrictEqual(deepClone(transform)); }); test('Context.getTransform', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); expect(ctx.getTransform()).toStrictEqual({ scale: 1, scrollX: 0, scrollY: 0, }); }); test('Context.setFillStyle', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const color = '#f0f0f0'; ctx.setFillStyle(color); ctx.fillRect(0, 0, opts.contextWidth, opts.contextHeight); expect(ctx2d.fillStyle).toStrictEqual(color); }); test('Context.fill', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); expect(calls).toMatchSnapshot(); }); test('Context.arc', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.arc(70, 80, 50, 0, Math.PI * 2, true); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.rect', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.rect(10, 20, 100, 200); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.fillRect', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.fillRect(10, 20, 80, 100); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); // expect(calls).toStrictEqual([ // { // type: 'fillRect', // transform: [ 1, 0, 0, 1, 0, 0 ], // props: { x: 0, y: 0, width: 2000, height: 1800 } // } // ]); }); test('Context.clearRect', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.clearRect(0, 0, opts.contextWidth, opts.contextHeight); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.beginPath', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.beginPath(); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.closePath', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.closePath(); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.lineTo', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.lineTo(10, 20); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.moveTo', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.moveTo(10, 20); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.arcTo', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.arcTo(50, 50, 100, 100, Math.PI * 2); ctx.fill(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.setLineWidth', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const lineWidth = 12; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.setLineWidth(lineWidth); expect(ctx2d.lineWidth).toStrictEqual(lineWidth * opts.devicePixelRatio); }); test('Context.setLineDash', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const lineDash = [10, 20]; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.setLineDash(lineDash); // @ts-ignore // const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); // expect(calls).toMatchSnapshot(); expect(ctx2d.getLineDash()).toStrictEqual(lineDash.map(n => n * opts.devicePixelRatio)); }); test('Context.setStrokeStyle', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const color = '#f0f0f0'; ctx.setStrokeStyle(color); ctx.fillRect(0, 0, opts.contextWidth, opts.contextHeight); expect(ctx2d.strokeStyle).toStrictEqual(color); }); // TODO test('Context.isPointInPath', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; // const lineDash = [10, 20]; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const x = 50; const y = 50; const w = 50; const h = 50; ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + w, y); ctx.lineTo(x + w, y + h); ctx.lineTo(x, y + h); ctx.lineTo(x, y); ctx.closePath(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); expect(ctx.isPointInPath(51, 51)) .toStrictEqual(ctx2d.isPointInPath(60 * opts.devicePixelRatio, 60 * opts.devicePixelRatio)); }); // TODO test('Context.isPointInPathWithoutScroll', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; // const lineDash = [10, 20]; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.setTransform({ scale: 2, scrollX: 10, scrollY: 10, }) ctx.beginPath(); ctx.rect(50, 50, 100, 100); ctx.closePath(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); expect(ctx.isPointInPathWithoutScroll(51, 51)) .toStrictEqual( ctx2d.isPointInPath( 60 * opts.devicePixelRatio, 60 * opts.devicePixelRatio ) ); }); test('Context.setStrokeStyle', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const color = '#f0f0f0'; ctx.setStrokeStyle(color); expect(ctx2d.strokeStyle).toStrictEqual(color); }); test('Context.stroke', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.rect(10, 20, 100, 200); ctx.stroke(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.translate', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const x = 50; const y = 60; ctx.translate(x, y); ctx.rect(10, 20, 100, 200); ctx.stroke(); ctx.translate(-x, -y); // @ts-ignore const calls = ctx2d.__getDrawCalls(); expect(calls).toMatchSnapshot(); }); test('Context.rotate', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const radian = Math.PI / 6; ctx.rotate(radian); ctx.rect(10, 20, 100, 200); ctx.stroke(); ctx.rotate(-radian); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.drawImage', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const img = new Image(); const dx = 11; const dy = 12; const dw = 51; const dh = 52; const sx = 61; const sy = 62; const sw = 101 const sh = 102; ctx.drawImage(img, dx, dy); ctx.drawImage(img, dx, dy, dw, dh); ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.createPattern', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const img = new Image(); const pattern = ctx.createPattern(img, 'repeat') as CanvasPattern; ctx.setFillStyle(pattern); ctx.fillRect(0, 0, 300, 300); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(ctx2d.fillStyle).toStrictEqual(pattern); expect(calls).toMatchSnapshot(); }); test('Context.measureText', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.setFont({ fontSize: 20 }); const size = ctx.measureText('Hello World!'); expect(size.width).toStrictEqual(12); }); test('Context.setTextAlign', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const textAlign = 'center'; ctx.setTextAlign(textAlign); ctx.fillRect(0, 0, opts.contextWidth, opts.contextHeight); expect(ctx2d.textAlign).toStrictEqual(textAlign); }); test('Context.fillText', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.fillText('Hello world', 50, 100); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.setFont', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const fontSize = 22; const fontFamily = 'Hello'; const fontWeight = 'bold'; ctx.setFont({ fontSize, fontFamily, fontWeight }); // console.log('ctx2d.font =', ctx2d.font); expect(ctx2d.font).toStrictEqual([fontWeight, (fontSize * opts.devicePixelRatio) + 'px', fontFamily].join(' ')) }); test('Context.setTextBaseline', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const textBaseline = 'bottom'; ctx.setTextBaseline(textBaseline); expect(ctx2d.textBaseline).toStrictEqual(textBaseline) }); test('Context.setGlobalAlpha', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const globalAlpha = 0.45; ctx.setGlobalAlpha(globalAlpha); expect(ctx2d.globalAlpha).toStrictEqual(globalAlpha) }); test('Context.save', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.save(); ctx.setFillStyle('#f0f0f0'); ctx.fillRect(10, 10, 100, 100); ctx.restore(); ctx.fillRect(150, 75, 100, 100); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.restore', async () => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); ctx.save(); ctx.setFillStyle('#f0f0f0'); ctx.fillRect(10, 10, 100, 100); ctx.restore(); ctx.fillRect(150, 75, 100, 100); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); test('Context.scale', async() => { const opts = deepClone(options); const canvas = document.createElement('canvas'); canvas.width = opts.contextWidth; canvas.height = opts.contextHeight; const ctx2d: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D; const ctx = new Context(ctx2d, opts); const scaleX = 2; const scaleY = 3; ctx.scale(scaleX, scaleY); ctx.rect(10, 20, 100, 200); ctx.stroke(); // @ts-ignore const calls = ctx2d.__getDrawCalls(); // console.log('calls =', JSON.stringify(calls, null, 2)); expect(calls).toMatchSnapshot(); }); })
the_stack
import {Mutable, Class, Arrays, ObserverType} from "@swim/util"; import {Affinity, Provider} from "@swim/component"; import {R2Box, Transform} from "@swim/math"; import { ViewContextType, ViewContext, ViewFlags, View, ViewWillRender, ViewDidRender, ViewWillRasterize, ViewDidRasterize, ViewWillComposite, ViewDidComposite, ViewEvent, ViewMouseEventInit, ViewMouseEvent, ViewPointerEventInit, ViewPointerEvent, ViewTouchInit, ViewTouch, ViewTouchEvent, } from "@swim/view"; import {HtmlViewInit, HtmlView} from "@swim/dom"; import {SpriteService} from "../sprite/SpriteService"; import type {AnyGraphicsRenderer, GraphicsRendererType, GraphicsRenderer} from "../graphics/GraphicsRenderer"; import type {GraphicsViewContext} from "../graphics/GraphicsViewContext"; import {GraphicsView} from "../graphics/GraphicsView"; import {WebGLRenderer} from "../webgl/WebGLRenderer"; import {CanvasRenderer} from "./CanvasRenderer"; import type {CanvasViewObserver} from "./CanvasViewObserver"; /** @internal */ export type CanvasFlags = number; /** @public */ export interface CanvasViewInit extends HtmlViewInit { renderer?: AnyGraphicsRenderer; clickEventsEnabled?: boolean; wheelEventsEnabled?: boolean; mouseEventsEnabled?: boolean; pointerEventsEnabled?: boolean; touchEventsEnabled?: boolean; } /** @public */ export class CanvasView extends HtmlView { constructor(node: HTMLCanvasElement) { super(node); Object.defineProperty(this, "renderer", { // override getter value: this.createRenderer(), writable: true, enumerable: true, configurable: true, }); this.viewFrame = R2Box.undefined(); this.canvasFlags = CanvasView.ClickEventsFlag; this.eventNode = node; this.mouse = null; this.pointers = null; this.touches = null; this.onClick = this.onClick.bind(this); this.onDblClick = this.onDblClick.bind(this); this.onContextMenu = this.onContextMenu.bind(this); this.onWheel = this.onWheel.bind(this); this.onMouseEnter = this.onMouseEnter.bind(this); this.onMouseLeave = this.onMouseLeave.bind(this); this.onMouseDown = this.onMouseDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onPointerEnter = this.onPointerEnter.bind(this); this.onPointerLeave = this.onPointerLeave.bind(this); this.onPointerDown = this.onPointerDown.bind(this); this.onPointerMove = this.onPointerMove.bind(this); this.onPointerUp = this.onPointerUp.bind(this); this.onPointerCancel = this.onPointerCancel.bind(this); this.onTouchStart = this.onTouchStart.bind(this); this.onTouchMove = this.onTouchMove.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); this.onTouchCancel = this.onTouchCancel.bind(this); this.initCanvas(); } override readonly observerType?: Class<CanvasViewObserver>; override readonly contextType?: Class<GraphicsViewContext>; override readonly node!: HTMLCanvasElement; protected initCanvas(): void { this.position.setState("absolute", Affinity.Intrinsic); } protected override onMount(): void { super.onMount(); this.attachEvents(this.eventNode); } protected override onUnmount(): void { this.detachEvents(this.eventNode); super.onUnmount(); } protected override needsUpdate(updateFlags: ViewFlags, immediate: boolean): ViewFlags { updateFlags = super.needsUpdate(updateFlags, immediate); updateFlags |= View.NeedsRender | View.NeedsComposite; this.setFlags(this.flags | (View.NeedsRender | View.NeedsComposite)); return updateFlags; } protected override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { if ((processFlags & View.ProcessMask) !== 0) { this.requireUpdate(View.NeedsRender | View.NeedsComposite); } return processFlags; } protected override onResize(viewContext: ViewContextType<this>): void { super.onResize(viewContext); this.resizeCanvas(this.node); this.resetRenderer(); this.requireUpdate(View.NeedsLayout | View.NeedsRender | View.NeedsComposite); } protected override onScroll(viewContext: ViewContextType<this>): void { super.onScroll(viewContext); this.setCulled(!this.intersectsViewport()); } protected override didDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): void { this.detectHitTargets(); super.didDisplay(displayFlags, viewContext); } protected override onRender(viewContext: ViewContextType<this>): void { this.clearCanvas(); } protected override needsDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { displayFlags |= View.NeedsRender | View.NeedsComposite; return displayFlags; } @Provider({ type: SpriteService, observes: false, service: SpriteService.global(), }) readonly spriteProvider!: Provider<this, SpriteService>; get pixelRatio(): number { return window.devicePixelRatio || 1; } readonly renderer!: GraphicsRenderer | null; setRenderer(renderer: AnyGraphicsRenderer | null): void { if (typeof renderer === "string") { renderer = this.createRenderer(renderer as GraphicsRendererType); } (this as Mutable<this>).renderer = renderer; this.resetRenderer(); } protected createRenderer(rendererType: GraphicsRendererType = "canvas"): GraphicsRenderer | null { if (rendererType === "canvas") { const context = this.node.getContext("2d"); if (context !== null) { const pixelRatio = this.pixelRatio; const transform = Transform.affine(pixelRatio, 0, 0, pixelRatio, 0, 0); return new CanvasRenderer(context, transform, pixelRatio); } else { throw new Error("Failed to create canvas rendering context"); } } else if (rendererType === "webgl") { const context = this.node.getContext("webgl"); if (context !== null) { return new WebGLRenderer(context, this.pixelRatio); } else { throw new Error("Failed to create webgl rendering context"); } } else { throw new Error("Failed to create " + rendererType + " renderer"); } } /** @internal */ readonly canvasFlags: CanvasFlags; /** @internal */ setCanvasFlags(canvasFlags: CanvasFlags): void { (this as Mutable<this>).canvasFlags = canvasFlags; } override extendViewContext(viewContext: ViewContext): ViewContextType<this> { const canvasViewContext = Object.create(viewContext); canvasViewContext.viewFrame = this.viewFrame; canvasViewContext.renderer = this.renderer; return canvasViewContext; } /** @internal */ readonly viewFrame: R2Box; setViewFrame(viewFrame: R2Box | null): void { // nop } get viewBounds(): R2Box { return this.viewFrame; } get hitBounds(): R2Box { return this.viewFrame; } cascadeHitTest(x: number, y: number, baseViewContext?: ViewContext): GraphicsView | null { if (!this.hidden && !this.culled && !this.intangible) { const hitBounds = this.hitBounds; if (hitBounds.contains(x, y)) { if (baseViewContext === void 0) { baseViewContext = this.superViewContext; } const viewContext = this.extendViewContext(baseViewContext); let hit = this.hitTestChildren(x, y, viewContext); if (hit === null) { const outerViewContext = ViewContext.current; try { ViewContext.current = viewContext; this.setFlags(this.flags | View.ContextualFlag); hit = this.hitTest(x, y, viewContext); } finally { this.setFlags(this.flags & ~View.ContextualFlag); ViewContext.current = outerViewContext; } } return hit; } } return null; } protected hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null { return null; } protected hitTestChildren(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null { let child = this.firstChild; while (child !== null) { if (child instanceof GraphicsView) { const hit = this.hitTestChild(child, x, y, viewContext); if (hit !== null) { return hit; } } child = child.nextSibling; } return null; } protected hitTestChild(childView: GraphicsView, x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null { return childView.cascadeHitTest(x, y, viewContext); } /** @internal */ protected detectHitTargets(clientBounds?: R2Box): void { if ((this.canvasFlags & CanvasView.MouseEventsFlag) !== 0) { const mouse = this.mouse; if (mouse !== null) { if (clientBounds === void 0) { clientBounds = this.clientBounds; } this.detectMouseTarget(mouse, this.clientBounds); } } if ((this.canvasFlags & CanvasView.PointerEventsFlag) !== 0) { const pointers = this.pointers; for (const id in pointers) { const pointer = pointers[id]!; if (clientBounds === void 0) { clientBounds = this.clientBounds; } this.detectPointerTarget(pointer, clientBounds); } } } readonly eventNode: HTMLElement; setEventNode(newEventNode: HTMLElement | null): void { if (newEventNode === null) { newEventNode = this.node; } const oldEventNode = this.eventNode; if (oldEventNode !== newEventNode) { this.detachEvents(oldEventNode); (this as Mutable<this>).eventNode = newEventNode; this.attachEvents(newEventNode); } } clickEventsEnabled(): boolean; clickEventsEnabled(clickEvents: boolean): this; clickEventsEnabled(newClickEvents?: boolean): boolean | this { const oldClickEvents = (this.canvasFlags & CanvasView.ClickEventsFlag) !== 0; if (newClickEvents === void 0) { return oldClickEvents; } else { if (newClickEvents && !oldClickEvents) { this.setCanvasFlags(this.canvasFlags | CanvasView.ClickEventsFlag); this.attachClickEvents(this.eventNode); } else if (!newClickEvents && oldClickEvents) { this.setCanvasFlags(this.canvasFlags & ~CanvasView.ClickEventsFlag); this.detachClickEvents(this.eventNode); } return this; } } wheelEventsEnabled(): boolean; wheelEventsEnabled(wheelEvents: boolean): this; wheelEventsEnabled(newWheelEvents?: boolean): boolean | this { const oldWheelEvents = (this.canvasFlags & CanvasView.WheelEventsFlag) !== 0; if (newWheelEvents === void 0) { return oldWheelEvents; } else { if (newWheelEvents && !oldWheelEvents) { this.setCanvasFlags(this.canvasFlags | CanvasView.WheelEventsFlag); this.attachWheelEvents(this.eventNode); } else if (!newWheelEvents && oldWheelEvents) { this.setCanvasFlags(this.canvasFlags & ~CanvasView.WheelEventsFlag); this.detachWheelEvents(this.eventNode); } return this; } } mouseEventsEnabled(): boolean; mouseEventsEnabled(mouseEvents: boolean): this; mouseEventsEnabled(newMouseEvents?: boolean): boolean | this { const oldMouseEvents = (this.canvasFlags & CanvasView.MouseEventsFlag) !== 0; if (newMouseEvents === void 0) { return oldMouseEvents; } else { if (newMouseEvents && !oldMouseEvents) { this.setCanvasFlags(this.canvasFlags | CanvasView.MouseEventsFlag); this.attachPassiveMouseEvents(this.eventNode); } else if (!newMouseEvents && oldMouseEvents) { this.setCanvasFlags(this.canvasFlags & ~CanvasView.MouseEventsFlag); this.detachPassiveMouseEvents(this.eventNode); } return this; } } pointerEventsEnabled(): boolean; pointerEventsEnabled(pointerEvents: boolean): this; pointerEventsEnabled(newPointerEvents?: boolean): boolean | this { const oldPointerEvents = (this.canvasFlags & CanvasView.PointerEventsFlag) !== 0; if (newPointerEvents === void 0) { return oldPointerEvents; } else { if (newPointerEvents && !oldPointerEvents) { this.setCanvasFlags(this.canvasFlags | CanvasView.PointerEventsFlag); this.attachPassivePointerEvents(this.eventNode); } else if (!newPointerEvents && oldPointerEvents) { this.setCanvasFlags(this.canvasFlags & ~CanvasView.PointerEventsFlag); this.detachPassivePointerEvents(this.eventNode); } return this; } } touchEventsEnabled(): boolean; touchEventsEnabled(touchEvents: boolean): this; touchEventsEnabled(newTouchEvents?: boolean): boolean | this { const oldTouchEvents = (this.canvasFlags & CanvasView.TouchEventsFlag) !== 0; if (newTouchEvents === void 0) { return oldTouchEvents; } else { if (newTouchEvents && !oldTouchEvents) { this.setCanvasFlags(this.canvasFlags | CanvasView.TouchEventsFlag); this.attachPassiveTouchEvents(this.eventNode); } else if (!newTouchEvents && oldTouchEvents) { this.setCanvasFlags(this.canvasFlags & ~CanvasView.TouchEventsFlag); this.detachPassiveTouchEvents(this.eventNode); } return this; } } /** @internal */ handleEvent(event: ViewEvent): void { // nop } /** @internal */ bubbleEvent(event: ViewEvent): View | null { this.handleEvent(event); return this; } /** @internal */ protected attachEvents(eventNode: HTMLElement): void { if ((this.canvasFlags & CanvasView.ClickEventsFlag) !== 0) { this.attachClickEvents(eventNode); } if ((this.canvasFlags & CanvasView.WheelEventsFlag) !== 0) { this.attachWheelEvents(eventNode); } if ((this.canvasFlags & CanvasView.MouseEventsFlag) !== 0) { this.attachPassiveMouseEvents(eventNode); } if ((this.canvasFlags & CanvasView.PointerEventsFlag) !== 0) { this.attachPassivePointerEvents(eventNode); } if ((this.canvasFlags & CanvasView.TouchEventsFlag) !== 0) { this.attachPassiveTouchEvents(eventNode); } } /** @internal */ protected detachEvents(eventNode: HTMLElement): void { this.detachClickEvents(eventNode); this.detachWheelEvents(eventNode); this.detachPassiveMouseEvents(eventNode); this.detachActiveMouseEvents(eventNode); this.detachPassivePointerEvents(eventNode); this.detachActivePointerEvents(eventNode); this.detachPassiveTouchEvents(eventNode); this.detachActiveTouchEvents(eventNode); } /** @internal */ fireEvent(event: ViewEvent, clientX: number, clientY: number): GraphicsView | null { const clientBounds = this.clientBounds; if (clientBounds.contains(clientX, clientY)) { const x = clientX - clientBounds.x; const y = clientY - clientBounds.y; const hit = this.cascadeHitTest(x, y); if (hit !== null) { event.targetView = hit; hit.bubbleEvent(event); return hit; } } return null; } /** @internal */ protected attachClickEvents(eventNode: HTMLElement): void { eventNode.addEventListener("click", this.onClick); eventNode.addEventListener("dblclick", this.onDblClick); eventNode.addEventListener("contextmenu", this.onContextMenu); } /** @internal */ protected detachClickEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("click", this.onClick); eventNode.removeEventListener("dblclick", this.onDblClick); eventNode.removeEventListener("contextmenu", this.onContextMenu); } /** @internal */ protected attachWheelEvents(eventNode: HTMLElement): void { eventNode.addEventListener("wheel", this.onWheel); } /** @internal */ protected detachWheelEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("wheel", this.onWheel); } /** @internal */ protected attachPassiveMouseEvents(eventNode: HTMLElement): void { eventNode.addEventListener("mouseenter", this.onMouseEnter); eventNode.addEventListener("mouseleave", this.onMouseLeave); eventNode.addEventListener("mousedown", this.onMouseDown); } /** @internal */ protected detachPassiveMouseEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("mouseenter", this.onMouseEnter); eventNode.removeEventListener("mouseleave", this.onMouseLeave); eventNode.removeEventListener("mousedown", this.onMouseDown); } /** @internal */ protected attachActiveMouseEvents(eventNode: HTMLElement): void { document.body.addEventListener("mousemove", this.onMouseMove); document.body.addEventListener("mouseup", this.onMouseUp); } /** @internal */ protected detachActiveMouseEvents(eventNode: HTMLElement): void { document.body.removeEventListener("mousemove", this.onMouseMove); document.body.removeEventListener("mouseup", this.onMouseUp); } /** @internal */ readonly mouse: ViewMouseEventInit | null; /** @internal */ protected updateMouse(mouse: ViewMouseEventInit, event: MouseEvent): void { mouse.button = event.button; mouse.buttons = event.buttons; mouse.altKey = event.altKey; mouse.ctrlKey = event.ctrlKey; mouse.metaKey = event.metaKey; mouse.shiftKey = event.shiftKey; mouse.clientX = event.clientX; mouse.clientY = event.clientY; mouse.screenX = event.screenX; mouse.screenY = event.screenY; mouse.movementX = event.movementX; mouse.movementY = event.movementY; mouse.view = event.view; mouse.detail = event.detail; mouse.relatedTarget = event.relatedTarget; } /** @internal */ protected fireMouseEvent(event: MouseEvent): GraphicsView | null { return this.fireEvent(event, event.clientX, event.clientY); } /** @internal */ protected onClick(event: MouseEvent): void { const mouse = this.mouse; if (mouse !== null) { this.updateMouse(mouse, event); } this.fireMouseEvent(event); } /** @internal */ protected onDblClick(event: MouseEvent): void { const mouse = this.mouse; if (mouse !== null) { this.updateMouse(mouse, event); } this.fireMouseEvent(event); } /** @internal */ protected onContextMenu(event: MouseEvent): void { const mouse = this.mouse; if (mouse !== null) { this.updateMouse(mouse, event); } this.fireMouseEvent(event); } /** @internal */ protected onWheel(event: WheelEvent): void { const mouse = this.mouse; if (mouse !== null) { this.updateMouse(mouse, event); } this.fireMouseEvent(event); } /** @internal */ protected onMouseEnter(event: MouseEvent): void { let mouse = this.mouse; if (mouse === null) { this.attachActiveMouseEvents(this.eventNode); mouse = {}; (this as Mutable<this>).mouse = mouse; } this.updateMouse(mouse, event); } /** @internal */ protected onMouseLeave(event: MouseEvent): void { const mouse = this.mouse; if (mouse !== null) { (this as Mutable<this>).mouse = null; this.detachActiveMouseEvents(this.eventNode); } } /** @internal */ protected onMouseDown(event: MouseEvent): void { let mouse = this.mouse; if (mouse === null) { this.attachActiveMouseEvents(this.eventNode); mouse = {}; (this as Mutable<this>).mouse = mouse; } this.updateMouse(mouse, event); this.fireMouseEvent(event); } /** @internal */ protected onMouseMove(event: MouseEvent): void { let mouse = this.mouse; if (mouse === null) { mouse = {}; (this as Mutable<this>).mouse = mouse; } this.updateMouse(mouse, event); const oldTargetView = mouse.targetView as GraphicsView | undefined; let newTargetView: GraphicsView | null | undefined = this.fireMouseEvent(event); if (newTargetView === null) { newTargetView = void 0; } if (newTargetView !== oldTargetView) { this.onMouseTargetChange(mouse, newTargetView, oldTargetView); } } /** @internal */ protected onMouseUp(event: MouseEvent): void { const mouse = this.mouse; if (mouse !== null) { this.updateMouse(mouse, event); } this.fireMouseEvent(event); } /** @internal */ protected onMouseTargetChange(mouse: ViewMouseEventInit, newTargetView: GraphicsView | undefined, oldTargetView: GraphicsView | undefined): void { mouse.bubbles = true; if (oldTargetView !== void 0) { const outEvent = new MouseEvent("mouseout", mouse) as ViewMouseEvent; outEvent.targetView = oldTargetView; outEvent.relatedTargetView = newTargetView; oldTargetView.bubbleEvent(outEvent); } mouse.targetView = newTargetView; if (newTargetView !== void 0) { const overEvent = new MouseEvent("mouseover", mouse) as ViewMouseEvent; overEvent.targetView = newTargetView; overEvent.relatedTargetView = oldTargetView; newTargetView.bubbleEvent(overEvent); } } /** @internal */ protected detectMouseTarget(mouse: ViewMouseEventInit, clientBounds: R2Box): void { const clientX = mouse.clientX!; const clientY = mouse.clientY!; if (clientBounds.contains(clientX, clientY)) { const x = clientX - clientBounds.x; const y = clientY - clientBounds.y; const oldTargetView = mouse.targetView as GraphicsView | undefined; let newTargetView: GraphicsView | null | undefined = this.cascadeHitTest(x, y); if (newTargetView === null) { newTargetView = void 0; } if (newTargetView !== oldTargetView) { this.onMouseTargetChange(mouse, newTargetView, oldTargetView); } } } /** @internal */ protected attachPassivePointerEvents(eventNode: HTMLElement): void { eventNode.addEventListener("pointerenter", this.onPointerEnter); eventNode.addEventListener("pointerleave", this.onPointerLeave); eventNode.addEventListener("pointerdown", this.onPointerDown); } /** @internal */ protected detachPassivePointerEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("pointerenter", this.onPointerEnter); eventNode.removeEventListener("pointerleave", this.onPointerLeave); eventNode.removeEventListener("pointerdown", this.onPointerDown); } /** @internal */ protected attachActivePointerEvents(eventNode: HTMLElement): void { document.body.addEventListener("pointermove", this.onPointerMove); document.body.addEventListener("pointerup", this.onPointerUp); document.body.addEventListener("pointercancel", this.onPointerCancel); } /** @internal */ protected detachActivePointerEvents(eventNode: HTMLElement): void { document.body.removeEventListener("pointermove", this.onPointerMove); document.body.removeEventListener("pointerup", this.onPointerUp); document.body.removeEventListener("pointercancel", this.onPointerCancel); } /** @internal */ readonly pointers: {[id: string]: ViewPointerEventInit | undefined} | null; /** @internal */ protected updatePointer(pointer: ViewPointerEventInit, event: PointerEvent): void { pointer.pointerId = event.pointerId; pointer.pointerType = event.pointerType; pointer.isPrimary = event.isPrimary; pointer.button = event.button; pointer.buttons = event.buttons; pointer.altKey = event.altKey; pointer.ctrlKey = event.ctrlKey; pointer.metaKey = event.metaKey; pointer.shiftKey = event.shiftKey; pointer.clientX = event.clientX; pointer.clientY = event.clientY; pointer.screenX = event.screenX; pointer.screenY = event.screenY; pointer.movementX = event.movementX; pointer.movementY = event.movementY; pointer.width = event.width; pointer.height = event.height; pointer.tiltX = event.tiltX; pointer.tiltY = event.tiltY; pointer.twist = event.twist; pointer.pressure = event.pressure; pointer.tangentialPressure = event.tangentialPressure; pointer.view = event.view; pointer.detail = event.detail; pointer.relatedTarget = event.relatedTarget; } /** @internal */ protected firePointerEvent(event: PointerEvent): GraphicsView | null { return this.fireEvent(event, event.clientX, event.clientY); } /** @internal */ protected onPointerEnter(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } let pointer = pointers[id]; if (pointer === void 0) { if (Object.keys(pointers).length === 0) { this.attachActivePointerEvents(this.eventNode); } pointer = {}; pointers[id] = pointer; } this.updatePointer(pointer, event); } /** @internal */ protected onPointerLeave(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } const pointer = pointers[id]; if (pointer !== void 0) { if (pointer.targetView !== void 0) { this.onPointerTargetChange(pointer, void 0, pointer.targetView as GraphicsView); } delete pointers[id]; if (Object.keys(pointers).length === 0) { this.detachActivePointerEvents(this.eventNode); } } } /** @internal */ protected onPointerDown(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } let pointer = pointers[id]; if (pointer === void 0) { if (Object.keys(pointers).length === 0) { this.attachActivePointerEvents(this.eventNode); } pointer = {}; pointers[id] = pointer; } this.updatePointer(pointer, event); this.firePointerEvent(event); } /** @internal */ protected onPointerMove(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } let pointer = pointers[id]; if (pointer === void 0) { if (Object.keys(pointers).length === 0) { this.attachActivePointerEvents(this.eventNode); } pointer = {}; pointers[id] = pointer; } this.updatePointer(pointer, event); const oldTargetView = pointer.targetView as GraphicsView | undefined; let newTargetView: GraphicsView | null | undefined = this.firePointerEvent(event); if (newTargetView === null) { newTargetView = void 0; } if (newTargetView !== oldTargetView) { this.onPointerTargetChange(pointer, newTargetView, oldTargetView); } } /** @internal */ protected onPointerUp(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } const pointer = pointers[id]; if (pointer !== void 0) { this.updatePointer(pointer, event); } this.firePointerEvent(event); if (pointer !== void 0 && event.pointerType !== "mouse") { if (pointer.targetView !== void 0) { this.onPointerTargetChange(pointer, void 0, pointer.targetView as GraphicsView); } delete pointers[id]; if (Object.keys(pointers).length === 0) { this.detachActivePointerEvents(this.eventNode); } } } /** @internal */ protected onPointerCancel(event: PointerEvent): void { const id = "" + event.pointerId; let pointers = this.pointers; if (pointers === null) { pointers = {}; (this as Mutable<this>).pointers = pointers; } const pointer = pointers[id]; if (pointer !== void 0) { this.updatePointer(pointer, event); } this.firePointerEvent(event); if (pointer !== void 0 && event.pointerType !== "mouse") { if (pointer.targetView !== void 0) { this.onPointerTargetChange(pointer, void 0, pointer.targetView as GraphicsView); } delete pointers[id]; if (Object.keys(pointers).length === 0) { this.detachActivePointerEvents(this.eventNode); } } } /** @internal */ protected onPointerTargetChange(pointer: ViewPointerEventInit, newTargetView: GraphicsView | undefined, oldTargetView: GraphicsView | undefined): void { pointer.bubbles = true; if (oldTargetView !== void 0) { const outEvent = new PointerEvent("pointerout", pointer) as ViewPointerEvent; outEvent.targetView = oldTargetView; outEvent.relatedTargetView = newTargetView; oldTargetView.bubbleEvent(outEvent); } pointer.targetView = newTargetView; if (newTargetView !== void 0) { const overEvent = new PointerEvent("pointerover", pointer) as ViewPointerEvent; overEvent.targetView = newTargetView; overEvent.relatedTargetView = oldTargetView; newTargetView.bubbleEvent(overEvent); } } /** @internal */ protected detectPointerTarget(pointer: ViewPointerEventInit, clientBounds: R2Box): void { const clientX = pointer.clientX!; const clientY = pointer.clientY!; if (clientBounds.contains(clientX, clientY)) { const x = clientX - clientBounds.x; const y = clientY - clientBounds.y; const oldTargetView = pointer.targetView as GraphicsView | undefined; let newTargetView: GraphicsView | null | undefined = this.cascadeHitTest(x, y); if (newTargetView === null) { newTargetView = void 0; } if (newTargetView !== oldTargetView) { this.onPointerTargetChange(pointer, newTargetView, oldTargetView); } } } /** @internal */ protected attachPassiveTouchEvents(eventNode: HTMLElement): void { eventNode.addEventListener("touchstart", this.onTouchStart); } /** @internal */ protected detachPassiveTouchEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("touchstart", this.onTouchStart); } /** @internal */ protected attachActiveTouchEvents(eventNode: HTMLElement): void { eventNode.addEventListener("touchmove", this.onTouchMove); eventNode.addEventListener("touchend", this.onTouchEnd); eventNode.addEventListener("touchcancel", this.onTouchCancel); } /** @internal */ protected detachActiveTouchEvents(eventNode: HTMLElement): void { eventNode.removeEventListener("touchmove", this.onTouchMove); eventNode.removeEventListener("touchend", this.onTouchEnd); eventNode.removeEventListener("touchcancel", this.onTouchCancel); } /** @internal */ readonly touches: {[id: string]: ViewTouchInit | undefined} | null; /** @internal */ protected updateTouch(touch: ViewTouchInit, event: Touch): void { touch.clientX = event.clientX; touch.clientY = event.clientY; touch.screenX = event.screenX; touch.screenY = event.screenY; touch.pageX = event.pageX; touch.pageY = event.pageY; touch.radiusX = event.radiusX; touch.radiusY = event.radiusY; touch.rotationAngle = event.rotationAngle; touch.force = event.force; } /** @internal */ protected fireTouchEvent(type: string, originalEvent: TouchEvent): void { const changedTouches = originalEvent.changedTouches; const dispatched: GraphicsView[] = []; for (let i = 0, n = changedTouches.length; i < n; i += 1) { const changedTouch = changedTouches[i]! as ViewTouch; const targetView = changedTouch.targetView as GraphicsView | undefined; if (targetView !== void 0 && dispatched.indexOf(targetView) < 0) { const startEvent: ViewTouchEvent = new TouchEvent(type, { changedTouches: changedTouches as unknown as Touch[], targetTouches: originalEvent.targetTouches as unknown as Touch[], touches: originalEvent.touches as unknown as Touch[], bubbles: true, }); startEvent.targetView = targetView; const targetViewTouches: Touch[] = [changedTouch]; for (let j = i + 1; j < n; j += 1) { const nextTouch = changedTouches[j]! as ViewTouch; if (nextTouch.targetView === targetView) { targetViewTouches.push(nextTouch); } } if (document.createTouchList !== void 0) { startEvent.targetViewTouches = document.createTouchList(...targetViewTouches); } else { (targetViewTouches as unknown as TouchList).item = function (index: number): Touch { return targetViewTouches[index]!; }; startEvent.targetViewTouches = targetViewTouches as unknown as TouchList; } targetView.bubbleEvent(startEvent); dispatched.push(targetView); } } } /** @internal */ protected onTouchStart(event: TouchEvent): void { let clientBounds: R2Box | undefined; let touches = this.touches; if (touches === null) { touches = {}; (this as Mutable<this>).touches = touches; } const changedTouches = event.changedTouches; for (let i = 0, n = changedTouches.length; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; let touch = touches[id]; if (touch === void 0) { if (Object.keys(touches).length === 0) { this.attachActiveTouchEvents(this.eventNode); } touch = { identifier: changedTouch.identifier, target: changedTouch.target, }; touches[id] = touch; } this.updateTouch(touch, changedTouch); const clientX = touch.clientX!; const clientY = touch.clientY!; if (clientBounds === void 0) { clientBounds = this.clientBounds; } if (clientBounds.contains(clientX, clientY)) { const x = clientX - clientBounds.x; const y = clientY - clientBounds.y; const hit = this.cascadeHitTest(x, y); if (hit !== null) { touch.targetView = hit; changedTouch.targetView = hit; } } } this.fireTouchEvent("touchstart", event); } /** @internal */ protected onTouchMove(event: TouchEvent): void { let touches = this.touches; if (touches === null) { touches = {}; (this as Mutable<this>).touches = touches; } const changedTouches = event.changedTouches; for (let i = 0, n = changedTouches.length; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; let touch = touches[id]; if (touch === void 0) { touch = { identifier: changedTouch.identifier, target: changedTouch.target, }; touches[id] = touch; } this.updateTouch(touch, changedTouch); changedTouch.targetView = touch.targetView; } this.fireTouchEvent("touchmove", event); } /** @internal */ protected onTouchEnd(event: TouchEvent): void { let touches = this.touches; if (touches === null) { touches = {}; (this as Mutable<this>).touches = touches; } const changedTouches = event.changedTouches; const n = changedTouches.length; for (let i = 0; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; let touch = touches[id]; if (touch === void 0) { touch = { identifier: changedTouch.identifier, target: changedTouch.target, }; touches[id] = touch; } this.updateTouch(touch, changedTouch); changedTouch.targetView = touch.targetView; } this.fireTouchEvent("touchend", event); for (let i = 0; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; delete touches[id]; if (Object.keys(touches).length === 0) { this.detachActiveTouchEvents(this.eventNode); } } } /** @internal */ protected onTouchCancel(event: TouchEvent): void { let touches = this.touches; if (touches === null) { touches = {}; (this as Mutable<this>).touches = touches; } const changedTouches = event.changedTouches; const n = changedTouches.length; for (let i = 0; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; let touch = touches[id]; if (touch === void 0) { touch = { identifier: changedTouch.identifier, target: changedTouch.target, }; touches[id] = touch; } this.updateTouch(touch, changedTouch); changedTouch.targetView = touch.targetView; } this.fireTouchEvent("touchcancel", event); for (let i = 0; i < n; i += 1) { const changedTouch = changedTouches[i] as ViewTouch; const id = "" + changedTouch.identifier; delete touches[id]; if (Object.keys(touches).length === 0) { this.detachActiveTouchEvents(this.eventNode); } } } protected resizeCanvas(canvas: HTMLCanvasElement): void { let width: number; let height: number; let pixelRatio: number; let parentNode = canvas.parentNode; if (parentNode instanceof HTMLElement) { do { width = Math.floor(parentNode.offsetWidth); height = Math.floor(parentNode.offsetHeight); if (width !== 0 && height !== 0) { break; } else if ((width === 0 || height === 0) && HtmlView.isPositioned(parentNode)) { this.requireUpdate(View.NeedsResize); // view might not yet have been laid out } parentNode = parentNode.parentNode; } while (parentNode instanceof HTMLElement); pixelRatio = this.pixelRatio; canvas.width = width * pixelRatio; canvas.height = height * pixelRatio; canvas.style.width = width + "px"; canvas.style.height = height + "px"; } else { width = Math.floor(canvas.width); height = Math.floor(canvas.height); pixelRatio = 1; } (this as Mutable<this>).viewFrame = new R2Box(0, 0, width, height); } clearCanvas(): void { const renderer = this.renderer; if (renderer instanceof CanvasRenderer) { const frame = this.viewFrame; renderer.context.clearRect(0, 0, frame.width, frame.height); } else if (renderer instanceof WebGLRenderer) { const context = renderer.context; context.clear(context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT); } } resetRenderer(): void { const renderer = this.renderer; if (renderer instanceof CanvasRenderer) { const pixelRatio = this.pixelRatio; renderer.context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); } else if (renderer instanceof WebGLRenderer) { const frame = this.viewFrame; renderer.context.viewport(0, 0, frame.width, frame.height); } } protected override onObserve(observer: ObserverType<this>): void { super.onObserve(observer); if (observer.viewWillRender !== void 0) { this.observerCache.viewWillRenderObservers = Arrays.inserted(observer as ViewWillRender, this.observerCache.viewWillRenderObservers); } if (observer.viewDidRender !== void 0) { this.observerCache.viewDidRenderObservers = Arrays.inserted(observer as ViewDidRender, this.observerCache.viewDidRenderObservers); } if (observer.viewWillRasterize !== void 0) { this.observerCache.viewWillRasterizeObservers = Arrays.inserted(observer as ViewWillRasterize, this.observerCache.viewWillRasterizeObservers); } if (observer.viewDidRasterize !== void 0) { this.observerCache.viewDidRasterizeObservers = Arrays.inserted(observer as ViewDidRasterize, this.observerCache.viewDidRasterizeObservers); } if (observer.viewWillComposite !== void 0) { this.observerCache.viewWillCompositeObservers = Arrays.inserted(observer as ViewWillComposite, this.observerCache.viewWillCompositeObservers); } if (observer.viewDidComposite !== void 0) { this.observerCache.viewDidCompositeObservers = Arrays.inserted(observer as ViewDidComposite, this.observerCache.viewDidCompositeObservers); } } protected override onUnobserve(observer: ObserverType<this>): void { super.onUnobserve(observer); if (observer.viewWillRender !== void 0) { this.observerCache.viewWillRenderObservers = Arrays.removed(observer as ViewWillRender, this.observerCache.viewWillRenderObservers); } if (observer.viewDidRender !== void 0) { this.observerCache.viewDidRenderObservers = Arrays.removed(observer as ViewDidRender, this.observerCache.viewDidRenderObservers); } if (observer.viewWillRasterize !== void 0) { this.observerCache.viewWillRasterizeObservers = Arrays.removed(observer as ViewWillRasterize, this.observerCache.viewWillRasterizeObservers); } if (observer.viewDidRasterize !== void 0) { this.observerCache.viewDidRasterizeObservers = Arrays.removed(observer as ViewDidRasterize, this.observerCache.viewDidRasterizeObservers); } if (observer.viewWillComposite !== void 0) { this.observerCache.viewWillCompositeObservers = Arrays.removed(observer as ViewWillComposite, this.observerCache.viewWillCompositeObservers); } if (observer.viewDidComposite !== void 0) { this.observerCache.viewDidCompositeObservers = Arrays.removed(observer as ViewDidComposite, this.observerCache.viewDidCompositeObservers); } } override init(init: CanvasViewInit): void { super.init(init); if (init.renderer !== void 0) { this.setRenderer(init.renderer); } if (init.clickEventsEnabled !== void 0) { this.clickEventsEnabled(init.clickEventsEnabled); } if (init.wheelEventsEnabled !== void 0) { this.wheelEventsEnabled(init.wheelEventsEnabled); } if (init.mouseEventsEnabled !== void 0) { this.mouseEventsEnabled(init.mouseEventsEnabled); } if (init.pointerEventsEnabled !== void 0) { this.pointerEventsEnabled(init.pointerEventsEnabled); } if (init.touchEventsEnabled !== void 0) { this.touchEventsEnabled(init.touchEventsEnabled); } } /** @internal */ static override readonly tag: string = "canvas"; /** @internal */ static readonly ClickEventsFlag: CanvasFlags = 1 << 0; /** @internal */ static readonly WheelEventsFlag: CanvasFlags = 1 << 1; /** @internal */ static readonly MouseEventsFlag: CanvasFlags = 1 << 2; /** @internal */ static readonly PointerEventsFlag: CanvasFlags = 1 << 3; /** @internal */ static readonly TouchEventsFlag: CanvasFlags = 1 << 4; /** @internal */ static readonly EventsMask: CanvasFlags = CanvasView.ClickEventsFlag | CanvasView.WheelEventsFlag | CanvasView.MouseEventsFlag | CanvasView.PointerEventsFlag | CanvasView.TouchEventsFlag; static override readonly UncullFlags: ViewFlags = HtmlView.UncullFlags | View.NeedsRender | View.NeedsComposite; static override readonly UnhideFlags: ViewFlags = HtmlView.UnhideFlags | View.NeedsRender | View.NeedsComposite; } declare global { interface Document { createTouchList?(...touches: Touch[]): TouchList; } }
the_stack
import * as XmlNames from './../defs/xml-names'; import * as XmlUtils from './../utils/xml-utils'; import { KdbxTimes } from './kdbx-times'; import { AutoTypeObfuscationOptions, Icons } from '../defs/consts'; import { ProtectedValue } from '../crypto/protected-value'; import { KdbxCustomData, KdbxCustomDataMap } from './kdbx-custom-data'; import { KdbxUuid } from './kdbx-uuid'; import { KdbxContext } from './kdbx-context'; import { KdbxBinaries, KdbxBinary, KdbxBinaryOrRef, KdbxBinaryWithHash } from './kdbx-binaries'; import { KdbxMeta } from './kdbx-meta'; import { KdbxGroup } from './kdbx-group'; import { MergeObjectMap } from './kdbx'; export type KdbxEntryField = string | ProtectedValue; export interface KdbxAutoTypeItem { window: string; keystrokeSequence: string; } export interface KdbxEntryAutoType { enabled: boolean; obfuscation: number; defaultSequence?: string; items: KdbxAutoTypeItem[]; } export interface KdbxEntryEditState { added: number[]; deleted: number[]; } export class KdbxEntry { uuid = new KdbxUuid(); icon: number | undefined; customIcon: KdbxUuid | undefined; fgColor: string | undefined; bgColor: string | undefined; overrideUrl: string | undefined; tags: string[] = []; times = new KdbxTimes(); fields = new Map<string, KdbxEntryField>(); binaries = new Map<string, KdbxBinary | KdbxBinaryWithHash>(); autoType: KdbxEntryAutoType = { enabled: true, obfuscation: AutoTypeObfuscationOptions.None, items: [] }; history: KdbxEntry[] = []; parentGroup: KdbxGroup | undefined; previousParentGroup: KdbxUuid | undefined; customData: KdbxCustomDataMap | undefined; qualityCheck: boolean | undefined; _editState: KdbxEntryEditState | undefined; get lastModTime(): number { return this.times.lastModTime?.getTime() ?? 0; } get locationChanged(): number { return this.times.locationChanged?.getTime() ?? 0; } private readNode(node: Element, ctx: KdbxContext) { switch (node.tagName) { case XmlNames.Elem.Uuid: this.uuid = XmlUtils.getUuid(node) ?? new KdbxUuid(); break; case XmlNames.Elem.Icon: this.icon = XmlUtils.getNumber(node) || Icons.Key; break; case XmlNames.Elem.CustomIconID: this.customIcon = XmlUtils.getUuid(node); break; case XmlNames.Elem.FgColor: this.fgColor = XmlUtils.getText(node); break; case XmlNames.Elem.BgColor: this.bgColor = XmlUtils.getText(node); break; case XmlNames.Elem.OverrideUrl: this.overrideUrl = XmlUtils.getText(node); break; case XmlNames.Elem.Tags: this.tags = XmlUtils.getTags(node); break; case XmlNames.Elem.Times: this.times = KdbxTimes.read(node); break; case XmlNames.Elem.String: this.readField(node); break; case XmlNames.Elem.Binary: this.readBinary(node, ctx); break; case XmlNames.Elem.AutoType: this.readAutoType(node); break; case XmlNames.Elem.History: this.readHistory(node, ctx); break; case XmlNames.Elem.CustomData: this.readCustomData(node); break; case XmlNames.Elem.QualityCheck: this.qualityCheck = XmlUtils.getBoolean(node) ?? undefined; break; case XmlNames.Elem.PreviousParentGroup: this.previousParentGroup = XmlUtils.getUuid(node); break; } } private readField(node: Element) { const keyNode = XmlUtils.getChildNode(node, XmlNames.Elem.Key), valueNode = XmlUtils.getChildNode(node, XmlNames.Elem.Value); if (keyNode && valueNode) { const key = XmlUtils.getText(keyNode), value = XmlUtils.getProtectedText(valueNode); if (key) { this.fields.set(key, value || ''); } } } private writeFields(parentNode: Node) { for (const [field, value] of this.fields) { if (value !== undefined && value !== null) { const node = XmlUtils.addChildNode(parentNode, XmlNames.Elem.String); XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.Key), field); XmlUtils.setProtectedText(XmlUtils.addChildNode(node, XmlNames.Elem.Value), value); } } } private readBinary(node: Element, ctx: KdbxContext) { const keyNode = XmlUtils.getChildNode(node, XmlNames.Elem.Key), valueNode = XmlUtils.getChildNode(node, XmlNames.Elem.Value); if (keyNode && valueNode) { const key = XmlUtils.getText(keyNode), value = XmlUtils.getProtectedBinary(valueNode); if (key && value) { if (KdbxBinaries.isKdbxBinaryRef(value)) { const binary = ctx.kdbx.binaries.getByRef(value); if (binary) { this.binaries.set(key, binary); } } else { this.binaries.set(key, value); } } } } private writeBinaries(parentNode: Node, ctx: KdbxContext) { for (const [id, data] of this.binaries) { let bin: KdbxBinaryOrRef; if (KdbxBinaries.isKdbxBinaryWithHash(data)) { const binaryRef = ctx.kdbx.binaries.getRefByHash(data.hash); if (!binaryRef) { return; } bin = binaryRef; } else { bin = data; } const node = XmlUtils.addChildNode(parentNode, XmlNames.Elem.Binary); XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.Key), id); XmlUtils.setProtectedBinary(XmlUtils.addChildNode(node, XmlNames.Elem.Value), bin); } } private readAutoType(node: Node) { for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { const childNode = <Element>cn[i]; switch (childNode.tagName) { case XmlNames.Elem.AutoTypeEnabled: this.autoType.enabled = XmlUtils.getBoolean(childNode) ?? true; break; case XmlNames.Elem.AutoTypeObfuscation: this.autoType.obfuscation = XmlUtils.getNumber(childNode) || AutoTypeObfuscationOptions.None; break; case XmlNames.Elem.AutoTypeDefaultSeq: this.autoType.defaultSequence = XmlUtils.getText(childNode); break; case XmlNames.Elem.AutoTypeItem: this.readAutoTypeItem(childNode); break; } } } private readAutoTypeItem(node: Node) { let window = ''; let keystrokeSequence = ''; for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { const childNode = <Element>cn[i]; switch (childNode.tagName) { case XmlNames.Elem.Window: window = XmlUtils.getText(childNode) || ''; break; case XmlNames.Elem.KeystrokeSequence: keystrokeSequence = XmlUtils.getText(childNode) || ''; break; } } if (window && keystrokeSequence) { this.autoType.items.push({ window, keystrokeSequence }); } } private writeAutoType(parentNode: Node) { const node = XmlUtils.addChildNode(parentNode, XmlNames.Elem.AutoType); XmlUtils.setBoolean( XmlUtils.addChildNode(node, XmlNames.Elem.AutoTypeEnabled), this.autoType.enabled ); XmlUtils.setNumber( XmlUtils.addChildNode(node, XmlNames.Elem.AutoTypeObfuscation), this.autoType.obfuscation || AutoTypeObfuscationOptions.None ); if (this.autoType.defaultSequence) { XmlUtils.setText( XmlUtils.addChildNode(node, XmlNames.Elem.AutoTypeDefaultSeq), this.autoType.defaultSequence ); } for (let i = 0; i < this.autoType.items.length; i++) { const item = this.autoType.items[i]; const itemNode = XmlUtils.addChildNode(node, XmlNames.Elem.AutoTypeItem); XmlUtils.setText(XmlUtils.addChildNode(itemNode, XmlNames.Elem.Window), item.window); XmlUtils.setText( XmlUtils.addChildNode(itemNode, XmlNames.Elem.KeystrokeSequence), item.keystrokeSequence ); } } private readHistory(node: Node, ctx: KdbxContext) { for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { const childNode = <Element>cn[i]; switch (childNode.tagName) { case XmlNames.Elem.Entry: this.history.push(KdbxEntry.read(childNode, ctx)); break; } } } private writeHistory(parentNode: Node, ctx: KdbxContext) { const historyNode = XmlUtils.addChildNode(parentNode, XmlNames.Elem.History); for (const historyEntry of this.history) { historyEntry.write(historyNode, ctx); } } private readCustomData(node: Node) { this.customData = KdbxCustomData.read(node); } private writeCustomData(parentNode: Node, ctx: KdbxContext) { if (this.customData) { KdbxCustomData.write(parentNode, ctx, this.customData); } } private setField(name: string, str: string, secure = false) { this.fields.set(name, secure ? ProtectedValue.fromString(str) : str); } private addHistoryTombstone(isAdded: boolean, dt: Date) { if (!this._editState) { this._editState = { added: [], deleted: [] }; } this._editState[isAdded ? 'added' : 'deleted'].push(dt.getTime()); } write(parentNode: Element, ctx: KdbxContext): void { const node = XmlUtils.addChildNode(parentNode, XmlNames.Elem.Entry); XmlUtils.setUuid(XmlUtils.addChildNode(node, XmlNames.Elem.Uuid), this.uuid); XmlUtils.setNumber(XmlUtils.addChildNode(node, XmlNames.Elem.Icon), this.icon || Icons.Key); if (this.customIcon) { XmlUtils.setUuid( XmlUtils.addChildNode(node, XmlNames.Elem.CustomIconID), this.customIcon ); } XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.FgColor), this.fgColor); XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.BgColor), this.bgColor); XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.OverrideUrl), this.overrideUrl); XmlUtils.setTags(XmlUtils.addChildNode(node, XmlNames.Elem.Tags), this.tags); if (typeof this.qualityCheck === 'boolean' && ctx.kdbx.versionIsAtLeast(4, 1)) { XmlUtils.setBoolean( XmlUtils.addChildNode(node, XmlNames.Elem.QualityCheck), this.qualityCheck ); } if (this.previousParentGroup !== undefined && ctx.kdbx.versionIsAtLeast(4, 1)) { XmlUtils.setUuid( XmlUtils.addChildNode(node, XmlNames.Elem.PreviousParentGroup), this.previousParentGroup ); } this.times.write(node, ctx); this.writeFields(node); this.writeBinaries(node, ctx); this.writeAutoType(node); this.writeCustomData(node, ctx); if (parentNode.tagName !== XmlNames.Elem.History) { this.writeHistory(node, ctx); } } pushHistory(): void { const historyEntry = new KdbxEntry(); historyEntry.copyFrom(this); this.history.push(historyEntry); if (historyEntry.times.lastModTime) { this.addHistoryTombstone(true, historyEntry.times.lastModTime); } } removeHistory(index: number, count = 1): void { for (let ix = index; ix < index + count; ix++) { if (ix < this.history.length) { const lastModTime = this.history[ix].times.lastModTime; if (lastModTime) { this.addHistoryTombstone(false, lastModTime); } } } this.history.splice(index, count); } copyFrom(entry: KdbxEntry): void { this.uuid = entry.uuid; this.icon = entry.icon; this.customIcon = entry.customIcon; this.fgColor = entry.fgColor; this.bgColor = entry.bgColor; this.overrideUrl = entry.overrideUrl; this.tags = entry.tags.slice(); this.times = entry.times.clone(); this.fields = new Map<string, KdbxEntryField>(); for (const [name, value] of entry.fields) { if (value instanceof ProtectedValue) { this.fields.set(name, value.clone()); } else { this.fields.set(name, value); } } this.binaries = new Map<string, KdbxBinary | KdbxBinaryWithHash>(); for (const [name, value] of entry.binaries) { if (value instanceof ProtectedValue) { this.binaries.set(name, value.clone()); } else if (KdbxBinaries.isKdbxBinaryWithHash(value)) { this.binaries.set(name, { hash: value.hash, value: value.value }); } else { this.binaries.set(name, value); } } this.autoType = <KdbxEntryAutoType>JSON.parse(JSON.stringify(entry.autoType)); } merge(objectMap: MergeObjectMap): void { const remoteEntry = objectMap.remoteEntries.get(this.uuid.id); if (!remoteEntry) { return; } const remoteHistory = remoteEntry.history.slice(); if (this.lastModTime < remoteEntry.lastModTime) { // remote is more new; push current state to history and update this.pushHistory(); this.copyFrom(remoteEntry); } else if (this.lastModTime > remoteEntry.lastModTime) { // local is more new; if remote state is not in history, push it const existsInHistory = this.history.some((historyEntry) => { return historyEntry.lastModTime === remoteEntry.lastModTime; }); if (!existsInHistory) { const historyEntry = new KdbxEntry(); historyEntry.copyFrom(remoteEntry); remoteHistory.push(historyEntry); } } this.history = this.mergeHistory(remoteHistory, remoteEntry.lastModTime); } /** * Merge entry history with remote entry history * Tombstones are stored locally and must be immediately discarded by replica after successful upstream push. * It's client responsibility, to save and load tombstones for local replica, and to clear them after successful upstream push. * * Implements remove-win OR-set CRDT with local tombstones stored in _editState. * * Format doesn't allow saving tombstones for history entries, so they are stored locally. * Any unmodified state from past or modifications of current state synced with central upstream will be successfully merged. * Assumes there's only one central upstream, may produce inconsistencies while merging outdated replica outside main upstream. * Phantom entries and phantom deletions will appear if remote replica checked out an old state and has just added a new state. * If a client is using central upstream for sync, the remote replica must first sync it state and * only after it update the upstream, so this should never happen. * * References: * * An Optimized Conflict-free Replicated Set arXiv:1210.3368 [cs.DC] * http://arxiv.org/abs/1210.3368 * * Gene T. J. Wuu and Arthur J. Bernstein. Efficient solutions to the replicated log and dictionary * problems. In Symp. on Principles of Dist. Comp. (PODC), pages 233–242, Vancouver, BC, Canada, August 1984. * https://pages.lip6.fr/Marc.Shapiro/papers/RR-7687.pdf */ private mergeHistory(remoteHistory: KdbxEntry[], remoteLastModTime: number) { // we can skip sorting but the history may not have been sorted this.history.sort((x, y) => x.lastModTime - y.lastModTime); remoteHistory.sort((x, y) => x.lastModTime - y.lastModTime); let historyIx = 0, remoteHistoryIx = 0; const newHistory = []; while (historyIx < this.history.length || remoteHistoryIx < remoteHistory.length) { const historyEntry = this.history[historyIx], remoteHistoryEntry = remoteHistory[remoteHistoryIx], entryTime = historyEntry && historyEntry.lastModTime, remoteEntryTime = remoteHistoryEntry && remoteHistoryEntry.lastModTime; if (entryTime === remoteEntryTime) { // exists in local and remote newHistory.push(historyEntry); historyIx++; remoteHistoryIx++; continue; } if (!historyEntry || entryTime > remoteEntryTime) { // local is absent if (!this._editState || this._editState.deleted.indexOf(remoteEntryTime) < 0) { // added remotely const remoteHistoryEntryClone = new KdbxEntry(); remoteHistoryEntryClone.copyFrom(remoteHistoryEntry); newHistory.push(remoteHistoryEntryClone); } // else: deleted locally remoteHistoryIx++; continue; } // (!remoteHistoryEntry || entryTime < remoteEntryTime) && historyEntry // remote is absent if (this._editState && this._editState.added.indexOf(entryTime) >= 0) { // added locally newHistory.push(historyEntry); } else if (entryTime > remoteLastModTime) { // outdated replica history has ended newHistory.push(historyEntry); } // else: deleted remotely historyIx++; } return newHistory; } static create(meta: KdbxMeta, parentGroup: KdbxGroup): KdbxEntry { const entry = new KdbxEntry(); entry.uuid = KdbxUuid.random(); entry.icon = Icons.Key; entry.times = KdbxTimes.create(); entry.parentGroup = parentGroup; entry.setField('Title', '', meta.memoryProtection.title); entry.setField('UserName', meta.defaultUser || '', meta.memoryProtection.userName); entry.setField('Password', '', meta.memoryProtection.password); entry.setField('URL', '', meta.memoryProtection.url); entry.setField('Notes', '', meta.memoryProtection.notes); entry.autoType.enabled = typeof parentGroup.enableAutoType === 'boolean' ? parentGroup.enableAutoType : true; entry.autoType.obfuscation = AutoTypeObfuscationOptions.None; return entry; } static read(xmlNode: Node, ctx: KdbxContext, parentGroup?: KdbxGroup): KdbxEntry { const entry = new KdbxEntry(); for (let i = 0, cn = xmlNode.childNodes, len = cn.length; i < len; i++) { const childNode = <Element>cn[i]; if (childNode.tagName) { entry.readNode(childNode, ctx); } } if (entry.uuid.empty) { // some clients don't write ids entry.uuid = KdbxUuid.random(); for (let j = 0; j < entry.history.length; j++) { entry.history[j].uuid = entry.uuid; } } entry.parentGroup = parentGroup; return entry; } }
the_stack
import {Injectable} from "@angular/core"; import {Issue} from "cwlts/models/helpers/validation"; import * as cwlSchemas from "cwlts/schemas"; import {WebWorker} from "../../core/web-worker/web-worker"; import {WebWorkerBuilderService} from "../../core/web-worker/web-worker-builder.service"; declare const jsyaml; declare const Ajv; export interface ValidationResponse { isValidatableCWL: boolean; isValidCWL: boolean; isValidJSON: boolean; errors: Issue[]; warnings: Issue[]; class?: string | "CommandLineTool" | "Workflow" | "ExpressionTool"; } @Injectable() export class CwlSchemaValidationWorkerService { private worker: WebWorker<any>; private draft4; private cwlSchema = cwlSchemas.schemas.mixed; constructor(private workerBuilder: WebWorkerBuilderService) { this.worker = this.workerBuilder.create(this.workerFunction, [ "ajv.min.js", "js-yaml.min.js" ], { cwlSchema: this.cwlSchema, // FIXME: will not work in browser, window.require call draft4: { "id": "http://json-schema.org/draft-04/schema#", "$schema": "http://json-schema.org/draft-04/schema#", "description": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": {"$ref": "#"} }, "positiveInteger": { "type": "integer", "minimum": 0 }, "positiveIntegerDefault0": { "allOf": [{"$ref": "#/definitions/positiveInteger"}, {"default": 0}] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true } }, "type": "object", "properties": { "id": { "type": "string", "format": "uri" }, "$schema": { "type": "string", "format": "uri" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": {}, "multipleOf": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "boolean", "default": false }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "boolean", "default": false }, "maxLength": {"$ref": "#/definitions/positiveInteger"}, "minLength": {"$ref": "#/definitions/positiveIntegerDefault0"}, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "anyOf": [ {"type": "boolean"}, {"$ref": "#"} ], "default": {} }, "items": { "anyOf": [ {"$ref": "#"}, {"$ref": "#/definitions/schemaArray"} ], "default": {} }, "maxItems": {"$ref": "#/definitions/positiveInteger"}, "minItems": {"$ref": "#/definitions/positiveIntegerDefault0"}, "uniqueItems": { "type": "boolean", "default": false }, "maxProperties": {"$ref": "#/definitions/positiveInteger"}, "minProperties": {"$ref": "#/definitions/positiveIntegerDefault0"}, "required": {"$ref": "#/definitions/stringArray"}, "additionalProperties": { "anyOf": [ {"type": "boolean"}, {"$ref": "#"} ], "default": {} }, "definitions": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "properties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": {"$ref": "#"}, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [ {"$ref": "#"}, {"$ref": "#/definitions/stringArray"} ] } }, "enum": { "type": "array", "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ {"$ref": "#/definitions/simpleTypes"}, { "type": "array", "items": {"$ref": "#/definitions/simpleTypes"}, "minItems": 1, "uniqueItems": true } ] }, "allOf": {"$ref": "#/definitions/schemaArray"}, "anyOf": {"$ref": "#/definitions/schemaArray"}, "oneOf": {"$ref": "#/definitions/schemaArray"}, "not": {"$ref": "#"} }, "dependencies": { "exclusiveMaximum": ["maximum"], "exclusiveMinimum": ["minimum"] }, "default": {} } }); } validate(content: string): Promise<ValidationResponse> { return this.worker.request(content); } destroy() { this.worker.terminate(); } private workerFunction(content) { let json; const cwlSchema = this.cwlSchema; const response = { isValidatableCWL: false, isValidCWL: false, isValidJSON: false, errors: [{message: "Not valid file format", loc: "document"}], warnings: [], class: null }; // First check if this is json or yaml content try { const warnings = []; json = jsyaml.safeLoad(content, { json: true, onWarning: (warn) => { warnings.push({ loc: "document", message: warn.message }); } } as any); response.isValidJSON = true; response.errors = []; response.warnings = warnings; } catch (e) { return response; } // Then check if it has the class prop if (!json || !json.class) { return Object.assign(response, { errors: [{ loc: "document", message: "Document is missing the “class” property." }] }); } // Check if the class is a valid one if (["Workflow", "CommandLineTool", "ExpressionTool"].indexOf(json.class) === -1) { return Object.assign(response, { errors: [{ loc: "document", message: "CWL class is not valid. Expected “Workflow”, “CommandLineTool” or “ExpressionTool”." }] }); } response.isValidatableCWL = true; response.class = json.class; const cwlVersion = json.cwlVersion || "sbg:draft-2"; const ajv = new Ajv(); ajv.addMetaSchema(this.draft4); let validation = false; let errors = []; let warnings = []; if (["sbg:draft-2", "v1.0"].indexOf(cwlVersion) !== -1) { validation = ajv.validate(cwlSchema, json); errors = ajv.errors || []; } else { warnings = [{ message: `unsupported cwlVersion "${cwlVersion}", expected "v1.0" or "sbg:draft-2"`, loc: "document" }]; } return Object.assign(response, { isValidCWL: validation, warnings: warnings, errors: errors.map(err => { let message = err.message; if (err.keyword === "enum") { message += ": " + err.params.allowedValues; } return { message: message, loc: `document${err.dataPath}` }; }).reduce((acc, curr) => { acc = acc.filter(err => { return err.message !== curr.message || err.loc !== curr.loc; }); acc.push(curr); return acc; }, []) }); } }
the_stack
declare namespace PIXI.filters { class AdjustmentFilter extends PIXI.Filter { constructor(options?: AdjustmentOptions); /** * The amount of luminance (default: 1) */ gamma?: number; /** * The amount of color saturation (default: 1) */ saturation?: number; /** * The amount of contrast (default: 1) */ contrast?: number; /** * The overall brightness (default: 1) */ brightness?: number; /** * The multipled red channel (default: 1) */ red?: number; /** * The multipled green channel (default: 1) */ green?: number; /** * The multipled blue channel (default: 1) */ blue?: number; /** * The overall alpha amount (default: 1) */ alpha?: number; } interface AdjustmentOptions { gamma?: number; contrast?: number; saturation?: number; brightness?: number; red?: number; green?: number; blue?: number; alpha?: number; } class AdvancedBloomFilter extends PIXI.Filter { constructor(options?: AdvancedBloomOptions); constructor(threshold?: number); /** * Defines how bright a color needs to be to affect bloom (default 0.5). */ threshold: number; /** * To adjust the strength of the bloom. Higher values is more intense brightness (default 1.0). */ bloomScale: number; /** * The brightness, lower value is more subtle brightness, higher value is blown-out (default 1.0). */ brightness: number; /** * Sets the kernels of the Blur Filter (default null). */ kernels: number[]; /** * Sets the strength of the Blur properties simultaneously (default 8). */ blur: number; /** * Sets the quality of the Blur Filter (default 4). */ quality: number; /** * Sets the pixelSize of the Kawase Blur filter (default 1). */ pixelSize: number | PIXI.Point | number[]; /** * The resolution of the filter. (default PIXI.settings.FILTER_RESOLUTION) */ resolution: number; } interface AdvancedBloomOptions { threshold?: number; bloomScale?: number; brightness?: number; kernels?: number[]; blur?: number; quality?: number; pixelSize?: number | PIXI.Point | number[]; resolution?: number; } class AsciiFilter extends PIXI.Filter { constructor(size?: number); /** * The pixel size used by the filter (default 8). */ size: number; } class BevelFilter extends PIXI.Filter { constructor(options?: BevelOptions); /** * The angle of the light in degrees (default 45). */ rotation: number; /** * The tickness of the bevel (default 2). */ thickness: number; /** * Color of the light (default 0xffffff). */ lightColor: number; /** * Alpha of the light (default 0.7). */ lightAlpha: number; /** * Color of the shadow (default 0x000000). */ shadowColor: number; /** * Alpha of the shadow (default 0.7). */ shadowAlpha: number; } interface BevelOptions { rotation: number; thickness: number; lightColor: number; lightAlpha: number; shadowColor: number; shadowAlpha: number; } class BloomFilter extends PIXI.Filter { constructor(options?: BloomOptions); /** * Sets the strength of both the blurX and blurY properties simultaneously (default 2). */ blur?: number | PIXI.Point | number[]; /** * The quality of the blurX & blurY filter (default 4). */ quality?: number; /** * The resolution of the blurX & blurY filter (default PIXI.settings.RESOLUTION). */ resolution?: number; /** * The kernelSize of the blurX & blurY filter.Options: 5, 7, 9, 11, 13, 15. (default 5). */ kernelSize?: number; } interface BloomOptions { blur: number | PIXI.Point | number[]; quality: number; resolution: number; kernelSize: number; } class BulgePinchFilter extends PIXI.Filter { constructor(options?: BulgePinchFilterOptions); /** * The x and y coordinates of the center of the circle of effect (default [0,0]). */ center?: PIXI.Point | [number, number]; /** * The radius of the circle of effect (default: 100). */ radius?: number; /** * The strength of the effect. -1 to 1: -1 is strong pinch, 0 is no effect, 1 is strong bulge (default: 1). */ strength?: number; } interface BulgePinchFilterOptions { center?: PIXI.Point | [number, number]; radius?: number; strength?: number; } class ColorMapFilter extends PIXI.Filter { constructor( colorMap?: | HTMLImageElement | HTMLCanvasElement | PIXI.BaseTexture | PIXI.Texture, nearest?: boolean, mix?: number, readonly colorSize: number ); /** * The colorMap texture of the filter. */ colorMap: | HTMLImageElement | HTMLCanvasElement | PIXI.BaseTexture | PIXI.Texture; /** * Whether use NEAREST for colorMap texture (default false). */ nearest: boolean; /** * The mix from 0 to 1, where 0 is the original image and 1 is the color mapped image (default 1). */ mix: number; /** * The size of one color slice (readonly). */ readonly colorSize: number; } class ColorOverlayFilter extends PIXI.Filter { constructor(color?: number | [number, number, number]); /** * The resulting color, as a 3 component RGB e.g. [1.0, 0.5, 1.0] (default 0x000000). */ color: number | [number, number, number]; } class ColorReplaceFilter extends PIXI.Filter { constructor( originalColor?: number | number[], newColor?: number | number[], epsilon?: number ); /** * The color that will be changed, as a 3 component RGB e.g. [1.0, 1.0, 1.0] (default 0xFF0000). */ originalColor: number | number[]; /** * The resulting color, as a 3 component RGB e.g. [1.0, 0.5, 1.0] (default 0x000000). */ newColor: number | number[]; /** * Tolerance/sensitivity of the floating-point comparison between colors: lower = more exact, higher = more inclusive (default 0.4). */ epsilon: number; } class ConvolutionFilter extends PIXI.Filter { constructor(matrix?: number[], width?: number, height?: number); /** * An array of values used for matrix transformation. Specified as a 9 point Array (default [0,0,0,0,0,0,0,0,0]). */ matrix?: number[]; /** * Width of the object you are transforming (default 200). */ width?: number; /** * Height of the object you are transforming (default 200). */ height?: number; } class CrossHatchFilter extends PIXI.Filter { constructor(); } class CRTFilter extends PIXI.Filter { constructor(options?: CRTFilterOptions); /** * Bent of interlaced lines, higher value means more bend (default 1). */ curvature: number; /** * Width of interlaced lines (default 1). */ lineWidth: number; /** * Contrast of interlaced lines (default 0.25). */ lineContrast: number; /** * `true` for vertical lines, `false` for horizontal lines (default false). */ verticalLine: boolean; /** * Opacity/intensity of the noise effect between `0` and `1` (default 0.3). */ noise: number; /** * The size of the noise particles (default 1.0). */ noiseSize: number; /** * A seed value to apply to the random noise generation (default 0). */ seed: number; /** * The radius of the vignette effect, smaller values produces a smaller vignette (default 0.3). */ vignetting: number; /** * Amount of opacity of vignette (default 1.0). */ vignettingAlpha: number; /** * Blur intensity of the vignette (default 0.3). */ vignettingBlur: number; /** * For animating interlaced lines (default 0). */ time: number; } interface CRTFilterOptions { curvature?: number; lineWidth?: number; lineContrast?: number; verticalLine?: boolean; noise?: number; noiseSize?: number; seed?: number; vignetting?: number; vignettingAlpha?: number; vignettingBlur?: number; time?: number; } class DotFilter extends PIXI.Filter { constructor(scale?: number, angle?: number); /** * The scale of the effect (default 1). */ scale: number; /** * The radius of the effect (default 5). */ angle: number; } class DropShadowFilter extends PIXI.Filter { constructor(options?: DropShadowFilterOptions); /** * The alpha of the shadow (default 0.5). */ alpha: number; /** * The blur of the shadow (default 2). */ blur: number; /** * The color of the shadow (default 0x000000). */ color: number; /** * Distance offset of the shadow (default 5). */ distance: number; /** * Sets the kernels of the Blur Filter (default null). */ kernels: number[]; /** * Sets the pixelSize of the Kawase Blur filter (default 1). */ pixelSize: number | number[] | PIXI.Point; /** * Sets the quality of the Blur Filter (default 3). */ quality: number; /** * The resolution of the filter (default PIXI.settings.RESOLUTION). */ resolution: number; /** * The angle of the shadow in degrees (default 45). */ rotation: number; /** * Whether render shadow only (default false). */ shadowOnly: boolean; } interface DropShadowFilterOptions { alpha?: number; blur?: number; color?: number; distance?: number; kernels?: number[]; pixelSize?: number | number[] | PIXI.Point; quality?: number; resolution?: number; rotation?: number; shadowOnly?: boolean; } class EmbossFilter extends PIXI.Filter { constructor(strength?: number); /** * Strength of emboss (default 5). */ strength: number; } class GlitchFilter extends PIXI.Filter { constructor(options?: GlitchFilterOptions); /** * The maximum number of slices (default 5). */ slices: number; /** * The maximum offset value for each of the slices (default 100). */ offset: number; /** * The angle in degree of the offset of slices (default 0). */ direction: number; /** * The fill mode of the space after the offset (default 0). * Acceptable values: * 0 TRANSPARENT * 1 ORIGINAL * 2 LOOP * 3 CLAMP * 4 MIRROR */ fillMode: number; /** * `true` will divide the bands roughly based on equal amounts * where as setting to `false` will vary the band sizes dramatically (more random looking). * (default false) */ average: boolean; /** * A seed value for randomizing color offset. Animating * this value to `Math.random()` produces a twitching effect. * (default 0) */ seed: number; /** * Red channel offset (default [0,0]). */ red: PIXI.Point; /** * Green channel offset (default [0,0]). */ green: PIXI.Point; /** * Blue channel offset (default [0,0]). */ blue: PIXI.Point; /** * Minimum size of slices as a portion of the `sampleSize` (default 8). */ minSize: number; /** * Height of the displacement map canvas (default 512). */ sampleSize: number; /** * Regenerating random size, offsets for slices. */ refresh(): void; /** * Shuffle the sizes of the slices, advanced usage. */ shuffle(): void; /** * Redraw displacement bitmap texture, advanced usage. */ redraw(): void; /** * The displacement map is used to generate the bands. * If using your own texture, `slices` will be ignored. */ readonly texture: PIXI.Texture; } interface GlitchFilterOptions { slices: number; offset: number; direction: number; fillMode: number; average: boolean; seed: number; red: PIXI.Point; green: PIXI.Point; blue: PIXI.Point; minSize: number; sampleSize: number; } class GlowFilter extends PIXI.Filter { constructor(options?: GlowFilterOptions); /** * The color of the glow (default 0xFFFFFF). */ color: number; /** * The distance of the glow. Make it 2 times more for resolution=2. * It can't be changed after filter creation. * (default 10) */ distance: number; /** * The strength of the glow inward from the edge of the sprite (default 0). */ innerStrength: number; /** * The strength of the glow outward from the edge of the sprite (default 4). */ outerStrength: number; /** * A number between 0 and 1 that describes the quality of the glow. * The higher the number the less performant. * (default 0.1) */ quality: number; /** * Only draw the glow, not the texture itself (default false). */ knockout: boolean; } interface GlowFilterOptions { color?: number; distance?: number; innerStrength?: number; outerStrength?: number; quality?: number; knockout?: boolean; } class GodrayFilter extends PIXI.Filter { constructor(options?: GodrayFilterOptions); /** * The angle/light-source of the rays in degrees. For instance, a value of 0 is vertical rays, * values of 90 or -90 produce horizontal rays (default 30). */ angle: number; /** * The position of the emitting point for light rays * only used if `parallel` is set to `false` (default [0, 0]). */ center: PIXI.Point | Array<number>; /** * `true` if light rays are parallel (uses angle), * `false` to use the focal `center` point. * (default true) */ parallel: boolean; /** * General intensity of the effect. A value closer to 1 will produce a more intense effect, * where a value closer to 0 will produce a subtler effect (default 0.5). */ gain: number; /** * The density of the fractal noise. A higher amount produces more rays and a smaller amount * produces fewer waves (default 2.5). */ lacunarity: number; /** * The current time position (default 0). */ time: number; } interface GodrayFilterOptions { angle: number; center: PIXI.Point | Array<number>; parallel: boolean; gain: number; lacunarity: number; time: number; } class KawaseBlurFilter extends PIXI.Filter { constructor(blur?: number | number[], quality?: number, clamp?: boolean); /** * The blur of the filter. Should be greater than `0`. * If value is an Array, setting kernels. (default 4). */ blur: number; /** * The quality of the filter. Should be an integer greater than `1`. (default 3). */ quality: number; /** * Clamp edges, useful for removing dark edges from fullscreen filters * or bleeding to the edge of filterArea. (default false). */ clamp: boolean; } class MotionBlurFilter extends PIXI.Filter { constructor( velocity?: PIXI.ObservablePoint | PIXI.Point | number[], kernelSize?: number, offset?: number ); /** * Sets the velocity (x and y) of the motion for blur effect (default [0,0]). */ velocity: PIXI.ObservablePoint | PIXI.Point | number[]; /** * The kernelSize of the blur, higher values are slower but look better. * Use odd value greater than 5 (default 5). */ kernelSize: number; /** * The offset of the blur filter (default 0). */ offset: number; } class MultiColorReplaceFilter extends PIXI.Filter { constructor( replacements: Array<number[] | number[][]>, epsilon?: number, maxColors?: number ); /** * The collection of replacement items. Each item is color-pair (an array length is 2). * In the pair, the first value is original color , the second value is target color. */ replacements: Array<number[] | number[][]>; /** * Tolerance of the floating-point comparison between colors (lower = more exact, higher = more inclusive). * (default 0.05) */ epsilon: number; /** * The maximum number of replacements filter is able to use. * Because the fragment is only compiled once, this cannot be changed after construction. * If omitted, the default value is the length of `replacements`. */ readonly maxColors: number; /** * Should be called after changing any of the contents of the replacements. * This is a convenience method for resetting the `replacements`. */ refresh(): void; } class OldFilmFilter extends PIXI.Filter { constructor(options?: OldFilmFilterOptions, seed?: number); constructor(seed?: number); /** * The amount of saturation of sepia effect, * a value of `1` is more saturation and closer to `0` is less, * and a value of `0` produces no sepia effect (default 0.3). */ sepia: number; /** * Opacity/intensity of the noise effect between `0` and `1` (default 0.3). */ noise: number; /** * The size of the noise particles (default 1). */ noiseSize: number; /** * How often scratches appear (default 0.5). */ scratch: number; /** * The density of the number of scratches (default 0.3). */ scratchDensity: number; /** * The width of the scratches (default 1.0). */ scratchWidth: number; /** * The radius of the vignette effect, smaller values produces a smaller vignette (default 0.3). */ vignetting: number; /** * Amount of opacity of vignette (default 1.0). */ vignettingAlpha: number; /** * Blur intensity of the vignette (default 0.3). */ vignettingBlur: number; /** * A seed value to apply to the random noise generation (default 0). */ seed: number; } interface OldFilmFilterOptions { sepia?: number; noise?: number; noiseSize?: number; scratch?: number; scratchDensity?: number; scratchWidth?: number; vignetting?: number; vignettingAlpha?: number; vignettingBlur?: number; } class OutlineFilter extends PIXI.Filter { constructor(thickness?: number, color?: number); /** * The color of the outline (default 0x000000). */ color: number; /** * The tickness of the outline. Make it 2 times more for resolution 2 (default 1). */ thickness: number; /** * The quality of the outline from `0` to `1`, using a higher quality setting will result in slower performance and more accuracy * (default 0.1). */ quality: number; } class PixelateFilter extends PIXI.Filter { constructor(size?: PIXI.Point | number[] | number); /** * Either the width/height of the size of the pixels, or square size (default 10). */ size: PIXI.Point | number[] | number; } class RadialBlurFilter extends PIXI.Filter { constructor( angle?: number, center?: number[] | PIXI.Point, kernelSize?: number, radius?: number ); /** * Sets the angle in degrees of the motion for blur effect (default 0). */ angle: number; /** * Center of the effect (default [0, 0]). */ center: number[] | PIXI.Point; /** * The kernelSize of the blur filter. But be odd number >= 3 (default 5). */ kernelSize: number; /** * Outer radius of the effect. The default value of `-1` is infinite (default -1). */ radius: number; } class ReflectionFilter extends PIXI.Filter { constructor(options?: ReflectionFilterOptions); /** * `true` to reflect the image, `false` for waves-only (default true). */ mirror: boolean; /** * Vertical position of the reflection point, default is middle. * Smaller numbers produce a larger reflection, larger numbers produce a smaller reflection. * (default 0.5) */ boundary: number; /** * Starting and ending amplitude of waves (default [0, 20]). */ amplitude: number[]; /** * Starting and ending length of waves (default [30, 100]). */ waveLength: number[]; /** * Starting and ending alpha values (default [1, 1]). */ alpha: number[]; /** * Time for animating position of waves (default 0). */ time: number; } interface ReflectionFilterOptions { mirror?: boolean; boundary?: number; amplitude?: number[]; waveLength?: number[]; alpha?: number[]; time?: number; } class RGBSplitFilter extends PIXI.Filter { constructor(red?: PIXI.Point, green?: PIXI.Point, blue?: PIXI.Point); /** * Red channel offset (default [-10,0]). */ red: PIXI.Point; /** * Green channel offset (default [0, 10]). */ green: PIXI.Point; /** * Blue channel offset (default [0, 0]). */ blue: PIXI.Point; } class ShockwaveFilter extends PIXI.Filter { constructor( center?: PIXI.Point | number[], options?: ShockwaveFilterOptions, time?: number ); /** * Sets the center of the shockwave in normalized screen coords. * That is (0,0) is the top-left and (1,1) is the bottom right. * (default [0.5, 0.5]) * NB: But in practice, it seems we need "world" coords. */ center: PIXI.Point | number[]; /** * The amplitude of the shockwave (default 0.5). */ amplitude?: number; /** * The wavelength of the shockwave (default 1.0). */ wavelength?: number; /** * The brightness of the shockwave (default 8). */ brightness?: number; /** * The speed about the shockwave ripples out (default 500.0). * The unit is `pixel/second`. */ speed?: number; /** * The maximum radius of shockwave. * `< 0.0` means it's infinity. * (default 4) */ radius?: number; /** * Sets the elapsed time of the shockwave. * It could control the current size of shockwave. * (default 0) */ time: number; } interface ShockwaveFilterOptions { amplitude?: number; wavelength?: number; brightness?: number; speed?: number; radius?: number; } class SimpleLightmapFilter extends PIXI.Filter { constructor(texture: PIXI.Texture, color?: number[] | number); /** * Default alpha set independent of color (if it's a number, not array). * When setting `color` as hex, this can be used to set alpha independently. * (default 1) */ alpha: number; /** * An RGBA array of the ambient color or a hex color without alpha (default 0x000000) */ color: number[] | number; /** * A texture where your lightmap is rendered. */ texture: PIXI.Texture; } class TiltShiftFilter extends PIXI.Filter { constructor( blur?: number, gradientBlur?: number, start?: PIXI.Point, end?: PIXI.Point ); /** * The strength of the blur (default 100). */ blur: number; /** * The strength of the gradient blur (default 600). */ gradientBlur: number; /** * The Y value to start the effect at (default null). */ start: PIXI.Point; /** * The Y value to end the effect at (default null). */ end: PIXI.Point; } class TwistFilter extends PIXI.Filter { constructor( radius?: number, angle?: number, padding?: number, offset?: PIXI.Point | [number, number] ); /** * The angle of the twist (default 4). */ angle: number; /** * The radius of the twist (default 200). */ radius: number; /** * Padding for filter area (default 20). */ padding: number; /** * Center of twist, in local, pixel coordinates. */ offset: PIXI.Point | [number, number]; } class ZoomBlurFilter extends PIXI.Filter { constructor(options?: ZoomBlurFilterOptions); constructor( strength?: number, center?: PIXI.Point | [number, number], innerRadius?: number, radius?: number ); /** * Strength of the zoom blur effect (default 0.1). */ strength: number; /** * Center of the effect (default [0, 0]). */ center: PIXI.Point | [number, number]; /** * The inner radius of zoom. The part in inner circle won't apply zoom blur effect * (default 0). */ innerRadius: number; /** * Outer radius of the effect. * The default value is `-1`. * `< 0.0` means it's infinity. */ radius: number; } interface ZoomBlurFilterOptions { strength?: number; center?: PIXI.Point | [number, number]; innerRadius?: number; radius?: number; } } declare namespace ct { /** A collection of shader filters for ct.js */ namespace filters { /** * The ability to adjust gamma, contrast, saturation, brightness, alpha or color-channel shift. This is a faster and much simpler to use than ColorMatrixFilter because it does not use a matrix. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.AdjustmentFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addAdjustment( target: PIXI.DisplayObject ): PIXI.filters.AdjustmentFilter; /** * The AdvancedBloomFilter applies a Bloom Effect to an object. Unlike the normal BloomFilter this had some advanced controls for adjusting the look of the bloom. Note: this filter is slower than normal BloomFilter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.AdvancedBloomFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addAdvancedBloom( target: PIXI.DisplayObject ): PIXI.filters.AdvancedBloomFilter; /** * Turns everything in ASCII text. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.AsciiFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addAscii(target: PIXI.DisplayObject): PIXI.filters.AsciiFilter; /** * Peforms an edge-beveling effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.BevelFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addBevel(target: PIXI.DisplayObject): PIXI.filters.BevelFilter; /** * The BloomFilter applies a Gaussian blur to an object. The strength of the blur can be set for x- and y-axis separately. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.BloomFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addBloom(target: PIXI.DisplayObject): PIXI.filters.BloomFilter; /** * Bulges or pinches the image in a circle. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.BulgePinchFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addBulgePinch( target: PIXI.DisplayObject ): PIXI.filters.BulgePinchFilter; /** * The ColorMapFilter applies a color-map effect to an object. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @param {HTMLImageElement|HTMLCanvasElement|PIXI.BaseTexture|PIXI.Texture} colorMap - The colorMap texture of the filter. * @return {PIXI.filters.ColorMapFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addColorMap( target: PIXI.DisplayObject, colorMap: HTMLImageElement|HTMLCanvasElement|PIXI.BaseTexture|PIXI.Texture, ): PIXI.filters.ColorMapFilter; /** * Replace all colors within a source graphic with a single color. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ColorOverlayFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addColorOverlay( target: PIXI.DisplayObject ): PIXI.filters.ColorOverlayFilter; /** * ColorReplaceFilter, originally by mishaa, updated by timetocode http://www.html5gamedevs.com/topic/10640-outline-a-sprite-change-certain-colors/?p=69966 * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ColorReplaceFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addColorReplace( target: PIXI.DisplayObject ): PIXI.filters.ColorReplaceFilter; /** * The ConvolutionFilter class applies a matrix convolution filter effect. A convolution combines pixels in the input image with neighboring pixels to produce a new image. A wide variety of image effects can be achieved through convolutions, including blurring, edge detection, sharpening, embossing, and beveling. The matrix should be specified as a 9 point Array. See http://docs.gimp.org/en/plug-in-convmatrix.html for more info. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ConvolutionFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addConvolution( target: PIXI.DisplayObject ): PIXI.filters.ConvolutionFilter; /** * A black and white cross-hatch effect filter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.CrossHatchFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addCrossHatch( target: PIXI.DisplayObject ): PIXI.filters.CrossHatchFilter; /** * Apply an effect resembling old CRT monitors. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.CRTFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addCRT(target: PIXI.DisplayObject): PIXI.filters.CRTFilter; /** * This filter applies a dotscreen effect making display objects appear to be made out of black and white halftone dots like an old printer. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.DotFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addDot(target: PIXI.DisplayObject): PIXI.filters.DotFilter; /** * Apply a drop shadow effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.DropShadowFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addDropShadow( target: PIXI.DisplayObject ): PIXI.filters.DropShadowFilter; /** * Apply an emboss effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.EmbossFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addEmboss(target: PIXI.DisplayObject): PIXI.filters.EmbossFilter; /** * Apply a glitch effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.GlitchFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addGlitch(target: PIXI.DisplayObject): PIXI.filters.GlitchFilter; /** * GlowFilter, originally by mishaa codepen. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.GlowFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addGlow(target: PIXI.DisplayObject): PIXI.filters.GlowFilter; /** * Apply and animate atmospheric light rays. Originally by Alain Galvan https://codepen.io/alaingalvan * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.GodrayFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addGodray(target: PIXI.DisplayObject): PIXI.filters.GodrayFilter; /** * A much faster blur than Gaussian blur, but more complicated to use. https://software.intel.com/content/www/us/en/develop/blogs/an-investigation-of-fast-real-time-gpu-based-image-blur-algorithms.html * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.KawaseBlurFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addKawaseBlur( target: PIXI.DisplayObject ): PIXI.filters.KawaseBlurFilter; /** * Apply a directional blur effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.MotionBlurFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addMotionBlur( target: PIXI.DisplayObject ): PIXI.filters.MotionBlurFilter; /** * Filter for replacing a color with another color. Similar to ColorReplaceFilter, but support multiple colors. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @param {Array<number[] | number[][]>} replacements - The collection of replacement items. Each item is color-pair (an array length is 2). In the pair, the first value is original color, the second value is target color. * @param {Array<number[] | number[][]>} epsilon - Tolerance of the floating-point comparison between colors. Lower = more exact, higher = more inclusive (default 0.05). * @return {PIXI.filters.MultiColorReplaceFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addMultiColorReplace( target: PIXI.DisplayObject, replacements: Array<number[] | number[][]>, epsilon: number ): PIXI.filters.MultiColorReplaceFilter; /** * Apply an old film effect with grain and scratches. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.OldFilmFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addOldFilm(target: PIXI.DisplayObject): PIXI.filters.OldFilmFilter; /** * Apply an outline/stroke effect. Originally by mishaa http://www.html5gamedevs.com/topic/10640-outline-a-sprite-change-certain-colors/?p=69966 http://codepen.io/mishaa/pen/emGNRB * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.OutlineFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addOutline(target: PIXI.DisplayObject): PIXI.filters.OutlineFilter; /** * Apply a pixelation effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.PixelateFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addPixelate( target: PIXI.DisplayObject ): PIXI.filters.PixelateFilter; /** * Apply a radial blur effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.RadialBlurFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addRadialBlur( target: PIXI.DisplayObject ): PIXI.filters.RadialBlurFilter; /** * Apply a reflection effect to simulate the reflection on water with waves. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ReflectionFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addReflection( target: PIXI.DisplayObject ): PIXI.filters.ReflectionFilter; /** * Filter to split and shift red, green or blue channels. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.RGBSplitFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addRGBSplit( target: PIXI.DisplayObject ): PIXI.filters.RGBSplitFilter; /** * Apply a shockwave-type effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ShockwaveFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addShockwave( target: PIXI.DisplayObject ): PIXI.filters.ShockwaveFilter; /** * SimpleLightmap, originally by Oza94 http://www.html5gamedevs.com/topic/20027-pixijs-simple-lightmapping/ http://codepen.io/Oza94/pen/EPoRxj * You have to specify filterArea, or suffer consequences. You may have to use it with filter.dontFit = true, until we rewrite this using same approach as for DisplacementFilter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.SimpleLightmapFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addSimpleLightmap( target: PIXI.DisplayObject ): PIXI.filters.SimpleLightmapFilter; /** * Apply a tilt-shift-like camera effect. Manages the pass of both a TiltShiftXFilter and TiltShiftYFilter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.TiltShiftFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addTiltShift( target: PIXI.DisplayObject ): PIXI.filters.TiltShiftFilter; /** * Apply a twist effect making display objects appear twisted in the given direction. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.TwistFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addTwist(target: PIXI.DisplayObject): PIXI.filters.TwistFilter; /** * Apply a zoom blur effect. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ZoomBlurFilter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addZoomBlur( target: PIXI.DisplayObject ): PIXI.filters.ZoomBlurFilter; /** * Simplest filter - applies alpha. * Use this instead of Container's alpha property to avoid visual layering of individual elements. AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. If elements are not opaque, they will blend with each other anyway. * Very handy if you want to use common features of all filters: * Assign a blendMode to this filter, blend all elements inside display object with background. * To use clipping in display coordinates, assign a filterArea to the same container that has this filter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.AlphaFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addAlpha(target: PIXI.DisplayObject): PIXI.filters.AlphaFilter; /** * The BlurFilter applies a Gaussian blur to an object. * The strength of the blur can be set for the x-axis and y-axis separately. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.BlurFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addBlur(target: PIXI.DisplayObject): PIXI.filters.BlurFilter; /** * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.BlurFilterPass } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addBlurPass( target: PIXI.DisplayObject ): PIXI.filters.BlurFilterPass; /** * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA color and alpha values of every pixel on your displayObject to produce a result with a new set of RGBA color and alpha values. It's pretty powerful! * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.ColorMatrixFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addColorMatrix( target: PIXI.DisplayObject ): PIXI.filters.ColorMatrixFilter; /** * The DisplacementFilter class uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object. * You can use this filter to apply all manor of crazy warping effects. Currently the r property of the texture is used to offset the x and the g property of the texture is used to offset the y. * The way it works is it uses the values of the displacement map to look up the correct pixels to output. * This means it's not technically moving the original. * Instead, it's starting at the output and asking "which pixel from the original goes here". * For example, if a displacement map pixel has red = 1 and the filter scale is 20, this filter will output the pixel approximately 20 pixels to the right of the original. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.DisplacementFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addDisplacement( target: PIXI.DisplayObject ): PIXI.filters.DisplacementFilter; /** * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.FXAAFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addFXAA( target: PIXI.DisplayObject ): PIXI.filters.FXAAFilter; /** * A Noise effect filter. * Original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filters.NoiseFilter } - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function addNoise( target: PIXI.DisplayObject ): PIXI.filters.NoiseFilter; /** * Add a custom filter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @param {String} vertex - The vertex part of the shader: https://www.khronos.org/opengl/wiki/Vertex_Shader * @param {String} fragment - The fragment part of the shader: https://www.khronos.org/opengl/wiki/Fragment_Shader * @param {Object} uniforms - Custom uniforms to use to augment the built-in ones: https://www.khronos.org/opengl/wiki/Uniform_(GLSL) * @return {PIXI.filter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function custom(target: PIXI.DisplayObject): PIXI.filter; /** * Remove a filter. * @param {PIXI.DisplayObject} target - Element (room, copy, container, etc.) to apply the filter. * @return {PIXI.filter} - Filter is a special type of WebGL shader that is applied to the screen or a part of the screen. */ function remove(target: PIXI.DisplayObject): PIXI.filter; } }
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623959667439, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of live nodes in the cluster.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `min(liveness_livenodes{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Live Nodes", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Live Node Count", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:637", format: "short", label: "nodes", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:638", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Memory in use across all nodes:\nRSS \nTotal memory in use by CockroachDB\n\nGo Allocated \nMemory allocated by the Go layer\n\nGo Total \nTotal memory managed by the Go layer\n\nC Allocated \nMemory allocated by the C layer\n\nC Total \nTotal memory managed by the C layer", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sys_rss{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Total memory (RSS)", refId: "A" }, { expr: `sum(sys_cgo_allocbytes{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Go Allocated", refId: "B" }, { expr: `sum(sys_go_totalbytes{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Go Total", refId: "D" }, { expr: `sum(sys_go_allocbytes{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "CGo Allocated", refId: "C" }, { expr: `sum(sys_cgo_totalbytes{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "CGo Total", refId: "E" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Memory Usage", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:863", format: "bytes", label: "memory usage", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:864", format: "bytes", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of Goroutines across all nodes. This count should rise and fall based on load.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 10, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sys_goroutines{integration_id="${integrationId}",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Goroutine Count", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Goroutine Count", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1235", format: "short", label: "goroutines", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1236", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of Goroutines waiting for CPU. This count should rise and fall based on load.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 16, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sys_runnable_goroutines_per_cpu{integration_id="${integrationId}",cluster=~"$cluster",instance=~"$node"}`, interval: "", intervalFactor: 1, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Runnable Goroutines per CPU", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:391", format: "short", label: "goroutines", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:392", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of times that Go’s garbage collector was invoked per second across all nodes.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 32 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(sys_gc_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "GC Runs", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "GC Runs", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1311", format: "short", label: "runs", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1312", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The amount of processor time used by Go’s garbage collector per second across all nodes. During garbage collection, application code execution is paused.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 40 }, hiddenSeries: false, id: 12, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sys_gc_pause_ns{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "GC Pause Time", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "GC Pause Time", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1387", format: "ns", label: "pause time", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1388", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 48 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sys_cpu_user_ns{integration_id="${integrationId}",instance=~"$node"}[5m]))`, instant: false, interval: "", intervalFactor: 2, legendFormat: "User CPU Time", refId: "A" }, { exemplar: true, expr: `sum(rate(sys_cpu_sys_ns{integration_id="${integrationId}",instance=~"$node"}[5m]))`, instant: false, interval: "", intervalFactor: 2, legendFormat: "Sys CPU Time", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "CPU Time", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1833", format: "ns", label: "cpu time", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1834", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Mean clock offset of each node against the rest of the cluster.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 56 }, hiddenSeries: false, id: 14, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `clock_offset_meannanos{integration_id="${integrationId}",instance=~"$node",cluster=~"$cluster"}`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Clock Offset", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:787", format: "ns", label: "offset", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:788", format: "short", label: "", logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: false, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheus-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 1, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "utc", title: "CRDB Console: Runtime", uid: `run-${integrationId}`, version: 3 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import { Nullable, Undefinable } from "../../../shared/types"; import * as React from "react"; import { Classes, ContextMenu, Intent, Menu, MenuDivider, MenuItem, Pre, Tag } from "@blueprintjs/core"; import Chart, { ChartDataSets } from "chart.js"; import "chartjs-plugin-dragdata"; import "chartjs-plugin-zoom"; import "chartjs-plugin-annotation"; import "chartjs-plugin-dragzone"; import { Animation, IAnimatable, IAnimationKey, KeyboardEventTypes, KeyboardInfo, Observer, Vector2 } from "babylonjs"; import Editor from "../../editor"; import { Icon } from "../../editor/gui/icon"; import { undoRedo } from "../../editor/tools/undo-redo"; import "./tools/augmentations"; import { SyncType } from "./tools/types"; import { SyncTool } from "./tools/sync-tools"; import { TimeTracker } from "./tools/time-tracker"; import { IVector2Like } from "./tools/augmentations"; import { PointSelection } from "./tools/points-select"; import { AnimationTools } from "./tools/animation-to-dataset"; import { AnimationKeyObject } from "./tools/animation-key-object"; export interface IChartEditorProps { /** * Defines the reference to the editor. */ editor: Editor; /** * Defines the synchronization type for animation when playing/moving time tracker. */ synchronizationType: SyncType; /** * Defines the callback called on the current frame value changed. */ onFrameChange: (value: number) => void; } export interface IChartEditorState { /** * Defines wether or not the mouse is over the canvas or not. */ isMouseHover: boolean; /** * Defines the mouse position on the chart (X and Y axis). */ mousePositionOnChart: IVector2Like; /** * Defines the synchronization type for animation when playing/moving time tracker. */ synchronizationType: SyncType; /** * Defines the reference to the selected animatable. */ selectedAnimatable: Nullable<IAnimatable>; /** * Defines the reference to the selected animation. */ selectedAnimation: Nullable<Animation>; } export class ChartEditor extends React.Component<IChartEditorProps, IChartEditorState> { /** * Defines the reference to the chart. */ public chart: Nullable<Chart> = null; /** * Defines the reference to the time tracker. */ public timeTracker: Nullable<TimeTracker> = null; private _editor: Editor; private _datasets: ChartDataSets[] = []; private _panDisabled: boolean = false; private _selection: Nullable<PointSelection> = null; private _selectedFrames: number[] = []; private _mousePositonOnChart: Vector2 = new Vector2(0, 0); private _undoRedoKeyData: Nullable<IVector2Like> = null; private _keyboardObserver: Nullable<Observer<KeyboardInfo>>; private _canvas: Nullable<HTMLCanvasElement> = null; private _refHandler = { getCanvas: (ref: HTMLCanvasElement) => this._canvas = ref, }; /** * Constructor. * @param props defines the component's props. */ public constructor(props: IChartEditorProps) { super(props); this._editor = props.editor; this.state = { isMouseHover: false, mousePositionOnChart: { x: 0, y: 0 }, synchronizationType: props.synchronizationType, selectedAnimatable: null, selectedAnimation: null, }; } /** * Renders the component. */ public render(): React.ReactNode { return ( <div style={{ position: "absolute", width: "calc(100% - 10px)", height: "calc(100% - 50px)" }}> <canvas ref={this._refHandler.getCanvas} onMouseEnter={() => this.setState({ isMouseHover: true })} onMouseLeave={() => this.setState({ isMouseHover: false })} onMouseMove={(ev) => this._handleMouseMove(ev)} onMouseDown={(ev) => this._handleMouseDown(ev)} onMouseUp={(ev) => this._handleMouseUp(ev)} onDoubleClick={(ev) => this._handleDoubleClick(ev)} ></canvas> <Tag intent={Intent.PRIMARY} style={{ position: "absolute", right: "0px", top: "0px", visibility: (this.state.isMouseHover ? "visible" : "hidden") }}>Frame: {this.state.mousePositionOnChart.x}</Tag> <Tag intent={Intent.PRIMARY} style={{ position: "absolute", right: "0px", top: "25px", visibility: (this.state.isMouseHover ? "visible" : "hidden") }}>Value: {this.state.mousePositionOnChart.y}</Tag> </div> ); } /** * Called on the component did mount. */ public componentDidMount(): void { if (!this._canvas) { return; } // Register events this._keyboardObserver = this._editor.keyboardEventObservable.add((infos) => this._handleKeyboardEvent(infos)); // Create chart this.chart = new Chart(this._canvas.getContext("2d")!, { type: "line", data: { datasets: [], }, options: { dragData: true, dragX: true, onDragStart: (e) => e.button === 0 && this._handleDragPointStart(), onDrag: (e, di, i, v) => e.button === 0 && this._handleDragPoint(e, di, i, v), onDragEnd: (e, di, i, v) => e.button === 0 && this._handleDragPointEnd(e, di, i, v), onClick: (e, elements) => this._handleChartClick(e, elements), showLines: false, responsive: true, maintainAspectRatio: false, animation: { duration: 0, }, tooltips: { caretPadding: 15, mode: "point", }, annotation: { events: ["mouseenter", "mouseleave"], annotations: [{ drawTime: "afterDatasetsDraw", id: "frame-tracker", type: "line", mode: "vertical", scaleID: "x-axis-0", value: 0, borderColor: "#000000", }, { drawTime: "afterDatasetsDraw", id: "value-tracker", type: "line", mode: "horizontal", scaleID: "y-axis-0", value: 0, borderColor: "#000000", }], }, legend: { labels: { fontColor: "black", }, }, plugins: { zoom: { pan: { enabled: true, mode: () => (this._panDisabled || this._selection?.ctrlPushed || this.timeTracker?.panDisabled) ? "" : "xy", onPan: () => this.chart?.render(0), onPanComplete: () => this.chart?.render(0), }, zoom: { enabled: true, mode: () => { if (this._mousePositonOnChart.x <= this.chart!["scales"]["x-axis-0"].left) { return "y"; } if (this._mousePositonOnChart.y >= this.chart!["scales"]["y-axis-0"].bottom) { return "x"; } if (this._mousePositonOnChart.y <= this.chart!["scales"]["y-axis-0"].top) { return "x"; } return "xy"; }, onZoom: () => this.chart?.render(0), onZoomComplete: () => this.chart?.render(0), }, }, }, scales: { xAxes: [{ type: "linear", position: "bottom", ticks: { min: -2, max: 60, fontSize: 12, fontStyle: "bold", fontColor: "#222222", }, }, { type: "linear", position: "top", ticks: { min: -2, max: 60, fontSize: 12, fontColor: "#ffffff", }, }], yAxes: [{ ticks: { min: -10, max: 10, fontSize: 12, fontStyle: "bold", fontColor: "#222222", }, }], } }, }); // X Axis time (in seconds) this.chart.config.options!.scales!.xAxes![1].ticks!.callback = (value) => { if (value < 0 || !this.state.selectedAnimation) { return ""; } return `${(value / this.state.selectedAnimation.framePerSecond).toFixed(1)}s`; }; // Create time tracker this.timeTracker = new TimeTracker(this.chart, { onMoved: () => this._handleTimeTrackerChanged(), }); this.chart.config.options!.annotation.annotations.push(this.timeTracker?.getAnnotationConfiguration()); // Create selection this._selection = new PointSelection(this.chart, { onSelectedFrames: (frames) => this._selectedFrames = frames, }); this._selection.configure(); } /** * Called on the component will unmount. */ public componentWillUnmount(): void { // Destroy chart try { this.chart?.destroy(); } catch (e) { this._editor.console.logError("[Animation Editor]: failed to destroy chart."); } // Remove events this._editor.keyboardEventObservable.remove(this._keyboardObserver); } /** * Refreshes the chart editor. */ public refresh(): void { this.setAnimation(this.state.selectedAnimation); this.updateObjectToCurrentFrame(); } /** * Sets the new animatable to edit. * @param animatable defines the reference to the animatable. */ public setAnimatable(animatable: IAnimatable): void { this.setState({ selectedAnimatable: animatable }); } /** * Sets the new animation to edit. * @param animation defines the reference of the selected animation to edit. * @param animate defines wether or not the chart should be animated. */ public setAnimation(animation: Nullable<Animation>, animate: boolean = false): void { if (!this.chart) { return; } this._selection?.reset(); const datasets = AnimationTools.ConvertToDatasets(animation); if (!datasets) { return; } this.chart.data.datasets = datasets; this.chart.config.options!.animation!.duration = animate ? 1000 : 0; this.chart.update(this.state.selectedAnimation === animation ? 0 : undefined); this._datasets = datasets; this.setState({ selectedAnimation: animation }); } /** * Sets the new synchronization type. * @param synchronizationType defines the new synchronization type. */ public setSyncType(synchronizationType: SyncType): void { this.setState({ synchronizationType }, () => { if (!this.timeTracker) { return; } this.resetObjectToFirstFrame(); this.timeTracker?.setValue(this.timeTracker.getValue()); this.updateObjectToCurrentFrame(); }); } /** * Plays the animation (moves the time tracker). */ public playAnimation(from: number, to?: number): void { if (!this.chart || !this.timeTracker || !this.state.selectedAnimation) { return; } this.timeTracker.playAnimation(this.state.selectedAnimation, this._editor.scene!, from, to); } /** * Stops the animation (moves the time tracker). */ public stopAnimation(): void { this.timeTracker?.stopAnimation(); } /** * Resets the current object to the first frame. */ public resetObjectToFirstFrame(): void { if (!this.chart || !this.timeTracker || !this.state.selectedAnimation) { return; } const range = AnimationTools.GetFramesRange(this.state.selectedAnimation); this.timeTracker.setValue(range.min); this.updateObjectToCurrentFrame(); } /** * Updates the current object to the current frame on animation. */ public updateObjectToCurrentFrame(): void { if (!this.state.selectedAnimatable || !this.state.selectedAnimation || !this.timeTracker) { return; } SyncTool.UpdateObjectToFrame( this.timeTracker.getValue(), SyncType.Scene, this.state.selectedAnimatable, this.state.selectedAnimation, this._editor.scene!, ); } /** * Sets the new frame value for the time tracker. * @param value defines the new value of time (frame). */ public setCurrentFrameValue(value: number): void { this.timeTracker?.setValue(value); } /** * Called on the user moves the time tracker. */ private _handleTimeTrackerChanged(): void { if (!this.timeTracker) { return; } this.updateObjectToCurrentFrame(); this.props.onFrameChange(this.timeTracker.getValue()); this.chart?.render(0); } /** * Called on the user fires a keyboard event. */ private _handleKeyboardEvent(infos: KeyboardInfo): void { this._selection?.keyboardEvent(infos); if (infos.event.key === " ") { if (this.chart?.config.options) { this.chart.config.options.dragX = infos.type === KeyboardEventTypes.KEYUP; } } } /** * Called on the mouse moves on the canvas. */ private _handleMouseMove(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void { this.setState({ mousePositionOnChart: this.timeTracker?.getPositionOnChart(ev.nativeEvent) ?? this.state.mousePositionOnChart }); this._mousePositonOnChart.set(ev.nativeEvent.offsetX, ev.nativeEvent.offsetY); this.timeTracker?.mouseMove(ev); } /** * Called on the mouse is down on the canvas. */ private _handleMouseDown(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void { this.timeTracker?.mouseDown(ev); this._selection?.mouseDown(ev); } /** * Called on the mouse is up on the canvas. */ private _handleMouseUp(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void { if (ev.button === 2 && !this.timeTracker?.draggingTimeTracker) { return this._handleContextMenu(ev); } this.timeTracker?.mouseUp(ev); this._selection?.mouseUp(ev); } /** * Called on the user double clicks on the chart. */ private _handleDoubleClick(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void { if (!this.chart || !this.timeTracker || !this.state.selectedAnimation) { return; } const elements = this.chart.getElementsAtEvent(ev); if (elements && elements.length > 0) { const keys = this.state.selectedAnimation.getKeys(); const key = keys[elements[0]["_index"]]; if (!key) { return; } this.timeTracker?.setValue(key.frame); } else { const positionOnChart = this.timeTracker.getPositionOnChart(ev.nativeEvent); if (positionOnChart) { this.timeTracker?.setValue(Math.max(positionOnChart.x, 0)); } } this.chart.update(0); this.updateObjectToCurrentFrame(); } /** * Called on an element of the chart is starting being dragged. */ private _handleDragPointStart(): void { this._panDisabled = true; } /** * Called on an element of the chart is being dragged. */ private _handleDragPoint(ev: MouseEvent, datasetIndex: number, index: number, value: IVector2Like): void { const mousePositionOnChart = this.timeTracker?.getPositionOnChart(ev) ?? this.state.mousePositionOnChart; if (!this._undoRedoKeyData && this.state.selectedAnimation) { this._undoRedoKeyData = { x: value.x, y: value.y }; } this._updateKey(datasetIndex, index, value); this.setState({ mousePositionOnChart }); } /** * Callback called on an element stops being dragged. */ private _handleDragPointEnd(_: MouseEvent, datasetIndex: number, index: number, value: IVector2Like): void { if (this._undoRedoKeyData && this.state.selectedAnimation) { const undoData = { x: this._undoRedoKeyData.x, y: this._undoRedoKeyData.y }; const redoData = { x: value.x, y: value.y }; undoRedo.push({ common: () => this.chart?.update(0), undo: () => this._updateKey(datasetIndex, index, undoData), redo: () => this._updateKey(datasetIndex, index, redoData), }); } else { this._updateKey(datasetIndex, index, value); } this._panDisabled = false; this._undoRedoKeyData = null; this.chart?.update(0); } /** * Updates the key (according to the given informations to retrieve it) with the given value. */ private _updateKey(datasetIndex: number, index: number, value: IVector2Like): void { if (!this.state.selectedAnimation || !this._datasets) { return; } // Limit frames to 0 if (value.x < 0) { value.x = 0; } const key = this.state.selectedAnimation.getKeys()[index]; if (!key) { return; } key.frame = value.x; (this._datasets[datasetIndex].data![index] as IVector2Like).y = value.y; switch (this.state.selectedAnimation.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: (this._datasets[0].data![index] as IVector2Like).x = value.x; key.value = value.y; break; // Vectors case Animation.ANIMATIONTYPE_VECTOR2: case Animation.ANIMATIONTYPE_VECTOR3: (this._datasets[0].data![index] as IVector2Like).x = value.x; (this._datasets[1].data![index] as IVector2Like).x = value.x; if (this.state.selectedAnimation.dataType === Animation.ANIMATIONTYPE_VECTOR3) { (this._datasets[2].data![index] as IVector2Like).x = value.x; } const vectorProperty = ["x", "y", "z"][datasetIndex]; if (vectorProperty) { key.value[vectorProperty] = value.y; } break; // Colors case Animation.ANIMATIONTYPE_COLOR3: case Animation.ANIMATIONTYPE_COLOR4: (this._datasets[0].data![index] as IVector2Like).x = value.x; (this._datasets[1].data![index] as IVector2Like).x = value.x; (this._datasets[2].data![index] as IVector2Like).x = value.x; if (this.state.selectedAnimation.dataType === Animation.ANIMATIONTYPE_COLOR4) { (this._datasets[3].data![index] as IVector2Like).x = value.x; } const colorProperty = ["r", "g", "b", "a"][datasetIndex]; if (colorProperty) { key.value[colorProperty] = value.y; } break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: (this._datasets[0].data![index] as IVector2Like).x = value.x; (this._datasets[1].data![index] as IVector2Like).x = value.x; (this._datasets[2].data![index] as IVector2Like).x = value.x; (this._datasets[3].data![index] as IVector2Like).x = value.x; const quaternionProperty = ["x", "y", "z", "w"][datasetIndex]; if (quaternionProperty) { key.value[quaternionProperty] = value.y; } break; } this.updateObjectToCurrentFrame(); } /** * Called on the user clicks on a point. */ private _handleChartClick(_: Undefinable<MouseEvent>, elements: Undefinable<{}[]>): void { if (!this.chart || !this.state.selectedAnimation) { return; } if (!elements?.length) { return this._selection?.chartClick(); } const element = elements[0]!; const key = this.state.selectedAnimation.getKeys()[element["_index"]]; if (key) { this._editor.inspector.setSelectedObject(new AnimationKeyObject(this.state.selectedAnimation, key, element["_index"], () => { if (this.state.selectedAnimation) { this.setAnimation(this.state.selectedAnimation); this.updateObjectToCurrentFrame(); } })); } } /** * Called on the user right-clicks on the canvas. */ private _handleContextMenu(ev: React.MouseEvent<HTMLCanvasElement, MouseEvent>): void { if (!this.chart || !this.timeTracker || !this.state.selectedAnimation) { return; } const chartPosition = this.timeTracker.getPositionOnChart(ev.nativeEvent); const elements = this.chart.getElementsAtEvent(ev); let removeElement: React.ReactNode; if (elements.length && this.state.selectedAnimation.getKeys().length > 2) { removeElement = ( <> <MenuDivider /> <MenuItem text={this._selectedFrames.length ? "Remove Selected Keys" : "Remove Key"} icon={<Icon src="times.svg" />} onClick={() => this._removeKeys(elements)} /> </> ); } ContextMenu.show( <Menu className={Classes.DARK}> <Pre> Coordinates: <br /> x: <Tag intent={Intent.PRIMARY}>{chartPosition.x}</Tag><br /> y: <Tag intent={Intent.PRIMARY}>{chartPosition.y}</Tag> </Pre> <MenuDivider /> <MenuItem text="Reset Zoom" icon="reset" onClick={() => this._resetZoom()} /> {removeElement} </Menu>, { left: ev.nativeEvent.clientX, top: ev.nativeEvent.clientY }, ); } /** * Called on the user wants to remove keys. */ private _removeKeys(elements: any[]): void { const animation = this.state.selectedAnimation!; const keys = animation.getKeys(); if (this._selectedFrames.length) { const selectedFrames = this._selectedFrames.slice(); const removedKeys: IAnimationKey[] = []; selectedFrames.forEach((f) => { keys.forEach((k) => { if (k.frame === f) { removedKeys.push(k); } }); }); undoRedo.push({ common: () => this.setAnimation(this.state.selectedAnimation), undo: () => { removedKeys.forEach((k) => keys.push(k)); keys.sort((a, b) => a.frame - b.frame); this._selectedFrames = selectedFrames.slice(); }, redo: () => { removedKeys.forEach((k) => { const index = keys.indexOf(k); if (index !== -1) { keys.splice(index, 1); } }); }, }); this._selectedFrames = []; } else { const element = elements[0]; const key = keys[element["_index"]]; undoRedo.push({ common: () => this.setAnimation(this.state.selectedAnimation), undo: () => { keys.push(key); keys.sort((a, b) => a.frame - b.frame); }, redo: () => { keys.splice(keys.indexOf(key), 1); }, }); } this.setAnimation(this.state.selectedAnimation); } /** * Resets the zoom to default. */ private _resetZoom(): void { if (!this.state.selectedAnimation || !this.chart) { return; } const xAxis1 = this.chart?.config?.options?.scales?.xAxes![0]?.ticks; if (!xAxis1) { return; } const xAxis2 = this.chart?.config?.options?.scales?.xAxes![1]?.ticks; if (!xAxis2) { return; } const yAxis = this.chart?.config?.options?.scales?.yAxes![0]?.ticks; if (!yAxis) { return; } const framesRange = AnimationTools.GetFramesRange(this.state.selectedAnimation); xAxis1.min = xAxis2.min = 0; xAxis1.max = xAxis2.max = framesRange.max * 2; const valuesRange = AnimationTools.GetValuesRange(this.state.selectedAnimation); yAxis.min = valuesRange.min * 2; yAxis.max = valuesRange.max * 2; this.chart.update(0); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/billingRoleAssignmentsMappers"; import * as Parameters from "../models/parameters"; import { BillingManagementClientContext } from "../billingManagementClientContext"; /** Class representing a BillingRoleAssignments. */ export class BillingRoleAssignments { private readonly client: BillingManagementClientContext; /** * Create a BillingRoleAssignments. * @param {BillingManagementClientContext} client Reference to the service client. */ constructor(client: BillingManagementClientContext) { this.client = client; } /** * Gets a role assignment for the caller on a billing account. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsGetByBillingAccountResponse> */ getByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsGetByBillingAccountResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ getByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ getByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; getByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsGetByBillingAccountResponse> { return this.client.sendOperationRequest( { billingAccountName, billingRoleAssignmentName, options }, getByBillingAccountOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsGetByBillingAccountResponse>; } /** * Deletes a role assignment for the caller on a billing account. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsDeleteByBillingAccountResponse> */ deleteByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsDeleteByBillingAccountResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ deleteByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ deleteByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; deleteByBillingAccount(billingAccountName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsDeleteByBillingAccountResponse> { return this.client.sendOperationRequest( { billingAccountName, billingRoleAssignmentName, options }, deleteByBillingAccountOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsDeleteByBillingAccountResponse>; } /** * Gets a role assignment for the caller on an invoice section. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsGetByInvoiceSectionResponse> */ getByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsGetByInvoiceSectionResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ getByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ getByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; getByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsGetByInvoiceSectionResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, invoiceSectionName, billingRoleAssignmentName, options }, getByInvoiceSectionOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsGetByInvoiceSectionResponse>; } /** * Deletes a role assignment for the caller on an invoice section. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsDeleteByInvoiceSectionResponse> */ deleteByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsDeleteByInvoiceSectionResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ deleteByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ deleteByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; deleteByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsDeleteByInvoiceSectionResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, invoiceSectionName, billingRoleAssignmentName, options }, deleteByInvoiceSectionOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsDeleteByInvoiceSectionResponse>; } /** * Gets a role assignment for the caller on a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsGetByBillingProfileResponse> */ getByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsGetByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ getByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ getByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; getByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsGetByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, billingRoleAssignmentName, options }, getByBillingProfileOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsGetByBillingProfileResponse>; } /** * Deletes a role assignment for the caller on a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsDeleteByBillingProfileResponse> */ deleteByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsDeleteByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param callback The callback */ deleteByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param billingRoleAssignmentName The ID that uniquely identifies a role assignment. * @param options The optional parameters * @param callback The callback */ deleteByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignment>): void; deleteByBillingProfile(billingAccountName: string, billingProfileName: string, billingRoleAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignment>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignment>): Promise<Models.BillingRoleAssignmentsDeleteByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, billingRoleAssignmentName, options }, deleteByBillingProfileOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsDeleteByBillingProfileResponse>; } /** * Lists the role assignments for the caller on a billing account. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByBillingAccountResponse> */ listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByBillingAccountResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param callback The callback */ listByBillingAccount(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param options The optional parameters * @param callback The callback */ listByBillingAccount(billingAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByBillingAccountResponse> { return this.client.sendOperationRequest( { billingAccountName, options }, listByBillingAccountOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByBillingAccountResponse>; } /** * Lists the role assignments for the caller on an invoice section. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByInvoiceSectionResponse> */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByInvoiceSectionResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param callback The callback */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param options The optional parameters * @param callback The callback */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByInvoiceSectionResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, invoiceSectionName, options }, listByInvoiceSectionOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByInvoiceSectionResponse>; } /** * Lists the role assignments for the caller on a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByBillingProfileResponse> */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param options The optional parameters * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, options }, listByBillingProfileOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByBillingProfileResponse>; } /** * Lists the role assignments for the caller on a billing account. The operation is supported for * billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer * Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByBillingAccountNextResponse> */ listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByBillingAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByBillingAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByBillingAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByBillingAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByBillingAccountNextOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByBillingAccountNextResponse>; } /** * Lists the role assignments for the caller on an invoice section. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByInvoiceSectionNextResponse> */ listByInvoiceSectionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByInvoiceSectionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByInvoiceSectionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByInvoiceSectionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByInvoiceSectionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByInvoiceSectionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByInvoiceSectionNextOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByInvoiceSectionNextResponse>; } /** * Lists the role assignments for the caller on a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingRoleAssignmentsListByBillingProfileNextResponse> */ listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingRoleAssignmentsListByBillingProfileNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): void; listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>, callback?: msRest.ServiceCallback<Models.BillingRoleAssignmentListResult>): Promise<Models.BillingRoleAssignmentsListByBillingProfileNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByBillingProfileNextOperationSpec, callback) as Promise<Models.BillingRoleAssignmentsListByBillingProfileNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getByBillingAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteByBillingAccountOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getByInvoiceSectionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteByInvoiceSectionOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.billingRoleAssignmentName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignment }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments", urlParameters: [ Parameters.billingAccountName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByInvoiceSectionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByInvoiceSectionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingProfileNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingRoleAssignmentListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { Clipboard, CommandRegistry, Config, ContextMenuManager, DeserializerManager, Disposable, GrammarRegistry, HistoryManager, KeymapManager, MenuManager, NotificationManager, PackageManager, Project, StyleManager, TextEditorRegistry, ThemeManager, TooltipManager, ViewRegistry, WindowLoadSettings, Workspace, } from '../index'; /** * Atom global for dealing with packages, themes, menus, and the window. * An instance of this class is always available as the atom global. */ export interface AtomEnvironment { // Properties /** A CommandRegistry instance. */ readonly commands: CommandRegistry; /** A Config instance. */ readonly config: Config; /** A Clipboard instance. */ readonly clipboard: Clipboard; /** A ContextMenuManager instance. */ readonly contextMenu: ContextMenuManager; /** A MenuManager instance. */ readonly menu: MenuManager; /** A KeymapManager instance. */ readonly keymaps: KeymapManager; /** A TooltipManager instance. */ readonly tooltips: TooltipManager; /** A NotificationManager instance. */ readonly notifications: NotificationManager; /** A Project instance. */ readonly project: Project; /** A GrammarRegistry instance. */ readonly grammars: GrammarRegistry; /** A HistoryManager instance. */ readonly history: HistoryManager; /** A PackageManager instance. */ readonly packages: PackageManager; /** A ThemeManager instance. */ readonly themes: ThemeManager; /** A StyleManager instance. */ readonly styles: StyleManager; /** A DeserializerManager instance. */ readonly deserializers: DeserializerManager; /** A ViewRegistry instance. */ readonly views: ViewRegistry; /** A Workspace instance. */ readonly workspace: Workspace; /** A TextEditorRegistry instance. */ readonly textEditors: TextEditorRegistry; // Event Subscription /** Invoke the given callback whenever ::beep is called. */ onDidBeep(callback: () => void): Disposable; /** * Invoke the given callback when there is an unhandled error, but before * the devtools pop open. */ onWillThrowError(callback: (event: PreventableExceptionThrownEvent) => void): Disposable; /** Invoke the given callback whenever there is an unhandled error. */ onDidThrowError(callback: (event: ExceptionThrownEvent) => void): Disposable; /** * Invoke the given callback as soon as the shell environment is loaded (or * immediately if it was already loaded). */ whenShellEnvironmentLoaded(callback: () => void): Disposable; // Atom Details /** Returns a boolean that is true if the current window is in development mode. */ inDevMode(): boolean; /** Returns a boolean that is true if the current window is in safe mode. */ inSafeMode(): boolean; /** Returns a boolean that is true if the current window is running specs. */ inSpecMode(): boolean; /** Get the full name of this Atom release (e.g. "Atom", "Atom Beta") */ getAppName(): string; /** Get the version of the Atom application. */ getVersion(): string; /** * Gets the release channel of the Atom application. * Returns the release channel, which can be 'dev', 'nightly', 'beta', or 'stable'. */ getReleaseChannel(): 'dev' | 'nightly' | 'beta' | 'stable'; /** Returns a boolean that is true if the current version is an official release. */ isReleasedVersion(): boolean; /** Get the time taken to completely load the current window. */ getWindowLoadTime(): number; /** Get the all the markers with the information about startup time. */ getStartupMarkers(): TimingMarker[]; /** Get the load settings for the current window. */ getLoadSettings(): WindowLoadSettings; // Managing the Atom Window /** Open a new Atom window using the given options. */ open(params?: { pathsToOpen: ReadonlyArray<string>; newWindow?: boolean | undefined; devMode?: boolean | undefined; safeMode?: boolean | undefined; }): void; /** Close the current window. */ close(): void; /** Get the size of current window. */ getSize(): { width: number; height: number }; /** Set the size of current window. */ setSize(width: number, height: number): void; /** Get the position of current window. */ getPosition(): { x: number; y: number }; /** Set the position of current window. */ setPosition(x: number, y: number): void; /** Prompt the user to select one or more folders. */ pickFolder(callback: (paths: string[] | null) => void): void; /** Get the current window. */ getCurrentWindow(): object; /** Move current window to the center of the screen. */ center(): void; /** Focus the current window. */ focus(): void; /** Show the current window. */ show(): void; /** Hide the current window. */ hide(): void; /** Reload the current window. */ reload(): void; /** Relaunch the entire application. */ restartApplication(): void; /** Returns a boolean that is true if the current window is maximized. */ isMaximized(): boolean; /** Returns a boolean that is true if the current window is in full screen mode. */ isFullScreen(): boolean; /** Set the full screen state of the current window. */ setFullScreen(fullScreen: boolean): void; /** Toggle the full screen state of the current window. */ toggleFullScreen(): void; /** * Restores the full screen and maximized state after the window has resized to prevent resize * glitches. */ displayWindow(): Promise<undefined>; /** Get the dimensions of this window. */ getWindowDimensions(): { x: number; y: number; width: number; height: number }; /** Set the dimensions of the window. */ setWindowDimensions(dimensions: { x?: number | undefined; y?: number | undefined; width?: number | undefined; height?: number | undefined }): Promise<object>; // Messaging the User /** Visually and audibly trigger a beep. */ beep(): void; /** * A flexible way to open a dialog akin to an alert dialog. If a callback * is provided, then the confirmation will work asynchronously, which is * recommended. * * If the dialog is closed (via `Esc` key or `X` in the top corner) without * selecting a button the first button will be clicked unless a "Cancel" or "No" * button is provided. * * Returns the chosen button index number if the buttons option was an array. * @param response The index of the button that was clicked. * @param checkboxChecked The checked state of the checkbox if `checkboxLabel` was set. * Otherwise false. */ confirm(options: ConfirmationOptions, callback: (response: number, checkboxChecked: boolean) => void): void; /** * A flexible way to open a dialog akin to an alert dialog. If a callback * is provided, then the confirmation will work asynchronously, which is * recommended. * * If the dialog is closed (via `Esc` key or `X` in the top corner) without * selecting a button the first button will be clicked unless a "Cancel" or "No" * button is provided. * * Returns the chosen button index number if the buttons option was an array. */ confirm(options: { message: string; detailedMessage?: string | undefined; buttons?: ReadonlyArray<string> | undefined }): void; /** * A flexible way to open a dialog akin to an alert dialog. If a callback * is provided, then the confirmation will work asynchronously, which is * recommended. * * If the dialog is closed (via `Esc` key or `X` in the top corner) without * selecting a button the first button will be clicked unless a "Cancel" or "No" * button is provided. * * Returns the chosen button index number if the buttons option was an array. */ confirm(options: { message: string; detailedMessage?: string | undefined; buttons?: { [key: string]: () => void; } | undefined; }): number; // Managing the Dev Tools /** Open the dev tools for the current window. */ openDevTools(): Promise<null>; /** Toggle the visibility of the dev tools for the current window. */ toggleDevTools(): Promise<null>; /** Execute code in dev tools. */ executeJavaScriptInDevTools(code: string): void; /** Undocumented: get Atom config directory path */ getConfigDirPath(): string; } export interface ExceptionThrownEvent { originalError: Error; message: string; url: string; line: number; column: number; } export interface PreventableExceptionThrownEvent extends ExceptionThrownEvent { preventDefault(): void; } export interface ConfirmationOptions { /** The type of the confirmation prompt. */ type?: 'none' | 'info' | 'error' | 'question' | 'warning' | undefined; /** The text for the buttons. */ buttons?: ReadonlyArray<string> | undefined; /** The index for the button to be selected by default in the prompt. */ defaultId?: number | undefined; /** The title for the prompt. */ title?: string | undefined; /** The content of the message box. */ message?: string | undefined; /** Additional information regarding the message. */ detail?: string | undefined; /** If provided, the message box will include a checkbox with the given label. */ checkboxLabel?: string | undefined; /** Initial checked state of the checkbox. false by default. */ checkboxChecked?: boolean | undefined; /** An Electron NativeImage to use as the prompt's icon. */ icon?: object | undefined; /** * The index of the button to be used to cancel the dialog, via the `Esc` key. * By default this is assigned to the first button with "cancel" or "no" as the * label. If no such labeled buttons exist and this option is not set, 0 will be * used as the return value or callback response. * * This option is ignored on Windows. */ cancelId?: number | undefined; /** * On Windows, Electron will try to figure out which one of the buttons are * common buttons (like `Cancel` or `Yes`), and show the others as command links * in the dialog. This can make the dialog appear in the style of modern Windows * apps. If you don't like this behavior, you can set noLink to true. */ noLink?: boolean | undefined; /** * Normalize the keyboard access keys across platforms. * Atom defaults this to true. */ normalizeAccessKeys?: boolean | undefined; } export interface TimingMarker { label: string; time: number; }
the_stack
import {FocusKeyManager} from '@angular/cdk/a11y'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; import {A, ENTER, hasModifierKey, SPACE} from '@angular/cdk/keycodes'; import {_getFocusedElementPierceShadowDom} from '@angular/cdk/platform'; import { AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, NgZone, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, ViewEncapsulation, } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {ThemePalette} from '@angular/material-experimental/mdc-core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {MatListBase} from './list-base'; import {MatListOption, SELECTION_LIST, SelectionList} from './list-option'; const MAT_SELECTION_LIST_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSelectionList), multi: true, }; /** Change event that is being fired whenever the selected state of an option changes. */ export class MatSelectionListChange { constructor( /** Reference to the selection list that emitted the event. */ public source: MatSelectionList, /** * Reference to the option that has been changed. * @deprecated Use `options` instead, because some events may change more than one option. * @breaking-change 12.0.0 */ public option: MatListOption, /** Reference to the options that have been changed. */ public options: MatListOption[], ) {} } @Component({ selector: 'mat-selection-list', exportAs: 'matSelectionList', host: { 'class': 'mat-mdc-selection-list mat-mdc-list-base mdc-list', 'role': 'listbox', '[attr.aria-multiselectable]': 'multiple', '(keydown)': '_handleKeydown($event)', }, template: '<ng-content></ng-content>', styleUrls: ['list.css'], encapsulation: ViewEncapsulation.None, providers: [ MAT_SELECTION_LIST_VALUE_ACCESSOR, {provide: MatListBase, useExisting: MatSelectionList}, {provide: SELECTION_LIST, useExisting: MatSelectionList}, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatSelectionList extends MatListBase implements SelectionList, ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy { private _initialized = false; private _keyManager: FocusKeyManager<MatListOption>; /** Emits when the list has been destroyed. */ private _destroyed = new Subject<void>(); /** Whether the list has been destroyed. */ private _isDestroyed: boolean; /** View to model callback that should be called whenever the selected options change. */ private _onChange: (value: any) => void = (_: any) => {}; @ContentChildren(MatListOption, {descendants: true}) _items: QueryList<MatListOption>; /** Emits a change event whenever the selected state of an option changes. */ @Output() readonly selectionChange: EventEmitter<MatSelectionListChange> = new EventEmitter<MatSelectionListChange>(); /** Theme color of the selection list. This sets the checkbox color for all list options. */ @Input() color: ThemePalette = 'accent'; /** * Function used for comparing an option against the selected value when determining which * options should appear as selected. The first argument is the value of an options. The second * one is a value from the selected value. A boolean must be returned. */ @Input() compareWith: (o1: any, o2: any) => boolean = (a1, a2) => a1 === a2; /** Whether selection is limited to one or multiple items (default multiple). */ @Input() get multiple(): boolean { return this._multiple; } set multiple(value: BooleanInput) { const newValue = coerceBooleanProperty(value); if (newValue !== this._multiple) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && this._initialized) { throw new Error( 'Cannot change `multiple` mode of mat-selection-list after initialization.', ); } this._multiple = newValue; this.selectedOptions = new SelectionModel(this._multiple, this.selectedOptions.selected); } } private _multiple = true; /** The currently selected options. */ selectedOptions = new SelectionModel<MatListOption>(this._multiple); /** Keeps track of the currently-selected value. */ _value: string[] | null; /** View to model callback that should be called if the list or its options lost focus. */ _onTouched: () => void = () => {}; constructor(public _element: ElementRef<HTMLElement>, private _ngZone: NgZone) { super(); this._isNonInteractive = false; } ngAfterViewInit() { // Mark the selection list as initialized so that the `multiple` // binding can no longer be changed. this._initialized = true; this._setupRovingTabindex(); // These events are bound outside the zone, because they don't change // any change-detected properties and they can trigger timeouts. this._ngZone.runOutsideAngular(() => { this._element.nativeElement.addEventListener('focusin', this._handleFocusin); this._element.nativeElement.addEventListener('focusout', this._handleFocusout); }); if (this._value) { this._setOptionsFromValues(this._value); } this._watchForSelectionChange(); } ngOnChanges(changes: SimpleChanges) { const disabledChanges = changes['disabled']; const disableRippleChanges = changes['disableRipple']; if ( (disableRippleChanges && !disableRippleChanges.firstChange) || (disabledChanges && !disabledChanges.firstChange) ) { this._markOptionsForCheck(); } } ngOnDestroy() { this._element.nativeElement.removeEventListener('focusin', this._handleFocusin); this._element.nativeElement.removeEventListener('focusout', this._handleFocusout); this._destroyed.next(); this._destroyed.complete(); this._isDestroyed = true; } /** Focuses the selection list. */ focus(options?: FocusOptions) { this._element.nativeElement.focus(options); } /** Selects all of the options. Returns the options that changed as a result. */ selectAll(): MatListOption[] { return this._setAllOptionsSelected(true); } /** Deselects all of the options. Returns the options that changed as a result. */ deselectAll(): MatListOption[] { return this._setAllOptionsSelected(false); } /** Reports a value change to the ControlValueAccessor */ _reportValueChange() { // Stop reporting value changes after the list has been destroyed. This avoids // cases where the list might wrongly reset its value once it is removed, but // the form control is still live. if (this.options && !this._isDestroyed) { const value = this._getSelectedOptionValues(); this._onChange(value); this._value = value; } } /** Emits a change event if the selected state of an option changed. */ _emitChangeEvent(options: MatListOption[]) { this.selectionChange.emit(new MatSelectionListChange(this, options[0], options)); } /** Implemented as part of ControlValueAccessor. */ writeValue(values: string[]): void { this._value = values; if (this.options) { this._setOptionsFromValues(values || []); } } /** Implemented as a part of ControlValueAccessor. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } /** Implemented as part of ControlValueAccessor. */ registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } /** Implemented as part of ControlValueAccessor. */ registerOnTouched(fn: () => void): void { this._onTouched = fn; } /** Watches for changes in the selected state of the options and updates the list accordingly. */ private _watchForSelectionChange() { this.selectedOptions.changed.pipe(takeUntil(this._destroyed)).subscribe(event => { // Sync external changes to the model back to the options. for (let item of event.added) { item.selected = true; } for (let item of event.removed) { item.selected = false; } if (!this._containsFocus()) { this._resetActiveOption(); } }); } /** Sets the selected options based on the specified values. */ private _setOptionsFromValues(values: string[]) { this.options.forEach(option => option._setSelected(false)); values.forEach(value => { const correspondingOption = this.options.find(option => { // Skip options that are already in the model. This allows us to handle cases // where the same primitive value is selected multiple times. return option.selected ? false : this.compareWith(option.value, value); }); if (correspondingOption) { correspondingOption._setSelected(true); } }); } /** Returns the values of the selected options. */ private _getSelectedOptionValues(): string[] { return this.options.filter(option => option.selected).map(option => option.value); } /** Marks all the options to be checked in the next change detection run. */ private _markOptionsForCheck() { if (this.options) { this.options.forEach(option => option._markForCheck()); } } /** * Sets the selected state on all of the options * and emits an event if anything changed. */ private _setAllOptionsSelected(isSelected: boolean, skipDisabled?: boolean): MatListOption[] { // Keep track of whether anything changed, because we only want to // emit the changed event when something actually changed. const changedOptions: MatListOption[] = []; this.options.forEach(option => { if ((!skipDisabled || !option.disabled) && option._setSelected(isSelected)) { changedOptions.push(option); } }); if (changedOptions.length) { this._reportValueChange(); } return changedOptions; } // Note: This getter exists for backwards compatibility. The `_items` query list // cannot be named `options` as it will be picked up by the interactive list base. /** The option components contained within this selection-list. */ get options(): QueryList<MatListOption> { return this._items; } /** Handles keydown events within the list. */ _handleKeydown(event: KeyboardEvent) { const activeItem = this._keyManager.activeItem; if ( (event.keyCode === ENTER || event.keyCode === SPACE) && !this._keyManager.isTyping() && activeItem && !activeItem.disabled ) { event.preventDefault(); activeItem._toggleOnInteraction(); } else if ( event.keyCode === A && this.multiple && !this._keyManager.isTyping() && hasModifierKey(event, 'ctrlKey') ) { const shouldSelect = this.options.some(option => !option.disabled && !option.selected); event.preventDefault(); this._emitChangeEvent(this._setAllOptionsSelected(shouldSelect, true)); } else { this._keyManager.onKeydown(event); } } /** Handles focusout events within the list. */ private _handleFocusout = () => { // Focus takes a while to update so we have to wrap our call in a timeout. setTimeout(() => { if (!this._containsFocus()) { this._resetActiveOption(); } }); }; /** Handles focusin events within the list. */ private _handleFocusin = (event: FocusEvent) => { const activeIndex = this._items .toArray() .findIndex(item => item._elementRef.nativeElement.contains(event.target as HTMLElement)); if (activeIndex > -1) { this._setActiveOption(activeIndex); } else { this._resetActiveOption(); } }; /** Sets up the logic for maintaining the roving tabindex. */ private _setupRovingTabindex() { this._keyManager = new FocusKeyManager(this._items) .withHomeAndEnd() .withTypeAhead() .withWrap() // Allow navigation to disabled items. .skipPredicate(() => false); // Set the initial focus. this._resetActiveOption(); // Move the tabindex to the currently-focused list item. this._keyManager.change .pipe(takeUntil(this._destroyed)) .subscribe(activeItemIndex => this._setActiveOption(activeItemIndex)); // If the active item is removed from the list, reset back to the first one. this._items.changes.pipe(takeUntil(this._destroyed)).subscribe(() => { const activeItem = this._keyManager.activeItem; if (!activeItem || !this._items.toArray().indexOf(activeItem)) { this._resetActiveOption(); } }); } /** * Sets an option as active. * @param index Index of the active option. If set to -1, no option will be active. */ private _setActiveOption(index: number) { this._items.forEach((item, itemIndex) => item._setTabindex(itemIndex === index ? 0 : -1)); this._keyManager.updateActiveItem(index); } /** Resets the active option to the first selected option. */ private _resetActiveOption() { const activeItem = this._items.find(item => item.selected && !item.disabled) || this._items.first; this._setActiveOption(activeItem ? this._items.toArray().indexOf(activeItem) : -1); } /** Returns whether the focus is currently within the list. */ private _containsFocus() { const activeElement = _getFocusedElementPierceShadowDom(); return activeElement && this._element.nativeElement.contains(activeElement); } }
the_stack
import axios from 'axios'; import * as BluePromise from 'bluebird'; import * as Debug from 'debug'; import { coerce, satisfies } from 'semver'; import config from '../config'; import { ExpressBrainDriver } from '../expressBrainDriver'; import * as Models from '../models'; import * as Brain from './brain'; import buildBrainUrl from './brain/urlBuilder'; import { Database } from './database'; import { DeviceBuilder } from './deviceBuilder'; import { RequestHandler } from './handler/requestHandler'; import DeviceState from './implementationservices/deviceState'; import ListBuilder from './lists/listBuilder'; import * as validation from './validation'; const MAXIMAL_CONNECTION_ATTEMPTS_TO_BRAIN = 8; let brainDriver: ExpressBrainDriver; const debug = Debug('neeo:device:device'); /* tslint:disable:max-line-length */ /** * Create new device factory, builds a searchable device for the NEEO Brain * @function * @see {@link DeviceBuilder} * @param {String} DeviceName The device name * @return {DeviceBuilder} factory methods to build device * @example * neeoapi.buildDevice('simpleDevice1') * .setManufacturer('NEEO') * .addAdditionalSearchToken('foo') * .setType('light') * .addButton({ name: 'example-button', label: 'my button' }, controller.button) * .addSwitch({ name: 'example-switch', label: 'my switch' }, * { setter: controller.switchSet, getter: controller.switchGet }) * .addSlider({ name: 'example-slider', label: 'my slider', range: [0,110], unit: '%' }, * { setter: controller.sliderSet, getter: controller.sliderGet }); */ const buildDevice = buildCustomDevice; // Using 2 lines because doxdox doesn't always understand export statements. export { buildDevice }; export function buildCustomDevice( adapterName: string, uniqueString?: string ): Models.DeviceBuilder { if (!adapterName) { throw new Error('MISSING_ADAPTERNAME'); } return new DeviceBuilder(adapterName, uniqueString); } /** * Create new list factory, builds a browsable list which can be used for a specific device, for example to browse a playlist * @function * @see {@link ListBuilder} * @param {Object} configuration JSON Configuration Object * @param {String} configuration.title title of the list * @param {Number} configuration.totalMatchingItems how many results the query included in total (used for pagination) * @param {Number} configuration.limit optional, how many items should be queried per page (used for pagination). The default and maximum is 64. * @param {Number} configuration.offset optional, default starting offset (used for pagination) * @param {String} configuration.browseIdentifier optional, identifier that is passed with a browse request to identify which "path" should be browsed * @return {ListBuilder} factory methods to build list * @example * neeoapi.buildBrowseList({ * title: 'list title', * totalMatchingItems: 100, * limit: 20, * offset: 0, * browseIdentifier: 'browseEverything' * }) * .addListHeader('NEEO Header') * .addListItem({ * title: 'foo' * }) */ export function buildBrowseList(options: Models.ListParameters): Models.ListBuilder { return new ListBuilder(options); } /** * This function builds a new DeviceState Object which helps organise client states, cache states and reachability * @function * @see {@link DeviceState} * @param {integer} cacheTimeMs how long should a devicestate be cached (optional, default is 2000ms) * @return {DeviceState} a new DeviceState instance * @example * const deviceState = neeoapi.buildDeviceState(2000); */ export function buildDeviceState(cacheTimeMs: number): Models.DeviceState { return new DeviceState(cacheTimeMs); } export function startServer(conf: Models.StartServerConfig, driver: ExpressBrainDriver) { if (!conf || !driver) { return BluePromise.reject(new Error('INVALID_STARTSERVER_PARAMETER')); } let { maxConnectionAttempts } = conf; const { baseurl, brain, brainport } = conf; brainDriver = driver; if (!maxConnectionAttempts) { maxConnectionAttempts = MAXIMAL_CONNECTION_ATTEMPTS_TO_BRAIN; } const adapterName = generateAdapterName(conf); const baseUrl = baseurl || generateBaseUrl(conf); return validateBrainVersion(brain, brainport) .then(() => buildDevicesDatabase(conf, adapterName)) .then((devicesDatabase) => RequestHandler.build(devicesDatabase)) .then((requestHandler) => startSdkAndRetryIfConnectionFailed(conf, adapterName, requestHandler, baseUrl) ) .then(() => fetchDeviceSubscriptionsIfNeeded(conf.devices)); } /** * Stops the internal REST server and unregister this adapter on the NEEO Brain * @function * @param {Object} configuration JSON Configuration Object * @param {NEEOBrain} configuration.brain NEEOBrain object * @param {String} configuration.name device name * @return {Promise} will be resolved when adapter is unregistered and REST server is stopped * @example * neeoapi.stopServer({ brain: brain, name: 'custom-adapter' }); */ export function stopServer(conf: Models.StopServerConfig) { if (!conf || !conf.brain || !conf.name) { return BluePromise.reject('INVALID_STOPSERVER_PARAMETER'); } const adapterName = validation.getUniqueName(conf.name); const stopDriver = brainDriver ? brainDriver.stop(conf) : Promise.resolve(); return Promise.all([Brain.stop({ brain: conf.brain, adapterName }), stopDriver]); } /* Note: the unique name needs to start with "src-" to be recognised by the Brain */ function generateAdapterName({ name }: { name: string }) { return name === 'neeo-deviceadapter' ? name : `src-${validation.getUniqueName(name)}`; } function generateBaseUrl({ port }: { port: number }) { const baseUrl = `http://${validation.getAnyIpAddress()}:${port}`; debug('Adapter baseUrl %s', baseUrl); return baseUrl; } function buildDevicesDatabase(conf, adapterName) { return new BluePromise((resolve) => { const devices = conf.devices.map((device) => { return buildAndRegisterDevice(device, adapterName); }); resolve(Database.build(devices)); }); } function buildAndRegisterDevice(device: Models.DeviceBuilder, adapterName: string) { if (!device || typeof device.build !== 'function') { throw new Error(`Invalid device detected! Check the ${adapterName} driver device exports.`); } const deviceModel = device.build(adapterName); if (deviceModel.subscriptionFunction) { const boundNotificationFunction = (param) => { debug('notification %o', param); return Brain.sendSensorNotification(param, deviceModel.adapterName); }; let optionalCallbacks = {}; if (device.hasPowerStateSensor) { const powerOnNotificationFunction = (uniqueDeviceId) => { const msg = { uniqueDeviceId, component: 'powerstate', value: true }; return Brain.sendNotification(msg, deviceModel.adapterName).catch((error) => { debug('POWERON_NOTIFICATION_FAILED', error.message); }); }; const powerOffNotificationFunction = (uniqueDeviceId) => { const msg = { uniqueDeviceId, component: 'powerstate', value: false }; return Brain.sendNotification(msg, deviceModel.adapterName).catch((error) => { debug('POWEROFF_NOTIFICATION_FAILED', error.message); }); }; optionalCallbacks = { powerOnNotificationFunction, powerOffNotificationFunction, }; } deviceModel.subscriptionFunction(boundNotificationFunction, optionalCallbacks); } return deviceModel; } function startSdkAndRetryIfConnectionFailed( conf: Models.StartServerConfig, adapterName: string, requestHandler: RequestHandler, baseUrl: string, attemptCount = 1 ): Promise<void> { const { brain, brainport, maxConnectionAttempts } = conf; return brainDriver .start(conf, requestHandler) .then(() => Brain.start({ brain, brainport, baseUrl, adapterName })) .catch((error) => { debug('ERROR: Could not connect to NEEO Brain %o', { attemptCount, error: error.message, }); if (maxConnectionAttempts && attemptCount > maxConnectionAttempts) { debug('maximal retry exceeded, fail now..'); return BluePromise.reject(new Error('BRAIN_NOT_REACHABLE')); } return BluePromise.delay(attemptCount * 1000).then(() => startSdkAndRetryIfConnectionFailed( conf, adapterName, requestHandler, baseUrl, attemptCount + 1 ) ); }); } function validateBrainVersion(brain: string | Models.BrainModel, brainPort?: number) { const urlPrefix = buildBrainUrl(brain, undefined, brainPort); return axios.get(`${urlPrefix}/systeminfo`).then(({ data }) => { const brainVersion = data.firmwareVersion; checkVersionSatisfaction(brainVersion); }); } function checkVersionSatisfaction(brainVersion: string) { const { brainVersionSatisfaction } = config; const brainVersionSatisfied = satisfies(coerce(brainVersion)!, brainVersionSatisfaction); if (!brainVersionSatisfied) { throw new Error( `The Brain version must satisfy ${brainVersionSatisfaction}. Please make sure that the firmware is up-to-date.` ); } } function fetchDeviceSubscriptionsIfNeeded(devices: ReadonlyArray<Models.DeviceBuilder>) { const promises = devices.reduce( (output, device) => { const deviceHandlers = device.deviceSubscriptionHandlers; if (deviceHandlers) { debug('Initializing device subscriptions for %s', device.devicename); output.push( Brain.getSubscriptions(device.deviceidentifier).then(deviceHandlers.initializeDeviceList) ); } return output; }, [] as Array<Promise<any>> ); if (!promises.length) { return; } // do not wait until the subscription promises are finished Promise.all(promises).catch((error) => { debug('Initializing device subscriptions failed for at least one device', error.message); }); }
the_stack
import { ProgramState } from './model' import { Injectable } from '@angular/core' import * as SupplyChainAdapter from '../supply-chain-adapter' import * as Blockchain from 'blockchain-js-core' export type RsaKeyPair = { privateKey: string; publicKey: string; } export interface OnBlockchainMessage { id: string author: string message: string encrypted: boolean } export type SupplyChainBranchesItem = string /** * Application state */ @Injectable() export class State { IDENTITY_REGISTRY_CONTRACT_ID = "identity-registry-1" SUPPLY_CHAIN_CONTRACT_ID = "supply-chain-v1" //const RANDOM_GENERATOR_CONTRACT_ID = "random-generator-v1" logs: string[] = [] log(message) { this.logs.unshift(message) if (this.logs.length > 20) this.logs.pop() } user: { id: string keys: RsaKeyPair } = null get registeredPseudo() { return this.user && this.identities && this.identities[this.user.id] && this.identities[this.user.id].pseudo } masterHead = '' hasIdentityContract = false registeredOnIdentityContract = false hasSupplyChainAccount = false private registrationDone = false private async updateFlags() { this.hasIdentityContract = this.smartContract.hasContract(this.IDENTITY_REGISTRY_CONTRACT_ID) this.registeredOnIdentityContract = this.hasIdentityContract && (() => { let identityContractState = this.smartContract.getContractState(this.IDENTITY_REGISTRY_CONTRACT_ID) return identityContractState && !!identityContractState.identities[this.user.id] })() this.hasSupplyChainAccount = (() => { if (!this.user || !this.user.id) return false let supplyChainState = this.smartContract.getContractState(this.SUPPLY_CHAIN_CONTRACT_ID) if (!supplyChainState || !supplyChainState.accounts || !supplyChainState.accounts[this.user.id]) return false return true })() if (this.registrationDone && !(this.hasIdentityContract && this.registeredOnIdentityContract && this.hasSupplyChainAccount)) { this.registrationDone = false setTimeout(() => this.registerIdentity(), 1000) return } } setUserInformations(userId: string, keys: RsaKeyPair) { if (!userId || !keys) // TODO better check return if (this.user) throw `error user already set` this.user = { id: userId, keys } } fullNode: Blockchain.FullNode.FullNode = null state: { [branch: string]: { head: string headBlockMetadata: Blockchain.Block.BlockMetadata } } = { "master": { head: null, headBlockMetadata: null } } messageSequence: Blockchain.SequenceStorage.SequenceStorage<OnBlockchainMessage> supplyChainBranchSequence: Blockchain.SequenceStorage.SequenceStorage<SupplyChainBranchesItem> supplyChainBranches: string[] = [] smartContract: Blockchain.SmartContract.SmartContract = null suppyChain: SupplyChainAdapter.SupplyChainAdapter = new SupplyChainAdapter.SupplyChainAdapter() // a counter to know which components are loading something loaders = 0 isLoading() { return this.loaders > 0 || this.fullNode.transfer.isLoading() || this.smartContract.processing } init() { this.initFullNode() this.registerIdentity() } get branches() { return Object.keys(this.state) } programState: ProgramState = null identities: { [id: string]: { pseudo: string; publicKey: string } } = {} private messages = [] callContract = async (contractUuid, iterationId, method, account, data) => { if (this.smartContract.hasContract(contractUuid)) { data.id = account.id let callId = await this.smartContract.callContract(contractUuid, iterationId, method, account ? Blockchain.HashTools.signAndPackData(data, account.keys.privateKey) : data) return await waitReturn(this.smartContract, callId) } return false } supplyChainCall = async (method, account, data) => this.callContract(this.SUPPLY_CHAIN_CONTRACT_ID, 0, method, account, data) remoteMining: (branch: string, data: any) => Promise<boolean> = null miningRouter: Blockchain.MinerApi.MinerApi = { addData: async (branch: string, data: any) => { if (this.remoteMining) { try { let ok = await this.remoteMining(branch, data) if (ok) return } catch (error) { console.warn(`exception while remotely mining`, error) } } this.localMiner.addData(branch, data) } } private localMiner: Blockchain.MinerImpl.MinerImpl private initFullNode() { this.fullNode = new Blockchain.FullNode.FullNode(this.miningRouter) this.localMiner = new Blockchain.MinerImpl.MinerImpl(this.fullNode.node) this.fullNode.node.addEventListener('head', null, (event) => { //this.log(`new head on branch '${event.branch}': ${event.headBlockId.substr(0, 7)}`) if (event.branch == Blockchain.Block.MASTER_BRANCH) this.masterHead = event.headBlockId.substr(0, 7) this.loadState(event.branch, event.headBlockId) }) this.supplyChainBranchSequence = new Blockchain.SequenceStorage.SequenceStorage( this.fullNode.node, Blockchain.Block.MASTER_BRANCH, `supply-chain-branch-sequence`, this.fullNode.miner) this.supplyChainBranchSequence.initialise() this.supplyChainBranchSequence.addEventListener('change', (sequenceItemsByBlock) => { this.supplyChainBranches = [] for (let { blockId, items } of sequenceItemsByBlock) { items.forEach(item => { if (typeof item === 'string') this.supplyChainBranches.push(item) }) } }) this.messageSequence = new Blockchain.SequenceStorage.SequenceStorage( this.fullNode.node, Blockchain.Block.MASTER_BRANCH, `demo-chat-v1`, this.fullNode.miner) this.messageSequence.initialise() this.messageSequence.addEventListener('change', (sequenceItemsByBlock) => this.updateStatusFromSequence(sequenceItemsByBlock)) this.smartContract = new Blockchain.SmartContract.SmartContract(this.fullNode.node, Blockchain.Block.MASTER_BRANCH, 'people', this.fullNode.miner) this.smartContract.addChangeListener(() => { this.updateFlags() this.programState = this.suppyChain.getSuppyChainState() // JSON.parse(JSON.stringify(this.suppyChain.getSuppyChainState())) if (this.smartContract.hasContract(this.IDENTITY_REGISTRY_CONTRACT_ID)) { let identityContractState = this.smartContract.getContractState(this.IDENTITY_REGISTRY_CONTRACT_ID) if (identityContractState && identityContractState.identities) { this.identities = identityContractState.identities } } }) this.smartContract.initialise() this.suppyChain.setSmartContract(this.smartContract) } private updateStatusFromSequence(sequenceItemsByBlock: { blockId: string; items: Blockchain.SequenceStorage.SequenceItem<OnBlockchainMessage>[] }[]) { this.messages = [] for (let idx = 0; idx < sequenceItemsByBlock.length; idx++) { let { items } = sequenceItemsByBlock[idx] this.messages = this.messages.concat(items) } this.messages = this.messages.reverse() } private async loadState(branch: string, blockId: string) { if (this.state && this.state[branch] && this.state[branch].head == blockId) return let blockMetadatas = await this.fullNode.node.blockChainBlockMetadata(blockId, 1) let blockMetadata = blockMetadatas && blockMetadatas[0] this.state[branch] = { head: blockId, headBlockMetadata: blockMetadata } } private async registerIdentity() { this.updateFlags() let callLater = 1 if (this.isLoading()) { //console.log(`registerIdentity : wait loading finished`) } else if (!this.user) { //console.log(`registerIdentity : wait user presence`) } else if (!this.hasIdentityContract) { //console.log(`registerIdentity : wait identity contract`) } else if (!this.registeredOnIdentityContract) { //console.log(`registerIdentity : wait identity contract registration`) callLater = await this.registerIdentityImpl() } else if (!this.hasSupplyChainAccount) { //console.log(`registerIdentity : wait supply chain account`) callLater = await this.registerSupplyChainAccount() } else { this.log(`all done for identity registration`) this.registrationDone = true callLater = -1 } if (callLater >= 0) setTimeout(() => this.registerIdentity(), 1000 * callLater) } private async registerIdentityImpl(): Promise<number> { if (!this.user || !this.user.id || !this.user.keys) return 1 if (!this.hasIdentityContract) { this.log(`no identity registry contract installed (${this.IDENTITY_REGISTRY_CONTRACT_ID})`) return 1 } let identityContractState = this.smartContract.getContractState(this.IDENTITY_REGISTRY_CONTRACT_ID) if (!identityContractState) { this.log(`no identity contract state`) return 1 } if (this.registeredOnIdentityContract) { this.log(`identity already registered (${this.user.id})`) return 0 } console.log(`registering identity...`) let account = { keys: this.user.keys, id: this.user.id } if (! await this.callContract(this.IDENTITY_REGISTRY_CONTRACT_ID, 0, 'registerIdentity', account, {})) { this.log(`failed to register identity`) return 2 } console.log(`identity registered with id ${account.id}`) return 1 } private async registerSupplyChainAccount() { let account = { id: this.user.id, keys: this.user.keys } if (!this.hasSupplyChainAccount) { this.log(`registering account on supply chain...`) await this.suppyChain.createAccount(account) return 1 } else { this.log(`already registered on supplychain`) return 0 } } } async function waitReturn(smartContract, callId) { await waitUntil(() => smartContract.hasReturnValue(callId)) return smartContract.getReturnValue(callId) } async function waitUntil(condition: () => Promise<boolean>) { while (!await condition()) await wait(50) } function wait(duration: number) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), duration) }) }
the_stack
import * as React from 'react'; import styles from './SpupsProperySync.module.scss'; import * as strings from 'SpupsProperySyncWebPartStrings'; import { DisplayMode } from '@microsoft/sp-core-library'; import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle"; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker"; import { IPropertyFieldGroupOrPerson } from '@pnp/spfx-property-controls/lib/propertyFields/peoplePicker/IPropertyFieldPeoplePicker'; import { PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { FilePicker, IFilePickerResult } from '@pnp/spfx-controls-react/lib/FilePicker'; import { FileTypeIcon, IconType } from "@pnp/spfx-controls-react/lib/FileTypeIcon"; import { Pivot, PivotItem } from 'office-ui-fabric-react/lib/Pivot'; import { Spinner } from 'office-ui-fabric-react/lib/Spinner'; import { css, ProgressIndicator } from 'office-ui-fabric-react/lib'; import { IPropertyMappings, FileContentType, MessageScope, SyncType } from '../../../Common/IModel'; import { WebPartContext } from '@microsoft/sp-webpart-base'; import SPHelper from '../../../Common/SPHelper'; import PropertyMappingList from './PropertyMapping/PropertyMappingList'; import UPPropertyData from './UPPropertyData'; import ManualPropertyUpdate from './ManualPropertyUpdate'; import AzurePropertyView from './AzurePropertyView'; import SyncJobsView from './SyncJobs/SyncJobs'; import TemplatesView from './TemplatesList/TemplatesView'; import BulkSyncList from './BulkSyncFiles/BulkSyncList'; import * as moment from 'moment/moment'; import MessageContainer from './MessageContainer'; const map: any = require('lodash/map'); export interface ISpupsProperySyncProps { context: WebPartContext; templateLib: string; displayMode: DisplayMode; appTitle: string; AzFuncUrl: string; UseCert: boolean; dateFormat: string; allowedUsers: IPropertyFieldGroupOrPerson[]; useFullWidth: boolean; openPropertyPane: () => void; updateProperty: (value: string) => void; } export interface ISpupsProperySyncState { listExists: boolean; isSiteAdmin: boolean; loading: boolean; accessDenied: boolean; propertyMappings: IPropertyMappings[]; uploadedTemplate?: IFilePickerResult; uploadedFileURL?: string; showUploadData: boolean; showUploadProgress: boolean; showPropsLoader: boolean; updatePropsLoader_Manual: boolean; updatePropsLoader_Azure: boolean; updatePropsLoader_Bulk: boolean; clearData: boolean; disablePropsButtons: boolean; uploadedData?: any; isCSV: boolean; selectedUsers?: any[]; manualPropertyData: any[]; azurePropertyData: any[]; reloadGetProperties: boolean; helper: SPHelper; selectedMenu?: string; globalMessage: string; noActivePropertyMappings: boolean; } export default class SpupsProperySync extends React.Component<ISpupsProperySyncProps, ISpupsProperySyncState> { // Private variables private helper: SPHelper = null; /** * Constructor * @param props */ constructor(props: ISpupsProperySyncProps) { super(props); this.state = { listExists: false, isSiteAdmin: false, loading: true, accessDenied: false, propertyMappings: [], showUploadData: false, showUploadProgress: false, showPropsLoader: false, updatePropsLoader_Manual: false, updatePropsLoader_Azure: false, updatePropsLoader_Bulk: false, clearData: false, disablePropsButtons: false, isCSV: false, selectedUsers: [], manualPropertyData: [], azurePropertyData: [], reloadGetProperties: false, helper: null, selectedMenu: '0', globalMessage: '', noActivePropertyMappings: true }; } /** * Component mount */ public componentDidMount = async () => { this._useFullWidth(); this.initializeHelper(); let currentUserInfo = await this.helper.getCurrentUserInfo(); if (currentUserInfo.IsSiteAdmin) { this.setState({ isSiteAdmin: true }); this._checkAndCreateLists(); } else { let allowedGroups: string[] = map(this.props.allowedUsers, 'login'); let accessAllowed: boolean = this.helper.checkCurrentUserGroup(allowedGroups, currentUserInfo.Groups); console.log(accessAllowed); if (accessAllowed) { this._checkAndCreateLists(); } else { this.setState({ loading: false, accessDenied: true }); } } } /** * Component update */ public componentDidUpdate = (prevProps: ISpupsProperySyncProps) => { if (prevProps.templateLib !== this.props.templateLib) this.initializeHelper(); //if (prevProps.appTitle !== this.props.appTitle || prevProps.dateFormat !== this.props.dateFormat || this.props.allowedUsers) this.render(); if (prevProps.useFullWidth !== this.props.useFullWidth) this._useFullWidth(); } /** * Check and create the required list */ public _checkAndCreateLists = async () => { this.setState({ loading: false }); let listExists = await this.helper.checkAndCreateLists(); if (listExists) { let propertyMappings: IPropertyMappings[] = await this.helper.getPropertyMappings(); let globalMessage: string = ""; let noActivePropertyMappings: boolean = true; if (propertyMappings.length <= 0) { globalMessage = strings.EmptyPropertyMappings; noActivePropertyMappings = true; } else { globalMessage = ""; noActivePropertyMappings = false; } propertyMappings.map(prop => { prop.IsIncluded = true; }); this.setState({ listExists, propertyMappings, globalMessage, noActivePropertyMappings, disablePropsButtons: noActivePropertyMappings }); } } /** * Initialize the helper with required arguments. */ private initializeHelper = () => { this.helper = new SPHelper(this.props.context.pageContext.legacyPageContext.siteAbsoluteUrl, this.props.context.pageContext.legacyPageContext.tenantDisplayName, this.props.context.pageContext.legacyPageContext.webDomain, this.props.context.pageContext.web.serverRelativeUrl, this.props.templateLib ); this.setState({ helper: this.helper }); } /** * Use full width */ private _useFullWidth = () => { if (this.props.useFullWidth) { const jQuery: any = require('jquery'); jQuery("#workbenchPageContent").prop("style", "max-width: none"); jQuery(".SPCanvas-canvas").prop("style", "max-width: none"); jQuery(".CanvasZone").prop("style", "max-width: none"); } } /** * Triggers when the users are selected for manual update */ private _getPeoplePickerItems = (items: any[]) => { let reloadGetProperties: boolean = false; if (this.state.selectedUsers.length > items.length) { if (this.state.manualPropertyData.length > 0 || this.state.azurePropertyData.length > 0) { reloadGetProperties = true; } } this.setState({ selectedUsers: items, reloadGetProperties, clearData: false }, () => { if (this.state.selectedUsers.length <= 0) { this.state.manualPropertyData.length > 0 ? this._getManualPropertyTable() : this._getAzurePropertyTable(); } }); } /** * Set the defaultusers property for people picker control, this is used when clearing the data. */ private _getSelectedUsersLoginNames = (items: any[]): string[] => { let retUsers: string[] = []; retUsers = map(items, (o) => { return o.loginName.split('|')[2]; }); return retUsers; } /** * Display the inline editing table to edit the properties for manual update */ private _getManualPropertyTable = () => { this.setState({ disablePropsButtons: true, showPropsLoader: true }); const { propertyMappings, selectedUsers } = this.state; let includedProperties: IPropertyMappings[] = propertyMappings.filter((o) => { return o.IsIncluded; }); let manualPropertyData: any[] = []; if (selectedUsers && selectedUsers.length > 0) { selectedUsers.map(user => { let userObj = new Object(); userObj['UserID'] = user.loginName; userObj['DisplayName'] = user.text; userObj['ImageUrl'] = user.imageUrl; includedProperties.map((propsMap: IPropertyMappings) => { userObj[propsMap.SPProperty] = ""; }); manualPropertyData.push(userObj); }); this.setState({ manualPropertyData, azurePropertyData: [], showPropsLoader: false, disablePropsButtons: false }); } else { this.setState({ disablePropsButtons: false, showPropsLoader: false, manualPropertyData: [] }); } } /** * Get the property values from Azure */ private _getAzurePropertyTable = async () => { this.setState({ disablePropsButtons: true, showPropsLoader: true }); const { propertyMappings, selectedUsers } = this.state; let includedProperties: IPropertyMappings[] = propertyMappings.filter((o) => { return o.IsIncluded; }); let selectFields: string = "id, userPrincipalName, displayName, " + map(includedProperties, 'AzProperty').join(','); let tempQuery: string[] = []; let filterQuery: string = ``; if (selectedUsers && selectedUsers.length > 0) { selectedUsers.map(user => { tempQuery.push(`userPrincipalName eq '${user.loginName.split('|')[2]}'`); }); filterQuery = tempQuery.join(' or '); let azurePropertyData = await this.helper.getAzurePropertyForUsers(selectFields, filterQuery); this.setState({ azurePropertyData, manualPropertyData: [], showPropsLoader: false, disablePropsButtons: false }); } else { this.setState({ disablePropsButtons: false, showPropsLoader: false, azurePropertyData: [] }); } } /** * On selecting the data file for update */ private _onSaveTemplate = (uploadedTemplate: IFilePickerResult) => { this.setState({ uploadedTemplate, showUploadData: true, clearData: false }); } /** * On changing the data file for update */ private _onChangeTemplate = (uploadedTemplate: IFilePickerResult) => { this.setState({ uploadedTemplate, showUploadData: true, clearData: false }); } /** * Uploading data file and displaying the contents of the file */ private _uploadDataToSync = async () => { this.setState({ showUploadProgress: true }); const { uploadedTemplate } = this.state; let filecontent: any = null; if (uploadedTemplate && uploadedTemplate.fileName) { let ext: string = uploadedTemplate.fileName.split('.').pop(); let filename: string = `${uploadedTemplate.fileNameWithoutExtension}_${moment().format("MMDDYYYYHHmmss")}.${ext}`; if (uploadedTemplate.fileAbsoluteUrl && null !== uploadedTemplate.fileAbsoluteUrl) { let filerelativeurl: string = ""; if (uploadedTemplate.fileAbsoluteUrl.indexOf(this.props.context.pageContext.legacyPageContext.webAbsoluteUrl) >= 0) { filerelativeurl = uploadedTemplate.fileAbsoluteUrl.replace(this.props.context.pageContext.legacyPageContext.webAbsoluteUrl, this.props.context.pageContext.legacyPageContext.webServerRelativeUrl); } filecontent = await this.helper.getFileContent(filerelativeurl, FileContentType.Blob); await this.helper.addDataFilesToFolder(filecontent, filename); if (ext.toLocaleLowerCase() == "csv") { filecontent = await this.helper.getFileContent(filerelativeurl, FileContentType.Text); } else if (ext.toLocaleLowerCase() == "json") { filecontent = await this.helper.getFileContent(filerelativeurl, FileContentType.JSON); } this.setState({ showUploadProgress: false, uploadedData: filecontent, isCSV: ext.toLocaleLowerCase() == "csv" }); } else { let dataToSync = await uploadedTemplate.downloadFileContent(); let filereader = new FileReader(); filereader.readAsBinaryString(dataToSync); filereader.onload = async () => { let dataUploaded = await this.helper.addDataFilesToFolder(filereader.result, filename); if (ext.toLocaleLowerCase() == "csv") { filecontent = await dataUploaded.file.getText(); } else if (ext.toLocaleLowerCase() == "json") { filecontent = await dataUploaded.file.getJSON(); } this.setState({ showUploadProgress: false, uploadedData: filecontent, isCSV: ext.toLocaleLowerCase() == "csv" }); }; } } } /** * Update with manual properties */ private _updateSPWithManualProperties = async (data: any[]) => { this.setState({ updatePropsLoader_Manual: true }); let itemID = await this.helper.createSyncItem(SyncType.Manual); let finalJson = this._prepareJSONForAzFunc(data, false, itemID); await this.helper.updateSyncItem(itemID, finalJson); this.helper.runAzFunction(this.props.context.httpClient, finalJson, this.props.AzFuncUrl, itemID); this.setState({ updatePropsLoader_Manual: false, clearData: true, selectedUsers: [], manualPropertyData: [] }); } /** * Update with azure properties */ private _updateSPWithAzureProperties = async (data: any[]) => { this.setState({ updatePropsLoader_Azure: true }); let itemID = await this.helper.createSyncItem(SyncType.Azure); let finalJson = this._prepareJSONForAzFunc(data, true, itemID); await this.helper.updateSyncItem(itemID, finalJson); this.helper.runAzFunction(this.props.context.httpClient, finalJson, this.props.AzFuncUrl, itemID); this.setState({ updatePropsLoader_Azure: false, clearData: true, selectedUsers: [], azurePropertyData: [] }); } /** * Update with csv or json file */ private _updateSPForBulkUsers = async (data: any[]) => { this.setState({ updatePropsLoader_Bulk: true }); let itemID = await this.helper.createSyncItem(SyncType.Template); let finalJson = this._prepareJSONForAzFunc(data, false, itemID); await this.helper.updateSyncItem(itemID, finalJson); this.helper.runAzFunction(this.props.context.httpClient, finalJson, this.props.AzFuncUrl, itemID); this.setState({ updatePropsLoader_Bulk: false, clearData: true, uploadedData: null, uploadedTemplate: null, uploadedFileURL: '', showUploadData: false }); } /** * Prepare JSON based on the manual or az data to call AZ FUNC. */ private _prepareJSONForAzFunc = (data: any[], isAzure: boolean, itemid: number): string => { let finalJson: string = ""; if (data && data.length > 0) { let userPropMapping = new Object(); userPropMapping['targetSiteUrl'] = this.props.context.pageContext.legacyPageContext.webAbsoluteUrl; userPropMapping['targetAdminUrl'] = `https://${this.props.context.pageContext.legacyPageContext.tenantDisplayName}-admin.${this.props.context.pageContext.legacyPageContext.webDomain}`; userPropMapping['usecert'] = this.props.UseCert ? this.props.UseCert : false; userPropMapping['itemId'] = itemid; let propValues: any[] = []; data.map((userprop: any) => { let userPropValue: any = {}; let userProperties: any[] = []; let userPropertiesKeys: string[] = Object.keys(userprop); userPropertiesKeys.map((prop: string) => { if (isAzure && prop.toLowerCase() == "userprincipalname") { userPropValue['userid'] = userprop[prop].indexOf('|') > 0 ? userprop[prop].split('|')[2] : userprop[prop]; } if (!isAzure && prop.toLowerCase() == "userid") { userPropValue['userid'] = userprop[prop].indexOf('|') > 0 ? userprop[prop].split('|')[2] : userprop[prop]; } if (prop.toLowerCase() !== "userid" && prop.toLowerCase() !== "id" && prop.toLowerCase() !== "displayname" && prop.toLowerCase() !== "userprincipalname" && prop.toLowerCase() !== "imageurl") { let objProp = new Object(); objProp['name'] = isAzure ? this._getSPPropertyName(prop) : prop; objProp['value'] = userprop[prop]; userProperties.push(JSON.parse(JSON.stringify(objProp))); } }); userPropValue['properties'] = JSON.parse(JSON.stringify(userProperties)); propValues.push(JSON.parse(JSON.stringify(userPropValue))); }); userPropMapping['value'] = propValues; finalJson = JSON.stringify(userPropMapping); } return finalJson; } /** * Get SPProperty name for Azure Property */ private _getSPPropertyName = (azPropName: string): string => { return this.state.propertyMappings.filter((o) => { return o.AzProperty.toLowerCase() === azPropName.toLowerCase(); })[0].SPProperty; } /** * On menu click */ private _onMenuClick = (item?: PivotItem, ev?: React.MouseEvent<HTMLElement, MouseEvent>): void => { if (item) { if (item.props.itemKey == "0") { this.setState({ updatePropsLoader_Manual: false, updatePropsLoader_Azure: false, clearData: false, selectedUsers: [], manualPropertyData: [], azurePropertyData: [] }); } else if (item.props.itemKey == "1") { this.setState({ uploadedData: null, uploadedTemplate: null, uploadedFileURL: '', showUploadData: false }); } this.setState({ selectedMenu: item.props.itemKey }, () => { }); } } /** * Component render */ public render(): React.ReactElement<ISpupsProperySyncProps> { const { templateLib, displayMode, appTitle, AzFuncUrl } = this.props; const { propertyMappings, uploadedTemplate, uploadedFileURL, showUploadData, showUploadProgress, uploadedData, isCSV, selectedUsers, manualPropertyData, azurePropertyData, disablePropsButtons, showPropsLoader, reloadGetProperties, selectedMenu, updatePropsLoader_Manual, updatePropsLoader_Azure, updatePropsLoader_Bulk, clearData, globalMessage, noActivePropertyMappings, listExists, isSiteAdmin, loading, accessDenied } = this.state; const fileurl = uploadedFileURL ? uploadedFileURL : uploadedTemplate && uploadedTemplate.fileAbsoluteUrl ? uploadedTemplate.fileAbsoluteUrl : uploadedTemplate && uploadedTemplate.fileName ? uploadedTemplate.fileName : ''; const showConfig = !templateLib || !AzFuncUrl ? true : false; const headerButtonProps = { 'disabled': showUploadProgress || updatePropsLoader_Manual || updatePropsLoader_Azure || updatePropsLoader_Bulk }; return ( <div className={styles.spupsProperySync}> <div className={styles.container}> <div className={styles.row}> <div className={styles.column}> <WebPartTitle displayMode={displayMode} title={appTitle ? appTitle : strings.DefaultAppTitle} updateProperty={this.props.updateProperty} /> {showConfig ? ( <> {isSiteAdmin ? ( <Placeholder iconName='DataManagementSettings' iconText={strings.PlaceholderIconText} description={strings.PlaceholderDescription} buttonLabel={strings.PlaceholderButtonLabel} hideButton={displayMode === DisplayMode.Read} onConfigure={this.props.openPropertyPane} /> ) : ( <> {loading && <ProgressIndicator label={strings.SitePrivilegeCheckLabel} description={strings.PropsLoader} /> } {!loading && <MessageContainer MessageScope={MessageScope.SevereWarning} Message={strings.AdminConfigHelp} /> } </> )} </> ) : ( <> {loading ? ( <ProgressIndicator label={strings.AccessCheckDesc} description={strings.PropsLoader} /> ) : ( <> {accessDenied ? ( <MessageContainer MessageScope={MessageScope.SevereWarning} Message={strings.AccessDenied} /> ) : ( <> {!listExists ? ( <ProgressIndicator label={strings.ListCreationText} description={strings.PropsLoader} /> ) : ( <> <div> {globalMessage.length > 0 && <div style={{ marginTop: '10px', marginBottom: '10px' }}> <MessageContainer MessageScope={MessageScope.Failure} Message={globalMessage} /> </div> } <Pivot defaultSelectedKey="0" selectedKey={selectedMenu} onLinkClick={this._onMenuClick} className={styles.periodmenu}> <PivotItem headerText={strings.TabMenu1} itemKey="0" itemIcon="SchoolDataSyncLogo" headerButtonProps={headerButtonProps} ></PivotItem> <PivotItem headerText={strings.TabMenu2} itemKey="1" itemIcon="BulkUpload" headerButtonProps={headerButtonProps}></PivotItem> <PivotItem headerText={strings.TabMenu3} itemKey="2" itemIcon="StackIndicator" headerButtonProps={headerButtonProps}></PivotItem> <PivotItem headerText={strings.TabMenu4} itemKey="3" itemIcon="FileTemplate" headerButtonProps={headerButtonProps}></PivotItem> <PivotItem headerText={strings.TabMenu5} itemKey="4" itemIcon="SyncStatus" headerButtonProps={headerButtonProps}></PivotItem> </Pivot> <div style={{ float: "right" }}> <PropertyMappingList mappingProperties={propertyMappings} helper={this.state.helper} siteurl={this.props.context.pageContext.web.serverRelativeUrl} disabled={showUploadProgress || updatePropsLoader_Manual || updatePropsLoader_Azure || updatePropsLoader_Bulk || noActivePropertyMappings} /> </div> </div> {selectedMenu == "0" && <div className={css(styles.menuContent)}> <PeoplePicker disabled={disablePropsButtons || updatePropsLoader_Manual || updatePropsLoader_Azure} context={this.props.context} titleText={strings.PPLPickerTitleText} personSelectionLimit={10} groupName={""} // Leave this blank in case you want to filter from all users showtooltip={false} isRequired={false} selectedItems={this._getPeoplePickerItems} showHiddenInUI={false} principalTypes={[PrincipalType.User]} resolveDelay={500} defaultSelectedUsers={selectedUsers.length > 0 ? this._getSelectedUsersLoginNames(selectedUsers) : []} /> {reloadGetProperties ? ( <> {selectedUsers.length > 0 && <div> <MessageContainer MessageScope={MessageScope.Info} Message={strings.UserListChanges} /> </div> } {selectedUsers.length <= 0 && !clearData && <div> <MessageContainer MessageScope={MessageScope.Info} Message={strings.UserListEmpty} ShowDismiss={true} /> </div> } </> ) : ( <></> ) } {selectedUsers && selectedUsers.length > 0 && <div style={{ marginTop: "5px" }}> <PrimaryButton text={strings.BtnManualProps} onClick={this._getManualPropertyTable} style={{ marginRight: '5px' }} disabled={disablePropsButtons || updatePropsLoader_Manual || updatePropsLoader_Azure} /> <PrimaryButton text={strings.BtnAzureProps} onClick={this._getAzurePropertyTable} disabled={disablePropsButtons || updatePropsLoader_Manual || updatePropsLoader_Azure} /> {showPropsLoader && <Spinner className={styles.generateTemplateLoader} label={strings.PropsLoader} ariaLive="assertive" labelPosition="right" />} </div> } {manualPropertyData && manualPropertyData.length > 0 && <ManualPropertyUpdate userProperties={manualPropertyData} UpdateSPUserWithManualProps={this._updateSPWithManualProperties} showProgress={updatePropsLoader_Manual} /> } {azurePropertyData && azurePropertyData.length > 0 && <AzurePropertyView userProperties={azurePropertyData} UpdateSPUserWithAzureProps={this._updateSPWithAzureProperties} showProgress={updatePropsLoader_Azure} /> } {clearData && <div><MessageContainer MessageScope={MessageScope.Success} Message={strings.JobIntializedSuccess} /></div> } </div> } {selectedMenu == "1" && <div className={css(styles.menuContent)}> <div> <FilePicker accepts={[".json", ".csv"]} buttonIcon="FileImage" onSave={this._onSaveTemplate} onChanged={this._onChangeTemplate} context={this.props.context} disabled={showUploadProgress || updatePropsLoader_Bulk || noActivePropertyMappings} buttonLabel={"Select Data file"} hideLinkUploadTab={true} hideOrganisationalAssetTab={true} hideWebSearchTab={true} /> </div> {fileurl && <div style={{ color: "black", padding: '10px' }}> <FileTypeIcon type={IconType.font} path={fileurl} />&nbsp;{uploadedTemplate.fileName} </div> } {showUploadData && <div style={{ padding: '10px', width: 'auto', display: 'inline-block' }}> <PrimaryButton text={strings.BtnUploadDataForSync} onClick={this._uploadDataToSync} disabled={showUploadProgress || updatePropsLoader_Bulk} /> {showUploadProgress && <div style={{ paddingLeft: '10px', display: 'inline-block' }}><Spinner className={styles.generateTemplateLoader} label={strings.UploadDataToSyncLoader} ariaLive="assertive" labelPosition="right" /></div> } </div> } <UPPropertyData items={uploadedData} isCSV={isCSV} UpdateSPForBulkUsers={this._updateSPForBulkUsers} showProgress={updatePropsLoader_Bulk} clearData={clearData} /> {clearData && <div><MessageContainer MessageScope={MessageScope.Success} Message={strings.JobIntializedSuccess} /></div> } </div> } {selectedMenu == "2" && <div className={css(styles.menuContent)}> <BulkSyncList helper={this.state.helper} siteurl={this.props.context.pageContext.web.serverRelativeUrl} dateFormat={this.props.dateFormat} /> </div> } {selectedMenu == "3" && <div className={css(styles.menuContent)}> <TemplatesView helper={this.state.helper} siteurl={this.props.context.pageContext.web.serverRelativeUrl} dateFormat={this.props.dateFormat} /> </div> } {selectedMenu == "4" && <div className={css(styles.menuContent)}> <SyncJobsView helper={this.state.helper} dateFormat={this.props.dateFormat} /> </div> } </> )} </> )} </> )} </> )} </div> </div> </div> </div> ); } }
the_stack
import { app, BrowserWindow, ipcMain } from 'electron'; import process = require('process'); import path = require('path'); import child_process = require('child_process'); import { AppMenu, LocaleString } from './appMenus'; import { isLinux } from '../utils/platform'; import { WindowSettings } from './windowSettings'; declare const ENV: { [key: string]: string | boolean | number | Record<string, unknown> }; const ENV_E2E = !!process.env.E2E; const HTML_PATH = `${__dirname}/index.html`; // allow non-content-aware native modules, needed for drivelist // see: https://github.com/balena-io-modules/drivelist/issues/373 app.allowRendererProcessReuse = false; const ElectronApp = { mainWindow: null as Electron.BrowserWindow, devWindow: null as Electron.BrowserWindow, appMenu: null as AppMenu, cleanupCounter: 0, forceExit: false, /** * Listen to Electron app events */ init(): void { app.on('ready', () => this.onReady()); // prevent app from exiting at first request: the user may attempt to exit the app // while transfers are in progress so we first send a request to the frontend // if no transfers are in progress, exit confirmation is received which makes the app close app.on('before-quit', (e) => { // TODO: detect interrupt console.log('before quit'); if (!this.forceExit) { console.log('no forceExit, sending exitRequest to renderer'); e.preventDefault(); this.mainWindow.webContents.send('exitRequest'); } else { console.log('forceExit is true, calling cleanupAndExit'); this.cleanupAndExit(); } }); app.on('activate', (e) => { if (this.mainWindow) { this.mainWindow.restore(); } }); // when interrupt is received we have to force exit process.on('SIGINT', function () { console.log('*** BREAK'); this.forceExit = true; }); }, /** * Create React-Explorer main window and: * - load entry html file * - bind close/minimize events * - create main menu */ createMainWindow(): void { console.log('Create Main Window'); const settings = WindowSettings.getSettings(0); // console.log('settings', settings); this.mainWindow = new BrowserWindow({ minWidth: WindowSettings.DEFAULTS.minWidth, minHeight: WindowSettings.DEFAULTS.minHeight, width: settings.width, height: settings.height, x: settings.x, y: settings.y, webPreferences: { nodeIntegration: true, enableRemoteModule: true, }, icon: (isLinux && path.join(__dirname, 'icon.png')) || undefined, }); settings.manage(this.mainWindow); if (!settings.custom) { settings.custom = { splitView: false, }; } console.log(settings.custom); this.mainWindow.initialSettings = settings.custom; // this.mainWindow.loadURL(HTML_PATH); this.mainWindow.loadFile(HTML_PATH); // this.mainWindow.on('close', () => app.quit()); // Prevent the window from closing in case transfers are in progress this.mainWindow.on('close', (e: Event) => { console.log('on:close'); if (!this.forceExit) { console.log('exit request and no force: sending back exitRequest'); e.preventDefault(); this.mainWindow.webContents.send('exitRequest'); } else { console.log('forceExit: let go exit event'); } }); this.mainWindow.on('minimize', () => { this.mainWindow.minimize(); }); // this.mainWindpw.on('page-title-updated', (e: Event) => { // e.preventDefault(); // }); this.appMenu = new AppMenu(this.mainWindow); }, /** * Install special React DevTools */ installReactDevTools(): void { console.log('Install React DevTools'); // eslint-disable-next-line @typescript-eslint/no-var-requires const { default: installExtension, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer'); installExtension(REACT_DEVELOPER_TOOLS) .then((name: string) => console.log(`Added Extension: ${name}`)) .catch((err: Error) => console.log('An error occurred: ', err)); }, /** * Install recursive file watcher to reload the app on fs change events * Note that this probably won't work correctly under Linux since fs.watch * doesn't support recrusive watch on this OS. */ // installWatcher(): void { // if (!ENV_E2E && !isPackage) { // console.log('Install Code Change Watcher'); // watch(SOURCE_PATH, { recursive: true }, () => this.reloadApp()); // } // }, /** * Clears the session cache and reloads main window without cache */ reloadApp(): void { const mainWindow = this.mainWindow; if (mainWindow) { mainWindow.webContents.session.clearCache(() => { mainWindow.webContents.reloadIgnoringCache(); }); } }, /** * Install listeners to handle messages coming from the renderer process: * * - reloadIgnoringCache: need to reload the main window (dev only) * - exit: wants to exit the app * - openTerminal(cmd): should open a new terminal process using specified cmd line * - languageChanged(strings): language has been changed so menus need to be updated * - selectAll: wants to generate a selectAll event */ installIpcMainListeners() { console.log('Install ipcMain Listeners'); ipcMain.on('reloadIgnoringCache', () => this.reloadApp()); ipcMain.handle('readyToExit', () => { console.log('readyToExit'); this.cleanupAndExit(); }); ipcMain.handle('openDevTools', () => { console.log('should open dev tools'); this.openDevTools(true); }); ipcMain.handle( 'openTerminal', (event: Event, cmd: string): Promise<{ code: number; terminal: string }> => { console.log('running', cmd); const exec = child_process.exec; return new Promise((resolve) => { exec(cmd, (error: child_process.ExecException) => { if (error) { resolve({ code: error.code, terminal: cmd }); } else { resolve(); } }).unref(); }); }, ); ipcMain.handle('languageChanged', (e: Event, strings: LocaleString, lang: string) => { if (this.appMenu) { this.appMenu.createMenu(strings, lang); } else { console.log('languageChanged but app not ready :('); } }); ipcMain.handle('selectAll', () => { if (this.mainWindow) { this.mainWindow.webContents.selectAll(); } }); ipcMain.handle('needsCleanup', () => { console.log('needscleanup'); this.cleanupCounter++; console.log('needscleanup, counter now:', this.cleanupCounter); }); ipcMain.handle('cleanedUp', () => this.onCleanUp()); // eslint-disable-next-line @typescript-eslint/no-explicit-any ipcMain.handle('setWindowSettings', (_: Event, data: { [key: string]: any }) => { console.log('changeWindowSettings', data); const { id, settings } = data; const state = WindowSettings.getSettings(id); console.log('got state', state); state.custom = settings; }); }, /** * Called when the app is ready to exit: this will send cleanup event to renderer process * */ cleanupAndExit(): void { console.log('cleanupAndExit'); if (this.cleanupCounter) { console.log('cleanupCounter non zero', this.cleanupCounter); this.mainWindow.webContents.send('cleanup'); } else { console.log('cleanupCount zero: exit'); app.exit(); } }, onCleanUp(): void { this.cleanupCounter--; // exit app if everything has been cleaned up // otherwise do nothing and wait for cleanup console.log('onCleanUp, counter now', this.cleanupCounter); if (!this.cleanupCounter) { console.log('cleanupCounter equals to zero, calling app.exit()'); app.exit(); } else { console.log('cleanupCounter non zero, cancel exit', this.cleanupCounter); } }, /** * Open the dev tools window */ openDevTools(force = false): void { // spectron problem if devtools is opened, see https://github.com/electron/spectron/issues/254 if ((!ENV_E2E && ENV.NODE_ENV) !== 'production' || force) { if (!this.devWindow || this.devWindow.isDestroyed()) { const winState = WindowSettings.getDevToolsSettings(); this.devWindow = new BrowserWindow({ width: winState.width, height: winState.height, x: winState.x, y: winState.y, }); winState.manage(this.devWindow); this.mainWindow.webContents.setDevToolsWebContents(this.devWindow.webContents); this.mainWindow.webContents.openDevTools({ mode: 'detach' }); } else { if (this.devWindow.isMinimized()) { this.devWindow.restore(); } else { this.devWindow.focus(); } } } }, /** * app.ready callback: that's the app's main entry point */ onReady(): void { console.log('App Ready'); // react-devtools doesn't work properly with file:// scheme, starting with Electron 9 // see: https://github.com/electron/electron/issues/24011 & // https://github.com/electron/electron/pull/25151 // if (!ENV_E2E && !isPackage) { // this.installReactDevTools(); // } this.installIpcMainListeners(); this.createMainWindow(); this.openDevTools(); }, }; console.log(`Electron Version ${app.getVersion()}`); ElectronApp.init();
the_stack
import { QueryQueue } from '../../src/orchestrator/QueryQueue'; export const QueryQueueTest = (name: string, options?: any) => { describe(`QueryQueue${name}`, () => { let delayCount = 0; const delayFn = (result, delay) => new Promise(resolve => setTimeout(() => resolve(result), delay)); let cancelledQuery; const queue = new QueryQueue('test_query_queue', { queryHandlers: { foo: async (query) => `${query[0]} bar`, delay: async (query, setCancelHandler) => { const result = query.result + delayCount; delayCount += 1; await setCancelHandler(result); return delayFn(result, query.delay); } }, cancelHandlers: { delay: (query) => { console.log(`cancel call: ${JSON.stringify(query)}`); cancelledQuery = query.queryKey; } }, continueWaitTimeout: 1, executionTimeout: 2, orphanedTimeout: 2, concurrency: 1, ...options }); afterAll(async () => { await options.redisPool.cleanup(); }); test('gutter', async () => { const query = ['select * from']; const result = await queue.executeInQueue('foo', query, query); expect(result).toBe('select * from bar'); }); test('instant double wait resolve', async () => { const results = await Promise.all([ queue.executeInQueue('delay', 'instant', { delay: 400, result: '2' }), queue.executeInQueue('delay', 'instant', { delay: 400, result: '2' }) ]); expect(results).toStrictEqual(['20', '20']); }); test('priority', async () => { delayCount = 0; const result = await Promise.all([ queue.executeInQueue('delay', '11', { delay: 600, result: '1' }, 1), queue.executeInQueue('delay', '12', { delay: 100, result: '2' }, 0), queue.executeInQueue('delay', '13', { delay: 100, result: '3' }, 10) ]); expect(parseInt(result.find(f => f[0] === '3'), 10) % 10).toBeLessThan(2); }); test('timeout', async () => { delayCount = 0; const query = ['select * from 2']; let errorString = ''; for (let i = 0; i < 5; i++) { try { await queue.executeInQueue('delay', query, { delay: 3000, result: '1' }); console.log(`Delay ${i}`); } catch (e) { if (e.message === 'Continue wait') { // eslint-disable-next-line no-continue continue; } errorString = e.toString(); break; } } expect(errorString).toEqual(expect.stringContaining('timeout')); }); test('stage reporting', async () => { delayCount = 0; const resultPromise = queue.executeInQueue('delay', '1', { delay: 200, result: '1' }, 0, { stageQueryKey: '1' }); await delayFn(null, 50); expect((await queue.getQueryStage('1')).stage).toBe('Executing query'); await resultPromise; expect(await queue.getQueryStage('1')).toEqual(undefined); }); test('priority stage reporting', async () => { delayCount = 0; const resultPromise = queue.executeInQueue('delay', '31', { delay: 200, result: '1' }, 20, { stageQueryKey: '12' }); await delayFn(null, 50); const resultPromise2 = queue.executeInQueue('delay', '32', { delay: 200, result: '1' }, 10, { stageQueryKey: '12' }); await delayFn(null, 50); expect((await queue.getQueryStage('12', 10)).stage).toBe('#1 in queue'); await resultPromise; await resultPromise2; expect(await queue.getQueryStage('12')).toEqual(undefined); }); test('negative priority', async () => { delayCount = 0; const results = []; await Promise.all([ queue.executeInQueue('delay', '31', { delay: 400, result: '4' }, -10).then(r => results.push(r)), queue.executeInQueue('delay', '32', { delay: 100, result: '3' }, -9).then(r => results.push(r)), queue.executeInQueue('delay', '33', { delay: 100, result: '2' }, -8).then(r => results.push(r)), queue.executeInQueue('delay', '34', { delay: 100, result: '1' }, -7).then(r => results.push(r)) ]); results.splice(0, 1); expect(results.map(r => parseInt(r[0], 10) - parseInt(results[0][0], 10))).toEqual([0, 1, 2]); }); test('orphaned', async () => { for (let i = 1; i <= 4; i++) { await queue.executeInQueue('delay', `11${i}`, { delay: 50, result: `${i}` }, 0); } cancelledQuery = null; delayCount = 0; let result = queue.executeInQueue('delay', '111', { delay: 800, result: '1' }, 0); delayFn(null, 50).then(() => queue.executeInQueue('delay', '112', { delay: 800, result: '2' }, 0)).catch(e => e); delayFn(null, 60).then(() => queue.executeInQueue('delay', '113', { delay: 500, result: '3' }, 0)).catch(e => e); delayFn(null, 70).then(() => queue.executeInQueue('delay', '114', { delay: 900, result: '4' }, 0)).catch(e => e); expect(await result).toBe('10'); await queue.executeInQueue('delay', '112', { delay: 800, result: '2' }, 0); result = await queue.executeInQueue('delay', '113', { delay: 900, result: '3' }, 0); expect(result).toBe('32'); await delayFn(null, 200); expect(cancelledQuery).toBe('114'); await queue.executeInQueue('delay', '114', { delay: 50, result: '4' }, 0); }); test('removed before reconciled', async () => { const query = ['select * from']; await queue.processQuery(query); const result = await queue.executeInQueue('foo', query, query); expect(result).toBe('select * from bar'); }); test('queue driver lock obtain race condition', async () => { const redisClient: any = await queue.queueDriver.createConnection(); const redisClient2: any = await queue.queueDriver.createConnection(); const priority = 10; const time = new Date().getTime(); const keyScore = time + (10000 - priority) * 1E14; // console.log(await redisClient.getQueryAndRemove('race')); // console.log(await redisClient.getQueryAndRemove('race1')); if (redisClient.redisClient) { await redisClient2.redisClient.setAsync(redisClient.queryProcessingLockKey('race'), '100'); await redisClient.redisClient.watchAsync(redisClient.queryProcessingLockKey('race')); await redisClient2.redisClient.setAsync(redisClient.queryProcessingLockKey('race'), Math.random()); const res = await redisClient.redisClient.multi() .set(redisClient.queryProcessingLockKey('race'), '100') .set(redisClient.queryProcessingLockKey('race1'), '100') .execAsync(); expect(res).toBe(null); await redisClient.redisClient.delAsync(redisClient.queryProcessingLockKey('race')); await redisClient.redisClient.delAsync(redisClient.queryProcessingLockKey('race1')); } await queue.reconcileQueue(); await redisClient.addToQueue( keyScore, 'race', time, 'handler', ['select'], priority, { stageQueryKey: 'race' } ); await redisClient.addToQueue( keyScore + 100, 'race2', time + 100, 'handler2', ['select2'], priority, { stageQueryKey: 'race2' } ); const processingId1 = await redisClient.getNextProcessingId(); const processingId4 = await redisClient.getNextProcessingId(); await redisClient.freeProcessingLock('race', processingId1, true); await redisClient.freeProcessingLock('race2', processingId4, true); await redisClient2.retrieveForProcessing('race2', await redisClient.getNextProcessingId()); const processingId = await redisClient.getNextProcessingId(); const retrieve6 = await redisClient.retrieveForProcessing('race', processingId); console.log(retrieve6); expect(!!retrieve6[5]).toBe(true); console.log(await redisClient.getQueryAndRemove('race')); console.log(await redisClient.getQueryAndRemove('race2')); await queue.queueDriver.release(redisClient); await queue.queueDriver.release(redisClient2); }); test('activated but lock is not acquired', async () => { const redisClient = await queue.queueDriver.createConnection(); const redisClient2 = await queue.queueDriver.createConnection(); const priority = 10; const time = new Date().getTime(); const keyScore = time + (10000 - priority) * 1E14; await queue.reconcileQueue(); await redisClient.addToQueue( keyScore, 'activated1', time, 'handler', ['select'], priority, { stageQueryKey: 'race' } ); await redisClient.addToQueue( keyScore + 100, 'activated2', time + 100, 'handler2', ['select2'], priority, { stageQueryKey: 'race2' } ); const processingId1 = await redisClient.getNextProcessingId(); const processingId2 = await redisClient.getNextProcessingId(); const processingId3 = await redisClient.getNextProcessingId(); const retrieve1 = await redisClient.retrieveForProcessing('activated1', processingId1); console.log(retrieve1); const retrieve2 = await redisClient2.retrieveForProcessing('activated2', processingId2); console.log(retrieve2); console.log(await redisClient.freeProcessingLock('activated1', processingId1, retrieve1 && retrieve1[2].indexOf('activated1') !== -1)); const retrieve3 = await redisClient.retrieveForProcessing('activated2', processingId3); console.log(retrieve3); console.log(await redisClient.freeProcessingLock('activated2', processingId3, retrieve3 && retrieve3[2].indexOf('activated2') !== -1)); console.log(retrieve2[2].indexOf('activated2') !== -1); console.log(await redisClient2.freeProcessingLock('activated2', processingId2, retrieve2 && retrieve2[2].indexOf('activated2') !== -1)); const retrieve4 = await redisClient.retrieveForProcessing('activated2', await redisClient.getNextProcessingId()); console.log(retrieve4); expect(retrieve4[0]).toBe(1); expect(!!retrieve4[5]).toBe(true); console.log(await redisClient.getQueryAndRemove('activated1')); console.log(await redisClient.getQueryAndRemove('activated2')); await queue.queueDriver.release(redisClient); await queue.queueDriver.release(redisClient2); }); }); };
the_stack
import { GraphicsIR, IDiagramArtist, Group, Text, mat3, safeAssign, Point, calculateTextDimensions, getPointAt, Rect, PathCommand, } from '@pintora/core' import { ErDiagramIR, Identification, Entity, Relationship } from './db' import { ErConf, getConf } from './config' import { createLayoutGraph, getGraphBounds, LayoutGraph, LayoutNode } from '../util/graph' import { makeMark, getBaseText, calcDirection, makeLabelBg } from '../util/artist-util' import dagre from '@pintora/dagre' import { drawMarkerTo } from './artist-util' import { getPointsCurvePath, getPointsLinearPath } from '../util/line-util' let conf: ErConf const erArtist: IDiagramArtist<ErDiagramIR, ErConf> = { draw(ir, config) { conf = getConf(ir.styleParams) // Now we have to construct the diagram in a specific way: // --- // 1. Create all the entities in the svg node at 0,0, but with the correct dimensions (allowing for text content) // 2. Make sure they are all added to the graph // 3. Add all the edges (relationships) to the graph aswell // 4. Let dagre do its magic to layout the graph. This assigns: // - the centre co-ordinates for each node, bearing in mind the dimensions and edge relationships // - the path co-ordinates for each edge // But it has no impact on the svg child nodes - the diagram remains with every entity rooted at 0,0 // 5. Now assign a transform to each entity in the svg node so that it gets drawn in the correct place, as determined by // its centre point, which is obtained from the graph, and it's width and height // 6. And finally, create all the edges in the svg node using information from the graph // --- const rootMark: Group = { type: 'group', attrs: {}, children: [], } const g = createLayoutGraph({ multigraph: true, directed: true, compound: false, }) .setGraph({ rankdir: conf.layoutDirection, nodesep: 80, edgesep: 80, ranksep: 100, }) .setDefaultEdgeLabel(function () { return {} }) drawEntities(rootMark, ir, g) // Add all the relationships to the graph const relationships = addRelationships(ir.relationships, g) dagre.layout(g, {}) // Adjust the positions of the entities so that they adhere to the layout adjustEntities(g) const relationsGroup: Group = { type: 'group', children: [], class: 'er__relations', } // Draw the relationships relationships.forEach(function (rel) { drawRelationshipFromLayout(relationsGroup, rel, g) }) rootMark.children.unshift(relationsGroup) const gBounds = getGraphBounds(g) // console.log('bounds', gBounds) const pad = conf.diagramPadding rootMark.matrix = mat3.fromTranslation(mat3.create(), [ -Math.min(0, gBounds.left) + pad, -Math.min(0, gBounds.top) + pad, ]) const width = gBounds.width + pad * 2 const height = gBounds.height + pad * 2 return { mark: rootMark, width, height, } as GraphicsIR }, } type AttributePair = { type: Text name: Text key?: Text } /** * Draw attributes for an entity * @param groupNode the svg group node for the entity * @param entityTextNode the svg node for the entity label text * @param attributes an array of attributes defined for the entity (each attribute has a type and a name) * @return the bounding box of the entity, after attributes have been added */ const drawAttributes = (group: Group, entityText: Text, attributes: Entity['attributes']) => { const attribPaddingY = conf.entityPaddingY / 2 // Padding internal to attribute boxes const attribPaddingX = conf.entityPaddingX / 2 // Ditto const attrFontSize = conf.fontSize * 0.85 const labelBBox = entityText.attrs const attributeNodes: AttributePair[] = [] // Intermediate storage for attribute nodes created so that we can do a second pass let maxTypeWidth = 0 let maxNameWidth = 0 let maxKeyWidth = 0 let cumulativeHeight = labelBBox.height + attribPaddingY * 2 let attrNum = 1 const hasKeyAttribute = attributes.some(item => Boolean(item.attributeKey)) const attributeGroup = makeMark('group', {}, { children: [] }) group.children.push(attributeGroup) attributes.forEach(item => { const attrPrefix = `${entityText.attrs.id}-attr-${attrNum}` const fontConfig = { fontSize: conf.fontSize } let keyText: Text if (item.attributeKey) { keyText = makeMark( 'text', { ...calculateTextDimensions(item.attributeKey, fontConfig), ...getBaseText(), text: item.attributeKey, id: `${attrPrefix}-key`, textAlign: 'left', textBaseline: 'middle', fontSize: attrFontSize, }, { class: 'er__entity-label' }, ) } const typeText = makeMark( 'text', { ...calculateTextDimensions(item.attributeType, fontConfig), ...getBaseText(), text: item.attributeType, id: `${attrPrefix}-type`, textAlign: 'left', textBaseline: 'middle', fontSize: attrFontSize, }, { class: 'er__entity-label' }, ) const nameText = makeMark( 'text', { ...calculateTextDimensions(item.attributeName, fontConfig), ...getBaseText(), text: item.attributeName, id: `${attrPrefix}-name`, textAlign: 'left', textBaseline: 'middle', fontSize: attrFontSize, }, { class: 'er__entity-label' }, ) if (item.attributeKey) attributeGroup.children.push(keyText) attributeGroup.children.push(typeText, nameText) // Keep a reference to the nodes so that we can iterate through them later attributeNodes.push({ type: typeText, name: nameText, key: keyText }) if (item.attributeKey) { maxKeyWidth = Math.max(maxKeyWidth, keyText.attrs.width) } maxTypeWidth = Math.max(maxTypeWidth, typeText.attrs.width) maxNameWidth = Math.max(maxNameWidth, nameText.attrs.width) cumulativeHeight += Math.max(typeText.attrs.height, nameText.attrs.height, keyText?.attrs.height || 0) + attribPaddingY * 2 attrNum += 1 }) const paddingXCount = hasKeyAttribute ? 6 : 4 // Calculate the new bounding box of the overall entity, now that attributes have been added const bBox = { width: Math.max( conf.minEntityWidth, Math.max( labelBBox.width + conf.entityPaddingX * 2, maxTypeWidth + maxNameWidth + maxKeyWidth + attribPaddingX * paddingXCount, ), ), height: attributes.length > 0 ? cumulativeHeight : Math.max(conf.minEntityHeight, labelBBox.height + conf.entityPaddingY * 2), } if (attributes.length > 0) { const nodeXOffsets: Record<keyof AttributePair, number> = { key: 0, type: maxKeyWidth, name: maxKeyWidth + maxTypeWidth + 2 * attribPaddingX, } if (hasKeyAttribute) { nodeXOffsets.type += 2 * attribPaddingX nodeXOffsets.name += 2 * attribPaddingX } // Position the entity label near the top of the entity bounding box entityText.matrix = mat3.fromTranslation(mat3.create(), [bBox.width / 2, attribPaddingY + labelBBox.height / 2]) // Add rectangular boxes for the attribute types/names let heightOffset = labelBBox.height + attribPaddingY * 2 // Start at the bottom of the entity label let attribStyle = 'attributeBoxOdd' // We will flip the style on alternate rows to achieve a banded effect const attributeFill = conf.attributeFill function makeAttribLabelRect(attrs: Partial<Rect['attrs']>) { return makeMark('rect', { fill: attributeFill, stroke: conf.stroke, ...attrs, }) } attributeNodes.forEach(nodePair => { const rowSegs: Text[] = [] if (nodePair.key) { rowSegs.push(nodePair.key) } rowSegs.push(nodePair.type) rowSegs.push(nodePair.name) const rowTextHeight = rowSegs.reduce((out, mark) => Math.max(out, mark.attrs.height), 0) const rowHeight = rowTextHeight + attribPaddingY * 2 // Calculate the alignment y co-ordinate for the type/name of the attribute const alignY = heightOffset + attribPaddingY + rowTextHeight / 2 if (nodePair.key) { const keyRect = makeAttribLabelRect({ x: entityText.attrs.x, y: heightOffset, width: maxKeyWidth + attribPaddingX * 2, height: rowHeight, }) attributeGroup.children.unshift(keyRect) nodePair.key.matrix = mat3.fromTranslation(mat3.create(), [nodeXOffsets.key + attribPaddingX, alignY]) } // Position the type of the attribute nodePair.type.matrix = mat3.fromTranslation(mat3.create(), [nodeXOffsets.type + attribPaddingX, alignY]) // Insert a rectangle for the type const typeRect = makeAttribLabelRect({ x: entityText.attrs.x + nodeXOffsets.type, y: heightOffset, width: maxTypeWidth + attribPaddingX * 2, height: rowHeight, }) // Position the name of the attribute nodePair.name.matrix = mat3.fromTranslation(mat3.create(), [nodeXOffsets.name + attribPaddingX, alignY]) // Insert a rectangle for the name const nameRect = makeAttribLabelRect({ x: entityText.attrs.x + nodeXOffsets.name, y: heightOffset, width: maxNameWidth + attribPaddingX * 2, height: rowHeight, }) // Increment the height offset to move to the next row heightOffset += Math.max(nodePair.name.attrs.height, nodePair.name.attrs.height) + attribPaddingY * 2 // Flip the attribute style for row banding attribStyle = attribStyle == 'attributeBoxOdd' ? 'attributeBoxEven' : 'attributeBoxOdd' attributeGroup.children.unshift(typeRect, nameRect) }) if (hasKeyAttribute) { // a background rect for key column const entityLabelOuterHeight = labelBBox.height + attribPaddingY * 2 const keyColBgRect = makeAttribLabelRect({ x: entityText.attrs.x, y: entityText.attrs.y + entityLabelOuterHeight, width: maxKeyWidth + attribPaddingX * 2, height: cumulativeHeight - entityLabelOuterHeight, }) attributeGroup.children.unshift(keyColBgRect) } } else { // Ensure the entity box is a decent size without any attributes bBox.height = Math.max(conf.minEntityHeight, cumulativeHeight) // Position the entity label in the middle of the box entityText.matrix = mat3.fromTranslation(mat3.create(), [bBox.width / 2, bBox.height / 2]) } return { ...bBox, attributeGroup, } } /** */ const drawEntities = function (rootMark: Group, ir: ErDiagramIR, graph: LayoutGraph) { const keys = Object.keys(ir.entities) const groups: Group[] = [] keys.forEach(function (id) { // Create a group for each entity const group = makeMark( 'group', { id, }, { children: [], class: 'er__entity' }, ) groups.push(group) // Label the entity - this is done first so that we can get the bounding box // which then determines the size of the rectangle const textId = 'entity-' + id const fontConfig = { fontSize: conf.fontSize, fontWeight: 'bold' as const } const textMark = makeMark( 'text', { ...getBaseText(), ...calculateTextDimensions(id, fontConfig), text: id, id: textId, textAlign: 'center', textBaseline: 'middle', fill: conf.textColor, ...fontConfig, }, { class: 'er__entity-label' }, ) // Draw the rectangle - insert it before the text so that the text is not obscured const rectMark = makeMark( 'rect', { ...getBaseText(), fill: conf.fill, stroke: conf.stroke, x: 0, y: 0, radius: conf.borderRadius, }, { class: 'er__entity-box' }, ) group.children.push(rectMark, textMark) const { width: entityWidth, height: entityHeight, attributeGroup, } = drawAttributes(group, textMark, ir.entities[id].attributes) safeAssign(rectMark.attrs, { width: entityWidth, height: entityHeight, }) // Add the entity to the graph graph.setNode(id, { width: entityWidth, height: entityHeight, id, onLayout(data) { const x = Math.floor(data.x) const y = Math.floor(data.y) // console.log('on layout', x, y) const marks = [rectMark, textMark] marks.forEach(mark => { // center the marks to dest point safeAssign(mark.attrs, { x: x - rectMark.attrs.width / 2, y: y - rectMark.attrs.height / 2 }) }) if (attributeGroup) { attributeGroup.children.forEach(child => { safeAssign(child.attrs, { x: x + child.attrs.x - entityWidth / 2, y: y + child.attrs.y - entityHeight / 2, }) }) } }, }) rootMark.children.push(group) }) return groups } // drawEntities const adjustEntities = function (graph: LayoutGraph) { graph.nodes().forEach(function (v) { const nodeData: LayoutNode = graph.node(v) as any if (nodeData) { // console.log('adjustEntities, graph node: ', nodeData) if (nodeData.onLayout) { nodeData.onLayout(nodeData) } } }) } const getEdgeName = function (rel) { return (rel.entityA + rel.roleA + rel.entityB).replace(/\s/g, '') } type EdgeData = { name: string relationship: Relationship points: Point[] } /** * Add each relationship to the graph * @param relationships the relationships to be added * @param g the graph * @return The array of relationships */ const addRelationships = function (relationships: ErDiagramIR['relationships'], g: LayoutGraph) { relationships.forEach(function (r) { g.setEdge(r.entityA, r.entityB, { name: getEdgeName(r), relationship: r } as EdgeData) }) return relationships } // addRelationships let relCnt = 0 /** * Draw a relationship using edge information from the graph * @param svg the svg node * @param rel the relationship to draw in the svg * @param g the graph containing the edge information */ const drawRelationshipFromLayout = function (group: Group, rel: Relationship, g: LayoutGraph) { relCnt++ // Find the edge relating to this relationship const edge: EdgeData = g.edge(rel.entityA, rel.entityB) const [startPoint, ...restPoints] = edge.points const secondPoint = restPoints[0] const lastPoint = restPoints[restPoints.length - 1] let pathCommands: PathCommand[] | string if (conf.curvedEdge) { const pathString = getPointsCurvePath(edge.points) pathCommands = pathString } else { pathCommands = getPointsLinearPath(edge.points) } const linePath = makeMark('path', { path: pathCommands, stroke: conf.edgeColor, lineJoin: 'round', }) // with dashes if necessary if (rel.relSpec.relType === Identification.NON_IDENTIFYING) { linePath.attrs.lineDash = [4, 4] } const endMarkerDirection = calcDirection(restPoints[restPoints.length - 1], restPoints[restPoints.length - 2]) const endMarker = drawMarkerTo(lastPoint, rel.relSpec.cardA, endMarkerDirection, { stroke: conf.stroke, id: `${edge.name}-end`, }) const startMarkerDirection = calcDirection(startPoint, secondPoint) const startMarker = drawMarkerTo(startPoint, rel.relSpec.cardB, startMarkerDirection, { stroke: conf.stroke, id: `${edge.name}-start`, }) // Now label the relationship // Find the half-way point const labelPoint = getPointAt(edge.points, 0.4, true) const labelX = labelPoint.x const labelY = labelPoint.y // Append a text node containing the label const labelId = 'rel' + relCnt const labelMark = makeMark( 'text', { text: rel.roleA, id: labelId, textAlign: 'center', textBaseline: 'middle', x: labelX, y: labelY, fill: conf.textColor, fontSize: conf.fontSize, }, { class: 'er__relationship-label' }, ) const labelDims = calculateTextDimensions(rel.roleA, { fontSize: conf.fontSize, fontFamily: 'sans-serif', fontWeight: 400, }) labelDims.width += conf.fontSize / 2 labelDims.height += conf.fontSize / 2 const labelBg = makeLabelBg(labelDims, { x: labelX, y: labelY }, { id: `#${labelId}`, fill: conf.labelBackground }) const insertingMarks = [linePath, labelBg, labelMark, startMarker, endMarker].filter(o => !!o) group.children.push(...insertingMarks) } export default erArtist
the_stack
import { Context } from '@textile/context' import { Identity, PrivateKey } from '@textile/crypto' import { ThreadID } from '@textile/threads-id' import { expect } from 'chai' import { Client, getFunctionBody, JSONSchema3or4, Update } from './index' import { Event, ReadTransaction, Where, WriteTransaction } from './models' const personSchema: JSONSchema3or4 = { $id: 'https://example.com/person.schema.json', $schema: 'http://json-schema.org/draft-07/schema#', title: 'Person', type: 'object', required: ['_id'], properties: { _id: { type: 'string', description: "The instance's id.", }, firstName: { type: 'string', description: "The person's first name.", }, lastName: { type: 'string', description: "The person's last name.", }, age: { description: 'Age in years which must be equal to or greater than zero.', type: 'integer', minimum: 0, }, }, } // Minimal schema representation const schema2: JSONSchema3or4 = { properties: { _id: { type: 'string' }, fullName: { type: 'string' }, age: { type: 'integer', minimum: 0 }, }, } interface Person { _id: string firstName: string lastName: string age: number } const createPerson = (): Person => { return { _id: '', firstName: 'Adam', lastName: 'Doe', age: 21, } } describe('Thread Client', function () { const dbID = ThreadID.fromRandom() let dbKey: string let identity: Identity const client = new Client(new Context('http://127.0.0.1:6007')) before(async function () { identity = PrivateKey.fromRandom() await client.getToken(identity) await client.newDB(dbID, 'test') }) describe('Collections', function () { it('newCollection should work and create an empty object', async function () { const register = await client.newCollection(dbID, { name: 'Person', schema: personSchema, }) expect(register).to.be.undefined }) it('newCollectionFromObject should create new collections from input objects', async function () { const register = await client.newCollectionFromObject( dbID, { _id: '', these: 'can', all: 83, values: ['that', 'arent', 'already'], specified: true, }, { name: 'FromObject', }, ) expect(register).to.be.undefined }) it('updateCollection should update an existing collection', async function () { await client.updateCollection(dbID, { name: 'FromObject', schema: schema2, indexes: [ { path: 'age', unique: false, }, ], }) await client.create(dbID, 'FromObject', [ { _id: '', fullName: 'Madonna', age: 0, }, ]) }) it('getCollectionInfo should return information about a collection', async function () { const info = await client.getCollectionInfo(dbID, 'FromObject') expect(info.name).to.equal('FromObject') expect(info.schema).to.deep.equal({ properties: { _id: { type: 'string', }, age: { type: 'integer', }, fullName: { type: 'string', }, }, }) // Just one index on age expect(info.indexes).to.have.lengthOf(1) }) it('getCollectionInfo should throw for a missing collection', async function () { try { await client.getCollectionInfo(dbID, 'Fake') throw new Error('should have thrown') } catch (err) { expect(err.toString()).to.include('collection not found') } }) it('getCollectionIndexes should list valid collection indexes', async function () { // @todo Update to latest APIs and mark this as deprecated const list = await client.getCollectionIndexes(dbID, 'FromObject') expect(list).to.have.length(1) }) it('deleteCollection should delete an existing collection', async function () { await client.deleteCollection(dbID, 'FromObject') try { await client.create(dbID, 'FromObject', [ { _id: 'blah', nothing: 'weve', seen: 84, }, ]) throw new Error('should have thrown') } catch (err) { expect(err.toString()).to.include('collection not found') } }) it('ListCollections should return a list of collections', async function () { const list = await client.listCollections(dbID) expect(list).to.have.length(1) }) }) describe('.listDBs', function () { it('should list the correct number of dbs with the correct name', async function () { const id2 = ThreadID.fromRandom() const random = Math.floor(Math.random() * 10) const name2 = `db2-${random}` await client.newDB(id2, name2) const list = await client.listDBs() expect(list.length).to.be.greaterThan(1) expect(list.map((db) => db.name)).to.include(name2) }) }) describe('.getDBInfo', function () { it('should return a valid db info object', async function () { const invites = await client.getDBInfo(dbID) expect(invites).to.not.be.undefined expect(invites.addrs[0]).to.not.be.undefined expect(invites.key).to.not.be.undefined dbKey = invites.key expect(invites).to.not.be.empty }) }) describe('.deleteDB', function () { it('should cleanly delete a database', async function () { const id = ThreadID.fromRandom() await client.newDB(id) const before = (await client.listDBs()).length await client.deleteDB(id) const after = (await client.listDBs()).length expect(before).to.equal(after + 1) try { await client.getDBInfo(id) throw new Error('should have thrown') } catch (err) { expect(err.toString()).to.include('thread not found') } }).timeout(5000) // Make sure our test doesn't timeout }) describe('.newDBFromAddr', function () { const client2 = new Client(new Context('http://127.0.0.1:6207')) before(async function () { identity = PrivateKey.fromRandom() await client2.getToken(identity) }) it('response should contain a valid list of thread protocol addrs', async function () { const info = await client.getDBInfo(dbID) // @hack: we're in docker and peers can't find each other; don't try this at home! info.addrs.forEach((addr) => { addr.replace('/ip4/127.0.0.1', '/dns4/threads1/') }) // We can 'exclude' the local addrs because we swapped them for "dns" entries const id1 = await client2.joinFromInfo(info, false, [ // Include the known collections to bootstrap with... { name: 'Person', schema: personSchema, }, { name: 'FromObject', schema: schema2, }, ]) expect(id1.equals(dbID)).to.equal(true) const info2 = await client2.getDBInfo(dbID) expect(info2.addrs.length).to.be.greaterThan(1) expect(info2.key).to.equal(info.key) // Now we should have it locally, so no need to add again try { const id2 = await client2.newDBFromAddr(info.addrs[0], dbKey, []) expect(id2.equals(id1)).to.equal(true) } catch (err) { // Expect this db to already exist on this peer expect(err.toString()).to.include('already exists') } }) }) describe('.create', function () { it('response should contain a JSON parsable instancesList', async function () { const instances = await client.create(dbID, 'Person', [createPerson()]) expect(instances.length).to.equal(1) }) }) describe('.readFilter', function () { interface Dog { _id: string name: string comments: any[] } // You can use typescript types to ensure type safety! const readFilter = (_reader: string, instance: Dog) => { instance.name = 'Clyde' return instance } it('should modify returned instances before they are received by the client', async function () { // Empty schema await client.newCollection(dbID, { name: 'Dog', readFilter, }) // Start with dog with empty id const dog: Dog = { _id: '', name: 'Fido', comments: [] } const [id] = await client.create(dbID, 'Dog', [dog]) // Now pull him back out const res = await client.findByID<Dog>(dbID, 'Dog', id) expect(res.name).to.equal('Clyde') // Even though we initially named him Fido! }) }) describe('.writeValidator', function () { interface Dog { _id: string name: string comments: any[] } // eslint-disable-next-line @typescript-eslint/no-unused-vars const writeValidator = (_writer: string, event: Event, _instance: Dog) => { var type = event.patch.type var patch = event.patch.json_patch switch (type) { case 'delete': return false default: if (patch.name !== 'Fido' && patch.name != 'Clyde') { return false } return true } } it('should handle string-based writeValidators', async function () { const replaceThisValidator = (writer: string) => { // eslint-disable-next-line prettier/prettier const ownerPub = 'replaceThis' if (writer === ownerPub) { return true } return false } const writeValidatorString = getFunctionBody( replaceThisValidator, ).replace('replaceThis', 'publicKeyString') await client.newCollection(dbID, { name: 'DontUseThisOne', writeValidator: writeValidatorString, }) }) it('should catch invalid write operations before they are added to the db', async function () { // Empty schema await client.updateCollection(dbID, { name: 'Dog', writeValidator, }) // Start with dog with empty id const dog: Dog = { _id: '', name: 'Fido', comments: [] } const [id] = await client.create(dbID, 'Dog', [dog]) // Update the properties dog._id = id dog.name = 'Bob' try { // Try saving, but it _shouldn't_ work! await client.save(dbID, 'Dog', [dog]) throw new Error('should have failed') } catch (err) { expect(err.message).to.include('app denied net record body') } dog.name = 'Clyde' // Yeh, Clyde is cool... let's do it await client.save(dbID, 'Dog', [dog]) // But now that we have Clyde... you better not delete him! try { await client.delete(dbID, 'Dog', [id]) throw new Error('should have failed') } catch (err) { expect(err.message).to.include('app denied net record body') } }) }) describe('.verify', function () { const writeValidator = ( _writer: string, event: Event, // eslint-disable-next-line @typescript-eslint/no-unused-vars _instance: Person, ) => { var type = event.patch.type var patch = event.patch.json_patch switch (type) { // Never allow deletion by anyone! case 'delete': return false default: // No person over the age of 50! // Note, this part could have been done using json-schema rules! if (patch.age > 50) { return false } // Otherwise, all good, let the schema validator take over return true } } it('should be able to verfiy incoming instances before writing/saving', async function () { // Start with a new collection await client.newCollection(dbID, { name: 'Verified', schema: personSchema, writeValidator, }) const person = createPerson() const [id] = await client.create(dbID, 'Verified', [person]) expect(id).to.not.be.undefined person._id = id person.age = 51 try { await client.verify(dbID, 'Verified', [person]) throw new Error('wrong error') } catch (err) { expect(err.message).to.include('app denied net record body') } person.age = 50 const err = await client.verify(dbID, 'Verified', [person]) expect(err).to.be.undefined }) }) describe('.save', function () { it('response should be defined and be an empty object', async function () { const person = createPerson() const instances = await client.create(dbID, 'Person', [person]) expect(instances.length).to.equal(1) person._id = instances[0] person!.age = 30 const save = await client.save(dbID, 'Person', [person]) expect(save).to.be.undefined }) }) describe('.delete', function () { it('response should be defined and be an empty object', async function () { const instances = await client.create(dbID, 'Person', [createPerson()]) expect(instances.length).to.equal(1) const personID = instances[0] const deleted = await client.delete(dbID, 'Person', [personID]) expect(deleted).to.be.undefined }) }) describe('create and delete many instances', function () { it('should not timeout or lead to hanging transaction', async function () { const many = Array.from({ length: 100 }, () => createPerson()) const ids = await client.create(dbID, 'Person', many) expect(ids.length).to.equal(many.length) const deleted = await client.delete(dbID, 'Person', ids) expect(deleted).to.be.undefined }).timeout(10000) // Make sure our test doesn't timeout }) describe('.has', function () { it('the created object should also return true for has', async function () { const instances = await client.create(dbID, 'Person', [createPerson()]) // Here we 'test' a different approach where we didn't use generics above to create the instance... expect(instances.length).to.equal(1) const has = await client.has(dbID, 'Person', instances) expect(has).to.be.true }).timeout(5000) // Make sure our test doesn't timeout }) describe('.find', function () { it('response should contain the same instance based on query', async function () { const frank = createPerson() frank.firstName = 'Frank' const instances = await client.create(dbID, 'Person', [frank]) expect(instances.length).to.equal(1) const personID = instances[0] const q = new Where('firstName').eq(frank.firstName) const found = await client.find<Person>(dbID, 'Person', q) expect(found).to.have.length(1) const foundPerson = found.pop()! expect(foundPerson).to.not.be.undefined expect(foundPerson).to.have.property('firstName', 'Frank') expect(foundPerson).to.have.property('lastName', 'Doe') expect(foundPerson).to.have.property('age', 21) expect(foundPerson).to.have.property('_id') expect(foundPerson['_id']).to.equal(personID) }) }) describe('.findById', function () { it('response should contain an instance', async function () { try { await client.findByID<Person>(dbID, 'Person', 'blah') // not a real id throw new Error('wrong error') } catch (err) { expect(err.toString()).to.not.include('wrong error') } const [id] = await client.create(dbID, 'Person', [createPerson()]) const instance = await client.findByID<Person>(dbID, 'Person', id) expect(instance).to.not.be.undefined expect(instance).to.have.property('firstName', 'Adam') expect(instance).to.have.property('lastName', 'Doe') expect(instance).to.have.property('age', 21) expect(instance).to.have.property('_id') }) }) describe('cross-collection ids', function () { it('should not require instance ids to be unique across collections', async function () { const person = createPerson() person._id = 'something-unique' const [first] = await client.create(dbID, 'Person', [person]) const [second] = await client.create(dbID, 'Verified', [person]) expect(first).to.equal(second) }) }) describe('.readTransaction', function () { let existingPersonID: string let transaction: ReadTransaction | undefined before(async function () { const instances = await client.create(dbID, 'Person', [createPerson()]) existingPersonID = instances.pop()! transaction = client.readTransaction(dbID, 'Person') }) it('should start a transaction', async function () { expect(transaction).to.not.be.undefined await transaction!.start() }) it('should able to check for an existing instance', async function () { const has = await transaction!.has([existingPersonID]) expect(has).to.be.true }) it('should be able to find an existing instance', async function () { const instance = await transaction!.findByID<Person>(existingPersonID) expect(instance).to.not.be.undefined expect(instance).to.have.property('firstName', 'Adam') expect(instance).to.have.property('lastName', 'Doe') expect(instance).to.have.property('age', 21) expect(instance).to.have.property('_id') expect(instance?._id).to.deep.equal(existingPersonID) }) it('should be able to close/end an transaction', async function () { await transaction!.end() }) it('should throw on invalid transaction information', async function () { const t = client.readTransaction(dbID, 'fake') await t.start() try { await t.has(['anything']) throw new Error('should have thrown') } catch (err) { expect(err.toString()).to.include('collection not found') } }) }) describe('.writeTransaction', function () { let existingPersonID: string let transaction: WriteTransaction | undefined context('complete transaction', function () { const person = createPerson() before(async function () { const instances = await client.create(dbID, 'Person', [person]) existingPersonID = instances.length ? instances[0] : '' person['_id'] = existingPersonID transaction = client.writeTransaction(dbID, 'Person') }) it('should start a transaction', async function () { expect(transaction).to.not.be.undefined await transaction!.start() }) it('should be able to create an instance', async function () { const newPerson = createPerson() const entities = await transaction!.create<Person>([newPerson]) expect(entities).to.not.be.undefined expect(entities!.length).to.equal(1) }) it('should able to check for an existing instance', async function () { const has = await transaction!.has([existingPersonID]) expect(has).to.be.true }) it('should be able to find an existing instance', async function () { const instance = await transaction!.findByID<Person>(existingPersonID) expect(instance).to.not.be.undefined expect(instance).to.have.property('firstName', 'Adam') expect(instance).to.have.property('lastName', 'Doe') expect(instance).to.have.property('age', 21) expect(instance).to.have.property('_id') expect(instance?._id).to.deep.equal(existingPersonID) }) it('should be able to validate an instance that is invalid', async function () { try { await transaction?.verify([createPerson()]) } catch (err) { // Regression test against old verify/save bahavior expect(err.message).to.not.include('unkown instance') // sic } }) it('should be able to save an existing instance', async function () { person.age = 99 const saved = await transaction!.save([person]) expect(saved).to.be.undefined const deleted = await transaction!.delete([person._id]) expect(deleted).to.be.undefined }) it('should be able to close/end an transaction', async function () { await transaction!.end() }) }) context('rejected transaction', function () { it('should not commit a discarded write transaction', async function () { const newPerson = createPerson() const [id] = await client.create(dbID, 'Person', [newPerson]) // Update _id to be on the safe side newPerson._id = id // Create a new write transaction, which we'll discard later const transaction = client.writeTransaction(dbID, 'Person') await transaction.start() newPerson.age = 38 // Update age, but discard in a moment // Abort/discard transaction const rejected = await transaction.discard() expect(rejected).to.be.undefined // Try to do something that should fail later (but not now) await transaction.save([newPerson]) // After discarding transaction, we end it... but it should throw here! try { await transaction.end() throw new Error('wrong error') } catch (err) { expect(err.message).to.include('discarded/committed txn') } const instance: Person = await client.findByID(dbID, 'Person', id) expect(instance.age).to.not.equal(38) }) }) }) describe('.listen', function () { const listener: { events: number; close?: () => void } = { events: 0 } const person = createPerson() before(async function () { const entities = await client.create(dbID, 'Person', [person]) person._id = entities[0] }) it('should stream responses.', (done) => { const callback = (reply?: Update<Person>, err?: Error) => { if (err) { throw err } const instance = reply?.instance expect(instance).to.not.be.undefined expect(instance).to.have.property('age') expect(instance?.age).to.be.greaterThan(21) listener.events += 1 if (listener.events > 1 && listener.close) { listener.close() } if (listener.events == 2) { done() } } const closer = client.listen<Person>( dbID, [ { collectionName: 'Person', actionTypes: ['ALL'], }, ], callback, ) setTimeout(() => { const person = createPerson() person.age = 40 client.create(dbID, 'Person', [person]) client.create(dbID, 'Person', [person]) }, 500) listener.close = () => closer.close() }).timeout(5000) // Make sure our test doesn't timeout it('should handle deletes.', (done) => { const callback = (reply?: Update<Person>, err?: Error) => { if (err) { throw err } expect(reply?.instance).to.be.undefined if (listener.close) { listener.close() } done() } const closer = client.listen<Person>( dbID, [ { collectionName: 'Person', actionTypes: ['DELETE'], }, ], callback, ) setTimeout(() => { const person = createPerson() client.create(dbID, 'Person', [person]).then((ids) => { setTimeout(() => { client.delete(dbID, 'Person', ids) }, 500) }) }, 500) listener.close = () => closer.close() }).timeout(5000) // Make sure our test doesn't timeout }) describe('Query', function () { before(async function () { const people = [...Array(8)].map((_, i) => { const person = createPerson() person.age = 60 + i return person }) await client.create(dbID, 'Person', people) }) it('Should return a full list of entities matching the given query', async function () { const q = new Where('age') .ge(60) .and('age') .lt(66) .or(new Where('age').eq(67)) .skipNum(1) .limitTo(5) .orderByID() const instances = await client.find<Person>(dbID, 'Person', q) expect(instances).to.have.length(5) }) }) describe('Invalid states', function () { it('should not compromise the thread to try to create the same object twice', async function () { const newPerson = createPerson() newPerson._id = 'new-person-id_one' const [id] = await client.create(dbID, 'Person', [newPerson]) expect(id).to.not.be.undefined try { await client.create(dbID, 'Person', [newPerson]) throw new Error('wrong error') } catch (err) { expect(err.message).to.include('existing instance') } const list = await client.find(dbID, 'Person', {}) expect(list.length).to.be.greaterThan(0) }) it('should also be safe inside a write transaction', async function () { const newPerson = createPerson() newPerson._id = 'new-person-id-two' const transaction = client.writeTransaction(dbID, 'Person') await transaction.start() const result = await transaction.create([newPerson]) expect(result).to.not.be.undefined // This check won't error here... await transaction.create([newPerson]) // But it should error here try { await transaction.end() throw new Error('wrong error') } catch (err) { expect(err.message).to.include('already existent instance') } const list = await client.find(dbID, 'Person', {}) expect(list.length).to.be.greaterThan(0) const collections = await client.listCollections(dbID) expect(collections).to.have.lengthOf(4) }) }) describe('Restart', function () { it('Should handle a whole new "restart" of the client', async function () { const newClient = new Client(new Context('http://127.0.0.1:6007')) const person = createPerson() await newClient.getToken(identity) const created = await newClient.create(dbID, 'Person', [person]) const got: Person = await newClient.findByID(dbID, 'Person', created[0]) expect(got).to.haveOwnProperty('_id', created[0]) expect(got).to.haveOwnProperty('firstName', 'Adam') }).timeout(5000) // Make sure our test doesn't timeout }) })
the_stack
export const enum errorCode { ERR_NO_ERROR = 0, /** GENERIC ERRORS */ ERR_MISSING_PARAMETERS = 1000, // Missing Parameters for the specified api endpoint ERR_INVALID_BODYTYPE = 1001, // Invalid Body Type; used by put / post handlers for parameter verification ERR_WRONG_PARAMETER_TYPE = 1002, // Wrong Parameter type supplied, for example field must be array, string given. ERR_INVALID_SORT_TYPE = 1003, // Unsupported sortBy / sort parameters ERR_UNSUPPORTED_SORTING = 1004, ERR_UNEXPECTED_ARGUMENT = 1005, // Unexpected Range etc ERR_MISSING_FEATURE = 1006, // Missing Feature / Unimplemented Code Path ERR_UNEXPECTED = 1007, // Unexpected Error; such as race-conditions upon registration (email check/namecheck -> final insert conflict etc.. ) ERR_PAGINATION_NEEDED = 1008, // The requested action requires pagination parameters set (offset/limit) ERR_PAGINATION_LIMIT_EXCEEDED = 1009, // The Requested Limits exceeds the Actions maximum supported limit ERR_PAGINATION_NO_MORE_DATA = 1010, // The requested action cannot provide any more data for the requested offset. ERR_ACTION_REQUIRES_EMAIL_SET = 1011, // The requested action requires a valid email set ERR_RECAPTCHA_INVALID = 1012, // Used to refuse recaptcha challenge /** AUTH ERRORS */ ERR_AUTH_TOKEN_INVALID = 2001, // Invalid or expored token (can be refresh or normal token) ERR_AUTH_MISSING_HEADERS = 2002, // Missing Authentication header for permission check ERR_AUTH_NO_PERMISSION = 2003, // User does not has the required permission assigned ERR_AUTH_USER_INVALID = 2100, // Used by local authentification, username unknown or wrong password ERR_AUTH_USER_NOT_FOUND = 2101, // /user/:id, user not found (also used by account validation) ERR_AUTH_NOT_VERIFIED = 2102, // User account not activated or verified ERR_AUTH_BLOCKED = 2103, // User Blocked (account suspended, blocked) ERR_AUTH_OAUTH_ONETIMETOKEN_INVALID = 2104, // The Given One-Time-Token for login/valdiation is invalid (UserVerifyToken System, Auth/User Controller) ERR_AUTH_OAUTH_REG_INCOMPLETE = 2105, // OAuth Regstration incomplete (Displayname/terms not ste) ERR_AUTH_TERMS_NOT_ACCEPTED = 2106, // User needs to accept new terms. ERR_AUTH_DISCOURSESSO_VALIDATION_FAILED = 2107, // Failed to validate the Discourse SSO Request (malformed url?) ERR_AUTH_DISCOURSESSO_PAYLOAD_DECODE_FAILED = 2708, // Payload Decode Failed (invalid payload supplied / incompatible etc ..) ERR_AUTH_SECONDFACTOR_REQUIRED = 2709, // User Has secondFactor enabled (additional parameter required) ERR_AUTH_SECONDFACTOR_INVALID = 2710, // User provided secondfactor code is invalid ERR_AUTH_SECONDFACTOR_RECOVERY_INVALID = 2711, // User provided secondfactor recovery code is invalid ERR_AUTH_SECONDFACTOR_RECOVERY_DENIED = 2712, // User provided secondfactor recovery code is valid, but denid (account is maintainer of apps) ERR_AUTH_SECONDFACTOR_EXTERNALPROVIDERLOGIN_INVALID = 2713, // User provided secondfactor code is invalid (while trying to login via external provider like steam / google etc) ERR_AUTH_UNSUPPORTED_AUTHORIZATION_SCHEMA = 2714, // Unsupported Type for 'Authorization'-Header (not Bearer) ERR_AUTH_TOKEN_CREATION_FAILED = 2715, // Internal error, cannot create token ERR_AUTH_RESETPASS_OAUTH_REG_INCOMPLETE = 2716, // Password reset refused/failed as the user has not completed his/her external-auth-provider registration (setup of displayname/terms) /** Bohne Erors (Staffinfo) */ ERR_BOHNE_NOT_FOUND = 2201, // Bohne Not found. ERR_BOHNE_INVALID_ROLE = 2202, // Unsupported Role. ERR_BOHNE_PORTAIT_INVALID = 2203, // The given image is unknown or invalid /** Image Uploader Errors */ ERR_IMAGEUPLOAD_INVALID_IMAGE = 2301, // Invalid or Missing Image ERR_IMAGEUPLOAD_INVALID_TYPE = 2302, // Invalid or unknown type ERR_IMAGEUPLOAD_TOOLARGE = 2303, // Uploaded file exceeds types maximum allowed filesize ERR_IMAGEUPLOAD_INVALID_DIMENSIONS = 2304, // Imagesize Invalid (min/max size) ERR_IMAGEUPLOAD_FAIL_TEMP = 2305, // Upload failed, failed to store entity (already pending temp images for this type) ERR_IMAGEUPLOAD_MISSING_PERMISSION = 2306, // Upload failed, the given image type requires a special permission, which the user-agent does not fulfil /** Blog Errors */ ERR_BLOG_AUTHOR_NOT_FOUND = 2401, // The given Author UserID is not found / not a bohne ERR_BLOG_POST_NOT_FOUND = 2402, // Blog Post not found ERR_BLOG_UNSUPPORTED_FEED_TYPE = 2403, // Unsupported Feed Type (RSS/ATOM ETC) ERR_BLOG_CATEGORY_NOT_FOUND = 2404, // Requested Blog Category not found ERR_BLOG_CATEGORY_INVALID = 2405, // Requested Blog Category does not match the requirements ERR_BLOG_CATEGORY_ALREADY_EXISTS = 2406, // Requested Blog Category already exists ERR_BLOG_CATEGORY_CONTAINS_POSTS = 2407, // Blog Category contains posts and cannot be deleted\ ERR_BLOG_INVALID_TITLE_IMAGE = 2408, // Unknown image id or invalid type - see message for details ERR_BLOG_INVALID_PROMO_IMAGE = 2409, // Unknown image id or invalid type - see message for details ERR_BLOG_INVALID_THUMB_IMAGE = 2410, // Unknown image id or invalid type - see message for details /** Streamcount Errors */ ERR_STREAMCOUNT_UNAVAILABLE = 2501, /** User Errors */ ERR_USER_UNKNOWN = 2601, // Unknown user / userid ERR_USER_DISPLAYNAME_TAKEN = 2602, // Displayname already in use ERR_USER_EMAIL_TAKEN = 2603, // Email Address used by another account ERR_USER_UNKNOWN_GROUP = 2604, // Unknown Group ERR_USER_DISPLAYNAME_INVALID = 2605, // Displayname Contains Invalid/Unallowed Characters ERR_USER_TERMS = 2606, // Terms Not Accepted ERR_USER_PRIVACYPOLICY = 2607, // Privacy Policy Not Accepted ERR_USER_SIGNUP_DISABLED = 2608, // Signup is disabled ERR_USER_PASSWORD_TOO_SHORT = 2609, // Password too short ERR_USER_VERIFYTOKEN_INVALID = 2610, // Invalid/Unknown Verification Token ERR_USER_VERIFYTOKEN_EMAILCHANGEDOK = 2611, // Indirect Error Code: Verify Token Was ok; email changed ERR_USER_VERIFYTOKEN_VALIDATEDOK = 2612, // Indirect Error Code: Verify Token Was ok; User Account Activated ERR_USER_VERIFYTOKEN_BLOCKED = 2613, // Token found & Valid; but user is blocked - cannot be applied ERR_USER_VERIFYTOKEN_INVALIDSTATE = 2614, // Token found & Valid, but user is not in verification state ERR_USER_VERIFYTOKEN_EMAILINUSE = 2615, // E-Mail Address is already in use (this can happen if the user has a pending change request while another user registers a new account this the requested addres while the change is pending) ERR_USER_REGISTER_OAUTH_INVALIDSTATE = 2616, // User is not in OAUTH_PENDING Account State or has displayname set && was trying to register ERR_USER_INVALID_PW = 2617, // Invalid/Incorrect Password ERR_USER_VERIFYTOKEN_PWCHANGEOK = 2618, // Indirect Error Code: Verify Token was ok; password changed ERR_USER_AUTHPROVIDER_NOTEXIST = 2619, // The given Auth Provideer (OAuth/External) does not exist for the given user ERR_USER_AUTHPROVIDER_ISLAST = 2620, // Used when the user tries to delete the last auth provider that's used to identify the account ERR_USER_VERIFYTOKEN_PAYPALOK = 2621, // Token found & valid, paypal address of the user has been verified ERR_USER_DELETE_FAIL = 2622, // Deletion failed ERR_USER_DELETE_PASS_INVALUD = 2623, // password invalid (deletion) ERR_USER_CHANGE_DISPLAYNAME_THROTTLED = 2624, // Display Name change Throttled. ERR_USER_VERIFYTOKEN_RAFFLEVALIDATE_OK = 2625, // Token found & Valid, raffle participation validated! ERR_USER_VERIFYTOKEN_RAFFLEVALIDATE_REG_OK = 2626, // Token foudn & Valid, raffle paritcipation validated, user account created! ERR_USER_SECONDFACTOR_ACC_NOT_SUITABLE = 2627, // User is not suitable to setup 2ndfactor, (User has no email/password set or 2ndfactor is already active) ERR_USER_SECONDFACTOR_REMOVE_INVALID_TOKEN = 2628, // Provided secondFactor Token is incorrect ERR_USER_SECONDFACTOR_REMOVE_FAIL = 2629, // User is not allowed to remove secondFactor (apps connected as developer?) ERR_USER_SECONDFACTOR_SETUP_TOKENFAIL = 2630, // User provided secondFactor token for completing the setup is invalid ERR_USER_DELETE_FAIL_HAS_OAUTH_APPS = 2631, // User can't be deleted, is owner of apps /** Group Errors */ ERR_GROUP_NOT_FOUND = 2701, // Unknown group (id) ERR_GROUP_PERM_UNASSIGNABLE = 2702, // Tried to assign an unassignable permission (see message for details) ERR_GROUP_NAME_IN_USE = 2703, // The given Name is already in use ERR_GROUP_NAME_IS_CONST = 2704, // Group name cannot be changed /** Schedule Errors */ ERR_SCHEDULE_INVALID_RANGE = 2801, // The given range between start & end is not supported ERR_SCHEDULE_LEGACY_LIMIT_EXCEEDED = 2802, // The given amount exceeds the supported maximum value ERR_SCHEDULE_LEGACY_NO_RUNNING_ITEM = 2803, // The current-running-item couldn't be determined /** CMS Errors */ ERR_CMS_PAGE_NOT_FOUND = 2901, // The requested identifier was not found ERR_CMS_PAGE_ID_INVALID = 2902, // The Requested identifier does not met the requirements ERR_CMS_PAGE_ID_IN_USE = 2903, // The Requested identifier is already in use ERR_CMS_ROUTE_NOT_FOUND = 2904, // The Requested route was not found ERR_CMS_ROUTE_INVALID = 2905, // The specified route identifier does not met the requirements ERR_CMS_ROUTE_IN_USE = 2906, // the Specified route is already in use / already exists /** EMAIL Errors */ ERR_EMAIL_INVALID = 3001, // Invalid Email Syntax ERR_EMAIL_PROVIDER_BLOCKED = 3002, // Mail Provider has been blocked ERR_EMAIL_TEMPLATE_TYPE_INVALID = 3003, // The given template type is unknown / invalid /** Media Errors */ ERR_MEDIA_SHOW_NOT_FOUND = 3101, // The requested show (by ID) does not exist ERR_MEDIA_SEASON_NOT_FOUND = 3102, // The requested season does not exist ERR_MEDIA_EPISODE_NOT_FOUND = 3103, // The request episode does not exist ERR_MEDIA_PROMOBOX_PROMO_NOT_FOUND = 3104, // The rquested promo does not exist ERR_MEDIA_PROMOBOX_INVALID_TYPE = 3105, // The given type is invalid ERR_MEDIA_PROMOBOX_IMAGE_INVALID = 3106, // The given image id is unknown or invalid /** Search Errors */ ERR_SEARCH_TERM_TOO_SHORT = 3201, // Search term was too short /** Subscription Errors */ ERR_SUBSCRIPTION_INVALID_TYPE = 3301, // Invalid type (in this context) ERR_SUBSCRIPTION_IMPOSSIBLE = 3302, // The given Entity can't be subscribed ERR_SUBSCRIPTION_FAILED = 3303, // Failed to get subscriptions ERR_SUBSCRIPTION_NOT_SUBSCRIBED = 3304, // The Requested type/id is not subscribed /** Simple Shop Errors */ ERR_SIMPLESHOP_ITEM_NOT_FOUND = 3401, // The requested Simple Shop Item does not exist ERR_SIMPLESHOP_ITEM_IMAGE_INVALID = 3402, // Invalid or unknown image supplied /** Supporters Club Errors */ ERR_SUPPORTER_IBAN_INVALID = 3501, // Invalid IBAN (Syntax Error) ERR_SUPPORTER_PAYPALMAIL_INVALID = 3502, // Invalid Paypal Email address (legacy paypal) ERR_SUPPORTER_PAYPAL_INVALID_VALUE = 3503, // invalid / unsupported subscription amount/value ERR_SUPPORTER_PAYPAL_ALREADY_SUBSCRIBED = 3504, // user already has a susbcription active and can't subscribe again ERR_SUPPORTER_PAYPAL_SUBSCRIBE_INTERNAL_ERROR = 3505, // Internal Paypal Error while creating the billing agreement ERR_SUPPORTER_PAYPAL_SUBSCRIBE_INVALID_TOKEN = 3506, // The provided payptoken is invalid / there was an error executing the agreement ERR_SUPPORTER_PAYPAL_SUBSCRIBE_CANCEL_FAIL = 3507, // Paypal Abo Cancellation failed ERR_SUPPORTER_PAYPAL_NOT_SUBSCRIBED = 3508, // No Subscription ERR_SUPPORTER_ADDRESS_TERMS_REQUIRED = 3509, // Must accept the shipping terms to set the address. ERR_SUPPORTER_ADDRESS_FIELD_VALIDATION_ERR = 3510, // Field validation Error /** Interaction */ ERR_INTERACTION_UNSUPPORTED_TYPE = 3601, // tried to create an unsupported interaction ERR_INTERACTION_INVALID_TYPE_FOR_OPERATION = 3602, // tried to perform an action on an interaction which doesn't support the requested operation ERR_INTERACTION_UNKNOWN = 3603, // the given interaction id is unknown or does not match the requested type. ERR_INTERACITON_ACTIVE = 3604, // Tried to modify an active interaction ERR_INTERACTION_UNKNOWN_POLLOPTION = 3605, // tried to modify an unknown poll option /** Billing */ ERR_BILLING_CSV_INVALID = 3701, // Invalid or Missing CSV File for CSV Upload ERR_BILLING_COMMERZBANK_TRANSACTION_NOT_FOUND = 3702, // the given transaction id was not found /** Raffle */ ERR_RAFFLE_ADDRESS_TERMS_REQUIRED = 3801, ERR_RAFFLE_ADDRESS_FIELD_VALIDATION_ERR = 3802, ERR_RAFFLE_NOT_FOUND = 3803, // Raffle does not exists ERR_RAFFLE_PARTICIPATE_ALREADY_ENTERED = 3804, // The Given E-Mail Address Already Participates ERR_RAFFLE_PARTICIPATE_EMAIL_HAS_USER = 3805, // The given E-Mail Address for guest-participation already exists as a user account ERR_RAFFLE_PARTICIPATE_EMAIL_BLOCKED = 3806, // The given e-mail address is invalid/blocked provider ERR_RAFFLE_TERMS_REQUIRED = 3807, ERR_RAFFLE_GDPR_REQUIRED = 3808, ERR_RAFFLE_PARTICIPATE_USER_ADDRESS_REQ = 3809, // Participation with RBTV-Account requires raffleshippingaddress to be set. ERR_RAFFLE_PARTICIPATE_NOT_IN_TIME = 3810, // Participation not possible, startDate && endDate requirements have not been met ERR_RAFFLE_CHALLENGE_RESPONSE_FAILED = 3811, // Challenge Response Number Verification failed ERR_RAFFLE_PARTICIPATE_SUPPORTER_ONLY = 3812, // Cannot Participate as the requested Raffle requires a supporterlevel ERR_RAFFLE_SLUG_VALDATIONFAIL = 3813, // Invalid Slug ERR_RAFFLE_SLUG_INUSE = 3814, // Slug In use ERR_RAFFLE_FORM_VALIDATION_ERR = 3815, // Form Field Validation error; used in admin ERR_RAFFLE_DELETE_IMPOSSIBLE = 3816, // Cannot Delete Raffle because of .. reason ERR_RAFFLE_PARTICIPANT_NOT_FOUND = 3817, // Participant not found ERR_RAFFLE_WINNER_NOT_FOUND = 3818, // Requested winner num does not exist/not found ERR_RAFFLE_ADDRESS_DELETE_FAIL_PARTICIPATING = 3819, // User currently has participations pending, cannot delete address. ERR_RAFFLE_WINNER_PRIZE_ALREADY_SENT = 3820, // prize notification already sent, requires conrimation ERR_RAFFLE_TERMS_NO_EDIT_PERM = 3821, // no permission to edit terms /** CDKey */ ERR_CDKEY_TYPE_NOT_FOUND = 3901, // Requested CDKey Type(id) does not exist ERR_CDKEY_TYPE_INVALID = 3902, // Out of Range, invalid (NaN) etc ERR_CDKEY_TYPE_EXISTS = 3903, // The Given CDKeyType already exists ERR_CDKEY_TYPE_FORM_VALIDATION_ERR = 3904, // Form validation error, see message + data for details ERR_CDKEY_TYPE_HAS_KEYS = 3905, // Action cannot performed: Type has keys assigned (delete) ERR_CDKEY_PRODUCT_NOT_FOUND = 3906, // Requested Product id for given type not found ERR_CDKEY_PRODUCT_INVALID = 3907, // Out of Range / invalid (nan) etc ERR_CDKEY_PRODUCT_FORM_VALIDATION_ERR = 3908, // Form validation error, see message+data for details ERR_CDKEY_INVALID = 3909, // Key Validation Error ERR_CDKEY_TOKEN_INVALID = 3910, // Token invalid/expired ERR_CDKEY_TOOMANY_USES = 3911, // All Free Uses are used up. ERR_CDKEY_ALREADY_CLAIMED = 3912, // Cannot claim the key, alrady claimed ERR_CDKEY_ALREADY_CLAIMED_SAMEUSER = 3913, // The Key is already claimed by the requesting user ERR_CDKEY_CLAIM_FAIL = 3914, // Claim faled, this happens @ doublecheck, user may have tried to claim twice in parallel. ERR_CDKEY_CLAIMED = 3915, // CDKey is claimed, cannot get download links ERR_CDKEY_NO_LICENCE = 3916, // Requesting usre has no license (key) to access the given product ERR_CDKEY_ALREADY_OWNED = 3917, // Keytype already owned by user /** OAuth: Auth */ // Error Codes by RFC/Specification: ERR_OAUTH_SPEC_INVALID_REQUEST = 4001, ERR_OAUTH_SPEC_UNAUTHORIZED_CLIENT = 4002, ERR_OAUTH_SPEC_ACCESS_DENIED = 4003, ERR_OAUTH_SPEC_UNSUPPORTED_RESPONSE_TYPE = 4004, ERR_OAUTH_SPEC_INVALID_SCOPE = 4005, ERR_OAUTH_SPEC_SERVER_ERROR = 4006, ERR_OAUTH_SPEC_TEMPORARILY_UNAVAILABLE = 4007, /** OAuth: APPS */ ERR_OAUTH_APP_NOT_FOUND = 4101, // App Does not exist ERR_OAUTH_APP_NO_PERMISSION = 4102, // No Permission for the given app id ERR_OAUTH_APP_FORM_VALIDATION_ERR = 4103, // Form Validation Error (used upon app creation / edit) ERR_OAUTH_APP_CREATE_MISSING_SECONDFACTOR = 4104, // Requesting Apiuser has no secondfactor authorizaiton activated ERR_OAUTH_APP_CREATE_LIMIT_EXCEEDED = 4105, // Requesting Apiuser has exceeded his/her limit of apps per account ERR_OAUTH_APP_VERIFYDEV_TERMS_REQ = 4106, // Must accept terms regarding mail for dev-verification ERR_OAUTH_APP_VERIFYDEV_NOT_FOUND = 4107, // Given UserID has no pendning verification request /** OAuth: Scopes */ ERR_OAUTH_SCOPE_NOT_FOUND = 4201, ERR_OAUTH_SCOPE_ALREADY_EXIST = 4202, ERR_OAUTH_SCOPE_FORM_VALIDATION_ERR = 4203, /** OAuth: Authorizations */ ERR_OAUTH_AUTHORIZATION_NOT_FOUND = 4301, // Given Authorization id is unknown or does not relate to the requesitng apiuser /** Mediacenter */ ERR_MEDIACENTER_IMAGE_NOT_FOUND = 4401, // Given Image ID is invalid / not found ERR_MEDIACENTER_IMAGE_ALREADY_PROCESSED = 4402, // Given Image ID has been already processed ERR_MEDIACENTER_FORM_VALIDATION_ERR = 4403, // Parameter Validation Failed (string length etc, see data for more info) ERR_MEDIACENTER_IMAGE_PROCESSING_FAILED = 4404, // Image Processing (scaling, upload) failed ERR_MEDIACENTER_IMAGE_UNPROCESSED = 4405, // Image is unprocessed, action cannot be performed ERR_MEDIACENTER_UNSUPPORTED_IMAGETYPE = 4406, // Given Image Type is unknown / unsupported ERR_MEDIACENTER_DELETE_REJECT_IN_USE = 4407, // Given Image is still being used - cannot be deleted /** Cache Administration */ ERR_CACHE_INVALID_NAME = 4501, // Invalid or Unknown Cache Name /** RBTV Event */ ERR_RBTVEVENT_EVENT_NOT_FOUND = 4601, // No event found with the given slug, or the slug is invalid ERR_RBTVEVENT_EVENT_FORM_VALIDATION_ERR = 4602, // Form Validation Error -> invalid input (such as invalid characters etc) ERR_RBTVEVENT_EVENT_SLUG_IN_USE = 4603, // The given Event-Slug is already in use ERR_RBTVEVENT_EVENT_ENABLE_FAIL = 4604, // Enable Failed (another event still active?) ERR_RBTVEVENT_EVENT_DISABLE_FAIL = 4605, // Disable Failed (not active?) ERR_RBTVEVENT_EVENT_DELETE_FAIL = 4606, // Event deletion failed (is the event still active?) ERR_RBTVEVENT_TEAM_NOT_FOUND = 4607, // The given team does not exist ERR_RBTVEVENT_TEAM_FORM_VALIDATION_ERR = 4608, // Form Validation Error -> invalid input (such as invalid cahracters, length etc) ERR_RBTVEVENT_TEAM_DELETE_FAIL = 4607, // Deletion Failed (is the relating event still active?) ERR_RBTVEVENT_NO_ACTIVE_EVENT = 4608, // No Active Event found (generic error, the given action requires an event being active) ERR_RBTVEVENT_EVENT_INVALID = 4609, // The given Event is invalid for the requested action. ERR_RBTVEVENT_TEAM_INVALID = 4610, // The given Team is invalid for the requested action. ERR_RBTVEVENT_TEAM_NOT_JOINABLE = 4611, // The given Team is not in a joinable state. ERR_RBTVEVENT_TEAM_JOIN_FAILED = 4612, // Join Request failed (already joined another team?) ERR_RBTVEVENT_EVENT_NOT_JOINED_TEAM = 4613, // The requesing user has not joined any team for the given event // ERR_LAST };
the_stack
import { ComboBox, IComboBox, IComboBoxOption, Link, PrimaryButton, Stack, TextField } from '@fluentui/react' import React, { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { StepWizardChildProps, StepWizardProps } from 'react-step-wizard' import { StackGap10, StackGap5 } from '../components/StackStyle' import { StepPanel } from '../components/StepPanel' import { useWindowSize } from '../components/UseWindowSize' import { HeaderMenuHeight, WizardNavBar } from '../components/WizardNavBar' import { AdapterChangedEvent, AdapterKind, ChangedField } from '../model/Adapter' import { getNavSteps } from '../model/DefaultNavSteps' import { AdapterDataSrv } from '../services/ConfigureAdapter' import { AppState } from '../store/configureStore' import '../css/configureAdapter.css' import { AdapterActions } from '../actions/ConfigureAdapterAction' import { InvalidAppStateNotification } from '../components/InvalidAppStateNotification' export function ConfigureAdapter (props: StepWizardProps) { const dispatch = useDispatch() const testSuiteInfo = useSelector((state: AppState) => state.testSuiteInfo) const configuration = useSelector((state: AppState) => state.configurations) const adapters = useSelector((state: AppState) => state.configureAdapter) const configureMethod = useSelector((state: AppState) => state.configureMethod) useEffect(() => { if (configuration.selectedConfiguration != null) { dispatch(AdapterDataSrv.getAdapters(configuration.selectedConfiguration.Id!)) } }, [dispatch, configuration.selectedConfiguration]) const wizardProps: StepWizardChildProps = props as StepWizardChildProps const navSteps = getNavSteps(wizardProps, configureMethod) const wizard = WizardNavBar(wizardProps, navSteps) const winSize = useWindowSize() if (testSuiteInfo.selectedTestSuite === undefined || configuration.selectedConfiguration === undefined) { return <InvalidAppStateNotification testSuite={testSuiteInfo.selectedTestSuite} configuration={configuration.selectedConfiguration} wizard={wizard} wizardProps={wizardProps} /> } const onAdapterChanged = (event: AdapterChangedEvent) => { dispatch(AdapterActions.onAdapterChanged(event)) } const adapterList = adapters.adapterList.map((item, index) => { return <AdapterItem key={index} Name={item.Name} DisplayName={item.DisplayName} AdapterType={item.AdapterType} Kind={item.Kind} ScriptDirectory={item.ScriptDirectory} SupportedKinds={item.SupportedKinds} ShellScriptDirectory={item.ShellScriptDirectory} onChange={onAdapterChanged} /> }) const onNextStepClicked = () => { if (verifyAdapterSettings()) { AdapterActions.setErrorMessage() dispatch(AdapterDataSrv.setAdapters(configuration.selectedConfiguration!.Id!, adapters.adapterList, (data: any) => { wizardProps.nextStep() })) } else { dispatch(AdapterActions.setErrorMessage(`[${(new Date()).toLocaleTimeString()}]: Adapter\'s required field is not set`)) } } const verifyAdapterSettings = (): boolean => { for (const item of adapters.adapterList) { if ((item.Kind === AdapterKind.Managed) && (!item.AdapterType)) { return false } else if ((item.Kind === AdapterKind.Shell && (!item.ShellScriptDirectory)) || (item.Kind === AdapterKind.PowerShell && (!item.ScriptDirectory))) { return false } } return true } return ( <div> <StepPanel leftNav={wizard} isLoading={adapters.isLoading} errorMsg={adapters.errorMsg} > <div style={{ height: winSize.height - HeaderMenuHeight - 45, overflowY: 'scroll' }}> {adapterList.length > 0 ? adapterList : <h1>There is no Adapter for current test suite, just click Next button to continue.</h1>} </div> <div className='buttonPanel'> <Stack horizontal horizontalAlign='end' tokens={StackGap10}> <PrimaryButton text="Previous" onClick={() => wizardProps.previousStep()} disabled={adapters.isPosting} /> <PrimaryButton text="Next" onClick={onNextStepClicked} disabled={adapters.isPosting} /> </Stack> </div> </StepPanel> </div> ) }; interface AdapterItemProp { Name: string DisplayName: string AdapterType: string Kind: AdapterKind ScriptDirectory: string SupportedKinds: AdapterKind[] ShellScriptDirectory: string onChange: (event: AdapterChangedEvent) => void } function AdapterItem (props: AdapterItemProp) { const INITIAL_OPTIONS: IComboBoxOption[] = [] const [adapterKind, setAdapterKind] = useState<AdapterKind>(props.Kind) const [paramAdapterType, setParamAdapterType] = useState<string>(props.AdapterType ? props.AdapterType : '') const [paramScriptDirectory, setParamScriptDirectory] = useState<string>(props.ScriptDirectory ? props.ScriptDirectory : '') const [paramShellScriptDirectory, setParamShellScriptDirectory] = useState<string>(props.ShellScriptDirectory ? props.ShellScriptDirectory : '') const [errorMsg, setErrorMsg] = useState('') // Add all supported kinds of plugin to INITIAL_OPTIONS if (props.SupportedKinds.length > 0) { for (const key in props.SupportedKinds) { const value = props.SupportedKinds[key] INITIAL_OPTIONS.push({ key: value, text: value }) } // The PTFCONFIG file's adapterKind is not in INITIAL_OPTIONS which are the adapter kinds supported by plugin, so we use INITIAL_OPTIONS[0] as default selected adapter kind. if (INITIAL_OPTIONS.filter((x) => x.key === ('' + adapterKind)).length === 0) { if (INITIAL_OPTIONS.length > 0) { setAdapterKind(AdapterKind[INITIAL_OPTIONS[0].key as keyof typeof AdapterKind]) } } } else { // Plugin doesn't show any adapter kind, so we list all adapter types for current AdapterItem. for (const [propertyKey, propertyValue] of Object.entries(AdapterKind)) { if (!Number.isNaN(Number(propertyKey))) { continue } INITIAL_OPTIONS.push({ key: propertyValue, text: propertyKey }) } } const onChange = React.useCallback( (ev: React.FormEvent<IComboBox>, option?: IComboBoxOption): void => { const kind = AdapterKind[option?.key as keyof typeof AdapterKind] setAdapterKind(kind) checkRequiredField(kind, paramAdapterType, paramScriptDirectory, paramShellScriptDirectory) props.onChange({ Field: ChangedField.AdapterKind, NewValue: option?.key, Adapter: props.Name }) }, [setAdapterKind, props] ) const onChangeParamManagedAdapterType = React.useCallback( (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => { setParamAdapterType(newValue || '') checkRequiredField(adapterKind, newValue!, paramScriptDirectory, paramShellScriptDirectory) props.onChange({ Field: ChangedField.AdapterType, NewValue: newValue, Adapter: props.Name }) }, [props] ) const onChangeParamScriptDirectory = React.useCallback( (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => { setParamScriptDirectory(newValue || '') checkRequiredField(adapterKind, paramAdapterType, newValue!, '') props.onChange({ Field: ChangedField.ScriptDirectory, NewValue: newValue, Adapter: props.Name }) }, [props] ) const onChangeParamShellScriptDirectory = React.useCallback( (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => { setParamShellScriptDirectory(newValue || '') checkRequiredField(adapterKind, paramAdapterType, '', newValue!) props.onChange({ Field: ChangedField.ShellScriptDirectory, NewValue: newValue, Adapter: props.Name }) }, [props] ) const checkRequiredField = (_adapterKind: AdapterKind, _paramAdapterType: string, _paramScriptDirectory: string, _paramShellScriptDirectory: string) => { if ((_adapterKind === AdapterKind.Managed) && (!_paramAdapterType)) { setErrorMsg('Adapter Type Can\'t be null') } else if ((_adapterKind === AdapterKind.PowerShell && !_paramScriptDirectory) || (_adapterKind === AdapterKind.Shell && !_paramShellScriptDirectory)) { setErrorMsg('Script Directory Can\'t be null') } else { setErrorMsg('') } } let description let paramsDiv switch (adapterKind) { case AdapterKind.Interactive: description = <div> <div>Interactive Adapter pops up a dialog when one of the following method is called.</div> <div>You need to do the operation manually and enter the results in the dialog box.</div> </div> paramsDiv = <div style={{ fontStyle: 'italic' }}>Interactive adapter has no configurations</div> break case AdapterKind.Managed: description = <div> <div>Managed Adapter uses managed code to implement the methods in the adapter.</div> <div>Usually, you do not need to change the configuration for managed adapter.</div> </div> paramsDiv = <div> <Stack horizontalAlign="start" horizontal tokens={StackGap10}> <div style={{ fontWeight: 'bold' }}>Adapter Type: </div> <TextField ariaLabel='Managed adapter type' value={paramAdapterType} className='input' onChange={onChangeParamManagedAdapterType} errorMessage={errorMsg} /> </Stack> </div> break case AdapterKind.PowerShell: description = <div> <div>PowerShell Adapter uses PowerShell scripts to implement the methods in the adapter.</div> <div>One PowerShell script file for each method.</div> </div> paramsDiv = <div className='parameters'> <div>You need to configure the location of the scripts.</div> <Stack horizontalAlign="start" horizontal tokens={StackGap10}> <div style={{ fontWeight: 'bold' }}>Script Directory: </div> <TextField ariaLabel='PowerShell adapter script directory' value={paramScriptDirectory} className='input' onChange={onChangeParamScriptDirectory} errorMessage={errorMsg} /> </Stack> </div> break case AdapterKind.Shell: description = <div> <div>Shell Adapter uses shell script to implement the methods in the adapter.</div> <div>One .sh file for each method.</div> </div> paramsDiv = <div className='parameters'> <div>You need to configure the location of the scripts.</div> <Stack horizontalAlign="start" horizontal tokens={StackGap10}> <div style={{ fontWeight: 'bold' }}>Script Directory: </div> <TextField ariaLabel='Shell adapter script directory' value={paramShellScriptDirectory} className='input' onChange={onChangeParamShellScriptDirectory} errorMessage={errorMsg} /> </Stack> </div> break default: console.log('Not support yet') break }; useEffect(() => { checkRequiredField(adapterKind, paramAdapterType, paramScriptDirectory, paramShellScriptDirectory) }, []) return (<div className="adapterItem"> <Stack tokens={StackGap5}> <div className='title'> {props.DisplayName} </div> <Stack horizontalAlign="start" horizontal> <div>Type:</div> <ComboBox className='input' allowFreeform={false} autoComplete={'on'} ariaLabel='Select an adapter type' options={INITIAL_OPTIONS} selectedKey={adapterKind} onChange={onChange} /> </Stack> <hr /> {description} {paramsDiv} </Stack> </div>) }
the_stack
import { withI18n, i18nMark } from "@lingui/react"; import { Trans, t } from "@lingui/macro"; import mixin from "reactjs-mixin"; import { Modal, Tooltip } from "reactjs-components"; import PropTypes from "prop-types"; import * as React from "react"; import { Icon, InfoBoxInline } from "@dcos/ui-kit"; import { purpleLighten1 } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import FormGroup from "#SRC/js/components/form/FormGroup"; import FormGroupHeading from "#SRC/js/components/form/FormGroupHeading"; import FormGroupHeadingContent from "#SRC/js/components/form/FormGroupHeadingContent"; import FormRow from "#SRC/js/components/form/FormRow"; import FieldError from "#SRC/js/components/form/FieldError"; import FieldInput from "#SRC/js/components/form/FieldInput"; import FieldTextarea from "#SRC/js/components/form/FieldTextarea"; import FieldFile from "#SRC/js/components/form/FieldFile"; import FieldLabel from "#SRC/js/components/form/FieldLabel"; import ModalHeading from "#SRC/js/components/modals/ModalHeading"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import PrivatePluginsConfig from "../../PrivatePluginsConfig"; import getSecretStore from "../stores/SecretStore"; const SecretStore = getSecretStore(); const FILE_SIZE_LIMIT_IN_BYTES = 786 * 1024; // 786KB is the max file size const FileSize = ({ value }) => { const sizeInBytes = value.size; function toString(num) { return num.toLocaleString({ maximumFractionDigits: 3 }); } if (sizeInBytes < 1024) { return ( <Trans id="{sizeInBytes} B" values={{ sizeInBytes: toString(sizeInBytes), }} /> ); } const sizeInKB = sizeInBytes / 1024; if (sizeInKB < 1024) { return ( <Trans id="{sizeInKB} kB" values={{ sizeInKB: toString(sizeInKB), }} /> ); } const sizeInMB = sizeInKB / 1024; return <Trans id="{sizeInMB} MB" values={{ sizeInMB: toString(sizeInMB) }} />; }; const FileOverview = ({ onDelete, file }) => ( <FormRow> <div className="column-12 secret-file-value flex flex-align-items-center"> <Icon ariaLabel="file" shape="system-page-document" color={purpleLighten1} /> <span className="flex-item-grow-1 text-overflow flex-item-basis-none"> {file.name} </span> <FileSize value={file} /> <a className="text-danger clickable" onClick={onDelete}> <Trans>Remove</Trans> </a> </div> </FormRow> ); const browserSupportsFileApi = (() => { try { new File([], ""); return true; } catch (e) { return false; } })(); class SecretFormModal extends mixin(StoreMixin) { static defaultProps = { secret: {}, onClose() {}, open: false, }; static propTypes = { secret: PropTypes.object, onClose: PropTypes.func, open: PropTypes.bool, }; state = { requestErrorType: null, requestErrorMessage: null, localErrors: null, path: null, textValue: null, fileValue: null, valueType: "text", pendingRequest: false, }; // prettier-ignore store_listeners = [ {name: "secrets", events: ["createSecretSuccess", "createSecretError", "updateSecretSuccess", "updateSecretError"]} ]; UNSAFE_componentWillUpdate(nextProps) { // Populate state with current secret's values, if provided. if ( nextProps.open && !this.props.open && Object.keys(nextProps.secret).length !== 0 ) { const isBinarySecret = nextProps.secret.isBinary(); this.setState({ path: nextProps.secret.path || "", textValue: !isBinarySecret ? nextProps.secret.value || "" : "", fileValue: isBinarySecret ? nextProps.secret.getValue() : undefined, valueType: isBinarySecret ? "file" : "text", }); } } UNSAFE_componentWillReceiveProps(nextProps) { // Reset state when the modal is closing. if (this.props.open && !nextProps.open) { this.setState({ requestErrorType: null, localErrors: null, path: null, textValue: null, fileValue: null, valueType: "text", pendingRequest: false, }); } } onSecretsStoreUpdateSecretSuccess = () => { this.setState({ requestErrorType: null }); SecretStore.fetchSecrets(); this.props.onClose(); }; onSecretsStoreCreateSecretSuccess = () => { this.setState({ requestErrorType: null }); SecretStore.fetchSecrets(); this.props.onClose(); }; onSecretsStoreCreateSecretError = (error) => { this.setState({ ...this.stateFromError(error, "create"), pendingRequest: false, }); }; onSecretsStoreUpdateSecretError = (error) => { this.setState({ ...this.stateFromError(error, "update"), pendingRequest: false, }); }; stateFromError(error, operation) { const { i18n } = this.props; if (this.isForbiddenError(error)) { return { requestErrorType: "permission", requestErrorMessage: i18n._(t`You do not have permission to`) + " " + operation + " " + i18n._( t`this secret. Please contact your super admin to learn more.` ), }; } return { requestErrorType: "failure", requestErrorMessage: i18n._(t`An error has occurred.`), }; } isForbiddenError(error) { return error && error.status === 403; } getPathFieldErrors = () => { const { i18n } = this.props; const { path } = this.state; if (path === "" || path == null) { return { path: i18n._(t`This field is required.`), }; } if (!this.isPathValid(path)) { return { path: i18n._( t`Invalid syntax. Cannot use slashes at the beginning or end.` ), }; } else if (!this.isValid(path)) { return { path: i18n._( t`Alphanumerical, dashes, underscores and slashes are allowed.` ), }; } return {}; }; getValueFieldErrors = () => { const { i18n } = this.props; const { textValue } = this.state; if (!textValue) { return { textValue: i18n._(t`This field is required.`), }; } return {}; }; getFileFieldErrors = () => { const { i18n } = this.props; const { fileValue } = this.state; if (!fileValue) { return { file: i18n._(t`This field is required.`), }; } if (fileValue.size > FILE_SIZE_LIMIT_IN_BYTES) { return { file: i18n._(t`The maximum file size for a secret is 786KB.`), }; } return {}; }; getErrorMessage() { const { requestErrorType, requestErrorMessage } = this.state; const showNotSupportedError = this.denyFileBasedSecret(); if (requestErrorType && requestErrorMessage) { return ( <React.Fragment> <InfoBoxInline appearance="danger" message={requestErrorMessage} /> <br /> </React.Fragment> ); } if (showNotSupportedError) { return ( <InfoBoxInline className="form-group" appearance="danger" message={ <Trans> This version of your browser does not support updating the file. To change the file, you can update your browser, use a different browser, or use the CLI. </Trans> } /> ); } return null; } getModalFooter() { const disableAfirmation = this.denyFileBasedSecret(); const { pendingRequest } = this.state; let affirmCopy = pendingRequest ? i18nMark("Creating...") : i18nMark("Create Secret"); if (this.isEditingSecret()) { affirmCopy = pendingRequest ? i18nMark("Saving...") : i18nMark("Save Secret"); } return ( <div className="flush-bottom flex flex-direction-top-to-bottom flex-align-items-stretch-screen-small flex-direction-left-to-right-screen-small flex-justify-items-space-between-screen-medium"> <button className="button button-primary-link flush-left" onClick={this.props.onClose} > <Trans render="span">Cancel</Trans> </button> {!disableAfirmation ? ( <button className="button button-primary" onClick={this.handleAffirmClick} disabled={this.state.pendingRequest} > <Trans render="span" id={affirmCopy} /> </button> ) : null} </div> ); } getModalHeading() { const title = this.isEditingSecret() ? i18nMark("Edit Secret") : i18nMark("Create New Secret"); return ( <ModalHeading> <Trans render="span" id={title} /> </ModalHeading> ); } getPathRow() { const { path: fieldValue } = this.state; const hasError = Boolean( this.state.localErrors && this.state.localErrors.path ); const isDisabled = this.isEditingSecret(); const formGroup = ( <FormGroup className="column-12" showError={hasError}> <FieldLabel> <FormGroupHeading required={true}> <Trans render={<FormGroupHeadingContent primary={true} title="ID" />} > ID </Trans> </FormGroupHeading> </FieldLabel> <FieldInput disabled={isDisabled} name="path" value={fieldValue} /> <FieldError>{hasError ? this.state.localErrors.path : null}</FieldError> </FormGroup> ); if (isDisabled) { return ( <Tooltip content="You cannot edit the ID." wrapperClassName="form-row row tooltip-block-wrapper tooltip-wrapper" > {formGroup} </Tooltip> ); } return <FormRow>{formGroup}</FormRow>; } handleSwitchToText = () => { this.setState({ valueType: "text" }); }; handleSwitchToFile = () => { this.setState({ valueType: "file" }); }; getTypeRow() { const isTextSecret = this.isTextSecret(); return ( <FormRow> <FormGroup className="column-12"> <FieldLabel> <Trans render="span">Type</Trans> </FieldLabel> <FieldLabel> <FieldInput checked={isTextSecret} onChange={this.handleSwitchToText} name="type" type="radio" value="text" /> <div className="flex flex-align-items-center"> <Trans>Key-Value Pair</Trans> </div> </FieldLabel> <FieldLabel> <FieldInput checked={!isTextSecret} onChange={this.handleSwitchToFile} name="type" type="radio" value="file" /> <Trans>File</Trans> </FieldLabel> </FormGroup> </FormRow> ); } getValueRow() { const { textValue: fieldValue, localErrors } = this.state; const hasError = Boolean(localErrors && localErrors.textValue); return ( <FormRow> <FormGroup className="column-12 flush-bottom" showError={hasError}> <FieldLabel> <FormGroupHeading required={true}> <Trans render={<FormGroupHeadingContent />}>Value</Trans> </FormGroupHeading> </FieldLabel> <FieldTextarea name="textValue" value={fieldValue} /> <FieldError>{hasError ? localErrors.textValue : null}</FieldError> </FormGroup> </FormRow> ); } getFileRow() { const { fileValue: fieldValue } = this.state; const hasError = Boolean( this.state.localErrors && this.state.localErrors.file ); return ( <FormRow> <FormGroup className="column-12 flush-bottom" showError={hasError}> <FieldLabel> <FormGroupHeading required={true}> <Trans render={<FormGroupHeadingContent />}>File</Trans> </FormGroupHeading> </FieldLabel> {fieldValue ? ( <FileOverview onDelete={this.handleFileClear} file={fieldValue} /> ) : ( <FieldFile name="file" onChange={this.handleFileChange} /> )} <FormRow> <FieldError className="column-12"> {hasError ? this.state.localErrors.file : null} </FieldError> </FormRow> </FormGroup> </FormRow> ); } getReadOnlyFileRow() { return ( <FormRow> <FormGroup className="column-12 flush-bottom"> <FieldLabel> <FormGroupHeading required={true}> <Trans render={<FormGroupHeadingContent />}>File</Trans> </FormGroupHeading> </FieldLabel> <FieldTextarea disabled={true} name="textValue" value="File Uploaded" /> </FormGroup> </FormRow> ); } handleAffirmClick = () => { const localErrors = this.validateFields(); this.setState({ localErrors, pendingRequest: Object.keys(localErrors).length < 1, }); if (Object.keys(localErrors).length) { return; } const { path, textValue, fileValue } = this.state; let value; if (this.isTextSecret()) { // Remove leading/trailing white space characters // and line terminators value = textValue.trim(); } else { value = fileValue; } if (this.isEditingSecret()) { const { secret: previousSecret } = this.props; SecretStore.updateSecret( PrivatePluginsConfig.secretsDefaultStore, previousSecret.getPath(), value ); return; } SecretStore.createSecret( PrivatePluginsConfig.secretsDefaultStore, path, value ); }; isTextSecret() { const { valueType } = this.state; return valueType === "text"; } handleFormChange = (event) => { this.setState({ [event.target.name]: event.target.value }); }; handleFileChange = (event) => { this.setState({ fileValue: event.target.files[0] }, () => { const fileErrors = this.getFileFieldErrors(); this.setState(({ localErrors }) => ({ localErrors: { ...localErrors, ...fileErrors }, })); }); }; handleFileClear = () => { this.setState({ fileValue: null, localErrors: null }); }; isEditingSecret() { return this.props.secret.path != null; } isPathValid(path) { // starts or ends with a dash return path && /^(?!\/).*[^/]$/.test(path); } isValid(path) { // all other errors return path && /^(\/?[a-zA-Z0-9-_])+$/.test(path); } validateFields = () => { return { ...this.getPathFieldErrors(), ...(this.isTextSecret() ? this.getValueFieldErrors() : this.getFileFieldErrors()), }; }; // We can not edit file based secrets because browsers like edge dont allow Files to be constructed denyFileBasedSecret() { return ( !this.isTextSecret() && !browserSupportsFileApi && this.isEditingSecret() ); } render() { let valueField = null; if (this.isTextSecret()) { valueField = this.getValueRow(); } else { valueField = this.denyFileBasedSecret() ? this.getReadOnlyFileRow() : this.getFileRow(); } return ( <Modal footer={this.getModalFooter()} header={this.getModalHeading()} modalClass="modal modal-small" onClose={this.props.onClose} open={this.props.open} showFooter={true} showHeader={true} > <div onChange={this.handleFormChange}> {this.getErrorMessage()} {this.getPathRow()} {this.getTypeRow()} {valueField} </div> </Modal> ); } } export default withI18n()(SecretFormModal);
the_stack
import Long from "long"; import _m0 from "protobufjs/minimal"; import { Coin } from "../../cosmos/base/v1beta1/coin"; import { Any } from "../../google/protobuf/any"; import { EthereumSigner } from "../../gravity/v1/gravity"; export const protobufPackage = "gravity.v1"; /** * MsgSendToEthereum submits a SendToEthereum attempt to bridge an asset over to * Ethereum. The SendToEthereum will be stored and then included in a batch and * then submitted to Ethereum. */ export interface MsgSendToEthereum { sender: string; ethereumRecipient: string; amount?: Coin; bridgeFee?: Coin; } /** * MsgSendToEthereumResponse returns the SendToEthereum transaction ID which * will be included in the batch tx. */ export interface MsgSendToEthereumResponse { id: Long; } /** * MsgCancelSendToEthereum allows the sender to cancel its own outgoing * SendToEthereum tx and recieve a refund of the tokens and bridge fees. This tx * will only succeed if the SendToEthereum tx hasn't been batched to be * processed and relayed to Ethereum. */ export interface MsgCancelSendToEthereum { id: Long; sender: string; } export interface MsgCancelSendToEthereumResponse {} /** * MsgRequestBatchTx requests a batch of transactions with a given coin * denomination to send across the bridge to Ethereum. */ export interface MsgRequestBatchTx { denom: string; signer: string; } export interface MsgRequestBatchTxResponse {} /** * MsgSubmitEthereumTxConfirmation submits an ethereum signature for a given * validator */ export interface MsgSubmitEthereumTxConfirmation { /** TODO: can we make this take an array? */ confirmation?: Any; signer: string; } /** * ContractCallTxConfirmation is a signature on behalf of a validator for a * ContractCallTx. */ export interface ContractCallTxConfirmation { invalidationScope: Uint8Array; invalidationNonce: Long; ethereumSigner: string; signature: Uint8Array; } /** BatchTxConfirmation is a signature on behalf of a validator for a BatchTx. */ export interface BatchTxConfirmation { tokenContract: string; batchNonce: Long; ethereumSigner: string; signature: Uint8Array; } /** * SignerSetTxConfirmation is a signature on behalf of a validator for a * SignerSetTx */ export interface SignerSetTxConfirmation { signerSetNonce: Long; ethereumSigner: string; signature: Uint8Array; } export interface MsgSubmitEthereumTxConfirmationResponse {} /** MsgSubmitEthereumEvent */ export interface MsgSubmitEthereumEvent { event?: Any; signer: string; } /** * SendToCosmosEvent is submitted when the SendToCosmosEvent is emitted by they * gravity contract. ERC20 representation coins are minted to the cosmosreceiver * address. */ export interface SendToCosmosEvent { eventNonce: Long; tokenContract: string; amount: string; ethereumSender: string; cosmosReceiver: string; ethereumHeight: Long; } /** * BatchExecutedEvent claims that a batch of BatchTxExecutedal operations on the * bridge contract was executed successfully on ETH */ export interface BatchExecutedEvent { tokenContract: string; eventNonce: Long; ethereumHeight: Long; batchNonce: Long; } /** * NOTE: bytes.HexBytes is supposed to "help" with json encoding/decoding * investigate? */ export interface ContractCallExecutedEvent { eventNonce: Long; invalidationId: Uint8Array; invalidationNonce: Long; ethereumHeight: Long; } /** * ERC20DeployedEvent is submitted when an ERC20 contract * for a Cosmos SDK coin has been deployed on Ethereum. */ export interface ERC20DeployedEvent { eventNonce: Long; cosmosDenom: string; tokenContract: string; erc20Name: string; erc20Symbol: string; erc20Decimals: Long; ethereumHeight: Long; } /** * This informs the Cosmos module that a validator * set has been updated. */ export interface SignerSetTxExecutedEvent { eventNonce: Long; signerSetTxNonce: Long; ethereumHeight: Long; members: EthereumSigner[]; } export interface MsgSubmitEthereumEventResponse {} /** * MsgDelegateKey allows validators to delegate their voting responsibilities * to a given orchestrator address. This key is then used as an optional * authentication method for attesting events from Ethereum. */ export interface MsgDelegateKeys { validatorAddress: string; orchestratorAddress: string; ethereumAddress: string; } export interface MsgDelegateKeysResponse {} const baseMsgSendToEthereum: object = { sender: "", ethereumRecipient: "" }; export const MsgSendToEthereum = { encode( message: MsgSendToEthereum, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.sender !== "") { writer.uint32(10).string(message.sender); } if (message.ethereumRecipient !== "") { writer.uint32(18).string(message.ethereumRecipient); } if (message.amount !== undefined) { Coin.encode(message.amount, writer.uint32(26).fork()).ldelim(); } if (message.bridgeFee !== undefined) { Coin.encode(message.bridgeFee, writer.uint32(34).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MsgSendToEthereum { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSendToEthereum } as MsgSendToEthereum; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.sender = reader.string(); break; case 2: message.ethereumRecipient = reader.string(); break; case 3: message.amount = Coin.decode(reader, reader.uint32()); break; case 4: message.bridgeFee = Coin.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgSendToEthereum { const message = { ...baseMsgSendToEthereum } as MsgSendToEthereum; if (object.sender !== undefined && object.sender !== null) { message.sender = String(object.sender); } else { message.sender = ""; } if ( object.ethereumRecipient !== undefined && object.ethereumRecipient !== null ) { message.ethereumRecipient = String(object.ethereumRecipient); } else { message.ethereumRecipient = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = Coin.fromJSON(object.amount); } else { message.amount = undefined; } if (object.bridgeFee !== undefined && object.bridgeFee !== null) { message.bridgeFee = Coin.fromJSON(object.bridgeFee); } else { message.bridgeFee = undefined; } return message; }, toJSON(message: MsgSendToEthereum): unknown { const obj: any = {}; message.sender !== undefined && (obj.sender = message.sender); message.ethereumRecipient !== undefined && (obj.ethereumRecipient = message.ethereumRecipient); message.amount !== undefined && (obj.amount = message.amount ? Coin.toJSON(message.amount) : undefined); message.bridgeFee !== undefined && (obj.bridgeFee = message.bridgeFee ? Coin.toJSON(message.bridgeFee) : undefined); return obj; }, fromPartial(object: DeepPartial<MsgSendToEthereum>): MsgSendToEthereum { const message = { ...baseMsgSendToEthereum } as MsgSendToEthereum; if (object.sender !== undefined && object.sender !== null) { message.sender = object.sender; } else { message.sender = ""; } if ( object.ethereumRecipient !== undefined && object.ethereumRecipient !== null ) { message.ethereumRecipient = object.ethereumRecipient; } else { message.ethereumRecipient = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = Coin.fromPartial(object.amount); } else { message.amount = undefined; } if (object.bridgeFee !== undefined && object.bridgeFee !== null) { message.bridgeFee = Coin.fromPartial(object.bridgeFee); } else { message.bridgeFee = undefined; } return message; }, }; const baseMsgSendToEthereumResponse: object = { id: Long.UZERO }; export const MsgSendToEthereumResponse = { encode( message: MsgSendToEthereumResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.id.isZero()) { writer.uint32(8).uint64(message.id); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgSendToEthereumResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSendToEthereumResponse, } as MsgSendToEthereumResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgSendToEthereumResponse { const message = { ...baseMsgSendToEthereumResponse, } as MsgSendToEthereumResponse; if (object.id !== undefined && object.id !== null) { message.id = Long.fromString(object.id); } else { message.id = Long.UZERO; } return message; }, toJSON(message: MsgSendToEthereumResponse): unknown { const obj: any = {}; message.id !== undefined && (obj.id = (message.id || Long.UZERO).toString()); return obj; }, fromPartial( object: DeepPartial<MsgSendToEthereumResponse> ): MsgSendToEthereumResponse { const message = { ...baseMsgSendToEthereumResponse, } as MsgSendToEthereumResponse; if (object.id !== undefined && object.id !== null) { message.id = object.id as Long; } else { message.id = Long.UZERO; } return message; }, }; const baseMsgCancelSendToEthereum: object = { id: Long.UZERO, sender: "" }; export const MsgCancelSendToEthereum = { encode( message: MsgCancelSendToEthereum, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.id.isZero()) { writer.uint32(8).uint64(message.id); } if (message.sender !== "") { writer.uint32(18).string(message.sender); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgCancelSendToEthereum { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgCancelSendToEthereum, } as MsgCancelSendToEthereum; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.uint64() as Long; break; case 2: message.sender = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgCancelSendToEthereum { const message = { ...baseMsgCancelSendToEthereum, } as MsgCancelSendToEthereum; if (object.id !== undefined && object.id !== null) { message.id = Long.fromString(object.id); } else { message.id = Long.UZERO; } if (object.sender !== undefined && object.sender !== null) { message.sender = String(object.sender); } else { message.sender = ""; } return message; }, toJSON(message: MsgCancelSendToEthereum): unknown { const obj: any = {}; message.id !== undefined && (obj.id = (message.id || Long.UZERO).toString()); message.sender !== undefined && (obj.sender = message.sender); return obj; }, fromPartial( object: DeepPartial<MsgCancelSendToEthereum> ): MsgCancelSendToEthereum { const message = { ...baseMsgCancelSendToEthereum, } as MsgCancelSendToEthereum; if (object.id !== undefined && object.id !== null) { message.id = object.id as Long; } else { message.id = Long.UZERO; } if (object.sender !== undefined && object.sender !== null) { message.sender = object.sender; } else { message.sender = ""; } return message; }, }; const baseMsgCancelSendToEthereumResponse: object = {}; export const MsgCancelSendToEthereumResponse = { encode( _: MsgCancelSendToEthereumResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgCancelSendToEthereumResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgCancelSendToEthereumResponse, } as MsgCancelSendToEthereumResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MsgCancelSendToEthereumResponse { const message = { ...baseMsgCancelSendToEthereumResponse, } as MsgCancelSendToEthereumResponse; return message; }, toJSON(_: MsgCancelSendToEthereumResponse): unknown { const obj: any = {}; return obj; }, fromPartial( _: DeepPartial<MsgCancelSendToEthereumResponse> ): MsgCancelSendToEthereumResponse { const message = { ...baseMsgCancelSendToEthereumResponse, } as MsgCancelSendToEthereumResponse; return message; }, }; const baseMsgRequestBatchTx: object = { denom: "", signer: "" }; export const MsgRequestBatchTx = { encode( message: MsgRequestBatchTx, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.denom !== "") { writer.uint32(10).string(message.denom); } if (message.signer !== "") { writer.uint32(18).string(message.signer); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MsgRequestBatchTx { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgRequestBatchTx } as MsgRequestBatchTx; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.denom = reader.string(); break; case 2: message.signer = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgRequestBatchTx { const message = { ...baseMsgRequestBatchTx } as MsgRequestBatchTx; if (object.denom !== undefined && object.denom !== null) { message.denom = String(object.denom); } else { message.denom = ""; } if (object.signer !== undefined && object.signer !== null) { message.signer = String(object.signer); } else { message.signer = ""; } return message; }, toJSON(message: MsgRequestBatchTx): unknown { const obj: any = {}; message.denom !== undefined && (obj.denom = message.denom); message.signer !== undefined && (obj.signer = message.signer); return obj; }, fromPartial(object: DeepPartial<MsgRequestBatchTx>): MsgRequestBatchTx { const message = { ...baseMsgRequestBatchTx } as MsgRequestBatchTx; if (object.denom !== undefined && object.denom !== null) { message.denom = object.denom; } else { message.denom = ""; } if (object.signer !== undefined && object.signer !== null) { message.signer = object.signer; } else { message.signer = ""; } return message; }, }; const baseMsgRequestBatchTxResponse: object = {}; export const MsgRequestBatchTxResponse = { encode( _: MsgRequestBatchTxResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgRequestBatchTxResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgRequestBatchTxResponse, } as MsgRequestBatchTxResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MsgRequestBatchTxResponse { const message = { ...baseMsgRequestBatchTxResponse, } as MsgRequestBatchTxResponse; return message; }, toJSON(_: MsgRequestBatchTxResponse): unknown { const obj: any = {}; return obj; }, fromPartial( _: DeepPartial<MsgRequestBatchTxResponse> ): MsgRequestBatchTxResponse { const message = { ...baseMsgRequestBatchTxResponse, } as MsgRequestBatchTxResponse; return message; }, }; const baseMsgSubmitEthereumTxConfirmation: object = { signer: "" }; export const MsgSubmitEthereumTxConfirmation = { encode( message: MsgSubmitEthereumTxConfirmation, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.confirmation !== undefined) { Any.encode(message.confirmation, writer.uint32(10).fork()).ldelim(); } if (message.signer !== "") { writer.uint32(18).string(message.signer); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgSubmitEthereumTxConfirmation { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSubmitEthereumTxConfirmation, } as MsgSubmitEthereumTxConfirmation; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.confirmation = Any.decode(reader, reader.uint32()); break; case 2: message.signer = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgSubmitEthereumTxConfirmation { const message = { ...baseMsgSubmitEthereumTxConfirmation, } as MsgSubmitEthereumTxConfirmation; if (object.confirmation !== undefined && object.confirmation !== null) { message.confirmation = Any.fromJSON(object.confirmation); } else { message.confirmation = undefined; } if (object.signer !== undefined && object.signer !== null) { message.signer = String(object.signer); } else { message.signer = ""; } return message; }, toJSON(message: MsgSubmitEthereumTxConfirmation): unknown { const obj: any = {}; message.confirmation !== undefined && (obj.confirmation = message.confirmation ? Any.toJSON(message.confirmation) : undefined); message.signer !== undefined && (obj.signer = message.signer); return obj; }, fromPartial( object: DeepPartial<MsgSubmitEthereumTxConfirmation> ): MsgSubmitEthereumTxConfirmation { const message = { ...baseMsgSubmitEthereumTxConfirmation, } as MsgSubmitEthereumTxConfirmation; if (object.confirmation !== undefined && object.confirmation !== null) { message.confirmation = Any.fromPartial(object.confirmation); } else { message.confirmation = undefined; } if (object.signer !== undefined && object.signer !== null) { message.signer = object.signer; } else { message.signer = ""; } return message; }, }; const baseContractCallTxConfirmation: object = { invalidationNonce: Long.UZERO, ethereumSigner: "", }; export const ContractCallTxConfirmation = { encode( message: ContractCallTxConfirmation, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.invalidationScope.length !== 0) { writer.uint32(10).bytes(message.invalidationScope); } if (!message.invalidationNonce.isZero()) { writer.uint32(16).uint64(message.invalidationNonce); } if (message.ethereumSigner !== "") { writer.uint32(26).string(message.ethereumSigner); } if (message.signature.length !== 0) { writer.uint32(34).bytes(message.signature); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ContractCallTxConfirmation { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseContractCallTxConfirmation, } as ContractCallTxConfirmation; message.invalidationScope = new Uint8Array(); message.signature = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.invalidationScope = reader.bytes(); break; case 2: message.invalidationNonce = reader.uint64() as Long; break; case 3: message.ethereumSigner = reader.string(); break; case 4: message.signature = reader.bytes(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ContractCallTxConfirmation { const message = { ...baseContractCallTxConfirmation, } as ContractCallTxConfirmation; message.invalidationScope = new Uint8Array(); message.signature = new Uint8Array(); if ( object.invalidationScope !== undefined && object.invalidationScope !== null ) { message.invalidationScope = bytesFromBase64(object.invalidationScope); } if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = Long.fromString(object.invalidationNonce); } else { message.invalidationNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = String(object.ethereumSigner); } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = bytesFromBase64(object.signature); } return message; }, toJSON(message: ContractCallTxConfirmation): unknown { const obj: any = {}; message.invalidationScope !== undefined && (obj.invalidationScope = base64FromBytes( message.invalidationScope !== undefined ? message.invalidationScope : new Uint8Array() )); message.invalidationNonce !== undefined && (obj.invalidationNonce = ( message.invalidationNonce || Long.UZERO ).toString()); message.ethereumSigner !== undefined && (obj.ethereumSigner = message.ethereumSigner); message.signature !== undefined && (obj.signature = base64FromBytes( message.signature !== undefined ? message.signature : new Uint8Array() )); return obj; }, fromPartial( object: DeepPartial<ContractCallTxConfirmation> ): ContractCallTxConfirmation { const message = { ...baseContractCallTxConfirmation, } as ContractCallTxConfirmation; if ( object.invalidationScope !== undefined && object.invalidationScope !== null ) { message.invalidationScope = object.invalidationScope; } else { message.invalidationScope = new Uint8Array(); } if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = object.invalidationNonce as Long; } else { message.invalidationNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = object.ethereumSigner; } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = object.signature; } else { message.signature = new Uint8Array(); } return message; }, }; const baseBatchTxConfirmation: object = { tokenContract: "", batchNonce: Long.UZERO, ethereumSigner: "", }; export const BatchTxConfirmation = { encode( message: BatchTxConfirmation, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tokenContract !== "") { writer.uint32(10).string(message.tokenContract); } if (!message.batchNonce.isZero()) { writer.uint32(16).uint64(message.batchNonce); } if (message.ethereumSigner !== "") { writer.uint32(26).string(message.ethereumSigner); } if (message.signature.length !== 0) { writer.uint32(34).bytes(message.signature); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxConfirmation { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseBatchTxConfirmation } as BatchTxConfirmation; message.signature = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tokenContract = reader.string(); break; case 2: message.batchNonce = reader.uint64() as Long; break; case 3: message.ethereumSigner = reader.string(); break; case 4: message.signature = reader.bytes(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): BatchTxConfirmation { const message = { ...baseBatchTxConfirmation } as BatchTxConfirmation; message.signature = new Uint8Array(); if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = String(object.tokenContract); } else { message.tokenContract = ""; } if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = Long.fromString(object.batchNonce); } else { message.batchNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = String(object.ethereumSigner); } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = bytesFromBase64(object.signature); } return message; }, toJSON(message: BatchTxConfirmation): unknown { const obj: any = {}; message.tokenContract !== undefined && (obj.tokenContract = message.tokenContract); message.batchNonce !== undefined && (obj.batchNonce = (message.batchNonce || Long.UZERO).toString()); message.ethereumSigner !== undefined && (obj.ethereumSigner = message.ethereumSigner); message.signature !== undefined && (obj.signature = base64FromBytes( message.signature !== undefined ? message.signature : new Uint8Array() )); return obj; }, fromPartial(object: DeepPartial<BatchTxConfirmation>): BatchTxConfirmation { const message = { ...baseBatchTxConfirmation } as BatchTxConfirmation; if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = object.tokenContract; } else { message.tokenContract = ""; } if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = object.batchNonce as Long; } else { message.batchNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = object.ethereumSigner; } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = object.signature; } else { message.signature = new Uint8Array(); } return message; }, }; const baseSignerSetTxConfirmation: object = { signerSetNonce: Long.UZERO, ethereumSigner: "", }; export const SignerSetTxConfirmation = { encode( message: SignerSetTxConfirmation, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.signerSetNonce.isZero()) { writer.uint32(8).uint64(message.signerSetNonce); } if (message.ethereumSigner !== "") { writer.uint32(18).string(message.ethereumSigner); } if (message.signature.length !== 0) { writer.uint32(26).bytes(message.signature); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): SignerSetTxConfirmation { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSignerSetTxConfirmation, } as SignerSetTxConfirmation; message.signature = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.signerSetNonce = reader.uint64() as Long; break; case 2: message.ethereumSigner = reader.string(); break; case 3: message.signature = reader.bytes(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SignerSetTxConfirmation { const message = { ...baseSignerSetTxConfirmation, } as SignerSetTxConfirmation; message.signature = new Uint8Array(); if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) { message.signerSetNonce = Long.fromString(object.signerSetNonce); } else { message.signerSetNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = String(object.ethereumSigner); } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = bytesFromBase64(object.signature); } return message; }, toJSON(message: SignerSetTxConfirmation): unknown { const obj: any = {}; message.signerSetNonce !== undefined && (obj.signerSetNonce = (message.signerSetNonce || Long.UZERO).toString()); message.ethereumSigner !== undefined && (obj.ethereumSigner = message.ethereumSigner); message.signature !== undefined && (obj.signature = base64FromBytes( message.signature !== undefined ? message.signature : new Uint8Array() )); return obj; }, fromPartial( object: DeepPartial<SignerSetTxConfirmation> ): SignerSetTxConfirmation { const message = { ...baseSignerSetTxConfirmation, } as SignerSetTxConfirmation; if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) { message.signerSetNonce = object.signerSetNonce as Long; } else { message.signerSetNonce = Long.UZERO; } if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) { message.ethereumSigner = object.ethereumSigner; } else { message.ethereumSigner = ""; } if (object.signature !== undefined && object.signature !== null) { message.signature = object.signature; } else { message.signature = new Uint8Array(); } return message; }, }; const baseMsgSubmitEthereumTxConfirmationResponse: object = {}; export const MsgSubmitEthereumTxConfirmationResponse = { encode( _: MsgSubmitEthereumTxConfirmationResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgSubmitEthereumTxConfirmationResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSubmitEthereumTxConfirmationResponse, } as MsgSubmitEthereumTxConfirmationResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MsgSubmitEthereumTxConfirmationResponse { const message = { ...baseMsgSubmitEthereumTxConfirmationResponse, } as MsgSubmitEthereumTxConfirmationResponse; return message; }, toJSON(_: MsgSubmitEthereumTxConfirmationResponse): unknown { const obj: any = {}; return obj; }, fromPartial( _: DeepPartial<MsgSubmitEthereumTxConfirmationResponse> ): MsgSubmitEthereumTxConfirmationResponse { const message = { ...baseMsgSubmitEthereumTxConfirmationResponse, } as MsgSubmitEthereumTxConfirmationResponse; return message; }, }; const baseMsgSubmitEthereumEvent: object = { signer: "" }; export const MsgSubmitEthereumEvent = { encode( message: MsgSubmitEthereumEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.event !== undefined) { Any.encode(message.event, writer.uint32(10).fork()).ldelim(); } if (message.signer !== "") { writer.uint32(18).string(message.signer); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgSubmitEthereumEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSubmitEthereumEvent } as MsgSubmitEthereumEvent; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.event = Any.decode(reader, reader.uint32()); break; case 2: message.signer = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgSubmitEthereumEvent { const message = { ...baseMsgSubmitEthereumEvent } as MsgSubmitEthereumEvent; if (object.event !== undefined && object.event !== null) { message.event = Any.fromJSON(object.event); } else { message.event = undefined; } if (object.signer !== undefined && object.signer !== null) { message.signer = String(object.signer); } else { message.signer = ""; } return message; }, toJSON(message: MsgSubmitEthereumEvent): unknown { const obj: any = {}; message.event !== undefined && (obj.event = message.event ? Any.toJSON(message.event) : undefined); message.signer !== undefined && (obj.signer = message.signer); return obj; }, fromPartial( object: DeepPartial<MsgSubmitEthereumEvent> ): MsgSubmitEthereumEvent { const message = { ...baseMsgSubmitEthereumEvent } as MsgSubmitEthereumEvent; if (object.event !== undefined && object.event !== null) { message.event = Any.fromPartial(object.event); } else { message.event = undefined; } if (object.signer !== undefined && object.signer !== null) { message.signer = object.signer; } else { message.signer = ""; } return message; }, }; const baseSendToCosmosEvent: object = { eventNonce: Long.UZERO, tokenContract: "", amount: "", ethereumSender: "", cosmosReceiver: "", ethereumHeight: Long.UZERO, }; export const SendToCosmosEvent = { encode( message: SendToCosmosEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.eventNonce.isZero()) { writer.uint32(8).uint64(message.eventNonce); } if (message.tokenContract !== "") { writer.uint32(18).string(message.tokenContract); } if (message.amount !== "") { writer.uint32(26).string(message.amount); } if (message.ethereumSender !== "") { writer.uint32(34).string(message.ethereumSender); } if (message.cosmosReceiver !== "") { writer.uint32(42).string(message.cosmosReceiver); } if (!message.ethereumHeight.isZero()) { writer.uint32(48).uint64(message.ethereumHeight); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): SendToCosmosEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSendToCosmosEvent } as SendToCosmosEvent; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.eventNonce = reader.uint64() as Long; break; case 2: message.tokenContract = reader.string(); break; case 3: message.amount = reader.string(); break; case 4: message.ethereumSender = reader.string(); break; case 5: message.cosmosReceiver = reader.string(); break; case 6: message.ethereumHeight = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SendToCosmosEvent { const message = { ...baseSendToCosmosEvent } as SendToCosmosEvent; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = Long.fromString(object.eventNonce); } else { message.eventNonce = Long.UZERO; } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = String(object.tokenContract); } else { message.tokenContract = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = String(object.amount); } else { message.amount = ""; } if (object.ethereumSender !== undefined && object.ethereumSender !== null) { message.ethereumSender = String(object.ethereumSender); } else { message.ethereumSender = ""; } if (object.cosmosReceiver !== undefined && object.cosmosReceiver !== null) { message.cosmosReceiver = String(object.cosmosReceiver); } else { message.cosmosReceiver = ""; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } return message; }, toJSON(message: SendToCosmosEvent): unknown { const obj: any = {}; message.eventNonce !== undefined && (obj.eventNonce = (message.eventNonce || Long.UZERO).toString()); message.tokenContract !== undefined && (obj.tokenContract = message.tokenContract); message.amount !== undefined && (obj.amount = message.amount); message.ethereumSender !== undefined && (obj.ethereumSender = message.ethereumSender); message.cosmosReceiver !== undefined && (obj.cosmosReceiver = message.cosmosReceiver); message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); return obj; }, fromPartial(object: DeepPartial<SendToCosmosEvent>): SendToCosmosEvent { const message = { ...baseSendToCosmosEvent } as SendToCosmosEvent; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = object.eventNonce as Long; } else { message.eventNonce = Long.UZERO; } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = object.tokenContract; } else { message.tokenContract = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = object.amount; } else { message.amount = ""; } if (object.ethereumSender !== undefined && object.ethereumSender !== null) { message.ethereumSender = object.ethereumSender; } else { message.ethereumSender = ""; } if (object.cosmosReceiver !== undefined && object.cosmosReceiver !== null) { message.cosmosReceiver = object.cosmosReceiver; } else { message.cosmosReceiver = ""; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } return message; }, }; const baseBatchExecutedEvent: object = { tokenContract: "", eventNonce: Long.UZERO, ethereumHeight: Long.UZERO, batchNonce: Long.UZERO, }; export const BatchExecutedEvent = { encode( message: BatchExecutedEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tokenContract !== "") { writer.uint32(10).string(message.tokenContract); } if (!message.eventNonce.isZero()) { writer.uint32(16).uint64(message.eventNonce); } if (!message.ethereumHeight.isZero()) { writer.uint32(24).uint64(message.ethereumHeight); } if (!message.batchNonce.isZero()) { writer.uint32(32).uint64(message.batchNonce); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): BatchExecutedEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseBatchExecutedEvent } as BatchExecutedEvent; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tokenContract = reader.string(); break; case 2: message.eventNonce = reader.uint64() as Long; break; case 3: message.ethereumHeight = reader.uint64() as Long; break; case 4: message.batchNonce = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): BatchExecutedEvent { const message = { ...baseBatchExecutedEvent } as BatchExecutedEvent; if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = String(object.tokenContract); } else { message.tokenContract = ""; } if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = Long.fromString(object.eventNonce); } else { message.eventNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = Long.fromString(object.batchNonce); } else { message.batchNonce = Long.UZERO; } return message; }, toJSON(message: BatchExecutedEvent): unknown { const obj: any = {}; message.tokenContract !== undefined && (obj.tokenContract = message.tokenContract); message.eventNonce !== undefined && (obj.eventNonce = (message.eventNonce || Long.UZERO).toString()); message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); message.batchNonce !== undefined && (obj.batchNonce = (message.batchNonce || Long.UZERO).toString()); return obj; }, fromPartial(object: DeepPartial<BatchExecutedEvent>): BatchExecutedEvent { const message = { ...baseBatchExecutedEvent } as BatchExecutedEvent; if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = object.tokenContract; } else { message.tokenContract = ""; } if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = object.eventNonce as Long; } else { message.eventNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = object.batchNonce as Long; } else { message.batchNonce = Long.UZERO; } return message; }, }; const baseContractCallExecutedEvent: object = { eventNonce: Long.UZERO, invalidationNonce: Long.UZERO, ethereumHeight: Long.UZERO, }; export const ContractCallExecutedEvent = { encode( message: ContractCallExecutedEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.eventNonce.isZero()) { writer.uint32(8).uint64(message.eventNonce); } if (message.invalidationId.length !== 0) { writer.uint32(18).bytes(message.invalidationId); } if (!message.invalidationNonce.isZero()) { writer.uint32(24).uint64(message.invalidationNonce); } if (!message.ethereumHeight.isZero()) { writer.uint32(32).uint64(message.ethereumHeight); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ContractCallExecutedEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseContractCallExecutedEvent, } as ContractCallExecutedEvent; message.invalidationId = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.eventNonce = reader.uint64() as Long; break; case 2: message.invalidationId = reader.bytes(); break; case 3: message.invalidationNonce = reader.uint64() as Long; break; case 4: message.ethereumHeight = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ContractCallExecutedEvent { const message = { ...baseContractCallExecutedEvent, } as ContractCallExecutedEvent; message.invalidationId = new Uint8Array(); if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = Long.fromString(object.eventNonce); } else { message.eventNonce = Long.UZERO; } if (object.invalidationId !== undefined && object.invalidationId !== null) { message.invalidationId = bytesFromBase64(object.invalidationId); } if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = Long.fromString(object.invalidationNonce); } else { message.invalidationNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } return message; }, toJSON(message: ContractCallExecutedEvent): unknown { const obj: any = {}; message.eventNonce !== undefined && (obj.eventNonce = (message.eventNonce || Long.UZERO).toString()); message.invalidationId !== undefined && (obj.invalidationId = base64FromBytes( message.invalidationId !== undefined ? message.invalidationId : new Uint8Array() )); message.invalidationNonce !== undefined && (obj.invalidationNonce = ( message.invalidationNonce || Long.UZERO ).toString()); message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); return obj; }, fromPartial( object: DeepPartial<ContractCallExecutedEvent> ): ContractCallExecutedEvent { const message = { ...baseContractCallExecutedEvent, } as ContractCallExecutedEvent; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = object.eventNonce as Long; } else { message.eventNonce = Long.UZERO; } if (object.invalidationId !== undefined && object.invalidationId !== null) { message.invalidationId = object.invalidationId; } else { message.invalidationId = new Uint8Array(); } if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = object.invalidationNonce as Long; } else { message.invalidationNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } return message; }, }; const baseERC20DeployedEvent: object = { eventNonce: Long.UZERO, cosmosDenom: "", tokenContract: "", erc20Name: "", erc20Symbol: "", erc20Decimals: Long.UZERO, ethereumHeight: Long.UZERO, }; export const ERC20DeployedEvent = { encode( message: ERC20DeployedEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.eventNonce.isZero()) { writer.uint32(8).uint64(message.eventNonce); } if (message.cosmosDenom !== "") { writer.uint32(18).string(message.cosmosDenom); } if (message.tokenContract !== "") { writer.uint32(26).string(message.tokenContract); } if (message.erc20Name !== "") { writer.uint32(34).string(message.erc20Name); } if (message.erc20Symbol !== "") { writer.uint32(42).string(message.erc20Symbol); } if (!message.erc20Decimals.isZero()) { writer.uint32(48).uint64(message.erc20Decimals); } if (!message.ethereumHeight.isZero()) { writer.uint32(56).uint64(message.ethereumHeight); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ERC20DeployedEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseERC20DeployedEvent } as ERC20DeployedEvent; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.eventNonce = reader.uint64() as Long; break; case 2: message.cosmosDenom = reader.string(); break; case 3: message.tokenContract = reader.string(); break; case 4: message.erc20Name = reader.string(); break; case 5: message.erc20Symbol = reader.string(); break; case 6: message.erc20Decimals = reader.uint64() as Long; break; case 7: message.ethereumHeight = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ERC20DeployedEvent { const message = { ...baseERC20DeployedEvent } as ERC20DeployedEvent; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = Long.fromString(object.eventNonce); } else { message.eventNonce = Long.UZERO; } if (object.cosmosDenom !== undefined && object.cosmosDenom !== null) { message.cosmosDenom = String(object.cosmosDenom); } else { message.cosmosDenom = ""; } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = String(object.tokenContract); } else { message.tokenContract = ""; } if (object.erc20Name !== undefined && object.erc20Name !== null) { message.erc20Name = String(object.erc20Name); } else { message.erc20Name = ""; } if (object.erc20Symbol !== undefined && object.erc20Symbol !== null) { message.erc20Symbol = String(object.erc20Symbol); } else { message.erc20Symbol = ""; } if (object.erc20Decimals !== undefined && object.erc20Decimals !== null) { message.erc20Decimals = Long.fromString(object.erc20Decimals); } else { message.erc20Decimals = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } return message; }, toJSON(message: ERC20DeployedEvent): unknown { const obj: any = {}; message.eventNonce !== undefined && (obj.eventNonce = (message.eventNonce || Long.UZERO).toString()); message.cosmosDenom !== undefined && (obj.cosmosDenom = message.cosmosDenom); message.tokenContract !== undefined && (obj.tokenContract = message.tokenContract); message.erc20Name !== undefined && (obj.erc20Name = message.erc20Name); message.erc20Symbol !== undefined && (obj.erc20Symbol = message.erc20Symbol); message.erc20Decimals !== undefined && (obj.erc20Decimals = (message.erc20Decimals || Long.UZERO).toString()); message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); return obj; }, fromPartial(object: DeepPartial<ERC20DeployedEvent>): ERC20DeployedEvent { const message = { ...baseERC20DeployedEvent } as ERC20DeployedEvent; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = object.eventNonce as Long; } else { message.eventNonce = Long.UZERO; } if (object.cosmosDenom !== undefined && object.cosmosDenom !== null) { message.cosmosDenom = object.cosmosDenom; } else { message.cosmosDenom = ""; } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = object.tokenContract; } else { message.tokenContract = ""; } if (object.erc20Name !== undefined && object.erc20Name !== null) { message.erc20Name = object.erc20Name; } else { message.erc20Name = ""; } if (object.erc20Symbol !== undefined && object.erc20Symbol !== null) { message.erc20Symbol = object.erc20Symbol; } else { message.erc20Symbol = ""; } if (object.erc20Decimals !== undefined && object.erc20Decimals !== null) { message.erc20Decimals = object.erc20Decimals as Long; } else { message.erc20Decimals = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } return message; }, }; const baseSignerSetTxExecutedEvent: object = { eventNonce: Long.UZERO, signerSetTxNonce: Long.UZERO, ethereumHeight: Long.UZERO, }; export const SignerSetTxExecutedEvent = { encode( message: SignerSetTxExecutedEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.eventNonce.isZero()) { writer.uint32(8).uint64(message.eventNonce); } if (!message.signerSetTxNonce.isZero()) { writer.uint32(16).uint64(message.signerSetTxNonce); } if (!message.ethereumHeight.isZero()) { writer.uint32(24).uint64(message.ethereumHeight); } for (const v of message.members) { EthereumSigner.encode(v!, writer.uint32(34).fork()).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): SignerSetTxExecutedEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSignerSetTxExecutedEvent, } as SignerSetTxExecutedEvent; message.members = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.eventNonce = reader.uint64() as Long; break; case 2: message.signerSetTxNonce = reader.uint64() as Long; break; case 3: message.ethereumHeight = reader.uint64() as Long; break; case 4: message.members.push(EthereumSigner.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SignerSetTxExecutedEvent { const message = { ...baseSignerSetTxExecutedEvent, } as SignerSetTxExecutedEvent; message.members = []; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = Long.fromString(object.eventNonce); } else { message.eventNonce = Long.UZERO; } if ( object.signerSetTxNonce !== undefined && object.signerSetTxNonce !== null ) { message.signerSetTxNonce = Long.fromString(object.signerSetTxNonce); } else { message.signerSetTxNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } if (object.members !== undefined && object.members !== null) { for (const e of object.members) { message.members.push(EthereumSigner.fromJSON(e)); } } return message; }, toJSON(message: SignerSetTxExecutedEvent): unknown { const obj: any = {}; message.eventNonce !== undefined && (obj.eventNonce = (message.eventNonce || Long.UZERO).toString()); message.signerSetTxNonce !== undefined && (obj.signerSetTxNonce = ( message.signerSetTxNonce || Long.UZERO ).toString()); message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); if (message.members) { obj.members = message.members.map((e) => e ? EthereumSigner.toJSON(e) : undefined ); } else { obj.members = []; } return obj; }, fromPartial( object: DeepPartial<SignerSetTxExecutedEvent> ): SignerSetTxExecutedEvent { const message = { ...baseSignerSetTxExecutedEvent, } as SignerSetTxExecutedEvent; message.members = []; if (object.eventNonce !== undefined && object.eventNonce !== null) { message.eventNonce = object.eventNonce as Long; } else { message.eventNonce = Long.UZERO; } if ( object.signerSetTxNonce !== undefined && object.signerSetTxNonce !== null ) { message.signerSetTxNonce = object.signerSetTxNonce as Long; } else { message.signerSetTxNonce = Long.UZERO; } if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } if (object.members !== undefined && object.members !== null) { for (const e of object.members) { message.members.push(EthereumSigner.fromPartial(e)); } } return message; }, }; const baseMsgSubmitEthereumEventResponse: object = {}; export const MsgSubmitEthereumEventResponse = { encode( _: MsgSubmitEthereumEventResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgSubmitEthereumEventResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgSubmitEthereumEventResponse, } as MsgSubmitEthereumEventResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MsgSubmitEthereumEventResponse { const message = { ...baseMsgSubmitEthereumEventResponse, } as MsgSubmitEthereumEventResponse; return message; }, toJSON(_: MsgSubmitEthereumEventResponse): unknown { const obj: any = {}; return obj; }, fromPartial( _: DeepPartial<MsgSubmitEthereumEventResponse> ): MsgSubmitEthereumEventResponse { const message = { ...baseMsgSubmitEthereumEventResponse, } as MsgSubmitEthereumEventResponse; return message; }, }; const baseMsgDelegateKeys: object = { validatorAddress: "", orchestratorAddress: "", ethereumAddress: "", }; export const MsgDelegateKeys = { encode( message: MsgDelegateKeys, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.validatorAddress !== "") { writer.uint32(10).string(message.validatorAddress); } if (message.orchestratorAddress !== "") { writer.uint32(18).string(message.orchestratorAddress); } if (message.ethereumAddress !== "") { writer.uint32(26).string(message.ethereumAddress); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MsgDelegateKeys { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgDelegateKeys } as MsgDelegateKeys; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.validatorAddress = reader.string(); break; case 2: message.orchestratorAddress = reader.string(); break; case 3: message.ethereumAddress = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MsgDelegateKeys { const message = { ...baseMsgDelegateKeys } as MsgDelegateKeys; if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = String(object.validatorAddress); } else { message.validatorAddress = ""; } if ( object.orchestratorAddress !== undefined && object.orchestratorAddress !== null ) { message.orchestratorAddress = String(object.orchestratorAddress); } else { message.orchestratorAddress = ""; } if ( object.ethereumAddress !== undefined && object.ethereumAddress !== null ) { message.ethereumAddress = String(object.ethereumAddress); } else { message.ethereumAddress = ""; } return message; }, toJSON(message: MsgDelegateKeys): unknown { const obj: any = {}; message.validatorAddress !== undefined && (obj.validatorAddress = message.validatorAddress); message.orchestratorAddress !== undefined && (obj.orchestratorAddress = message.orchestratorAddress); message.ethereumAddress !== undefined && (obj.ethereumAddress = message.ethereumAddress); return obj; }, fromPartial(object: DeepPartial<MsgDelegateKeys>): MsgDelegateKeys { const message = { ...baseMsgDelegateKeys } as MsgDelegateKeys; if ( object.validatorAddress !== undefined && object.validatorAddress !== null ) { message.validatorAddress = object.validatorAddress; } else { message.validatorAddress = ""; } if ( object.orchestratorAddress !== undefined && object.orchestratorAddress !== null ) { message.orchestratorAddress = object.orchestratorAddress; } else { message.orchestratorAddress = ""; } if ( object.ethereumAddress !== undefined && object.ethereumAddress !== null ) { message.ethereumAddress = object.ethereumAddress; } else { message.ethereumAddress = ""; } return message; }, }; const baseMsgDelegateKeysResponse: object = {}; export const MsgDelegateKeysResponse = { encode( _: MsgDelegateKeysResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MsgDelegateKeysResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMsgDelegateKeysResponse, } as MsgDelegateKeysResponse; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MsgDelegateKeysResponse { const message = { ...baseMsgDelegateKeysResponse, } as MsgDelegateKeysResponse; return message; }, toJSON(_: MsgDelegateKeysResponse): unknown { const obj: any = {}; return obj; }, fromPartial( _: DeepPartial<MsgDelegateKeysResponse> ): MsgDelegateKeysResponse { const message = { ...baseMsgDelegateKeysResponse, } as MsgDelegateKeysResponse; return message; }, }; /** Msg defines the state transitions possible within gravity */ export interface Msg { SendToEthereum( request: MsgSendToEthereum ): Promise<MsgSendToEthereumResponse>; CancelSendToEthereum( request: MsgCancelSendToEthereum ): Promise<MsgCancelSendToEthereumResponse>; RequestBatchTx( request: MsgRequestBatchTx ): Promise<MsgRequestBatchTxResponse>; SubmitEthereumTxConfirmation( request: MsgSubmitEthereumTxConfirmation ): Promise<MsgSubmitEthereumTxConfirmationResponse>; SubmitEthereumEvent( request: MsgSubmitEthereumEvent ): Promise<MsgSubmitEthereumEventResponse>; SetDelegateKeys(request: MsgDelegateKeys): Promise<MsgDelegateKeysResponse>; } export class MsgClientImpl implements Msg { private readonly rpc: Rpc; constructor(rpc: Rpc) { this.rpc = rpc; this.SendToEthereum = this.SendToEthereum.bind(this); this.CancelSendToEthereum = this.CancelSendToEthereum.bind(this); this.RequestBatchTx = this.RequestBatchTx.bind(this); this.SubmitEthereumTxConfirmation = this.SubmitEthereumTxConfirmation.bind( this ); this.SubmitEthereumEvent = this.SubmitEthereumEvent.bind(this); this.SetDelegateKeys = this.SetDelegateKeys.bind(this); } SendToEthereum( request: MsgSendToEthereum ): Promise<MsgSendToEthereumResponse> { const data = MsgSendToEthereum.encode(request).finish(); const promise = this.rpc.request("gravity.v1.Msg", "SendToEthereum", data); return promise.then((data) => MsgSendToEthereumResponse.decode(new _m0.Reader(data)) ); } CancelSendToEthereum( request: MsgCancelSendToEthereum ): Promise<MsgCancelSendToEthereumResponse> { const data = MsgCancelSendToEthereum.encode(request).finish(); const promise = this.rpc.request( "gravity.v1.Msg", "CancelSendToEthereum", data ); return promise.then((data) => MsgCancelSendToEthereumResponse.decode(new _m0.Reader(data)) ); } RequestBatchTx( request: MsgRequestBatchTx ): Promise<MsgRequestBatchTxResponse> { const data = MsgRequestBatchTx.encode(request).finish(); const promise = this.rpc.request("gravity.v1.Msg", "RequestBatchTx", data); return promise.then((data) => MsgRequestBatchTxResponse.decode(new _m0.Reader(data)) ); } SubmitEthereumTxConfirmation( request: MsgSubmitEthereumTxConfirmation ): Promise<MsgSubmitEthereumTxConfirmationResponse> { const data = MsgSubmitEthereumTxConfirmation.encode(request).finish(); const promise = this.rpc.request( "gravity.v1.Msg", "SubmitEthereumTxConfirmation", data ); return promise.then((data) => MsgSubmitEthereumTxConfirmationResponse.decode(new _m0.Reader(data)) ); } SubmitEthereumEvent( request: MsgSubmitEthereumEvent ): Promise<MsgSubmitEthereumEventResponse> { const data = MsgSubmitEthereumEvent.encode(request).finish(); const promise = this.rpc.request( "gravity.v1.Msg", "SubmitEthereumEvent", data ); return promise.then((data) => MsgSubmitEthereumEventResponse.decode(new _m0.Reader(data)) ); } SetDelegateKeys(request: MsgDelegateKeys): Promise<MsgDelegateKeysResponse> { const data = MsgDelegateKeys.encode(request).finish(); const promise = this.rpc.request("gravity.v1.Msg", "SetDelegateKeys", data); return promise.then((data) => MsgDelegateKeysResponse.decode(new _m0.Reader(data)) ); } } interface Rpc { request( service: string, method: string, data: Uint8Array ): Promise<Uint8Array>; } declare var self: any | undefined; declare var window: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== "undefined") return globalThis; if (typeof self !== "undefined") return self; if (typeof window !== "undefined") return window; if (typeof global !== "undefined") return global; throw "Unable to locate global object"; })(); const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, "base64").toString("binary")); function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, "binary").toString("base64")); function base64FromBytes(arr: Uint8Array): string { const bin: string[] = []; for (let i = 0; i < arr.byteLength; ++i) { bin.push(String.fromCharCode(arr[i])); } return btoa(bin.join("")); } type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined | Long; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); }
the_stack
import crypto from 'crypto'; import { promises as fs } from 'fs'; import path from 'path'; import { IOAuthController, IAPIController, JacksonOption, OAuthReqBody, OAuthTokenReq, SAMLResponsePayload, } from '../src/typings'; import sinon from 'sinon'; import tap from 'tap'; import { JacksonError } from '../src/controller/error'; import readConfig from '../src/read-config'; import saml from '@boxyhq/saml20'; import { authz_request_normal, authz_request_normal_with_access_type, authz_request_normal_with_scope, bodyWithDummyCredentials, bodyWithInvalidClientSecret, bodyWithInvalidCode, bodyWithUnencodedClientId_InvalidClientSecret_gen, invalid_client_id, redirect_uri_not_allowed, redirect_uri_not_set, response_type_not_code, saml_binding_absent, state_not_set, token_req_encoded_client_id, token_req_unencoded_client_id_gen, } from './fixture'; let apiController: IAPIController; let oauthController: IOAuthController; const code = '1234567890'; const token = '24c1550190dd6a5a9bd6fe2a8ff69d593121c7b9'; const metadataPath = path.join(__dirname, '/data/metadata'); const options = <JacksonOption>{ externalUrl: 'https://my-cool-app.com', samlAudience: 'https://saml.boxyhq.com', samlPath: '/sso/oauth/saml', db: { engine: 'mem', }, clientSecretVerifier: 'TOP-SECRET', }; const configRecords: Array<any> = []; const addMetadata = async (metadataPath) => { const configs = await readConfig(metadataPath); for (const config of configs) { const _record = await apiController.config(config); configRecords.push(_record); } }; tap.before(async () => { const controller = await (await import('../src/index')).default(options); apiController = controller.apiController; oauthController = controller.oauthController; await addMetadata(metadataPath); }); tap.teardown(async () => { process.exit(0); }); tap.test('authorize()', async (t) => { t.test('Should throw an error if `redirect_uri` null', async (t) => { const body = redirect_uri_not_set; try { await oauthController.authorize(<OAuthReqBody>body); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Please specify a redirect URL.', 'got expected error message'); t.equal(statusCode, 400, 'got expected status code'); } t.end(); }); t.test('Should return OAuth Error response if `state` is not set', async (t) => { const body = state_not_set; const { redirect_url } = await oauthController.authorize(<OAuthReqBody>body); t.equal( redirect_url, `${body.redirect_uri}?error=invalid_request&error_description=Please+specify+a+state+to+safeguard+against+XSRF+attacks`, 'got OAuth error' ); t.end(); }); t.test('Should return OAuth Error response if `response_type` is not `code`', async (t) => { const body = response_type_not_code; const { redirect_url } = await oauthController.authorize(<OAuthReqBody>body); t.equal( redirect_url, `${body.redirect_uri}?error=unsupported_response_type&error_description=Only+Authorization+Code+grant+is+supported`, 'got OAuth error' ); t.end(); }); t.test('Should return OAuth Error response if saml binding could not be retrieved', async (t) => { const body = saml_binding_absent; const { redirect_url } = await oauthController.authorize(<OAuthReqBody>body); t.equal( redirect_url, `${body.redirect_uri}?error=invalid_request&error_description=SAML+binding+could+not+be+retrieved`, 'got OAuth error' ); t.end(); }); t.test('Should return OAuth Error response if request creation fails', async (t) => { const body = authz_request_normal; const stubSamlRequest = sinon.stub(saml, 'request').throws(Error('Internal error: Fatal')); const { redirect_url } = await oauthController.authorize(<OAuthReqBody>body); t.equal( redirect_url, `${body.redirect_uri}?error=server_error&error_description=Internal+error%3A+Fatal`, 'got OAuth error' ); stubSamlRequest.restore(); t.end(); }); t.test('Should throw an error if `client_id` is invalid', async (t) => { const body = invalid_client_id; try { await oauthController.authorize(<OAuthReqBody>body); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'SAML configuration not found.', 'got expected error message'); t.equal(statusCode, 403, 'got expected status code'); } t.end(); }); t.test('Should throw an error if `redirect_uri` is not allowed', async (t) => { const body = redirect_uri_not_allowed; try { await oauthController.authorize(<OAuthReqBody>body); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Redirect URL is not allowed.', 'got expected error message'); t.equal(statusCode, 403, 'got expected status code'); } t.end(); }); t.test('Should return the Idp SSO URL', async (t) => { t.test('accepts client_id', async (t) => { const body = authz_request_normal; const response = await oauthController.authorize(<OAuthReqBody>body); const params = new URLSearchParams(new URL(response.redirect_url!).search); t.ok('redirect_url' in response, 'got the Idp authorize URL'); t.ok(params.has('RelayState'), 'RelayState present in the query string'); t.ok(params.has('SAMLRequest'), 'SAMLRequest present in the query string'); t.end(); }); t.test('accepts access_type', async (t) => { const body = authz_request_normal_with_access_type; const response = await oauthController.authorize(<OAuthReqBody>body); const params = new URLSearchParams(new URL(response.redirect_url!).search); t.ok('redirect_url' in response, 'got the Idp authorize URL'); t.ok(params.has('RelayState'), 'RelayState present in the query string'); t.ok(params.has('SAMLRequest'), 'SAMLRequest present in the query string'); t.end(); }); t.test('accepts scope', async (t) => { const body = authz_request_normal_with_scope; const response = await oauthController.authorize(<OAuthReqBody>body); const params = new URLSearchParams(new URL(response.redirect_url!).search); t.ok('redirect_url' in response, 'got the Idp authorize URL'); t.ok(params.has('RelayState'), 'RelayState present in the query string'); t.ok(params.has('SAMLRequest'), 'SAMLRequest present in the query string'); t.end(); }); }); t.end(); }); tap.test('samlResponse()', async (t) => { const authBody = authz_request_normal; const { redirect_url } = await oauthController.authorize(<OAuthReqBody>authBody); const relayState = new URLSearchParams(new URL(redirect_url!).search).get('RelayState'); const rawResponse = await fs.readFile(path.join(__dirname, '/data/saml_response'), 'utf8'); t.test('Should throw an error if `RelayState` is missing', async (t) => { const responseBody: Partial<SAMLResponsePayload> = { SAMLResponse: rawResponse, }; try { await oauthController.samlResponse(<SAMLResponsePayload>responseBody); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal( message, 'IdP (Identity Provider) flow has been disabled. Please head to your Service Provider to login.', 'got expected error message' ); t.equal(statusCode, 403, 'got expected status code'); } t.end(); }); t.test('Should return OAuth Error response if response validation fails', async (t) => { const responseBody = { SAMLResponse: rawResponse, RelayState: relayState, }; const stubValidate = sinon.stub(saml, 'validate').throws(Error('Internal error: Fatal')); const response = await oauthController.samlResponse(<SAMLResponsePayload>responseBody); const params = new URLSearchParams(new URL(response.redirect_url!).search); t.match(params.get('error'), 'access_denied'); t.match(params.get('error_description'), 'Internal error: Fatal'); stubValidate.restore(); t.end(); }); t.test('Should return a URL with code and state as query params', async (t) => { const responseBody = { SAMLResponse: rawResponse, RelayState: relayState, }; const stubValidate = sinon .stub(saml, 'validate') .resolves({ audience: '', claims: {}, issuer: '', sessionIndex: '' }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const stubRandomBytes = sinon.stub(crypto, 'randomBytes').returns(code); const response = await oauthController.samlResponse(<SAMLResponsePayload>responseBody); const params = new URLSearchParams(new URL(response.redirect_url!).search); t.ok(stubValidate.calledOnce, 'validate called once'); t.ok(stubRandomBytes.calledOnce, 'randomBytes called once'); t.ok('redirect_url' in response, 'response contains redirect_url'); t.ok(params.has('code'), 'query string includes code'); t.ok(params.has('state'), 'query string includes state'); t.match(params.get('state'), authBody.state, 'state value is valid'); stubRandomBytes.restore(); stubValidate.restore(); t.end(); }); t.end(); }); tap.test('token()', (t) => { t.test('Should throw an error if `grant_type` is not `authorization_code`', async (t) => { const body = { grant_type: 'authorization_code_1', }; try { await oauthController.token(<OAuthTokenReq>body); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Unsupported grant_type', 'got expected error message'); t.equal(statusCode, 400, 'got expected status code'); } t.end(); }); t.test('Should throw an error if `code` is missing', async (t) => { const body = { grant_type: 'authorization_code', }; try { await oauthController.token(<OAuthTokenReq>body); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Please specify code', 'got expected error message'); t.equal(statusCode, 400, 'got expected status code'); } t.end(); }); t.test('Should throw an error if `code` or `client_secret` is invalid', async (t) => { try { await oauthController.token(<OAuthTokenReq>bodyWithInvalidCode); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Invalid code', 'got expected error message'); t.equal(statusCode, 403, 'got expected status code'); } try { await oauthController.token(<OAuthTokenReq>bodyWithInvalidClientSecret); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Invalid client_secret', 'got expected error message'); t.equal(statusCode, 401, 'got expected status code'); } try { const bodyWithUnencodedClientId_InvalidClientSecret = bodyWithUnencodedClientId_InvalidClientSecret_gen(configRecords); await oauthController.token(<OAuthTokenReq>bodyWithUnencodedClientId_InvalidClientSecret); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Invalid client_id or client_secret', 'got expected error message'); t.equal(statusCode, 401, 'got expected status code'); } try { await oauthController.token(<OAuthTokenReq>bodyWithDummyCredentials); t.fail('Expecting JacksonError.'); } catch (err) { const { message, statusCode } = err as JacksonError; t.equal(message, 'Invalid client_secret', 'got expected error message'); t.equal(statusCode, 401, 'got expected status code'); } t.end(); }); t.test('Should return the `access_token`/`userprofile` for a valid request', async (t) => { t.test('encoded client_id', async (t) => { const body = token_req_encoded_client_id; const stubRandomBytes = sinon .stub(crypto, 'randomBytes') .onFirstCall() // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore .returns(token); const response = await oauthController.token(<OAuthTokenReq>body); t.ok(stubRandomBytes.calledOnce, 'randomBytes called once'); t.ok('access_token' in response, 'includes access_token'); t.ok('token_type' in response, 'includes token_type'); t.ok('expires_in' in response, 'includes expires_in'); t.match(response.access_token, token); t.match(response.token_type, 'bearer'); t.match(response.expires_in, 300); stubRandomBytes.restore(); t.end(); }); t.test('unencoded client_id', async (t) => { // have to call authorize, because previous happy path deletes the code. const authBody = authz_request_normal; const { redirect_url } = await oauthController.authorize(<OAuthReqBody>authBody); const relayState = new URLSearchParams(new URL(redirect_url!).search).get('RelayState'); const rawResponse = await fs.readFile(path.join(__dirname, '/data/saml_response'), 'utf8'); const responseBody = { SAMLResponse: rawResponse, RelayState: relayState, }; sinon.stub(saml, 'validate').resolves({ audience: '', claims: {}, issuer: '', sessionIndex: '' }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const stubRandomBytes = sinon.stub(crypto, 'randomBytes').returns(code).onSecondCall().returns(token); await oauthController.samlResponse(<SAMLResponsePayload>responseBody); const body = token_req_unencoded_client_id_gen(configRecords); const tokenRes = await oauthController.token(<OAuthTokenReq>body); t.ok('access_token' in tokenRes, 'includes access_token'); t.ok('token_type' in tokenRes, 'includes token_type'); t.ok('expires_in' in tokenRes, 'includes expires_in'); t.match(tokenRes.access_token, token); t.match(tokenRes.token_type, 'bearer'); t.match(tokenRes.expires_in, 300); const profile = await oauthController.userInfo(tokenRes.access_token); t.equal(profile.requested.client_id, authz_request_normal.client_id); t.equal(profile.requested.state, authz_request_normal.state); t.equal(profile.requested.tenant, new URLSearchParams(authz_request_normal.client_id).get('tenant')); t.equal(profile.requested.product, new URLSearchParams(authz_request_normal.client_id).get('product')); stubRandomBytes.restore(); t.end(); }); }); t.end(); });
the_stack
import { Kind } from 'graphql/language'; import { GraphQLNonNegativeInt } from '../src/scalars/NonNegativeInt'; import { GraphQLUnsignedInt } from '../src/scalars/UnsignedInt'; describe('NonNegativeInt', () => { describe('valid', () => { describe('greater than zero', () => { describe('as int', () => { test('serialize', () => { expect(GraphQLNonNegativeInt.serialize(123)).toBe(123); }); test('parseValue', () => { expect(GraphQLNonNegativeInt.parseValue(123)).toBe(123); }); test('parseLiteral', () => { expect( GraphQLNonNegativeInt.parseLiteral( { value: '123', kind: Kind.INT }, {}, ), ).toBe(123); }); }); describe('as string', () => { test('serialize', () => { expect(GraphQLNonNegativeInt.serialize('123')).toBe(123); }); test('parseValue', () => { expect(GraphQLNonNegativeInt.parseValue('123')).toBe(123); }); test('parseLiteral', () => { expect( GraphQLNonNegativeInt.parseLiteral( { value: '123', kind: Kind.INT }, {}, ), ).toBe(123); }); }); }); describe('zero', () => { describe('as int', () => { test('serialize', () => { expect(GraphQLNonNegativeInt.serialize(0)).toBe(0); }); test('parseValue', () => { expect(GraphQLNonNegativeInt.parseValue(0)).toBe(0); }); test('parseLiteral', () => { expect( GraphQLNonNegativeInt.parseLiteral( { value: '0', kind: Kind.INT }, {}, ), ).toBe(0); }); }); describe('as string', () => { test('serialize', () => { expect(GraphQLNonNegativeInt.serialize('0')).toBe(0); }); test('parseValue', () => { expect(GraphQLNonNegativeInt.parseValue('0')).toBe(0); }); test('parseLiteral', () => { expect( GraphQLNonNegativeInt.parseLiteral( { value: '0', kind: Kind.INT }, {}, ), ).toBe(0); }); }); }); }); describe('invalid', () => { describe('null', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(null)).toThrow( /Value is not a number/, ); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue(null)).toThrow( /Value is not a number/, ); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: null, kind: Kind.INT }, {}, ), ).toThrow(/Value is not a number/); }); }); describe('undefined', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(undefined)).toThrow( /Value is not a number/, ); }); // FIXME: Does nothing. No throw. Call doesn't even seem to get to the parseValue() function. // test('parseValue', () => { // expect(() => GraphQLNonNegativeInt.parseValue(undefined)).toThrow( // /Value is not a number/, // ); // }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: undefined, kind: Kind.INT }, {}, ), ).toThrow(/Value is not a number/); }); }); describe('unsafe integer', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(2 ** 53)).toThrow( /Value is not a safe integer/, ); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue(2 ** 53)).toThrow( /Value is not a safe integer/, ); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: (2 ** 53).toString(), kind: Kind.INT }, {}, ), ).toThrow(/Value is not a safe integer/); }); }); describe('less than zero', () => { describe('as int', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(-1)).toThrow( /Value is not a non-negative number/, ); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue(-1)).toThrow( /Value is not a non-negative number/, ); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: '-1', kind: Kind.INT }, {}, ), ).toThrow(/Value is not a non-negative number/); }); }); describe('as string', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize('-1')).toThrow( /Value is not a non-negative number/, ); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue('-1')).toThrow( /Value is not a non-negative number/, ); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: '-1', kind: Kind.INT }, {}, ), ).toThrow(/Value is not a non-negative number/); }); }); }); describe('infinity', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(Number.POSITIVE_INFINITY), ).toThrow(/Value is not a finite number/); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue(Number.POSITIVE_INFINITY), ).toThrow(/Value is not a finite number/); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: Number.POSITIVE_INFINITY.toString(), kind: Kind.INT, }, {}, ), ).toThrow(/Value is not a finite number/); }); }); describe('not a number', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize('not a number')).toThrow( /Value is not a number/, ); }); test('parseValue', () => { expect(() => GraphQLNonNegativeInt.parseValue('not a number')).toThrow( /Value is not a number/, ); }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: 'not a number', kind: Kind.STRING, }, {}, ), ).toThrow( /Can only validate integers as non-negative integers but got a/, ); }); }); describe('NaN', () => { test('serialize', () => { expect(() => GraphQLNonNegativeInt.serialize(Number.NaN)).toThrow( /Value is not a number/, ); }); // FIXME: Does nothing. No throw. Call doesn't even seem to get to the parseValue() function. // test('parseValue', () => { // expect(() => GraphQLNonNegativeInt.parseValue(Number.NaN)).toThrow( // /Value is not a number/, // ); // }); test('parseLiteral', () => { expect(() => GraphQLNonNegativeInt.parseLiteral( { value: Number.NaN.toString(), kind: Kind.STRING }, {}, ), ).toThrow( /Can only validate integers as non-negative integers but got a/, ); }); }); }); }); describe('UnsignedInt', () => { describe('valid', () => { describe('greater than zero', () => { describe('as int', () => { test('serialize', () => { expect(GraphQLUnsignedInt.serialize(123)).toBe(123); }); test('parseValue', () => { expect(GraphQLUnsignedInt.parseValue(123)).toBe(123); }); test('parseLiteral', () => { expect( GraphQLUnsignedInt.parseLiteral( { value: '123', kind: Kind.INT }, {}, ), ).toBe(123); }); }); describe('as string', () => { test('serialize', () => { expect(GraphQLUnsignedInt.serialize('123')).toBe(123); }); test('parseValue', () => { expect(GraphQLUnsignedInt.parseValue('123')).toBe(123); }); test('parseLiteral', () => { expect( GraphQLUnsignedInt.parseLiteral( { value: '123', kind: Kind.INT }, {}, ), ).toBe(123); }); }); }); describe('zero', () => { describe('as int', () => { test('serialize', () => { expect(GraphQLUnsignedInt.serialize(0)).toBe(0); }); test('parseValue', () => { expect(GraphQLUnsignedInt.parseValue(0)).toBe(0); }); test('parseLiteral', () => { expect( GraphQLUnsignedInt.parseLiteral({ value: '0', kind: Kind.INT }, {}), ).toBe(0); }); }); describe('as string', () => { test('serialize', () => { expect(GraphQLUnsignedInt.serialize('0')).toBe(0); }); test('parseValue', () => { expect(GraphQLUnsignedInt.parseValue('0')).toBe(0); }); test('parseLiteral', () => { expect( GraphQLUnsignedInt.parseLiteral({ value: '0', kind: Kind.INT }, {}), ).toBe(0); }); }); }); }); describe('invalid', () => { describe('null', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(null)).toThrow( /Value is not a number/, ); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue(null)).toThrow( /Value is not a number/, ); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral({ value: null, kind: Kind.INT }, {}), ).toThrow(/Value is not a number/); }); }); describe('undefined', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(undefined)).toThrow( /Value is not a number/, ); }); // FIXME: Does nothing. No throw. Call doesn't even seem to get to the parseValue() function. // test('parseValue', () => { // expect(() => GraphQLUnsignedInt.parseValue(undefined)).toThrow( // /Value is not a number/, // ); // }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: undefined, kind: Kind.INT }, {}, ), ).toThrow(/Value is not a number/); }); }); describe('unsafe integer', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(2 ** 53)).toThrow( /Value is not a safe integer/, ); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue(2 ** 53)).toThrow( /Value is not a safe integer/, ); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: (2 ** 53).toString(), kind: Kind.INT }, {}, ), ).toThrow(/Value is not a safe integer/); }); }); describe('less than zero', () => { describe('as int', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(-1)).toThrow( /Value is not a non-negative number/, ); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue(-1)).toThrow( /Value is not a non-negative number/, ); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: '-1', kind: Kind.INT }, {}, ), ).toThrow(/Value is not a non-negative number/); }); }); describe('as string', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize('-1')).toThrow( /Value is not a non-negative number/, ); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue('-1')).toThrow( /Value is not a non-negative number/, ); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: '-1', kind: Kind.INT }, {}, ), ).toThrow(/Value is not a non-negative number/); }); }); }); describe('infinity', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(Number.POSITIVE_INFINITY), ).toThrow(/Value is not a finite number/); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue(Number.POSITIVE_INFINITY), ).toThrow(/Value is not a finite number/); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: Number.POSITIVE_INFINITY.toString(), kind: Kind.INT, }, {}, ), ).toThrow(/Value is not a finite number/); }); }); describe('not a number', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize('not a number')).toThrow( /Value is not a number/, ); }); test('parseValue', () => { expect(() => GraphQLUnsignedInt.parseValue('not a number')).toThrow( /Value is not a number/, ); }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: 'not a number', kind: Kind.STRING, }, {}, ), ).toThrow( /Can only validate integers as non-negative integers but got a/, ); }); }); describe('NaN', () => { test('serialize', () => { expect(() => GraphQLUnsignedInt.serialize(Number.NaN)).toThrow( /Value is not a number/, ); }); // FIXME: Does nothing. No throw. Call doesn't even seem to get to the parseValue() function. // test('parseValue', () => { // expect(() => GraphQLUnsignedInt.parseValue(Number.NaN)).toThrow( // /Value is not a number/, // ); // }); test('parseLiteral', () => { expect(() => GraphQLUnsignedInt.parseLiteral( { value: Number.NaN.toString(), kind: Kind.STRING }, {}, ), ).toThrow( /Can only validate integers as non-negative integers but got a/, ); }); }); }); });
the_stack
import Permissions from './permissions'; export const RESOURCE_KEYS = { ABOUT: { EDITION_AND_LICENSE: 'about.edition_and_license', }, REPORTING: { SITE_STATISTICS: 'reporting.site_statistics', TEAM_STATISTICS: 'reporting.team_statistics', SERVER_LOGS: 'reporting.server_logs', }, USER_MANAGEMENT: { USERS: 'user_management.users', GROUPS: 'user_management.groups', TEAMS: 'user_management.teams', CHANNELS: 'user_management.channels', PERMISSIONS: 'user_management.permissions', SYSTEM_ROLES: 'user_management.system_roles', }, AUTHENTICATION: { SIGNUP: 'authentication.signup', EMAIL: 'authentication.email', PASSWORD: 'authentication.password', MFA: 'authentication.mfa', LDAP: 'authentication.ldap', SAML: 'authentication.saml', OPENID: 'authentication.openid', GUEST_ACCESS: 'authentication.guest_access', }, INTEGRATIONS: { INTEGRATION_MANAGEMENT: 'integrations.integration_management', BOT_ACCOUNTS: 'integrations.bot_accounts', GIF: 'integrations.gif', CORS: 'integrations.cors', }, COMPLIANCE: { DATA_RETENTION_POLICY: 'compliance.data_retention_policy', COMPLIANCE_EXPORT: 'compliance.compliance_export', COMPLIANCE_MONITORING: 'compliance.compliance_monitoring', CUSTOM_TERMS_OF_SERVICE: 'compliance.custom_terms_of_service', }, SITE: { CUSTOMIZATION: 'site.customization', LOCALIZATION: 'site.localization', USERS_AND_TEAMS: 'site.users_and_teams', NOTIFICATIONS: 'site.notifications', ANNOUNCEMENT_BANNER: 'site.announcement_banner', EMOJI: 'site.emoji', POSTS: 'site.posts', FILE_SHARING_AND_DOWNLOADS: 'site.file_sharing_and_downloads', PUBLIC_LINKS: 'site.public_links', NOTICES: 'site.notices', }, EXPERIMENTAL: { FEATURES: 'experimental.features', FEATURE_FLAGS: 'experimental.feature_flags', BLEVE: 'experimental.bleve', }, ENVIRONMENT: { WEB_SERVER: 'environment.web_server', DATABASE: 'environment.database', ELASTICSEARCH: 'environment.elasticsearch', FILE_STORAGE: 'environment.file_storage', IMAGE_PROXY: 'environment.image_proxy', SMTP: 'environment.smtp', PUSH_NOTIFICATION_SERVER: 'environment.push_notification_server', HIGH_AVAILABILITY: 'environment.high_availability', RATE_LIMITING: 'environment.rate_limiting', LOGGING: 'environment.logging', SESSION_LENGTHS: 'environment.session_lengths', PERFORMANCE_MONITORING: 'environment.performance_monitoring', DEVELOPER: 'environment.developer', }, }; export const ResourceToSysConsolePermissionsTable: Record<string, string[]> = { [RESOURCE_KEYS.ABOUT.EDITION_AND_LICENSE]: [Permissions.SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE, Permissions.SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE], billing: [Permissions.SYSCONSOLE_READ_BILLING, Permissions.SYSCONSOLE_WRITE_BILLING], [RESOURCE_KEYS.REPORTING.SITE_STATISTICS]: [Permissions.SYSCONSOLE_READ_REPORTING_SITE_STATISTICS, Permissions.SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS], [RESOURCE_KEYS.REPORTING.TEAM_STATISTICS]: [Permissions.SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS, Permissions.SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS], [RESOURCE_KEYS.REPORTING.SERVER_LOGS]: [Permissions.SYSCONSOLE_READ_REPORTING_SERVER_LOGS, Permissions.SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS], [RESOURCE_KEYS.USER_MANAGEMENT.USERS]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_USERS, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_USERS], [RESOURCE_KEYS.USER_MANAGEMENT.GROUPS]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_GROUPS, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS], [RESOURCE_KEYS.USER_MANAGEMENT.TEAMS]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_TEAMS, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS], [RESOURCE_KEYS.USER_MANAGEMENT.CHANNELS]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS], [RESOURCE_KEYS.USER_MANAGEMENT.PERMISSIONS]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS], [RESOURCE_KEYS.USER_MANAGEMENT.SYSTEM_ROLES]: [Permissions.SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES, Permissions.SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES], [RESOURCE_KEYS.SITE.CUSTOMIZATION]: [Permissions.SYSCONSOLE_READ_SITE_CUSTOMIZATION, Permissions.SYSCONSOLE_WRITE_SITE_CUSTOMIZATION], [RESOURCE_KEYS.SITE.LOCALIZATION]: [Permissions.SYSCONSOLE_READ_SITE_LOCALIZATION, Permissions.SYSCONSOLE_WRITE_SITE_LOCALIZATION], [RESOURCE_KEYS.SITE.USERS_AND_TEAMS]: [Permissions.SYSCONSOLE_READ_SITE_USERS_AND_TEAMS, Permissions.SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS], [RESOURCE_KEYS.SITE.NOTIFICATIONS]: [Permissions.SYSCONSOLE_READ_SITE_NOTIFICATIONS, Permissions.SYSCONSOLE_WRITE_SITE_NOTIFICATIONS], [RESOURCE_KEYS.SITE.ANNOUNCEMENT_BANNER]: [Permissions.SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER, Permissions.SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER], [RESOURCE_KEYS.SITE.EMOJI]: [Permissions.SYSCONSOLE_READ_SITE_EMOJI, Permissions.SYSCONSOLE_WRITE_SITE_EMOJI], [RESOURCE_KEYS.SITE.POSTS]: [Permissions.SYSCONSOLE_READ_SITE_POSTS, Permissions.SYSCONSOLE_WRITE_SITE_POSTS], [RESOURCE_KEYS.SITE.FILE_SHARING_AND_DOWNLOADS]: [Permissions.SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS, Permissions.SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS], [RESOURCE_KEYS.SITE.PUBLIC_LINKS]: [Permissions.SYSCONSOLE_READ_SITE_PUBLIC_LINKS, Permissions.SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS], [RESOURCE_KEYS.SITE.NOTICES]: [Permissions.SYSCONSOLE_READ_SITE_NOTICES, Permissions.SYSCONSOLE_WRITE_SITE_NOTICES], [RESOURCE_KEYS.ENVIRONMENT.WEB_SERVER]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER], [RESOURCE_KEYS.ENVIRONMENT.DATABASE]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_DATABASE, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE], [RESOURCE_KEYS.ENVIRONMENT.ELASTICSEARCH]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH], [RESOURCE_KEYS.ENVIRONMENT.FILE_STORAGE]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE], [RESOURCE_KEYS.ENVIRONMENT.IMAGE_PROXY]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY], [RESOURCE_KEYS.ENVIRONMENT.SMTP]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_SMTP, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_SMTP], [RESOURCE_KEYS.ENVIRONMENT.PUSH_NOTIFICATION_SERVER]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER], [RESOURCE_KEYS.ENVIRONMENT.HIGH_AVAILABILITY]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY], [RESOURCE_KEYS.ENVIRONMENT.RATE_LIMITING]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING], [RESOURCE_KEYS.ENVIRONMENT.LOGGING]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_LOGGING, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING], [RESOURCE_KEYS.ENVIRONMENT.SESSION_LENGTHS]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS], [RESOURCE_KEYS.ENVIRONMENT.PERFORMANCE_MONITORING]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING], [RESOURCE_KEYS.ENVIRONMENT.DEVELOPER]: [Permissions.SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER, Permissions.SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER], [RESOURCE_KEYS.AUTHENTICATION.SIGNUP]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_SIGNUP, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP], [RESOURCE_KEYS.AUTHENTICATION.EMAIL]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_EMAIL, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL], [RESOURCE_KEYS.AUTHENTICATION.PASSWORD]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_PASSWORD, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD], [RESOURCE_KEYS.AUTHENTICATION.MFA]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_MFA, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_MFA], [RESOURCE_KEYS.AUTHENTICATION.LDAP]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_LDAP, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_LDAP], [RESOURCE_KEYS.AUTHENTICATION.SAML]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_SAML, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_SAML], [RESOURCE_KEYS.AUTHENTICATION.OPENID]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_OPENID, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_OPENID], [RESOURCE_KEYS.AUTHENTICATION.GUEST_ACCESS]: [Permissions.SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS, Permissions.SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS], plugins: [Permissions.SYSCONSOLE_READ_PLUGINS, Permissions.SYSCONSOLE_WRITE_PLUGINS], [RESOURCE_KEYS.INTEGRATIONS.INTEGRATION_MANAGEMENT]: [Permissions.SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT, Permissions.SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT], [RESOURCE_KEYS.INTEGRATIONS.BOT_ACCOUNTS]: [Permissions.SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS, Permissions.SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS], [RESOURCE_KEYS.INTEGRATIONS.GIF]: [Permissions.SYSCONSOLE_READ_INTEGRATIONS_GIF, Permissions.SYSCONSOLE_WRITE_INTEGRATIONS_GIF], [RESOURCE_KEYS.INTEGRATIONS.CORS]: [Permissions.SYSCONSOLE_READ_INTEGRATIONS_CORS, Permissions.SYSCONSOLE_WRITE_INTEGRATIONS_CORS], [RESOURCE_KEYS.COMPLIANCE.DATA_RETENTION_POLICY]: [Permissions.SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY, Permissions.SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY], [RESOURCE_KEYS.COMPLIANCE.COMPLIANCE_EXPORT]: [Permissions.SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT, Permissions.SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT], [RESOURCE_KEYS.COMPLIANCE.COMPLIANCE_MONITORING]: [Permissions.SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING, Permissions.SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING], [RESOURCE_KEYS.COMPLIANCE.CUSTOM_TERMS_OF_SERVICE]: [Permissions.SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE, Permissions.SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE], [RESOURCE_KEYS.EXPERIMENTAL.FEATURES]: [Permissions.SYSCONSOLE_READ_EXPERIMENTAL_FEATURES, Permissions.SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES], [RESOURCE_KEYS.EXPERIMENTAL.FEATURE_FLAGS]: [Permissions.SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS, Permissions.SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS], [RESOURCE_KEYS.EXPERIMENTAL.BLEVE]: [Permissions.SYSCONSOLE_READ_EXPERIMENTAL_BLEVE, Permissions.SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE], };
the_stack
export interface DescribeFaceIdResultsRequest { /** * 调用方信息 */ Caller: Caller; /** * 慧眼业务ID */ WbAppId: string; /** * 订单号(orderNo); 限制在3个或以内 */ OrderNumbers: Array<string>; /** * 1:视频+照片,2:照片,3:视频,0(或其他数字):无; 可选 */ FileType?: number; } /** * CreateSubOrganization请求参数结构体 */ export interface CreateSubOrganizationRequest { /** * 调用方信息 */ Caller: Caller; /** * 机构证件号码类型可选值: 1. USCC - 统一社会信用代码 2. BIZREGISTNO - 营业执照注册号 */ IdCardType: string; /** * 机构证件号码 */ IdCardNumber: string; /** * 机构类型可选值: 1. ENTERPRISE - 企业 2. INDIVIDUALBIZ - 个体工商户 3. PUBLICINSTITUTION - 政府/事业单位 4. OTHERS - 其他组织 */ OrganizationType: string; /** * 机构法人/经营者姓名 */ LegalName: string; /** * 机构法人/经营者证件类型可选值: 1. ID_CARD - 居民身份证 2. PASSPORT - 护照 3. MAINLAND_TRAVEL_PERMIT_FOR_HONGKONG_AND_MACAO_RESIDENTS - 港澳居民来往内地通行证 4. MAINLAND_TRAVEL_PERMIT_FOR_TAIWAN_RESIDENTS - 台湾居民来往大陆通行证 5. HOUSEHOLD_REGISTER - 户口本 6. TEMP_ID_CARD - 临时居民身份证 */ LegalIdCardType: string; /** * 机构法人/经营者证件号码; OrganizationType 为 ENTERPRISE时,INDIVIDUALBIZ 时必填,其他情况选填 */ LegalIdCardNumber: string; /** * 机构名称全称 */ Name: string; /** * 机构在第三方的唯一标识,32位以内标识符 */ OpenId?: string; /** * 是否使用OpenId作为数据主键,如果为true,请确保OpenId在当前应用号唯一 */ UseOpenId?: boolean; /** * 机构证件文件类型可选值: 1. USCCFILE - 统一社会信用代码证书 2. LICENSEFILE - 营业执照 */ IdCardFileType?: string; /** * 机构证件照片文件,base64编码,支持jpg、jpeg、png格式 */ BizLicenseFile?: string; /** * 机构证件照片文件名 */ BizLicenseFileName?: string; /** * 机构法人/经营者/联系人手机号码 */ LegalMobile?: string; /** * 组织联系人姓名 */ ContactName?: string; /** * 实名认证的客户端IP */ VerifyClientIp?: string; /** * 实名认证的服务器IP */ VerifyServerIp?: string; /** * 企业联系地址 */ ContactAddress?: Address; /** * 机构电子邮箱 */ Email?: string; } /** * 此结构体 (Component) 用于描述控件属性。 */ export interface Component { /** * 控件编号 注: 当GenerateMode=3时,通过"^"来决定是否使用关键字整词匹配能力。 例: 当GenerateMode=3时,如果传入关键字"^甲方签署^",则会在PDF文件中有且仅有"甲方签署"关键字的地方进行对应操作。 如传入的关键字为"甲方签署",则PDF文件中每个出现关键字的位置都会执行相应操作。 */ ComponentId?: string; /** * 如果是Component控件类型,则可选的字段为: TEXT - 普通文本控件; DATE - 普通日期控件; SELECT- 勾选框控件; 如果是SignComponent控件类型,则可选的字段为 SIGN_SEAL- 签署印章控件; SIGN_DATE- 签署日期控件; SIGN_SIGNATURE - 用户签名控件; */ ComponentType?: string; /** * 控件名称 */ ComponentName?: string; /** * 定义控件是否为必填项,默认为false */ ComponentRequired?: boolean; /** * 控件所属文件的序号 (模板中的resourceId排列序号) */ FileIndex?: number; /** * 控件生成的方式: 0 - 普通控件 1 - 表单域 2 - html 控件 3 - 关键字 */ GenerateMode?: number; /** * 参数控件宽度,单位px */ ComponentWidth?: number; /** * 参数控件高度,单位px */ ComponentHeight?: number; /** * 参数控件所在页码 */ ComponentPage?: number; /** * 参数控件X位置,单位px */ ComponentPosX?: number; /** * 参数控件Y位置,单位px */ ComponentPosY?: number; /** * 参数控件样式 */ ComponentExtra?: string; /** * 印章ID,如果是手写签名则为jpg或png格式的base64图片 SIGN_SEAL控件,可以用ORG_DEFAULT_SEAL表示主企业的默认印章 SIGN_SEAL控件,可以用SUBORG_DEFAULT_SEAL表示子企业的默认印章 SIGN_SEAL控件,可以用USER_DEFAULT_SEAL表示个人默认印章 */ ComponentValue?: string; /** * 如果是SIGN_SEAL类型的签署控件, 参数标识H5签署界面是否在该签署区上进行放置展示, 1为放置,其他为不放置 */ SealOperate?: number; /** * 不同GenerateMode对应的额外信息 */ GenerateExtra?: string; } /** * CreateSeal请求参数结构体 */ export interface CreateSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 印章类型: 1. PERSONAL - 个人私章 2. OFFICIAL - 公章 3. SPECIAL_FINANCIAL - 财务专用章 4. CONTRACT - 合同专用章 5. LEGAL_REPRESENTATIVE - 法定代表人章 6. SPECIAL_NATIONWIDE_INVOICE - 发票专用章 7. OTHER-其他 */ SealType: string; /** * 印章名称 */ SealName: string; /** * 请求创建印章的客户端IP */ SourceIp: string; /** * 印章图片,base64编码(与FileId参数二选一,同时传入参数时优先使用Image参数) */ Image?: string; /** * 印章文件图片ID(与Image参数二选一,同时传入参数时优先使用Image参数) */ FileId?: string; /** * 需要创建印章的用户ID */ UserId?: string; /** * 是否是默认印章 true:是,false:否 */ IsDefault?: boolean; } /** * CancelFlow返回参数结构体 */ export interface CancelFlowResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 此结构体 (FaceIdPhoto) 用于描述慧眼人脸核身照片信息。 */ export interface FaceIdPhoto { /** * 核身结果: 0 - 通过; 1 - 未通过 */ Result: number; /** * 核身失败描述 */ Description: string; /** * 照片数据 (base64编码, 一般为JPG或PNG) */ Photo: string; /** * 订单号 (orderNo) */ OrderNumber: string; } /** * VerifySubOrganization请求参数结构体 */ export interface VerifySubOrganizationRequest { /** * 调用方信息,该接口SubOrganizationId必填 */ Caller: Caller; /** * 机构在第三方的唯一标识,32位定长字符串,与 Caller 中 SubOrgnizationId 二者至少需要传入一个,全部传入时则使用 SubOrganizationId 信息 */ OpenId?: string; } /** * VerifyUser请求参数结构体 */ export interface VerifyUserRequest { /** * 调用方信息 */ Caller: Caller; /** * 电子签平台用户ID */ UserId: string; /** * 是否需要下发个人长效证书,默认为false 注:如您有下发个人长效证书需求,请提前邮件至e-contract@oa.com进行申请。 */ CertificateRequired?: boolean; } /** * DescribeFaceIdPhotos返回参数结构体 */ export interface DescribeFaceIdPhotosResponse { /** * 照片信息列表 */ Photos?: Array<FaceIdPhoto>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckVerifyCodeMatchFlowId请求参数结构体 */ export interface CheckVerifyCodeMatchFlowIdRequest { /** * 调用方信息 */ Caller: Caller; /** * 手机号 */ Mobile: string; /** * 验证码 */ VerifyCode: string; /** * 流程(目录) id */ FlowId: string; } /** * CheckBankCard2EVerification请求参数结构体 */ export interface CheckBankCard2EVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 银行卡号 */ BankCard: string; /** * 姓名 */ Name: string; } /** * DescribeFileIdsByCustomIds返回参数结构体 */ export interface DescribeFileIdsByCustomIdsResponse { /** * <自定义Id,文件id>数组 */ CustomIdList: Array<CustomFileIdMap>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifySubOrganizationInfo返回参数结构体 */ export interface ModifySubOrganizationInfoResponse { /** * 子机构ID */ SubOrganizationId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCatalogApprovers请求参数结构体 */ export interface DescribeCatalogApproversRequest { /** * 调用方信息 */ Caller: Caller; /** * 目录ID */ CatalogId: string; /** * 查询指定用户是否为参与者,为空表示查询所有参与者 */ UserId?: string; } /** * CheckFaceIdentify请求参数结构体 */ export interface CheckFaceIdentifyRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 人脸核身渠道; 必选; WEIXINAPP:腾讯电子签小程序,FACEID:腾讯电子签慧眼,None:白名单中的客户直接通过 */ VerifyChannel: string; /** * 核身订单号; 必选; 对于WEIXINAPP,直接取响应的{VerifyResult};对于FACEID,使用{WbAppId}:{OrderNo}拼接 */ VerifyResult: string; /** * 要对比的姓名; 可选; 未填写时对比caller.OperatorId的实名信息 */ Name?: string; /** * 要对比的身份证号码; 可选; 未填写时对比caller.OperatorId的实名信息 */ IdCardNumber?: string; /** * 是否取认证时的照片 */ GetPhoto?: boolean; } /** * CreateServerFlowSign返回参数结构体 */ export interface CreateServerFlowSignResponse { /** * 任务状态: 0:失败 1:成功 */ SignStatus: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyUser返回参数结构体 */ export interface ModifyUserResponse { /** * 腾讯电子签平台用户唯一标识 */ UserId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckBankCard4EVerification返回参数结构体 */ export interface CheckBankCard4EVerificationResponse { /** * 检测结果 计费结果码: 0: 认证通过 1: 认证未通过 2: 持卡人信息有误 3: 未开通无卡支付 4: 此卡被没收 5: 无效卡号 6: 此卡无对应发卡行 7: 该卡未初始化或睡眠卡 8: 作弊卡、吞卡 9: 此卡已挂失 10: 该卡已过期 11: 受限制的卡 12: 密码错误次数超限 13: 发卡行不支持此交易 不收费结果码: 101: 姓名校验不通过 102: 银行卡号码有误 103: 验证中心服务繁忙 104: 身份证号码有误 105: 手机号码不合法 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFileUrls请求参数结构体 */ export interface DescribeFileUrlsRequest { /** * 调用方信息 */ Caller: Caller; /** * 业务编号数组,如模板编号、文档编号、印章编号、流程编号、目录编号 */ BusinessIds: Array<string>; /** * 业务类型: 1. TEMPLATE - 模板 2. SEAL - 印章 3. FLOW - 流程 4.CATALOG - 目录 */ BusinessType: string; /** * 下载后的文件命名,只有FileType为“ZIP”时生效 */ FileName?: string; /** * 单个业务ID多个资源情况下,指定资源起始偏移量 */ ResourceOffset?: number; /** * 单个业务ID多个资源情况下,指定资源数量 */ ResourceLimit?: number; /** * 文件类型,支持"JPG", "PDF","ZIP"等,默认为上传的文件类型 */ FileType?: string; } /** * 此结构体 (FlowFileInfo) 用于描述流程文档信息。 */ export interface FlowFileInfo { /** * 文件序号 */ FileIndex: number; /** * 文件类型 */ FileType: string; /** * 文件的MD5码 */ FileMd5: string; /** * 文件名 */ FileName: string; /** * 文件大小,单位为Byte */ FileSize: number; /** * 文件创建时间戳 */ CreatedOn: number; /** * 文件的下载地址 */ Url: string; } /** * 此结构体 (SmsTemplate) 用于描述短信模板。 */ export interface SmsTemplate { /** * 模板ID,必须填写已审核通过的模板ID。模板ID可登录短信控制台查看。 */ TemplateId: string; /** * 短信签名内容,使用UTF-8编码,必须填写已审核通过的签名,签名信息可登录短信控制台查看。 */ Sign: string; } /** * 此结构体 (Address) 用于描述住址或通讯地址。 */ export interface Address { /** * 省份 */ Province: string; /** * 城市 */ City: string; /** * 区县 */ County: string; /** * 详细地址 */ Details: string; /** * 国家,默认中国 */ Country?: string; } /** * ModifyUserDefaultSeal请求参数结构体 */ export interface ModifyUserDefaultSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 用户唯一标识,需要重新指定默认印章的用户ID */ UserId: string; /** * 重新指定的默认印章ID */ SealId: string; /** * 请求重新指定个人默认印章的客户端IP */ SourceIp: string; } /** * GenerateUserSeal请求参数结构体 */ export interface GenerateUserSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 用户ID */ UserId: string; /** * 请求生成个人印章的客户端IP */ SourceIp: string; /** * 电子印章名称 */ SealName?: string; /** * 是否是默认印章 true:是,false:否 */ IsDefault?: boolean; } /** * CheckIdCardVerification返回参数结构体 */ export interface CheckIdCardVerificationResponse { /** * 检测结果; 收费错误码: 0: 通过, 1: 姓名和身份证号不一致, 免费错误码: 101: 非法身份证号(长度,格式等不正确), 102: 非法姓名(长度,格式等不正确), 103: 验证平台异常, 104: 证件库中无此身份证记录 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFlow返回参数结构体 */ export interface DescribeFlowResponse { /** * 流程创建者信息 */ Creator: Caller; /** * 流程编号 */ FlowId: string; /** * 流程名称 */ FlowName: string; /** * 流程描述 */ FlowDescription: string; /** * 流程的类型: ”劳务合同“,”租赁合同“,”销售合同“,”其他“ */ FlowType: string; /** * 流程状态: 0-创建; 1-签署中; 2-拒签; 3-撤回; 4-签完存档完成; 5-已过期; 6-已销毁 7-签署完成未归档 */ FlowStatus: number; /** * 流程创建时间 */ CreatedOn: number; /** * 流程完成时间 */ UpdatedOn: number; /** * 流程截止日期 */ Deadline: number; /** * 回调地址 */ CallbackUrl: string; /** * 流程中止原因 */ FlowMessage: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateSubOrganizationAndSeal请求参数结构体 */ export interface CreateSubOrganizationAndSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 机构名称全称 */ Name: string; /** * 机构证件号码类型可选值: 1. USCC - 统一社会信用代码 2. BIZREGISTNO - 营业执照注册号 */ IdCardType: string; /** * 机构证件号码 */ IdCardNumber: string; /** * 机构类型可选值: 1. ENTERPRISE - 企业 2. INDIVIDUALBIZ - 个体工商户 3. PUBLICINSTITUTION - 政府/事业单位 4. OTHERS - 其他组织 */ OrganizationType: string; /** * 机构法人/经营者姓名 */ LegalName: string; /** * 机构法人/经营者证件类型可选值: 1. ID_CARD - 居民身份证 2. PASSPORT - 护照 3. MAINLAND_TRAVEL_PERMIT_FOR_HONGKONG_AND_MACAO_RESIDENTS - 港澳居民来往内地通行证 4. MAINLAND_TRAVEL_PERMIT_FOR_TAIWAN_RESIDENTS - 台湾居民来往大陆通行证 5. HOUSEHOLD_REGISTER - 户口本 6. TEMP_ID_CARD - 临时居民身份证 */ LegalIdCardType: string; /** * 机构法人/经营者证件号码; OrganizationType 为 ENTERPRISE时,INDIVIDUALBIZ 时必填,其他情况选填 */ LegalIdCardNumber: string; /** * 实名认证的客户端IP/请求生成企业印章的客户端Ip */ VerifyClientIp: string; /** * 机构电子邮箱 */ Email?: string; /** * 机构证件文件类型可选值: 1. USCCFILE - 统一社会信用代码证书 2. LICENSEFILE - 营业执照 */ IdCardFileType?: string; /** * 机构证件照片文件,base64编码,支持jpg、jpeg、png格式 */ BizLicenseFile?: string; /** * 机构证件照片文件名 */ BizLicenseFileName?: string; /** * 机构法人/经营者/联系人手机号码 */ LegalMobile?: string; /** * 组织联系人姓名 */ ContactName?: string; /** * 实名认证的服务器IP */ VerifyServerIp?: string; /** * 企业联系地址 */ ContactAddress?: Address; /** * 电子印章名称 */ SealName?: string; /** * 印章类型:默认: CONTRACT 1. OFFICIAL-公章 2. SPECIAL_FINANCIAL-财务专用章 3. CONTRACT-合同专用章 4. LEGAL_REPRESENTATIVE-法定代表人章 5. SPECIAL_NATIONWIDE_INVOICE-发票专用章 6. OTHER-其他 */ SealType?: string; /** * 企业印章横向文字,最多可填8个汉字(可为空,默认为"电子签名专用章") */ SealHorizontalText?: string; /** * 机构在第三方的唯一标识,32位以内标识符 */ OpenId?: string; /** * 是否使用OpenId作为数据主键,如果为true,请确保OpenId在当前应用号唯一 */ UseOpenId?: boolean; } /** * CheckMobileVerification请求参数结构体 */ export interface CheckMobileVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 手机号 */ Mobile: string; /** * 姓名 */ Name: string; /** * 身份证件号码 */ IdCardNumber: string; /** * 身份证件类型; ID_CARD */ IdCardType?: string; } /** * SendFlowUrl返回参数结构体 */ export interface SendFlowUrlResponse { /** * 签署任务ID,标识每一次的流程发送 */ SignId: string; /** * 签署链接 */ SignUrl?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCatalogApprovers返回参数结构体 */ export interface DescribeCatalogApproversResponse { /** * 参与者列表 */ Approvers: Array<CatalogApprovers>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * <自定义Id,文件id>映射对象 */ export interface CustomFileIdMap { /** * 用户自定义ID */ CustomId: string; /** * 文件id */ FileId: string; } /** * SendFlow返回参数结构体 */ export interface SendFlowResponse { /** * 签署任务ID,标识每一次的流程发送 */ SignId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 目录流程参与者 */ export interface CatalogApprovers { /** * 流程ID */ FlowId: string; /** * 参与者列表 */ Approvers: Array<FlowApproverInfo>; } /** * DescribeSeals请求参数结构体 */ export interface DescribeSealsRequest { /** * 调用方信息 */ Caller: Caller; /** * 印章ID列表 */ SealIds: Array<string>; /** * 用户唯一标识 */ UserId?: string; } /** * 此结构体 (FlowApproverInfo) 用于描述流程参与者信息。 */ export interface FlowApproverInfo { /** * 用户ID */ UserId: string; /** * 认证方式: WEIXINAPP - 微信小程序; FACEID - 慧眼 (默认); VERIFYCODE - 验证码; THIRD - 第三方 (暂不支持) */ VerifyChannel: Array<string>; /** * 签署状态: 0 - 待签署; 1- 已签署; 2 - 拒绝; 3 - 过期未处理; 4 - 流程已撤回, 12-审核中, 13-审核驳回 注意:此字段可能返回 null,表示取不到有效值。 */ ApproveStatus: number; /** * 拒签/签署/审核驳回原因 注意:此字段可能返回 null,表示取不到有效值。 */ ApproveMessage: string; /** * 签约时间的时间戳 注意:此字段可能返回 null,表示取不到有效值。 */ ApproveTime: number; /** * 签署企业ID 注意:此字段可能返回 null,表示取不到有效值。 */ SubOrganizationId: string; /** * 签署完成后跳转的URL 注意:此字段可能返回 null,表示取不到有效值。 */ JumpUrl: string; /** * 用户签署区ID到印章ID的映射集合 注意:此字段可能返回 null,表示取不到有效值。 */ ComponentSeals: Array<ComponentSeal>; /** * 签署前置条件:是否强制用户全文阅读,即阅读到待签署文档的最后一页。默认FALSE */ IsFullText: boolean; /** * 签署前置条件:强制阅读时长,页面停留时长不足则不允许签署。默认不限制 */ PreReadTime: number; /** * 签署人手机号,脱敏显示 */ Mobile: string; /** * 签署链接截止时间,默认签署流程发起后7天失效 */ Deadline: number; /** * 是否为最后一个签署人, 若为最后一人,则其签署完成后自动归档 */ IsLastApprover: boolean; /** * 短信模板 注意:此字段可能返回 null,表示取不到有效值。 */ SmsTemplate: SmsTemplate; /** * 身份证号,脱敏显示 */ IdCardNumber: string; /** * 用户姓名 */ Name: string; /** * 是否支持线下核身 */ CanOffLine: boolean; /** * 证件号码类型:ID_CARD - 身份证,PASSPORT - 护照,MAINLAND_TRAVEL_PERMIT_FOR_HONGKONG_AND_MACAO_RESIDENTS - 港澳居民来往内地通行证; 暂不支持用于电子签自有平台实名认证,MAINLAND_TRAVEL_PERMIT_FOR_TAIWAN_RESIDENTS - 台湾居民来往大陆通行证; 暂不支持用于电子签自有平台实名认证,HOUSEHOLD_REGISTER - 户口本; 暂不支持用于电子签自有平台实名认证,TEMP_ID_CARD - 临时居民身份证; 暂不支持用于电子签自有平台实名认证 注意:此字段可能返回 null,表示取不到有效值。 */ IdCardType: string; /** * 签署回调地址 注意:此字段可能返回 null,表示取不到有效值。 */ CallbackUrl: string; /** * 签署任务ID,标识每一次的流程发送 注意:此字段可能返回 null,表示取不到有效值。 */ SignId: string; } /** * DescribeFlowFiles请求参数结构体 */ export interface DescribeFlowFilesRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 需要查询的流程ID */ FlowId: string; } /** * DescribeCustomFlowIds返回参数结构体 */ export interface DescribeCustomFlowIdsResponse { /** * 自定义流程 id 映射列表 */ CustomIdList: Array<CustomFlowIdMap>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 此结构体 (SubOrganizationDetail) 用于描述子机构或子企业的详情信息。 */ export interface SubOrganizationDetail { /** * 组织ID */ Id: string; /** * 机构名称全称 */ Name: string; /** * 机构电子邮箱 */ Email: string; /** * 机构证件号码类型 */ IdCardType: string; /** * 机构证件号码 */ IdCardNumber: string; /** * 机构类型 */ OrganizationType: string; /** * 机构证件文件类型 注意:此字段可能返回 null,表示取不到有效值。 */ IdCardFileType: string; /** * 机构证件照片文件,base64编码 注意:此字段可能返回 null,表示取不到有效值。 */ BizLicenseFile: string; /** * 机构证件照片文件名 */ BizLicenseFileName: string; /** * 机构法人/经营者姓名 */ LegalName: string; /** * 机构法人/经营者证件类型 */ LegalIdCardType: string; /** * 机构法人/经营者证件号码 */ LegalIdCardNumber: string; /** * 机构法人/经营者/联系人手机号码 */ LegalMobile: string; /** * 组织联系人姓名 注意:此字段可能返回 null,表示取不到有效值。 */ ContactName: string; /** * 机构实名状态 */ VerifyStatus: string; /** * 机构通过实名时间 注意:此字段可能返回 null,表示取不到有效值。 */ VerifiedOn: number; /** * 机构创建时间 */ CreatedOn: number; /** * 机构更新时间 注意:此字段可能返回 null,表示取不到有效值。 */ UpdatedOn: number; /** * 实名认证的客户端IP 注意:此字段可能返回 null,表示取不到有效值。 */ VerifyClientIp: string; /** * 实名认证的服务器IP 注意:此字段可能返回 null,表示取不到有效值。 */ VerifyServerIp: string; /** * 企业联系地址 注意:此字段可能返回 null,表示取不到有效值。 */ ContactAddress: Address; } /** * CheckIdCardVerification请求参数结构体 */ export interface CheckIdCardVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 姓名 */ Name: string; /** * 身份证件号码 */ IdCardNumber: string; /** * 身份证件类型; ID_CARD */ IdCardType?: string; } /** * CreateSignUrl返回参数结构体 */ export interface CreateSignUrlResponse { /** * 合同签署链接 */ SignUrl: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifySubOrganizationInfo请求参数结构体 */ export interface ModifySubOrganizationInfoRequest { /** * 调用方信息,该接口 SubOrganizationId 字段与 OpenId 字段二者至少需要传入一个,全部传入时则使用 SubOrganizationId 信息 */ Caller: Caller; /** * 机构在第三方的唯一标识,32位定长字符串,与 Caller 中 SubOrgnizationId 二者至少需要传入一个,全部传入时则使用 SubOrganizationId 信息 */ OpenId?: string; /** * 机构名称全称,修改后机构状态将变为未实名,需要调用实名接口重新实名。 */ Name?: string; /** * 机构类型可选值: 1. ENTERPRISE - 企业; 2. INDIVIDUALBIZ - 个体工商户; 3. PUBLICINSTITUTION - 政府/事业单位 4. OTHERS - 其他组织 */ OrganizationType?: string; /** * 机构证件照片文件,base64编码。支持jpg,jpeg,png格式;如果传值,则重新上传文件后,机构状态将变为未实名,需要调用实名接口重新实名。 */ BizLicenseFile?: string; /** * 机构证件照片文件名 */ BizLicenseFileName?: string; /** * 机构法人/经营者姓名 */ LegalName?: string; /** * 机构法人/经营者证件类型,可选值:ID_CARD - 居民身份证。OrganizationType 为 ENTERPRISE、INDIVIDUALBIZ 时,此项必填,其他情况选填。 */ LegalIdCardType?: string; /** * 机构法人/经营者证件号码。OrganizationType 为 ENTERPRISE、INDIVIDUALBIZ 时,此项必填,其他情况选填 */ LegalIdCardNumber?: string; /** * 机构法人/经营者/联系人手机号码 */ LegalMobile?: string; /** * 组织联系人姓名 */ ContactName?: string; /** * 企业联系地址 */ ContactAddress?: Address; /** * 机构电子邮箱 */ Email?: string; } /** * SendSignInnerVerifyCode返回参数结构体 */ export interface SendSignInnerVerifyCodeResponse { /** * true: 验证码正确,false: 验证码错误 */ Result: boolean; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFaceIdPhotos请求参数结构体 */ export interface DescribeFaceIdPhotosRequest { /** * 调用方信息 */ Caller: Caller; /** * 慧眼业务ID */ WbAppId: string; /** * 订单号(orderNo); 限制在3个或以内 */ OrderNumbers: Array<string>; } /** * 此结构体 (FileUrl) 用于描述下载文件的URL信息。 */ export interface FileUrl { /** * 下载文件的URL */ Url: string; /** * 下载文件的附加信息 */ Option: string; /** * 下载文件所属的资源序号 */ Index: number; /** * 目录业务下,文件对应的流程 */ FlowId: string; } /** * CreateUser返回参数结构体 */ export interface CreateUserResponse { /** * 用户ID,按应用号隔离 */ UserId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckVerifyCodeMatchFlowId返回参数结构体 */ export interface CheckVerifyCodeMatchFlowIdResponse { /** * true: 验证码正确,false: 验证码错误 */ Success: boolean; /** * 0: 验证码正确 1:验证码错误或过期 2:验证码错误 3:验证码和流程不匹配 4:验证码输入错误超过次数 5:内部错误 6:参数错误 */ Result: number; /** * 结果描述 */ Description: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyOrganizationDefaultSeal请求参数结构体 */ export interface ModifyOrganizationDefaultSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 重新指定的默认印章ID */ SealId: string; /** * 请求重新指定企业默认印章的客户端IP */ SourceIp: string; } /** * CreateFaceIdSign返回参数结构体 */ export interface CreateFaceIdSignResponse { /** * 慧眼API签名 */ Sign?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFlowApprovers返回参数结构体 */ export interface DescribeFlowApproversResponse { /** * 流程编号 */ FlowId: string; /** * 流程参与者信息 */ Approvers: Array<FlowApproverInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckMobileAndName请求参数结构体 */ export interface CheckMobileAndNameRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 手机号 */ Mobile: string; /** * 姓名 */ Name: string; } /** * DeleteSeal请求参数结构体 */ export interface DeleteSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 印章ID */ SealId: string; /** * 请求删除印章的客户端IP */ SourceIp: string; /** * 用户唯一标识,默认为空时删除企业印章,如非空则删除个人印章 */ UserId?: string; } /** * CheckBankCardVerification返回参数结构体 */ export interface CheckBankCardVerificationResponse { /** * 检测结果 计费结果码: 0: 认证通过 1: 认证未通过 2: 持卡人信息有误 3: 未开通无卡支付 4: 此卡被没收 5: 无效卡号 6: 此卡无对应发卡行 7: 该卡未初始化或睡眠卡 8: 作弊卡、吞卡 9: 此卡已挂失 10: 该卡已过期 11: 受限制的卡 12: 密码错误次数超限 13: 发卡行不支持此交易 不收费结果码: 101: 姓名校验不通过 102: 银行卡号码有误 103: 验证中心服务繁忙 104: 身份证号码有误 105: 手机号码不合法 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ArchiveFlow请求参数结构体 */ export interface ArchiveFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程ID */ FlowId: string; } /** * CreateUserAndSeal返回参数结构体 */ export interface CreateUserAndSealResponse { /** * 用户唯一标识,按应用号隔离 */ UserId: string; /** * 默认印章ID */ SealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 此结构体 (FaceIdResult) 用于描述慧眼人脸核身结果。 */ export interface FaceIdResult { /** * 核身结果: 0 - 通过; 1 - 未通过 */ Result: number; /** * 核身失败描述 */ Description: string; /** * 订单号 (orderNo) */ OrderNumber: string; /** * 姓名 注意:此字段可能返回 null,表示取不到有效值。 */ Name: string; /** * 身份证件类型: ID_CARD - 居民身份证 注意:此字段可能返回 null,表示取不到有效值。 */ IdCardType: string; /** * 身份证件号码 注意:此字段可能返回 null,表示取不到有效值。 */ IdCardNumber: string; /** * 活体检测得分 (百分制) 注意:此字段可能返回 null,表示取不到有效值。 */ LiveRate: number; /** * 人脸检测得分 (百分制) 注意:此字段可能返回 null,表示取不到有效值。 */ Similarity: number; /** * 刷脸时间 (UNIX时间戳) 注意:此字段可能返回 null,表示取不到有效值。 */ OccurredTime: number; /** * 照片数据 (base64编码, 一般为JPG或PNG) 注意:此字段可能返回 null,表示取不到有效值。 */ Photo: string; /** * 视频数据 (base64编码, 一般为MP4) 注意:此字段可能返回 null,表示取不到有效值。 */ Video: string; } /** * CreateSignUrl请求参数结构体 */ export interface CreateSignUrlRequest { /** * 调用方信息 */ Caller: Caller; /** * 签署人ID */ UserId: string; /** * 文件签署截止时间戳 */ Deadline: number; /** * 目录ID。当 SignUrlType 为 CATALOG 时必填 */ CatalogId?: string; /** * 流程ID。当 SignUrlType 为 FLOW 时必填 */ FlowId?: string; /** * 签署链接类型: 1. FLOW - 单流程签署 (默认) 2. CATALOG - 目录签署 */ SignUrlType?: string; /** * 发送流程或目录时生成的签署任务ID */ SignId?: string; } /** * 此结构体 (ComponentSeal) 用于描述“签署区ID”到“印章ID”的映射。 */ export interface ComponentSeal { /** * 签署区ID */ ComponentId: string; /** * 印章ID */ SealId: string; } /** * DeleteSeal返回参数结构体 */ export interface DeleteSealResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UploadFiles请求参数结构体 */ export interface UploadFilesRequest { /** * 调用方信息 */ Caller: Caller; /** * 文件对应业务类型,用于区分文件存储路径: 1. TEMPLATE - 模版; 文件类型:.pdf/.html 2. DOCUMENT - 签署过程及签署后的合同文档 文件类型:.pdf/.html 3. FLOW - 签署过程 文件类型:.pdf/.html 4. SEAL - 印章; 文件类型:.jpg/.jpeg/.png 5. BUSINESSLICENSE - 营业执照 文件类型:.jpg/.jpeg/.png 6. IDCARD - 身份证 文件类型:.jpg/.jpeg/.png */ BusinessType: string; /** * 上传文件内容数组,最多支持20个文件 */ FileInfos?: Array<UploadFile>; /** * 上传文件链接数组,最多支持20个URL */ FileUrls?: Array<string>; /** * 是否将pdf灰色矩阵置白 true--是,处理置白 false--否,不处理 */ CoverRect?: boolean; /** * 特殊文件类型需要指定文件类型: HTML-- .html文件 */ FileType?: string; /** * 用户自定义ID数组,与上传文件一一对应 */ CustomIds?: Array<string>; } /** * DescribeUsers请求参数结构体 */ export interface DescribeUsersRequest { /** * 调用方信息 */ Caller: Caller; /** * UserId列表,最多支持100个UserId */ UserIds: Array<string>; } /** * CreateFlowByFiles请求参数结构体 */ export interface CreateFlowByFilesRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程创建信息 */ FlowInfo: FlowInfo; /** * 文件资源列表 (支持多文件) */ FileIds: Array<string>; /** * 自定义流程id */ CustomId?: string; } /** * 目录流程签署区 */ export interface CatalogComponents { /** * 流程ID */ FlowId: string; /** * 签署区列表 */ SignComponents: Array<Component>; /** * 签署任务ID */ SignId: string; } /** * ArchiveFlow返回参数结构体 */ export interface ArchiveFlowResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 此结构体 (FlowInfo) 用于描述流程信息。 */ export interface FlowInfo { /** * 合同名字 */ FlowName: string; /** * 签署截止时间戳,超过有效签署时间则该签署流程失败 */ Deadline: number; /** * 合同描述 */ FlowDescription?: string; /** * 合同类型: 1. “劳务” 2. “销售” 3. “租赁” 4. “其他” */ FlowType?: string; /** * 回调地址 */ CallbackUrl?: string; /** * 用户自定义数据 */ UserData?: string; } /** * 此结构体 (UserDescribe) 用于描述个人帐号查询结果。 */ export interface UserDescribe { /** * 用户ID */ UserId: string; /** * 手机号,隐藏中间4位数字,用*代替 */ Mobile: string; /** * 注册时间点 (UNIX时间戳) */ CreatedOn: number; /** * 实名认证状态: 0 - 未实名; 1 - 通过实名 */ VerifyStatus: number; /** * 真实姓名 */ Name: string; /** * 实名认证通过时间 (UNIX时间戳) */ VerifiedOn: number; /** * 身份证件类型; ID_CARD - 居民身份证; PASSPORT - 护照; MAINLAND_TRAVEL_PERMIT_FOR_HONGKONG_AND_MACAO_RESIDENTS - 港澳居民来往内地通行证; MAINLAND_TRAVEL_PERMIT_FOR_TAIWAN_RESIDENTS - 台湾居民来往大陆通行证; HOUSEHOLD_REGISTER - 户口本; TEMP_ID_CARD - 临时居民身份证 */ IdCardType: string; /** * 身份证件号码 (脱敏) */ IdCardNumber: string; } /** * CheckBankCard2EVerification返回参数结构体 */ export interface CheckBankCard2EVerificationResponse { /** * 检测结果 计费结果码: 0: 认证通过 1: 认证未通过 2: 持卡人信息有误 3: 未开通无卡支付 4: 此卡被没收 5: 无效卡号 6: 此卡无对应发卡行 7: 该卡未初始化或睡眠卡 8: 作弊卡、吞卡 9: 此卡已挂失 10: 该卡已过期 11: 受限制的卡 12: 密码错误次数超限 13: 发卡行不支持此交易 不收费结果码: 101: 姓名校验不通过 102: 银行卡号码有误 103: 验证中心服务繁忙 104: 身份证号码有误 105: 手机号码不合法 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * VerifySubOrganization返回参数结构体 */ export interface VerifySubOrganizationResponse { /** * 子机构ID */ SubOrganizationId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeSeals返回参数结构体 */ export interface DescribeSealsResponse { /** * 印章信息 */ Seals: Array<Seal>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFileUrls返回参数结构体 */ export interface DescribeFileUrlsResponse { /** * 文件下载URL数组 */ FileUrls: Array<FileUrl>; /** * URL数量 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifySeal请求参数结构体 */ export interface ModifySealRequest { /** * 调用方信息 */ Caller: Caller; /** * 请求更新印章的客户端IP */ SourceIp: string; /** * 电子印章ID。若为空,则修改个人/机构的默认印章。 */ SealId?: string; /** * 电子印章名称 */ SealName?: string; /** * 印章图片,base64编码(与FileId参数二选一,同时传入参数时优先使用Image参数) */ Image?: string; /** * 印章图片文件ID(与Image参数二选一,同时传入参数时优先使用Image参数) */ FileId?: string; /** * 需要更新印章的用户ID */ UserId?: string; } /** * CheckBankCard3EVerification请求参数结构体 */ export interface CheckBankCard3EVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 银行卡号 */ BankCard: string; /** * 姓名 */ Name: string; /** * 身份证件号码 */ IdCardNumber: string; /** * 身份证件类型; ID_CARD */ IdCardType?: string; } /** * CheckBankCardVerification请求参数结构体 */ export interface CheckBankCardVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 银行卡号 */ BankCard: string; /** * 姓名 */ Name: string; /** * 身份证件号码 */ IdCardNumber?: string; /** * 手机号 */ Mobile?: string; /** * 身份证件类型; ID_CARD */ IdCardType?: string; } /** * RejectFlow请求参数结构体 */ export interface RejectFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程编号 */ FlowId: string; /** * 意愿确认票据。 1. VerifyChannel 为 WEIXINAPP,使用响应的VerifyResult; 2. VerifyChannel 为 FACEID时,使用OrderNo; 3. VerifyChannel 为 VERIFYCODE,使用短信验证码 4. VerifyChannel 为 NONE,传空值 (注:普通情况下,VerifyResult不能为None,如您不希望腾讯电子签对用户签署意愿做校验,请提前与客户经理或邮件至e-contract@tencent.com与我们联系) */ VerifyResult: string; /** * 意愿确认渠道: 1. WEIXINAPP - 微信小程序 2. FACEID - 慧眼 (默认) 3. VERIFYCODE - 验证码 4. THIRD - 第三方 (暂不支持) 5. NONE - 无需电子签系统验证 (注:普通情况下,VerifyChannel不能为None,如您不希望腾讯电子签对用户签署意愿做校验,请提前与客户经理或邮件至e-contract@tencent.com与我们联系) */ VerifyChannel: string; /** * 客户端来源IP */ SourceIp: string; /** * 拒签原因 */ RejectMessage?: string; /** * 签署参与者编号 */ SignId?: string; } /** * DescribeSubOrganizations请求参数结构体 */ export interface DescribeSubOrganizationsRequest { /** * 调用方信息 */ Caller: Caller; /** * 子机构ID数组 */ SubOrganizationIds: Array<string>; } /** * 此结构体 (SignSeal) 用于描述签名/印章信息。 */ export interface SignSeal { /** * 签署控件ID */ ComponentId: string; /** * 签署印章类型: SIGN_SIGNATURE - 签名 SIGN_SEAL - 印章 SIGN_DATE - 日期 SIGN_IMAGE - 图片 */ SignType: string; /** * 合同文件ID */ FileIndex: number; /** * 印章ID,仅当 SignType 为 SIGN_SEAL 时必填 */ SealId?: string; /** * 签名内容,仅当 SignType 为SIGN_SIGNATURE或SIGN_IMAGE 时必填,base64编码 */ SealContent?: string; } /** * DescribeCatalogSignComponents请求参数结构体 */ export interface DescribeCatalogSignComponentsRequest { /** * 调用方信息 */ Caller: Caller; /** * 目录ID */ CatalogId: string; } /** * ModifyOrganizationDefaultSeal返回参数结构体 */ export interface ModifyOrganizationDefaultSealResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateFlowByFiles返回参数结构体 */ export interface CreateFlowByFilesResponse { /** * 流程ID */ FlowId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyUserDefaultSeal返回参数结构体 */ export interface ModifyUserDefaultSealResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UploadFiles返回参数结构体 */ export interface UploadFilesResponse { /** * 文件id数组 */ FileIds: Array<string>; /** * 上传成功文件数量 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckBankCard3EVerification返回参数结构体 */ export interface CheckBankCard3EVerificationResponse { /** * 检测结果 计费结果码: 0: 认证通过 1: 认证未通过 2: 持卡人信息有误 3: 未开通无卡支付 4: 此卡被没收 5: 无效卡号 6: 此卡无对应发卡行 7: 该卡未初始化或睡眠卡 8: 作弊卡、吞卡 9: 此卡已挂失 10: 该卡已过期 11: 受限制的卡 12: 密码错误次数超限 13: 发卡行不支持此交易 不收费结果码: 101: 姓名校验不通过 102: 银行卡号码有误 103: 验证中心服务繁忙 104: 身份证号码有误 105: 手机号码不合法 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SignFlow请求参数结构体 */ export interface SignFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程编号 */ FlowId: string; /** * 意愿确认票据。 1. VerifyChannel 为 WEIXINAPP,使用响应的VerifyResult; 2. VerifyChannel 为 FACEID时,使用OrderNo; 3. VerifyChannel 为 VERIFYCODE,使用短信验证码 4. VerifyChannel 为 NONE,传空值 (注:普通情况下,VerifyResult不能为None,如您不希望腾讯电子签对用户签署意愿做校验,请提前与客户经理或邮件至e-contract@tencent.com与我们联系) */ VerifyResult: string; /** * 意愿确认渠道: 1. WEIXINAPP - 微信小程序 2. FACEID - 慧眼 (默认) 3. VERIFYCODE - 验证码 4. THIRD - 第三方 (暂不支持) 5. NONE - 无需电子签系统验证 (注:普通情况下,VerifyChannel不能为None,如您不希望腾讯电子签对用户签署意愿做校验,请提前与客户经理或邮件至e-contract@tencent.com与我们联系) */ VerifyChannel: string; /** * 客户端来源IP */ SourceIp: string; /** * 签署内容 */ SignSeals: Array<SignSeal>; /** * 签署备注 */ ApproveMessage?: string; /** * 签署参与者编号 */ SignId?: string; } /** * 自定义流程id映射关系 */ export interface CustomFlowIdMap { /** * 自定义id */ CustomId: string; /** * 流程id */ FlowId: string; } /** * DescribeCustomFlowIdsByFlowId请求参数结构体 */ export interface DescribeCustomFlowIdsByFlowIdRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程 id 列表,最多同时查询 10 个流程 id */ FlowIds: Array<string>; } /** * 此结构体 (UploadFile) 用于描述多文件上传的文件信息。 */ export interface UploadFile { /** * Base64编码后的文件内容 */ FileBody: string; /** * 文件名 */ FileName?: string; } /** * DescribeUsers返回参数结构体 */ export interface DescribeUsersResponse { /** * 用户信息查询结果 */ Users: Array<UserDescribe>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateH5FaceIdUrl请求参数结构体 */ export interface CreateH5FaceIdUrlRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 慧眼业务ID; 不填写时后台使用Caller反查 */ WbAppId?: string; /** * 姓名; 可选(未通过实名认证的用户必选) */ Name?: string; /** * 用户证件类型; 可选; 默认ID_CARD:中国居民身份证 */ IdCardType?: string; /** * 用户证件号; 可选(未通过实名认证的用户必选) */ IdCardNumber?: string; /** * H5人脸核身完成后回调的第三方Url; 可选; 不需要做Encode, 跳转的参数: ?code=XX&orderNo=XX&liveRate=xx, code=0表示成功,orderNo为订单号,liveRate为百分制活体检测得分 */ JumpUrl?: string; /** * 参数值为"1":直接跳转到url回调地址; 可选; 其他值:跳转提供的结果页面 */ JumpType?: string; /** * browser:表示在浏览器启动刷脸, app:表示在App里启动刷脸,默认值为browser; 可选 */ OpenFrom?: string; /** * 跳转类型; 可选; 参数值为"1"时,刷脸页面使用replace方式跳转,不在浏览器history中留下记录;不传或其他值则正常跳转 */ RedirectType?: string; } /** * CheckMobileVerification返回参数结构体 */ export interface CheckMobileVerificationResponse { /** * 检测结果 计费结果码: 0: 验证结果一致 1: 手机号未实名 2: 姓名和手机号不一致 3: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致) 不收费结果码: 101: 查无记录 102: 非法姓名(长度,格式等不正确) 103: 非法手机号(长度,格式等不正确) 104: 非法身份证号(长度,校验位等不正确) 105: 认证未通过 106: 验证平台异常 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFlowFiles返回参数结构体 */ export interface DescribeFlowFilesResponse { /** * 流程编号 */ FlowId?: string; /** * 流程文件列表 */ FlowFileInfos?: Array<FlowFileInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateUser请求参数结构体 */ export interface CreateUserRequest { /** * 调用方信息 */ Caller: Caller; /** * 第三方平台唯一标识;要求应用内OpenId唯一; len<=32 */ OpenId: string; /** * 用户姓名 */ Name: string; /** * 用户证件类型: 1. ID_CARD - 居民身份证 2. PASSPORT - 护照 3. MAINLAND_TRAVEL_PERMIT_FOR_HONGKONG_AND_MACAO_RESIDENTS - 港澳居民来往内地通行证 4. MAINLAND_TRAVEL_PERMIT_FOR_TAIWAN_RESIDENTS - 台湾居民来往大陆通行证 5. HOUSEHOLD_REGISTER - 户口本 6. TEMP_ID_CARD - 临时居民身份证 */ IdCardType: string; /** * 用户证件号 */ IdCardNumber: string; /** * 是否以OpenId作为UserId (为true时将直接以OpenId生成腾讯电子签平台的UserId) */ UseOpenId?: boolean; /** * 用户邮箱,不要求唯一 */ Email?: string; /** * 用户手机号码,不要求唯一 */ Mobile?: string; } /** * CreatePreviewSignUrl请求参数结构体 */ export interface CreatePreviewSignUrlRequest { /** * 调用方信息 */ Caller: Caller; /** * URL过期时间戳 */ Deadline: number; /** * 目录ID。当 SignUrlType 为 CATALOG 时必填 */ CatalogId?: string; /** * 流程ID。当 SignUrlType 为 FLOW 时必填 */ FlowId?: string; /** * 签署链接类型: 1. FLOW - 单流程签署 (默认) 2. CATALOG - 目录签署 */ SignUrlType?: string; } /** * CreateUserAndSeal请求参数结构体 */ export interface CreateUserAndSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 第三方平台唯一标识,要求应用内OpenId唯一 */ OpenId: string; /** * 用户姓名 */ Name: string; /** * 用户证件类型: 1. ID_CARD - 居民身份证 5. HOUSEHOLD_REGISTER - 户口本 6. TEMP_ID_CARD - 临时居民身份证 */ IdCardType: string; /** * 用户证件号 */ IdCardNumber: string; /** * 请求生成个人印章的客户端IP */ SourceIp: string; /** * 用户手机号码,不要求唯一 */ Mobile?: string; /** * 用户邮箱,不要求唯一 */ Email?: string; /** * 默认印章名称 */ SealName?: string; /** * 是否以OpenId作为UserId (为true时将直接以OpenId生成腾讯电子签平台的UserId) */ UseOpenId?: boolean; } /** * CreatePreviewSignUrl返回参数结构体 */ export interface CreatePreviewSignUrlResponse { /** * 合同预览URL */ PreviewSignUrl: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateFaceIdSign请求参数结构体 */ export interface CreateFaceIdSignRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 除api_ticket之外的其它要参与签名的参数值,包括UserId */ Values: Array<string>; } /** * DescribeCustomFlowIdsByFlowId返回参数结构体 */ export interface DescribeCustomFlowIdsByFlowIdResponse { /** * 自定义流程 id 映射列表 */ CustomIdList: Array<CustomFlowIdMap>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SignFlow返回参数结构体 */ export interface SignFlowResponse { /** * 签署任务状态。签署成功 - SUCCESS、提交审核 - REVIEW */ Status: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * RejectFlow返回参数结构体 */ export interface RejectFlowResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeFlow请求参数结构体 */ export interface DescribeFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 需要查询的流程ID */ FlowId: string; } /** * DescribeFileIdsByCustomIds请求参数结构体 */ export interface DescribeFileIdsByCustomIdsRequest { /** * 调用方信息, OrganizationId必填 */ Caller: Caller; /** * 用户自定义ID */ CustomIds?: Array<string>; } /** * CreateSeal返回参数结构体 */ export interface CreateSealResponse { /** * 电子印章Id */ SealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GenerateOrganizationSeal返回参数结构体 */ export interface GenerateOrganizationSealResponse { /** * 电子印章Id */ SealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeSubOrganizations返回参数结构体 */ export interface DescribeSubOrganizationsResponse { /** * 子机构信息列表 */ SubOrganizationInfos: Array<SubOrganizationDetail>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DestroyFlowFile请求参数结构体 */ export interface DestroyFlowFileRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程ID */ FlowId: string; } /** * CheckFaceIdentify返回参数结构体 */ export interface CheckFaceIdentifyResponse { /** * 核身结果; 0:通过,1:不通过 */ Result?: number; /** * 核身结果描述 */ Description?: string; /** * 渠道名 */ ChannelName?: string; /** * 认证通过时间 注意:此字段可能返回 null,表示取不到有效值。 */ VerifiedOn?: number; /** * 核身流水号 */ SerialNumber?: string; /** * 渠道核身服务器IP 注意:此字段可能返回 null,表示取不到有效值。 */ VerifyServerIp?: string; /** * 核身照片文件名 注意:此字段可能返回 null,表示取不到有效值。 */ PhotoFileName?: string; /** * 核身照片内容base64(文件格式见文件名后缀,一般为jpg) 注意:此字段可能返回 null,表示取不到有效值。 */ PhotoFileData?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 此结构体 (Seal) 用于描述电子印章的信息。 */ export interface Seal { /** * 电子印章ID */ SealId: string; /** * 电子印章名称 */ SealName: string; /** * 电子印章类型 */ SealType: string; /** * 电子印章来源: CREATE - 通过图片上传 GENERATE - 通过文字生成 */ SealSource: string; /** * 电子印章创建者 */ Creator: Caller; /** * 电子印章创建时间戳 */ CreatedOn: number; /** * 电子印章所有人 */ UserId: string; /** * 电子印章URL */ FileUrl: FileUrl; /** * 是否为默认印章,false-非默认,true-默认 */ DefaultSeal: boolean; } /** * SendFlowUrl请求参数结构体 */ export interface SendFlowUrlRequest { /** * 调用方信息 */ Caller: Caller; /** * 需要推送合同的流程ID */ FlowId: string; /** * 签署人ID */ UserId: string; /** * 签署控件信息 (支持添加多个控件) */ SignComponents: Array<Component>; /** * 签署人手机号 (如果选择短信验证码签署,则此字段必填) */ Mobile?: string; /** * 签署人对应的子机构ID,个人签署者此字段不填 */ SubOrganizationId?: string; /** * 签名后校验方式: 1. WEIXINAPP - 微信小程序; 2. FACEID - 慧眼 (默认) ; 3. VERIFYCODE - 验证码; 4. NONE - 无。此选项为白名单参数,暂不支持公开调用。如需开通权限,请通过客户经理或邮件至e-contract@tencent.com与我们联系; 5. THIRD - 第三方 (暂不支持) 6. OFFLINE - 线下人工审核 */ VerifyChannel?: Array<string>; /** * 签署链接失效截止时间,默认为7天 */ Deadline?: number; /** * 是否为最后一个签署人。若为最后一人,本次签署完成以后自动归档 */ IsLastApprover?: boolean; /** * 签署完成后,前端跳转的url */ JumpUrl?: string; /** * 短信模板 默认使用腾讯电子签官方短信模板,如有自定义需求,请通过客户经理或邮件至e-contract@tencent.com与我们联系。 */ SmsTemplate?: SmsTemplate; /** * 签署前置条件:是否要全文阅读,默认否 */ IsFullText?: boolean; /** * 签署前置条件:强制用户阅读待签署文件时长,默认不限制 */ PreReadTime?: number; /** * 当前参与者是否支持线下核身,默认为不支持 */ CanOffLine?: boolean; /** * 签署任务的回调地址 */ CallbackUrl?: string; } /** * CancelFlow请求参数结构体 */ export interface CancelFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程ID */ FlowId: string; /** * 撤销原因 */ CancelMessage?: string; } /** * CreateH5FaceIdUrl返回参数结构体 */ export interface CreateH5FaceIdUrlResponse { /** * 跳转到人脸核身页面的链接 */ Url?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCustomFlowIds请求参数结构体 */ export interface DescribeCustomFlowIdsRequest { /** * 调用方信息 */ Caller: Caller; /** * 自定义 id 列表,最多同时查询 10 个自定义 id */ CustomIds: Array<string>; } /** * DescribeFlowApprovers请求参数结构体 */ export interface DescribeFlowApproversRequest { /** * 调用方信息 */ Caller: Caller; /** * 需要查询的流程ID */ FlowId: string; /** * 需要查询的用户ID,为空则默认查询所有用户信息 */ UserId?: string; /** * 需要查询的签署ID,为空则不按签署ID过滤 */ SignId?: string; } /** * DescribeFaceIdResults返回参数结构体 */ export interface DescribeFaceIdResultsResponse { /** * 核身结果列表 */ Results?: Array<FaceIdResult>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CheckBankCard4EVerification请求参数结构体 */ export interface CheckBankCard4EVerificationRequest { /** * 调用方信息; 必选 */ Caller: Caller; /** * 银行卡号 */ BankCard: string; /** * 姓名 */ Name: string; /** * 身份证件号码 */ IdCardNumber?: string; /** * 手机号 */ Mobile?: string; /** * 身份证件类型; ID_CARD */ IdCardType?: string; } /** * GenerateUserSeal返回参数结构体 */ export interface GenerateUserSealResponse { /** * 电子印章Id */ SealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCatalogSignComponents返回参数结构体 */ export interface DescribeCatalogSignComponentsResponse { /** * 签署区列表 */ SignComponents: Array<CatalogComponents>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GenerateOrganizationSeal请求参数结构体 */ export interface GenerateOrganizationSealRequest { /** * 调用方信息 */ Caller: Caller; /** * 印章类型: OFFICIAL-公章 SPECIAL_FINANCIAL-财务专用章 CONTRACT-合同专用章 LEGAL_REPRESENTATIVE-法定代表人章 SPECIAL_NATIONWIDE_INVOICE-发票专用章 OTHER-其他 */ SealType: string; /** * 请求生成企业印章的客户端Ip */ SourceIp: string; /** * 电子印章名称 */ SealName?: string; /** * 企业印章横向文字,最多可填8个汉字(可不填,默认为"电子签名专用章") */ SealHorizontalText?: string; /** * 是否是默认印章 true:是,false:否 */ IsDefault?: boolean; } /** * CreateServerFlowSign请求参数结构体 */ export interface CreateServerFlowSignRequest { /** * 调用方信息 */ Caller: Caller; /** * 流程ID */ FlowId: string; /** * 签署区域信息 */ SignComponents: Array<Component>; /** * 客户端IP */ SourceIp: string; } /** * 此结构体 (Caller) 用于描述调用方属性。 */ export interface Caller { /** * 应用号 */ ApplicationId: string; /** * 下属机构ID */ SubOrganizationId?: string; /** * 经办人的用户ID */ OperatorId?: string; } /** * VerifyUser返回参数结构体 */ export interface VerifyUserResponse { /** * 电子签平台用户ID */ UserId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendFlow请求参数结构体 */ export interface SendFlowRequest { /** * 调用方信息 */ Caller: Caller; /** * 需要推送合同的流程ID */ FlowId: string; /** * 签署人用户ID */ UserId: string; /** * 签署控件信息 (支持添加多个控件) */ SignComponents: Array<Component>; /** * 签署人手机号 (如果选择短信验证码签署,则此字段必填) */ Mobile?: string; /** * 签署人对应的子机构ID,个人签署者此字段不填 */ SubOrganizationId?: string; /** * 签名后校验方式: 1. WEIXINAPP - 微信小程序; 2. FACEID - 慧眼 (默认) ; 3. VERIFYCODE - 验证码; 4. NONE - 无。此选项为白名单参数,暂不支持公开调用。如需开通权限,请通过客户经理或邮件至e-contract@tencent.com与我们联系; 5. THIRD - 第三方 (暂不支持) */ VerifyChannel?: Array<string>; /** * 签署链接失效截止时间,默认为7天 */ Deadline?: number; /** * 是否为最后一个签署人。若为最后一人,本次签署完成以后自动归档。 */ IsLastApprover?: boolean; /** * 签署完成后,前端跳转的URL */ JumpUrl?: string; /** * 短信模板。默认使用腾讯电子签官方短信模板,如有自定义需求,请通过客户经理或邮件至e-contract@tencent.com与我们联系。 */ SmsTemplate?: SmsTemplate; /** * 签署前置条件:是否要全文阅读,默认否 */ IsFullText?: boolean; /** * 签署前置条件:强制用户阅读待签署文件时长,默认不限制 */ PreReadTime?: number; /** * 当前参与者是否支持线下核身,默认为不支持 */ CanOffLine?: boolean; /** * 签署任务的回调地址 */ CallbackUrl?: string; } /** * SendSignInnerVerifyCode请求参数结构体 */ export interface SendSignInnerVerifyCodeRequest { /** * 调用方信息 */ Caller: Caller; /** * 手机号 */ Mobile: string; /** * 验证码类型,取值(SIGN) */ VerifyType: string; /** * 用户 id */ UserId?: string; /** * 模板 id */ VerifyTemplateId?: string; /** * 签名 */ VerifySign?: string; /** * 流程(目录) id */ FlowId?: string; /** * 三要素检测结果 */ CheckThreeElementResult?: number; } /** * DestroyFlowFile返回参数结构体 */ export interface DestroyFlowFileResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateSubOrganization返回参数结构体 */ export interface CreateSubOrganizationResponse { /** * 子机构ID */ SubOrganizationId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateSubOrganizationAndSeal返回参数结构体 */ export interface CreateSubOrganizationAndSealResponse { /** * 子机构在电子文件签署平台唯一标识 */ SubOrganizationId: string; /** * 电子印章ID */ SealId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyUser请求参数结构体 */ export interface ModifyUserRequest { /** * 调用方信息 */ Caller: Caller; /** * 第三方平台用户唯一标识; OpenId 和 UserId 二选一填写, 两个都不为空则优先使用UserId */ OpenId?: string; /** * 腾讯电子签平台用户唯一标识; OpenId 和 UserId 二选一填写, 两个都不为空则优先使用UserId */ UserId?: string; /** * 用户手机号码,不要求唯一 */ Mobile?: string; /** * 用户邮箱,不要求唯一 */ Email?: string; /** * 用户姓名 */ Name?: string; } /** * CheckMobileAndName返回参数结构体 */ export interface CheckMobileAndNameResponse { /** * 检测结果 计费结果码: 0: 验证结果一致 1: 手机号未实名 2: 姓名和手机号不一致 3: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致) 不收费结果码: 101: 查无记录 102: 非法姓名(长度,格式等不正确) 103: 非法手机号(长度,格式等不正确) 104: 非法身份证号(长度,校验位等不正确) 105: 认证未通过 106: 验证平台异常 */ Result?: number; /** * 结果描述; 未通过时必选 */ Description?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifySeal返回参数结构体 */ export interface ModifySealResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; }
the_stack
import BitArray from '../../common/BitArray'; import IllegalArgumentException from '../../IllegalArgumentException'; import StringUtils from '../../common/StringUtils'; import BitMatrix from '../../common/BitMatrix'; import AztecCode from './AztecCode'; import ReedSolomonEncoder from '../../common/reedsolomon/ReedSolomonEncoder'; import GenericGF from '../../common/reedsolomon/GenericGF'; import HighLevelEncoder from './HighLevelEncoder'; import { int } from '../../../customTypings'; import Integer from '../../util/Integer'; /* * Copyright 2013 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // package com.google.zxing.aztec.encoder; // import com.google.zxing.common.BitArray; // import com.google.zxing.common.BitMatrix; // import com.google.zxing.common.reedsolomon.GenericGF; // import com.google.zxing.common.reedsolomon.ReedSolomonEncoder; /** * Generates Aztec 2D barcodes. * * @author Rustam Abdullaev */ export default /*public final*/ class Encoder { public static /*final*/ DEFAULT_EC_PERCENT: int = 33; // default minimal percentage of error check words public static /*final*/ DEFAULT_AZTEC_LAYERS: int = 0; private static /*final*/ MAX_NB_BITS: int = 32; private static /*final*/ MAX_NB_BITS_COMPACT: int = 4; private static /*final*/ WORD_SIZE: Int32Array = Int32Array.from([ 4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 ]); private constructor() { } /** * Encodes the given binary content as an Aztec symbol * * @param data input data string * @return Aztec symbol matrix with metadata */ public static encodeBytes(data: Uint8Array): AztecCode { return Encoder.encode(data, Encoder.DEFAULT_EC_PERCENT, Encoder.DEFAULT_AZTEC_LAYERS); } /** * Encodes the given binary content as an Aztec symbol * * @param data input data string * @param minECCPercent minimal percentage of error check words (According to ISO/IEC 24778:2008, * a minimum of 23% + 3 words is recommended) * @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers * @return Aztec symbol matrix with metadata */ public static encode(data: Uint8Array, minECCPercent: int, userSpecifiedLayers: int): AztecCode { // High-level encode let bits: BitArray = new HighLevelEncoder(data).encode(); // stuff bits and choose symbol size let eccBits: int = Integer.truncDivision((bits.getSize() * minECCPercent), 100) + 11; let totalSizeBits: int = bits.getSize() + eccBits; let compact: boolean; let layers: int; let totalBitsInLayer: int; let wordSize: int; let stuffedBits: BitArray; if (userSpecifiedLayers !== Encoder.DEFAULT_AZTEC_LAYERS) { compact = userSpecifiedLayers < 0; layers = Math.abs(userSpecifiedLayers); if (layers > (compact ? Encoder.MAX_NB_BITS_COMPACT : Encoder.MAX_NB_BITS)) { throw new IllegalArgumentException( StringUtils.format('Illegal value %s for layers', userSpecifiedLayers)); } totalBitsInLayer = Encoder.totalBitsInLayer(layers, compact); wordSize = Encoder.WORD_SIZE[layers]; let usableBitsInLayers: int = totalBitsInLayer - (totalBitsInLayer % wordSize); stuffedBits = Encoder.stuffBits(bits, wordSize); if (stuffedBits.getSize() + eccBits > usableBitsInLayers) { throw new IllegalArgumentException('Data to large for user specified layer'); } if (compact && stuffedBits.getSize() > wordSize * 64) { // Compact format only allows 64 data words, though C4 can hold more words than that throw new IllegalArgumentException('Data to large for user specified layer'); } } else { wordSize = 0; stuffedBits = null; // We look at the possible table sizes in the order Compact1, Compact2, Compact3, // Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1) // is the same size, but has more data. for (let i /*int*/ = 0; ; i++) { if (i > Encoder.MAX_NB_BITS) { throw new IllegalArgumentException('Data too large for an Aztec code'); } compact = i <= 3; layers = compact ? i + 1 : i; totalBitsInLayer = Encoder.totalBitsInLayer(layers, compact); if (totalSizeBits > totalBitsInLayer) { continue; } // [Re]stuff the bits if this is the first opportunity, or if the // wordSize has changed if (stuffedBits == null || wordSize !== Encoder.WORD_SIZE[layers]) { wordSize = Encoder.WORD_SIZE[layers]; stuffedBits = Encoder.stuffBits(bits, wordSize); } let usableBitsInLayers: int = totalBitsInLayer - (totalBitsInLayer % wordSize); if (compact && stuffedBits.getSize() > wordSize * 64) { // Compact format only allows 64 data words, though C4 can hold more words than that continue; } if (stuffedBits.getSize() + eccBits <= usableBitsInLayers) { break; } } } let messageBits: BitArray = Encoder.generateCheckWords(stuffedBits, totalBitsInLayer, wordSize); // generate mode message let messageSizeInWords: int = stuffedBits.getSize() / wordSize; let modeMessage: BitArray = Encoder.generateModeMessage(compact, layers, messageSizeInWords); // allocate symbol let baseMatrixSize: int = (compact ? 11 : 14) + layers * 4; // not including alignment lines let alignmentMap: Int32Array = new Int32Array(baseMatrixSize); let matrixSize: int; if (compact) { // no alignment marks in compact mode, alignmentMap is a no-op matrixSize = baseMatrixSize; for (let i /*int*/ = 0; i < alignmentMap.length; i++) { alignmentMap[i] = i; } } else { matrixSize = baseMatrixSize + 1 + 2 * Integer.truncDivision((Integer.truncDivision(baseMatrixSize, 2) - 1), 15); let origCenter: int = Integer.truncDivision(baseMatrixSize, 2); let center: int = Integer.truncDivision(matrixSize, 2); for (let i /*int*/ = 0; i < origCenter; i++) { let newOffset: int = i + Integer.truncDivision(i, 15); alignmentMap[origCenter - i - 1] = center - newOffset - 1; alignmentMap[origCenter + i] = center + newOffset + 1; } } let matrix: BitMatrix = new BitMatrix(matrixSize); // draw data bits for (let i /*int*/ = 0, rowOffset = 0; i < layers; i++) { let rowSize: int = (layers - i) * 4 + (compact ? 9 : 12); for (let j /*int*/ = 0; j < rowSize; j++) { let columnOffset: int = j * 2; for (let k /*int*/ = 0; k < 2; k++) { if (messageBits.get(rowOffset + columnOffset + k)) { matrix.set(alignmentMap[i * 2 + k], alignmentMap[i * 2 + j]); } if (messageBits.get(rowOffset + rowSize * 2 + columnOffset + k)) { matrix.set(alignmentMap[i * 2 + j], alignmentMap[baseMatrixSize - 1 - i * 2 - k]); } if (messageBits.get(rowOffset + rowSize * 4 + columnOffset + k)) { matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - k], alignmentMap[baseMatrixSize - 1 - i * 2 - j]); } if (messageBits.get(rowOffset + rowSize * 6 + columnOffset + k)) { matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - j], alignmentMap[i * 2 + k]); } } } rowOffset += rowSize * 8; } // draw mode message Encoder.drawModeMessage(matrix, compact, matrixSize, modeMessage); // draw alignment marks if (compact) { Encoder.drawBullsEye(matrix, Integer.truncDivision(matrixSize, 2), 5); } else { Encoder.drawBullsEye(matrix, Integer.truncDivision(matrixSize, 2), 7); for (let i /*int*/ = 0, j = 0; i < Integer.truncDivision(baseMatrixSize, 2) - 1; i += 15, j += 16) { for (let k /*int*/ = Integer.truncDivision(matrixSize, 2) & 1; k < matrixSize; k += 2) { matrix.set(Integer.truncDivision(matrixSize, 2) - j, k); matrix.set(Integer.truncDivision(matrixSize, 2) + j, k); matrix.set(k, Integer.truncDivision(matrixSize, 2) - j); matrix.set(k, Integer.truncDivision(matrixSize, 2) + j); } } } let aztec: AztecCode = new AztecCode(); aztec.setCompact(compact); aztec.setSize(matrixSize); aztec.setLayers(layers); aztec.setCodeWords(messageSizeInWords); aztec.setMatrix(matrix); return aztec; } private static drawBullsEye(matrix: BitMatrix, center: int, size: int): void { for (let i /*int*/ = 0; i < size; i += 2) { for (let j /*int*/ = center - i; j <= center + i; j++) { matrix.set(j, center - i); matrix.set(j, center + i); matrix.set(center - i, j); matrix.set(center + i, j); } } matrix.set(center - size, center - size); matrix.set(center - size + 1, center - size); matrix.set(center - size, center - size + 1); matrix.set(center + size, center - size); matrix.set(center + size, center - size + 1); matrix.set(center + size, center + size - 1); } static generateModeMessage(compact: boolean, layers: int, messageSizeInWords: int): BitArray { let modeMessage: BitArray = new BitArray(); if (compact) { modeMessage.appendBits(layers - 1, 2); modeMessage.appendBits(messageSizeInWords - 1, 6); modeMessage = Encoder.generateCheckWords(modeMessage, 28, 4); } else { modeMessage.appendBits(layers - 1, 5); modeMessage.appendBits(messageSizeInWords - 1, 11); modeMessage = Encoder.generateCheckWords(modeMessage, 40, 4); } return modeMessage; } private static drawModeMessage(matrix: BitMatrix, compact: boolean, matrixSize: int, modeMessage: BitArray): void { let center: int = Integer.truncDivision(matrixSize, 2); if (compact) { for (let i /*int*/ = 0; i < 7; i++) { let offset: int = center - 3 + i; if (modeMessage.get(i)) { matrix.set(offset, center - 5); } if (modeMessage.get(i + 7)) { matrix.set(center + 5, offset); } if (modeMessage.get(20 - i)) { matrix.set(offset, center + 5); } if (modeMessage.get(27 - i)) { matrix.set(center - 5, offset); } } } else { for (let i /*int*/ = 0; i < 10; i++) { let offset: int = center - 5 + i + Integer.truncDivision(i, 5); if (modeMessage.get(i)) { matrix.set(offset, center - 7); } if (modeMessage.get(i + 10)) { matrix.set(center + 7, offset); } if (modeMessage.get(29 - i)) { matrix.set(offset, center + 7); } if (modeMessage.get(39 - i)) { matrix.set(center - 7, offset); } } } } private static generateCheckWords(bitArray: BitArray, totalBits: int, wordSize: int): BitArray { // bitArray is guaranteed to be a multiple of the wordSize, so no padding needed let messageSizeInWords: int = bitArray.getSize() / wordSize; let rs: ReedSolomonEncoder = new ReedSolomonEncoder(Encoder.getGF(wordSize)); let totalWords: int = Integer.truncDivision(totalBits, wordSize); let messageWords: Int32Array = Encoder.bitsToWords(bitArray, wordSize, totalWords); rs.encode(messageWords, totalWords - messageSizeInWords); let startPad: int = totalBits % wordSize; let messageBits: BitArray = new BitArray(); messageBits.appendBits(0, startPad); for (const messageWord/*: int*/ of Array.from(messageWords)) { messageBits.appendBits(messageWord, wordSize); } return messageBits; } private static bitsToWords(stuffedBits: BitArray, wordSize: int, totalWords: int): Int32Array { let message: Int32Array = new Int32Array(totalWords); let i: int; let n: int; for (i = 0, n = stuffedBits.getSize() / wordSize; i < n; i++) { let value: int = 0; for (let j /*int*/ = 0; j < wordSize; j++) { value |= stuffedBits.get(i * wordSize + j) ? (1 << wordSize - j - 1) : 0; } message[i] = value; } return message; } private static getGF(wordSize: int): GenericGF { switch (wordSize) { case 4: return GenericGF.AZTEC_PARAM; case 6: return GenericGF.AZTEC_DATA_6; case 8: return GenericGF.AZTEC_DATA_8; case 10: return GenericGF.AZTEC_DATA_10; case 12: return GenericGF.AZTEC_DATA_12; default: throw new IllegalArgumentException('Unsupported word size ' + wordSize); } } static stuffBits(bits: BitArray, wordSize: int): BitArray { let out: BitArray = new BitArray(); let n: int = bits.getSize(); let mask: int = (1 << wordSize) - 2; for (let i /*int*/ = 0; i < n; i += wordSize) { let word: int = 0; for (let j /*int*/ = 0; j < wordSize; j++) { if (i + j >= n || bits.get(i + j)) { word |= 1 << (wordSize - 1 - j); } } if ((word & mask) === mask) { out.appendBits(word & mask, wordSize); i--; } else if ((word & mask) === 0) { out.appendBits(word | 1, wordSize); i--; } else { out.appendBits(word, wordSize); } } return out; } private static totalBitsInLayer(layers: int, compact: boolean): int { return ((compact ? 88 : 112) + 16 * layers) * layers; } }
the_stack
import { EventEmitter2 } from 'eventemitter2'; /** * Represents a generic callback which receives a single TreeNode argument. */ export interface NodeIteratee { (node: TreeNode): any; } /** * Represents a processor for nodes matched during search. */ export interface MatchProcessor { (matches: TreeNodes): any; } /** * Represents a search matcher which is given resolve/reject callbacks. */ export interface SearchMatcher { (query: string, resolve: any, reject: any): any; } // Copied from EventEmitter2 to avoid imports, see below type eventNS = string[]; interface Listener { (...values: any[]): void; } interface EventAndListener { (event: string | string[], ...values: any[]): void; } /** * Represents a tree configuration object, of which only "data" is required. */ export interface Config { allowLoadEvents?: Array<string>; contextMenu?: boolean; data?(node: TreeNode, resolve: (nodes: Array<NodeConfig>) => any, reject: (err: Error) => any): any|Array<NodeConfig>|Promise<Array<NodeConfig>>; deferredLoading?: boolean; editable?: boolean; editing?: { add?: boolean; edit?: boolean; remove?: boolean; }; nodes?: { resetStateOnRestore?: boolean; }; pagination?: { limit?: number; }; renderer?: any; search?: { matcher: SearchMatcher; matchProcess: MatchProcessor; }; selection?: { allow?: NodeIteratee; autoDeselect?: boolean; autoSelectChildren?: boolean; disableDirectDeselection?: boolean; mode?: string; multiple?: boolean; require?: boolean; }; sort?: string; multiselect?: boolean; } export interface NodeConfig { children?: Array<NodeConfig>|true, id?: string, text: string, itree?: { a?: { attributes?: any }, icon?: string, li?: { attributes?: any }, state?: { checked?: boolean, collapsed?: boolean, draggable?: boolean, 'drop-target'?: boolean, editable?: boolean, focused?: boolean, hidden?: boolean, indeterminate?: boolean, loading?: boolean, matched?: boolean, removed?: boolean, rendered?: boolean, selectable?: boolean, selected?: boolean, } } } /** * Represents a TreeNodes pagination configuration object. */ export interface Pagination { limit: number; total: number; } export interface TreeEvents { /** @event changes.applied (InspireTree | TreeNode context) - Indicates batched changes are complete for the context. */ 'changes.applied'?: (context: InspireTree | TreeNode) => void; /** @event children.loaded (TreeNode node) - Children were dynamically loaded for a node. */ 'children.loaded'?: (node: TreeNode) => void; /** @event data.loaded (Array nodes) - Data has been loaded successfully (only for data loaded via xhr/callbacks). */ 'data.loaded'?: (nodes: any[]) => void; /** @event data.loaderror (Error err) - Loading failed. */ 'data.loaderror'?: (err: Error) => void; /** @event model.loaded (Array nodes) - Data has been parsed into an internal model. */ 'model.loaded'?: (node: TreeNode) => void; /** @event node.added (TreeNode node) - Node added. */ 'node.added'?: (node: TreeNode) => void; /** @event node.click (TreeNode node) - Node os clicked. */ 'node.click'?: (node: TreeNode) => void; /** @event node.blurred (TreeNode node, bool isLoadEvent) - Node lost focus. */ 'node.blurred'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.checked (TreeNode node, bool isLoadEvent) - Node checked. */ 'node.checked'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.collapsed (TreeNode node) - Node collapsed. */ 'node.collapsed'?: (node: TreeNode) => void; /** @event node.deselected (TreeNode node) - Node deselected. */ 'node.deselected'?: (node: TreeNode) => void; /** @event node.edited (TreeNode node), (string oldValue), (string newValue) - Node text was altered via inline editing. */ 'node.edited'?: (node: TreeNode) => void; /** @event node.expanded (TreeNode node, bool isLoadEvent) - Node expanded. */ 'node.expanded'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.focused (TreeNode node, bool isLoadEvent) - Node focused. */ 'node.focused'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.hidden (TreeNode node, bool isLoadEvent) - Node hidden. */ 'node.hidden'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.moved (TreeNode node, TreeNodes source, int oldIndex, TreeNodes target, int newIndex) - Node moved. */ 'node.moved'?: (node: TreeNode) => void; /** @event node.paginated (TreeNode context), (Object pagination) (Event event) - Nodes were paginated. Context is undefined when for the root level. */ 'node.paginated'?: (node: TreeNode) => void; /** @event node.propertchanged - (TreeNode node), (String property), (Mixed oldValue), (Mixed) newValue) - A node's root property has changed. */ 'node.property.changed'?: (node: TreeNode) => void; /** @event node.removed (object node) - Node removed. */ 'node.removed'?: (node: TreeNode) => void; /** @event node.restored (TreeNode node) - Node restored. */ 'node.restored'?: (node: TreeNode) => void; /** @event node.selected (TreeNode node, bool isLoadEvent) - Node selected. */ 'node.selected'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.statchanged - (TreeNode node), (String property), (Mixed oldValue), (Mixed) newValue) - A node state boolean has changed. */ 'node.state.changed'?: (node: TreeNode) => void; /** @event node.shown (TreeNode node) - Node shown. */ 'node.shown'?: (node: TreeNode) => void; /** @event node.softremoved (TreeNode node, bool isLoadEvent) - Node soft removed. */ 'node.softremoved'?: (node: TreeNode, isLoadEvent: boolean) => void; /** @event node.unchecked (TreeNode node) - Node unchecked. */ 'node.unchecked'?: (node: TreeNode) => void; } export interface InspireTree { emit<E extends keyof TreeEvents>(event: E | E[], ...values: any[]): boolean; emitAsync<E extends keyof TreeEvents>(event: E | E[], ...values: any[]): Promise<any[]>; addListener<E extends keyof TreeEvents>(event: E, listener: TreeEvents[E]): this; on<E extends keyof TreeEvents>(event: E, listener: TreeEvents[E]): this; prependListener<E extends keyof TreeEvents>(event: E | E[], listener: TreeEvents[E]): this; once<E extends keyof TreeEvents>(event: E, listener: TreeEvents[E]): this; prependOnceListener<E extends keyof TreeEvents>(event: E | E[], listener: TreeEvents[E]): this; many<E extends keyof TreeEvents>(event: E | E[], timesToListen: number, listener: TreeEvents[E]): this; prependMany<E extends keyof TreeEvents>(event: E | E[], timesToListen: number, listener: TreeEvents[E]): this; onAny(listener: EventAndListener): this; prependAny(listener: EventAndListener): this; offAny(listener: Listener): this; removeListener<E extends keyof TreeEvents>(event: E | E[], listener: TreeEvents[E]): this; off<E extends keyof TreeEvents>(event: E, listener: TreeEvents[E]): this; } export class InspireTree extends EventEmitter2 { addNode(node: NodeConfig): TreeNode; addNodes(node: Array<NodeConfig>): TreeNodes; available(): TreeNodes; blur(): TreeNodes; blurDeep(): TreeNodes; boundingNodes(): Array<TreeNode>; canAutoDeselect(): boolean; checked(): TreeNodes; clean(): TreeNodes; clearSearch(): InspireTree; clone(): TreeNodes; collapse(): TreeNodes; collapsed(full?: boolean): TreeNodes; collapseDeep(): TreeNodes; constructor(opts: Config); constructor(tree: InspireTree, array: Array<any>|TreeNodes); constructor(tree: InspireTree); context(): TreeNode; copy(dest: InspireTree, hierarchy?: boolean, includeState?: boolean): TreeNodes; createNode(obj: any): TreeNode; deepest(): TreeNodes; deselect(): TreeNodes; deselectDeep(): TreeNodes; disableDeselection(): InspireTree; each(iteratee: NodeIteratee): TreeNodes; editable(full?: boolean): TreeNodes; editing(full?: boolean): TreeNodes; enableDeselection(): InspireTree; expand(): Promise<TreeNodes>; expandDeep(): TreeNodes; expanded(full?: boolean): TreeNodes; expandParents(): TreeNodes; extract(predicate: string|NodeIteratee): TreeNodes; filterBy(predicate: string|NodeIteratee): TreeNodes; find(predicate: (node: TreeNode, index?: number, obj?: TreeNode[]) => boolean, thisArg?: any): TreeNode; first(predicate: (node: TreeNode) => boolean): TreeNode; flatten(predicate: string|NodeIteratee): TreeNodes; focused(full?: boolean): TreeNodes; get(index: number): TreeNode; hidden(full?: boolean): TreeNodes; hide(): TreeNodes; hideDeep(): TreeNodes; id: string | number; config: Config; preventDeselection: boolean; indeterminate(full?: boolean): TreeNodes; insertAt(index: number, object: any): TreeNode; invoke(methods: string|Array<string>): TreeNodes; invokeDeep(methods: string|Array<string>): TreeNodes; isEventMuted(eventName: string): boolean; static isTreeNode(object: any): boolean; static isTreeNodes(object: any): boolean; last(predicate: (node: TreeNode) => boolean): TreeNode; lastSelectedNode(): TreeNode; load(loader: Promise<TreeNodes>): Promise<TreeNodes>; loading(full?: boolean): TreeNodes; matched(full?: boolean): TreeNodes; move(index: number, newIndex: number, target: TreeNodes): TreeNode; mute(events: Array<string>): InspireTree; muted(): boolean; node(id: string|number): TreeNode; nodes(ids?: Array<string>|Array<number>): TreeNodes; pagination(): Pagination; recurseDown(iteratee: NodeIteratee): TreeNodes; reload(): Promise<TreeNodes>; removeAll(): InspireTree; removed(full?: boolean): TreeNodes; restore(): TreeNodes; restoreDeep(): TreeNodes; search(query: string|RegExp|NodeIteratee): Promise<TreeNodes>; select(): TreeNodes; selectable(full?: boolean): TreeNodes; selectBetween(start: TreeNode, end: TreeNode): InspireTree; selectDeep(): TreeNodes; selected(full?: boolean): TreeNodes; selectFirstAvailableNode(): TreeNode; show(): TreeNodes; showDeep(): TreeNodes; softRemove(): TreeNodes; sortBy(sorter: string|NodeIteratee): TreeNodes; state(key: string, val: boolean): TreeNodes; stateDeep(key: string, val: boolean): TreeNodes; swap(node1: TreeNode, node2: TreeNode): TreeNodes; toArray(): Array<any>; toArray(): Array<any>; tree(): InspireTree; unmute(events: Array<string>): InspireTree; visible(full?: boolean): TreeNodes; } export class TreeNodes extends Array<TreeNode> { addNode(node: NodeConfig): TreeNode; available(): TreeNodes; blur(): TreeNodes; blurDeep(): TreeNodes; checked(): TreeNodes; clean(): TreeNodes; clone(): TreeNodes; collapse(): TreeNodes; collapsed(full?: boolean): TreeNodes; collapseDeep(): TreeNodes; constructor(tree: InspireTree, array: Array<any>|TreeNodes); constructor(tree: InspireTree); context(): TreeNode; copy(dest: InspireTree, hierarchy?: boolean, includeState?: boolean): TreeNodes; deepest(): TreeNodes; deselect(): TreeNodes; deselectDeep(): TreeNodes; each(iteratee: NodeIteratee): TreeNodes; editable(full?: boolean): TreeNodes; editing(full?: boolean): TreeNodes; expand(): TreeNodes; expandDeep(): Promise<TreeNodes>; expanded(full?: boolean): TreeNodes; expandParents(): TreeNodes; extract(predicate: string|NodeIteratee): TreeNodes; filterBy(predicate: string|NodeIteratee): TreeNodes; find(predicate: (node: TreeNode, index?: number, obj?: TreeNode[]) => boolean, thisArg?: any): TreeNode; flatten(predicate: string|NodeIteratee): TreeNodes; focused(full?: boolean): TreeNodes; get(index: number): TreeNode; hidden(full?: boolean): TreeNodes; hide(): TreeNodes; hideDeep(): TreeNodes; indeterminate(full?: boolean): TreeNodes; insertAt(index: number, object: any): TreeNode; invoke(methods: string|Array<string>): TreeNodes; invokeDeep(methods: string|Array<string>): TreeNodes; loading(full?: boolean): TreeNodes; matched(full?: boolean): TreeNodes; move(index: number, newIndex: number, target: TreeNodes): TreeNode; node(id: string|number): TreeNode; nodes(ids?: Array<string>|Array<number>): TreeNodes; pagination(): Pagination; recurseDown(iteratee: NodeIteratee): TreeNodes; removed(full?: boolean): TreeNodes; restore(): TreeNodes; restoreDeep(): TreeNodes; select(): TreeNodes; selectable(full?: boolean): TreeNodes; selectBetween(start: TreeNode, end: TreeNode): InspireTree; selectDeep(): TreeNodes; selected(full?: boolean): TreeNodes; show(): TreeNodes; showDeep(): TreeNodes; softRemove(): TreeNodes; sortBy(sorter: string|NodeIteratee): TreeNodes; state(key: string, val: boolean): TreeNodes; stateDeep(key: string, val: boolean): TreeNodes; swap(node1: TreeNode, node2: TreeNode): TreeNodes; toArray(): Array<any>; tree(): InspireTree; visible(full?: boolean): TreeNodes; } export interface TreeNode {} export class TreeNode { addChild(node: NodeConfig): TreeNode; addChildren(nodes: Array<NodeConfig>): TreeNodes; assign(...sources: object[]): TreeNode; available(): boolean; blur(): TreeNode; check(shallow?: boolean): TreeNode; checked(): boolean; clean(): TreeNode; clone(excludeKeys?: Array<string>): TreeNode; collapse(): TreeNode; collapsed(): boolean; constructor(tree: InspireTree, source: any|TreeNode, excludeKeys: Array<string>); constructor(tree: InspireTree, source: any|TreeNode); constructor(tree: InspireTree); text: string; id: string; itree?: NodeConfig['itree']; context(): TreeNodes; copy(dest: InspireTree, hierarchy?: boolean, includeState?: boolean): TreeNode; copyHierarchy(excludeNode?: boolean, includeState?: boolean): TreeNode; deselect(shallow?: boolean): TreeNode; editable(): boolean; editing(): boolean; expand(): Promise<TreeNode>; expanded(): boolean; expandParents(): TreeNode; focus(): TreeNode; focused(): boolean; getChildren(): TreeNodes; getParent(): TreeNode; getParents(): TreeNodes; getTextualHierarchy(): Array<string>; hasAncestor(): boolean; hasChildren(): boolean; hasOrWillHaveChildren(): boolean; hasParent(): boolean; hasVisibleChildren(): boolean; hidden(): boolean; hide(): TreeNode; indeterminate(): boolean; indexPath(): string; isFirstRenderable(): boolean; isLastRenderable(): boolean; lastDeepestVisibleChild(): TreeNode; loadChildren(): Promise<TreeNodes>; loading(): boolean; markDirty(): TreeNode; matched(): TreeNodes; nextVisibleAncestralSiblingNode(): TreeNode; nextVisibleChildNode(): TreeNode; nextVisibleNode(): TreeNode; nextVisibleSiblingNode(): TreeNode; pagination(): Pagination; previousVisibleNode(): TreeNode; previousVisibleSiblingNode(): TreeNode; recurseDown(iteratee: NodeIteratee): TreeNode; recurseUp(iteratee: NodeIteratee): TreeNode; refreshIndeterminateState(): TreeNode; reload(): Promise<TreeNodes>; remove(includeState?: boolean): any; removed(): boolean; renderable(): boolean; rendered(): boolean; restore(): TreeNode; select(shallow?: boolean): TreeNode; selectable(): boolean; selected(): boolean; set(key: number|string, val: any): TreeNode; show(): TreeNode; softRemove(): TreeNode; state(key: object|string, val?: boolean): boolean|object; states(keys: Array<string>, val: boolean): boolean; toggleCheck(): TreeNode; toggleCollapse(): TreeNode; toggleEditing(): TreeNode; toggleSelect(): TreeNode; toObject(excludeChildren?: boolean, includeState?: boolean): any; toString(): string; tree(): InspireTree; uncheck(shallow?: boolean): TreeNode; visible(): boolean; } export default InspireTree;
the_stack
import { Component, Element, Prop, Watch, h, Event, EventEmitter } from '@stencil/core'; import { select, event } from 'd3-selection'; import { min, max } from 'd3-array'; import { linkHorizontal } from 'd3-shape'; import { easeCircleIn } from 'd3-ease'; // import { IAlluvialDiagramProps } from './alluvial-diagram-props'; import { IBoxModelType, IHoverStyleType, IClickStyleType, IDataLabelType, ITooltipLabelType, IAccessibilityType, IAnimationConfig, INodeConfigType, ILinkConfigType } from '@visa/charts-types'; import { AlluvialDiagramDefaultValues } from './alluvial-diagram-default-values'; import { v4 as uuid } from 'uuid'; import 'd3-transition'; import Utils from '@visa/visa-charts-utils'; const { initializeDescriptionRoot, setAccessibilityController, initializeElementAccess, setElementFocusHandler, setElementAccessID, setAccessChartCounts, hideNonessentialGroups, setAccessTitle, setAccessSubtitle, setAccessLongDescription, setAccessExecutiveSummary, setAccessPurpose, setAccessContext, setAccessStatistics, setAccessStructure, setAccessAnnotation, retainAccessFocus, checkAccessFocus, setElementInteractionAccessState, setAccessibilityDescriptionWidth, roundTo, resolveLabelCollision, transitionEndAll, annotate, checkClicked, checkInteraction, convertVisaColor, createTextStrokeFilter, drawTooltip, findTagLevel, formatDataLabel, getColors, getPadding, initTooltipStyle, overrideTitleTooltip, scopeDataKeys, chartAccessors, sankey, sankeyCenter, sankeyJustify, sankeyLeft, sankeyLinkHorizontal, sankeyRight, prepareRenderChange } = Utils; @Component({ tag: 'alluvial-diagram', styleUrl: 'alluvial-diagram.scss' }) export class AlluvialDiagram { @Event() clickFunc: EventEmitter; @Event() hoverFunc: EventEmitter; @Event() mouseOutFunc: EventEmitter; // Chart Attributes (1/7) @Prop({ mutable: true }) mainTitle: string = AlluvialDiagramDefaultValues.mainTitle; @Prop({ mutable: true }) subTitle: string = AlluvialDiagramDefaultValues.subTitle; @Prop({ mutable: true }) height: number = AlluvialDiagramDefaultValues.height; @Prop({ mutable: true }) width: number = AlluvialDiagramDefaultValues.width; @Prop({ mutable: true }) highestHeadingLevel: string | number = AlluvialDiagramDefaultValues.highestHeadingLevel; @Prop({ mutable: true }) margin: IBoxModelType = AlluvialDiagramDefaultValues.margin; @Prop({ mutable: true }) padding: IBoxModelType = AlluvialDiagramDefaultValues.padding; // Data (2/7) @Prop() linkData: object[]; @Prop() nodeData: object[]; @Prop() uniqueID: string; @Prop({ mutable: true }) sourceAccessor: string = AlluvialDiagramDefaultValues.sourceAccessor; @Prop({ mutable: true }) targetAccessor: string = AlluvialDiagramDefaultValues.targetAccessor; @Prop({ mutable: true }) valueAccessor: string = AlluvialDiagramDefaultValues.valueAccessor; @Prop({ mutable: true }) groupAccessor: string = AlluvialDiagramDefaultValues.groupAccessor; @Prop({ mutable: true }) nodeIDAccessor: string = AlluvialDiagramDefaultValues.nodeIDAccessor; // Color & Shape (4/7) @Prop({ mutable: true }) nodeConfig: INodeConfigType = AlluvialDiagramDefaultValues.nodeConfig; @Prop({ mutable: true }) linkConfig: ILinkConfigType = AlluvialDiagramDefaultValues.linkConfig; @Prop({ mutable: true }) colorPalette: string = AlluvialDiagramDefaultValues.colorPalette; @Prop({ mutable: true }) colors: string[]; @Prop({ mutable: true }) hoverStyle: IHoverStyleType = AlluvialDiagramDefaultValues.hoverStyle; @Prop({ mutable: true }) clickStyle: IClickStyleType = AlluvialDiagramDefaultValues.clickStyle; @Prop({ mutable: true }) cursor: string = AlluvialDiagramDefaultValues.cursor; @Prop({ mutable: true }) hoverOpacity: number = AlluvialDiagramDefaultValues.hoverOpacity; @Prop({ mutable: true }) animationConfig: IAnimationConfig = AlluvialDiagramDefaultValues.animationConfig; // Data label (5/7) @Prop({ mutable: true }) dataLabel: IDataLabelType = AlluvialDiagramDefaultValues.dataLabel; @Prop({ mutable: true }) showTooltip: boolean = AlluvialDiagramDefaultValues.showTooltip; @Prop({ mutable: true }) tooltipLabel: ITooltipLabelType = AlluvialDiagramDefaultValues.tooltipLabel; @Prop({ mutable: true }) accessibility: IAccessibilityType = AlluvialDiagramDefaultValues.accessibility; @Prop({ mutable: true }) annotations: object[] = AlluvialDiagramDefaultValues.annotations; // Interactivity (7/7) @Prop() suppressEvents: boolean = AlluvialDiagramDefaultValues.suppressEvents; @Prop({ mutable: true }) hoverHighlight: object; @Prop({ mutable: true }) clickHighlight: object[] = AlluvialDiagramDefaultValues.clickHighlight; @Prop({ mutable: true }) interactionKeys: string[]; // Testing (8/7) @Prop() unitTest: boolean = false; // @Prop() debugMode: boolean = false; @Element() alluvialDiagramEl: HTMLElement; shouldValidateAccessibility: boolean = true; svg: any; root: any; rootG: any; nest: any; alluvialProperties: any; labels: any; tooltipG: any; defaults: boolean; duration: number; innerHeight: number; innerWidth: number; innerPaddedHeight: number; innerPaddedWidth: number; dataTest: any; chartID: string; enterNodeGroups: any; exitNodeGroups: any; updateNodeGroups: any; enterNodes: any; exitNodes: any; updateNodes: any; enterLinks: any; exitLinks: any; enterLinkGroups: any; exitLinkGroups: any; updateLinkGroups: any; updateLinks: any; enteringLabels: any; exitingLabels: any; updatingLabels: any; nodeList: any; linkList: any; innerNodeData: any; innerLinkData: any; preppedData: any; oldNodeCount: any; nodeCount: any; newColumn: any; nodeG: any; linkG: any; labelG: any; innerLinkFillMode: any; innerLabelAccessor: any; innerIDAccessor: any; innerNodeAlignment: any; innerNodeInteractionKeys: any; innerLinkInteractionKeys: any; innerInteractionKeys: any = []; interactionKeysWithObjs: any; colorArr: any; noLinksLeftPadding: any; widthAllNodesNoLinks: any; previousNodeLayers: any; currentNodeLayers: any; previousMinNodeLayer: any; previousMaxNodeLayer: any; currentMaxNodeLayer: any; currentMinNodeLayer: any; topLevel: string = 'h2'; bottomLevel: string = 'p'; sourceLinksString: string = 'sourceLinks'; targetLinksString: string = 'targetLinks'; groupKeys: any; shouldSetDimensions: boolean = false; shouldUpdateData: boolean = false; shouldSetColors: boolean = false; shouldSetTagLevels: boolean = false; shouldRedrawWrapper: boolean = false; shouldUpdateDescriptionWrapper: boolean = false; shouldSetChartAccessibilityCount: boolean = false; shouldSetChartAccessibilityTitle: boolean = false; shouldSetChartAccessibilitySubtitle: boolean = false; shouldSetChartAccessibilityLongDescription: boolean = false; shouldSetChartAccessibilityExecutiveSummary: boolean = false; shouldSetChartAccessibilityPurpose: boolean = false; shouldSetChartAccessibilityContext: boolean = false; shouldSetChartAccessibilityStatisticalNotes: boolean = false; shouldSetChartAccessibilityStructureNotes: boolean = false; shouldSetParentSVGAccessibility: boolean = false; shouldSetGeometryAccessibilityAttributes: boolean = false; shouldSetGeometryAriaLabels: boolean = false; shouldSetGroupAccessibilityLabel: boolean = false; shouldSetSelectionClass: boolean = false; shouldSetAnnotationAccessibility: boolean = false; shouldSetGlobalSelections: boolean = false; shouldSetTestingAttributes: boolean = false; shouldDrawInteractionState: boolean = false; shouldEnterUpdateExit: boolean = false; shouldUpdateNodeGeometries: boolean = false; shouldUpdateLinkGeometries: boolean = false; shouldDrawNodeLabels: boolean = false; bitmaps: any; @Watch('linkData') linkDataWatcher(_newData, _oldData) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; // this.shouldDrawInteractionState = true; } @Watch('nodeData') nodeDataWatcher(_newData, _oldData) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; // this.shouldDrawInteractionState = true; } @Watch('uniqueID') idWatcher(newID, _oldID) { this.chartID = newID || 'alluvial-diagram-' + uuid(); this.alluvialDiagramEl.id = this.chartID; } @Watch('mainTitle') mainTitleWatcher(_newVal, _oldVal) {} @Watch('subTitle') subTitleWatcher(_newVal, _oldVal) {} @Watch('highestHeadingLevel') headingWatcher(_newVal, _oldVal) { this.shouldRedrawWrapper = true; this.shouldSetTagLevels = true; this.shouldSetChartAccessibilityCount = true; this.shouldUpdateDescriptionWrapper = true; this.shouldSetAnnotationAccessibility = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetChartAccessibilitySubtitle = true; this.shouldSetChartAccessibilityLongDescription = true; this.shouldSetChartAccessibilityContext = true; this.shouldSetChartAccessibilityExecutiveSummary = true; this.shouldSetChartAccessibilityPurpose = true; this.shouldSetChartAccessibilityStatisticalNotes = true; this.shouldSetChartAccessibilityStructureNotes = true; } @Watch('height') @Watch('width') @Watch('padding') @Watch('margin') dimensionWatcher(_newVal, _oldVal) { this.shouldSetDimensions = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('sourceAccessor') sourceAccessorWatcher(_newVal, _oldVal) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('targetAccessor') targetAccessorWatcher(_newVal, _oldVal) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('valueAccessor') valueAccessorWatcher(_newVal, _oldVal) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('groupAccessor') groupAccessorWatcher(_newVal, _oldVal) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('nodeIDAccessor') nodeIDAccessorWatcher(_newVal, _oldVal) { this.shouldSetGlobalSelections = true; this.shouldEnterUpdateExit = true; this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('nodeConfig') nodeConfigWatcher(_newVal, _oldVal) { // const newFillVal = _newVal && _newVal.fill; // const oldFillVal = _oldVal && _oldVal.fill; // const newWidthVal = _newVal && _newVal.width; // const oldWidthVal = _oldVal && _oldVal.width; // const newPaddingVal = _newVal && _newVal.padding; // const oldPaddingVal = _oldVal && _oldVal.padding; // const newAlignmentVal = _newVal && _newVal.alignment; // const oldAlignmentVal = _oldVal && _oldVal.alignment; // const newCompareVal = _newVal && _newVal.compare; // const oldCompareVal = _oldVal && _oldVal.compare; this.shouldEnterUpdateExit = true; // this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('linkConfig') linkConfigWatcher(_newVal, _oldVal) { this.shouldEnterUpdateExit = true; // this.shouldDrawInteractionState = true; this.shouldUpdateNodeGeometries = true; this.shouldUpdateLinkGeometries = true; this.shouldDrawNodeLabels = true; } @Watch('colorPalette') colorPaletteWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('colors') colorsWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('clickStyle') clickStyleWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('hoverStyle') hoverStyleWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('cursor') cursorWatcher(_newVal, _oldVal) {} @Watch('hoverOpacity') hoverOpacityWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('dataLabel') dataLabelWatcher(_newVal, _oldVal) { this.shouldDrawNodeLabels = true; // const newVisibleVal = _newVal && _newVal.visible; // const oldVisibleVal = _oldVal && _oldVal.visible; // if (newVisibleVal !== oldVisibleVal) { // this.shouldSetLabelOpacity = true; // } this.shouldDrawInteractionState = true; } @Watch('tooltipLabel') tooltipLabelWatcher(_newVal, _oldVal) {} @Watch('showTooltip') showTooltipWatcher(_newVal, _oldVal) {} @Watch('accessibility') accessibilityWatcher(_newVal, _oldVal) { // this.shouldValidate = true; const newTitle = _newVal && _newVal.title ? _newVal.title : false; const oldTitle = _oldVal && _oldVal.title ? _oldVal.title : false; if (newTitle !== oldTitle) { this.shouldUpdateDescriptionWrapper = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetParentSVGAccessibility = true; } const newExecutiveSummary = _newVal && _newVal.executiveSummary ? _newVal.executiveSummary : false; const oldExecutiveSummary = _oldVal && _oldVal.executiveSummary ? _oldVal.executiveSummary : false; if (newExecutiveSummary !== oldExecutiveSummary) { this.shouldSetChartAccessibilityExecutiveSummary = true; } const newPurpose = _newVal && _newVal.purpose ? _newVal.purpose : false; const oldPurpose = _oldVal && _oldVal.purpose ? _oldVal.purpose : false; if (newPurpose !== oldPurpose) { this.shouldSetChartAccessibilityPurpose = true; } const newLongDescription = _newVal && _newVal.longDescription ? _newVal.longDescription : false; const oldLongDescription = _oldVal && _oldVal.longDescription ? _oldVal.longDescription : false; if (newLongDescription !== oldLongDescription) { this.shouldSetChartAccessibilityLongDescription = true; } const newContext = _newVal && _newVal.contextExplanation ? _newVal.contextExplanation : false; const oldContext = _oldVal && _oldVal.contextExplanation ? _oldVal.contextExplanation : false; if (newContext !== oldContext) { this.shouldSetChartAccessibilityContext = true; } const newStatisticalNotes = _newVal && _newVal.statisticalNotes ? _newVal.statisticalNotes : false; const oldStatisticalNotes = _oldVal && _oldVal.statisticalNotes ? _oldVal.statisticalNotes : false; if (newStatisticalNotes !== oldStatisticalNotes) { this.shouldSetChartAccessibilityStatisticalNotes = true; } const newStructureNotes = _newVal && _newVal.structureNotes ? _newVal.structureNotes : false; const oldStructureNotes = _oldVal && _oldVal.structureNotes ? _oldVal.structureNotes : false; if (newStructureNotes !== oldStructureNotes) { this.shouldSetChartAccessibilityStructureNotes = true; } const newincludeDataKeyNames = _newVal && _newVal.includeDataKeyNames; const oldincludeDataKeyNames = _oldVal && _oldVal.includeDataKeyNames; const newElementDescriptionAccessor = _newVal && _newVal.elementDescriptionAccessor ? _newVal.elementDescriptionAccessor : false; const oldElementDescriptionAccessor = _oldVal && _oldVal.elementDescriptionAccessor ? _oldVal.elementDescriptionAccessor : false; if ( newincludeDataKeyNames !== oldincludeDataKeyNames || newElementDescriptionAccessor !== oldElementDescriptionAccessor ) { if (newincludeDataKeyNames !== oldincludeDataKeyNames) { // this one is tricky because it needs to run after the lifecycle // AND it could run in the off-chance this prop is changed this.shouldSetGroupAccessibilityLabel = true; } this.shouldSetGeometryAriaLabels = true; this.shouldSetParentSVGAccessibility = true; } // const newTextures = _newVal && _newVal.hideTextures ? _newVal.hideTextures : false; // const oldTextures = _oldVal && _oldVal.hideTextures ? _oldVal.hideTextures : false; // const newExTextures = _newVal && _newVal.showExperimentalTextures ? _newVal.showExperimentalTextures : false; // const oldExTextures = _oldVal && _oldVal.showExperimentalTextures ? _oldVal.showExperimentalTextures : false; // if (newTextures !== oldTextures || newExTextures !== oldExTextures) { // this.shouldSetTextures = true; // this.shouldUpdateLegend = true; // this.shouldDrawInteractionState = true; // this.shouldCheckLabelColor = true; // } // const newStrokes = _newVal && _newVal.hideStrokes ? _newVal.hideStrokes : false; // const oldStrokes = _oldVal && _oldVal.hideStrokes ? _oldVal.hideStrokes : false; // if (newStrokes !== oldStrokes) { // this.shouldSetStrokes = true; // this.shouldUpdateLegend = true; // this.shouldDrawInteractionState = true; // } } @Watch('annotations') annotationsWatcher(_newVal, _oldVal) { this.shouldSetAnnotationAccessibility = true; } @Watch('clickHighlight') clickWatcher(_newVal, _oldVal) { this.shouldDrawInteractionState = true; } @Watch('hoverHighlight') hoverWatcher(_newVal, _oldVal) { this.shouldDrawInteractionState = true; } @Watch('interactionKeys') interactionWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('suppressEvents') suppressWatcher(_newVal, _oldVal) { // this.shouldDrawInteractionState = true; } @Watch('unitTest') unitTestWatcher(_newVal, _oldVal) { this.shouldSetTestingAttributes = true; } componentWillLoad() { // contrary to componentWillUpdate, this method appears safe to use for // any calculations we need. Keeping them here reduces future refactor, // since componentWillUpdate should eventually mirror this method return new Promise(resolve => { this.duration = 0; this.defaults = true; this.chartID = this.uniqueID || 'alluvial-diagram-' + uuid(); this.alluvialDiagramEl.id = this.chartID; this.setTagLevels(); this.setDimensions(); this.prepareData(); this.validateIdAccessor(); this.validateLabelText(); this.validateLinkFillMode(); this.validateNodeAlignment(); this.validateInteractionKeys(); this.validateLinkGroups(); this.setColors(); resolve('component will load'); }); } componentWillUpdate() { // NEVER put items in this method that rely on props (until stencil bug is resolved) // All items that belong here are currently at the top of render // see: https://github.com/ionic-team/stencil/issues/2061#issuecomment-578282178 return new Promise(resolve => { resolve('component will update'); }); } componentDidLoad() { return new Promise(resolve => { this.renderRootElements(); this.setChartDescriptionWrapper(); this.setChartAccessibilityTitle(); this.setChartAccessibilitySubtitle(); this.setChartAccessibilityLongDescription(); this.setChartAccessibilityExecutiveSummary(); this.setChartAccessibilityPurpose(); this.setChartAccessibilityContext(); this.setChartAccessibilityStatisticalNotes(); this.setChartAccessibilityStructureNotes(); this.setParentSVGAccessibility(); this.reSetRoot(); this.setTooltipInitialStyle(); this.setNodesDimensions(); this.callSankeyGenerator(); this.setGlobalSelections(); this.setTestingAttributes(); this.enterLinkGeometries(); this.updateLinkGeometries(); this.exitLinkGeometries(); this.enterNodeGeometries(); this.updateNodeGeometries(); this.exitNodeGeometries(); this.enterNodeLabels(); this.updateNodeLabels(); this.exitNodeLabels(); this.drawNodeGeometries(); this.drawLinkGeometries(); this.setGeometryAccessibilityAttributes(); this.setGeometryAriaLabels(); this.setGroupAccessibilityID(); this.setChartCountAccessibility(); this.setSelectedClass(); this.drawNodeLabels(); this.drawAnnotations(); this.setAnnotationAccessibility(); this.duration = 750; this.defaults = false; hideNonessentialGroups(this.root.node(), null); resolve('component did load'); }); } componentDidUpdate() { return new Promise(resolve => { this.duration = !this.animationConfig || !this.animationConfig.disabled ? 750 : 0; this.reSetRoot(); if (this.shouldUpdateDescriptionWrapper) { this.setChartDescriptionWrapper(); this.shouldUpdateDescriptionWrapper = false; } if (this.shouldSetChartAccessibilityCount) { this.setChartCountAccessibility(); this.shouldSetChartAccessibilityCount = false; } if (this.shouldSetChartAccessibilityTitle) { this.setChartAccessibilityTitle(); this.shouldSetChartAccessibilityTitle = false; } if (this.shouldSetChartAccessibilitySubtitle) { this.setChartAccessibilitySubtitle(); this.shouldSetChartAccessibilitySubtitle = false; } if (this.shouldSetChartAccessibilityLongDescription) { this.setChartAccessibilityLongDescription(); this.shouldSetChartAccessibilityLongDescription = false; } if (this.shouldSetChartAccessibilityExecutiveSummary) { this.setChartAccessibilityExecutiveSummary(); this.shouldSetChartAccessibilityExecutiveSummary = false; } if (this.shouldSetChartAccessibilityPurpose) { this.setChartAccessibilityPurpose(); this.shouldSetChartAccessibilityPurpose = false; } if (this.shouldSetChartAccessibilityContext) { this.setChartAccessibilityContext(); this.shouldSetChartAccessibilityContext = false; } if (this.shouldSetChartAccessibilityStatisticalNotes) { this.setChartAccessibilityStatisticalNotes(); this.shouldSetChartAccessibilityStatisticalNotes = false; } if (this.shouldSetChartAccessibilityStructureNotes) { this.setChartAccessibilityStructureNotes(); this.shouldSetChartAccessibilityStructureNotes = false; } if (this.shouldSetParentSVGAccessibility) { this.setParentSVGAccessibility(); this.shouldSetParentSVGAccessibility = false; } this.setNodesDimensions(); this.callSankeyGenerator(); // if (this.shouldSetGlobalSelections) { this.setGlobalSelections(); // this.shouldSetGlobalSelections = false; // } if (this.shouldSetTestingAttributes) { this.setTestingAttributes(); this.shouldSetTestingAttributes = false; } if (this.shouldEnterUpdateExit) { this.enterLinkGeometries(); this.updateLinkGeometries(); this.exitLinkGeometries(); this.enterNodeGeometries(); this.updateNodeGeometries(); this.exitNodeGeometries(); this.enterNodeLabels(); this.updateNodeLabels(); this.exitNodeLabels(); this.shouldEnterUpdateExit = false; } if (this.shouldUpdateNodeGeometries) { this.drawNodeGeometries(); this.shouldUpdateNodeGeometries = false; } if (this.shouldUpdateLinkGeometries) { this.drawLinkGeometries(); this.shouldUpdateLinkGeometries = false; } if (this.shouldSetGeometryAccessibilityAttributes) { this.setGeometryAccessibilityAttributes(); this.shouldSetGeometryAccessibilityAttributes = false; } if (this.shouldSetGeometryAriaLabels) { this.setGeometryAriaLabels(); this.shouldSetGeometryAriaLabels = false; } if (this.shouldSetGroupAccessibilityLabel) { this.setGroupAccessibilityID(); this.shouldSetGroupAccessibilityLabel = false; } if (this.shouldSetSelectionClass) { this.setSelectedClass(); this.shouldSetSelectionClass = false; } if (this.shouldDrawNodeLabels) { this.drawNodeLabels(); this.shouldDrawNodeLabels = false; } this.drawAnnotations(); if (this.shouldDrawInteractionState) { this.updateInteractionState(); this.shouldDrawInteractionState = false; } if (this.shouldSetAnnotationAccessibility) { this.setAnnotationAccessibility(); this.shouldSetAnnotationAccessibility = false; } resolve('component did update'); }); } setDimensions() { this.padding = typeof this.padding === 'string' ? getPadding(this.padding) : this.padding; this.innerHeight = this.height - this.margin.top - this.margin.bottom; this.innerWidth = this.width - this.margin.left - this.margin.right; this.innerPaddedHeight = this.innerHeight - this.padding.top - this.padding.bottom; this.innerPaddedWidth = this.innerWidth - this.padding.left - this.padding.right; } prepareData() { this.nodeList = []; this.linkList = []; this.linkData.forEach((obj, i) => { const linkObj = { source: obj[this.sourceAccessor], target: obj[this.targetAccessor], value: obj[this.valueAccessor], data: obj }; linkObj[this.groupAccessor] = obj[this.groupAccessor]; this.linkList[i] = linkObj; }); // if the user did not set this.nodeData, generate node data from link data this.nodeData && this.nodeData.length > 1 ? (this.nodeList = this.nodeData) : this.createNodeList(); } createNodeList() { this.nodeList = []; this.linkData.map(link => { if (!this.nodeList.some(e => e.id === link[this.sourceAccessor])) { const uniqueSourceID = { id: link[this.sourceAccessor] }; this.nodeList.push(uniqueSourceID); } if (!this.nodeList.some(e => e.id === link[this.targetAccessor])) { const uniqueTargetID = { id: link[this.targetAccessor] }; this.nodeList.push(uniqueTargetID); } }); } validateLabelText() { // if label accessor is passed use that, otherwise default to value hardcoded which is the total // of valueAccessor at the node level this.innerLabelAccessor = this.dataLabel.labelAccessor ? this.dataLabel.labelAccessor : 'value'; } // if there is no nodeData present, use 'id', otherwise use the nodeIDAccessor that is passed validateIdAccessor() { this.innerIDAccessor = this.nodeData && this.nodeData.length > 1 ? this.nodeList[0][this.nodeIDAccessor] ? this.nodeIDAccessor : 'id' : 'id'; } validateLinkFillMode() { this.innerLinkFillMode = this.groupAccessor && this.linkConfig.fillMode === 'group' ? 'group' : this.linkConfig.fillMode === 'source' ? 'source' : this.linkConfig.fillMode === 'target' ? 'target' : this.linkConfig.fillMode === 'path' ? 'path' : 'none'; } validateNodeAlignment() { this.innerNodeAlignment = this.nodeConfig.alignment === 'right' ? sankeyRight : this.nodeConfig.alignment === 'center' ? sankeyCenter : this.nodeConfig.alignment === 'justify' ? sankeyJustify : sankeyLeft; } validateInteractionKeys() { this.interactionKeysWithObjs = []; this.innerInteractionKeys = []; this.innerInteractionKeys = this.interactionKeys && this.interactionKeys.length ? this.interactionKeys : [this.sourceAccessor, this.targetAccessor]; } validateLinkGroups() { this.groupKeys = []; if (this.groupAccessor) { this.groupKeys = this.linkData.map(d => d[this.groupAccessor]).filter((x, i, a) => a.indexOf(x) === i); } } setNodesDimensions() { //controls node width and node padding this.alluvialProperties = sankey(this.nodeConfig.compare, this.linkConfig.visible) .nodeId(d => d[this.innerIDAccessor]) .nodeWidth(this.nodeConfig.width) .nodePadding(this.nodeConfig.padding) .nodeAlign(this.innerNodeAlignment) .nodeSort(null) .size([this.innerPaddedWidth, this.innerPaddedHeight]); } callSankeyGenerator() { const sankeyData = (nodes, links) => this.alluvialProperties({ nodes: nodes.map(d => ({ ...d })), links: links.map(d => ({ ...d })) }); this.preppedData = sankeyData(this.nodeList, this.linkList); this.nodeCount = max(this.preppedData.nodes, d => d.layer); } renderRootElements() { this.svg = select(this.alluvialDiagramEl) .select('.visa-viz-d3-alluvial-container') .append('svg') .attr('width', this.width) .attr('height', this.height); // .attr('viewBox', '0 0 ' + this.width + ' ' + this.height); this.root = this.svg.append('g').attr('id', 'visa-viz-margin-container-g-' + this.chartID); this.rootG = this.root.append('g').attr('id', 'visa-viz-padding-container-g-' + this.chartID); this.nodeG = this.rootG.append('g').attr('class', 'alluvial-node-group'); this.linkG = this.rootG.append('g').attr('class', 'alluvial-link-group'); this.labelG = this.rootG.append('g').attr('class', 'alluvial-dataLabel-group'); this.tooltipG = select(this.alluvialDiagramEl).select('.alluvial-tooltip'); } // reset graph size based on window size reSetRoot() { const changeSvg = prepareRenderChange({ selection: this.svg, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeSvg .attr('width', this.width) .attr('height', this.height) .attr('viewBox', '0 0 ' + this.width + ' ' + this.height); const changeRoot = prepareRenderChange({ selection: this.root, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeRoot.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`); const changeRootG = prepareRenderChange({ selection: this.rootG, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeRootG.attr('transform', `translate(${this.padding.left}, ${this.padding.top})`); setAccessibilityDescriptionWidth(this.chartID, this.width); } setGlobalSelections() { if (this.currentNodeLayers) { this.previousNodeLayers = this.currentNodeLayers; } const dataBoundToNodes = this.nodeG .selectAll('.node-wrapper') .data(this.preppedData.nodes, d => d[this.innerIDAccessor]); this.enterNodes = dataBoundToNodes .enter() .append('g') .attr('class', 'node-wrapper') .attr('data-offset-group', 'true'); this.enterNodes.append('rect').attr('class', 'alluvial-node'); this.exitNodes = dataBoundToNodes.exit(); this.updateNodes = dataBoundToNodes.merge(this.enterNodes); //.selectAll('rect'); this.updateNodes.selectAll('.alluvial-node').data(d => [d]); this.currentNodeLayers = this.preppedData.nodes; if (this.previousNodeLayers) { const updatingNodesWithoutEnteringNodes = this.currentNodeLayers.filter(item => this.previousNodeLayers.map(a => a[this.innerIDAccessor]).includes(item.id) ); this.previousMaxNodeLayer = max(updatingNodesWithoutEnteringNodes, d => d.layer); this.previousMinNodeLayer = min(updatingNodesWithoutEnteringNodes, d => d.layer); const updatingNodesWithoutExitingNodes = this.previousNodeLayers.filter(item => this.currentNodeLayers.map(a => a[this.innerIDAccessor]).includes(item.id) ); this.currentMaxNodeLayer = max(updatingNodesWithoutExitingNodes, d => d.layer); this.currentMinNodeLayer = min(updatingNodesWithoutExitingNodes, d => d.layer); } // temporary, to be removed when lifecycle functions are added // tslint:disable-next-line:no-unused-expression // this.updateLinkGroups && this.updateLinkGroups.remove(); // tslint:disable-next-line:no-unused-expression // this.updateLinks && this.updateLinks.remove(); if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { this.updateNodes.each((_, i, n) => { initializeElementAccess(n[i]); }); const linkDataGroups = this.preppedData.nodes; const dataBoundToLinkGroups = this.linkG .selectAll('.alluvial-link-wrapper') .data(linkDataGroups, d => d[this.innerIDAccessor]); this.enterLinkGroups = dataBoundToLinkGroups.enter().append('g'); this.exitLinkGroups = dataBoundToLinkGroups.exit().remove(); this.updateLinkGroups = dataBoundToLinkGroups.merge(this.enterLinkGroups); const dataBoundToLinks = this.updateLinkGroups .selectAll('.alluvial-link') .data(d => d.sourceLinks, d => d.data[this.sourceAccessor] + d.data[this.targetAccessor]); this.enterLinks = dataBoundToLinks.enter().append('path'); this.exitLinks = dataBoundToLinks.exit(); this.updateLinks = dataBoundToLinks.merge(this.enterLinks).attr('data-offset-element', this.innerLinkFillMode); } else { this.updateNodes.attr('tabindex', null); const dataBoundToLinks = this.linkG .selectAll('.alluvial-link') .data(this.preppedData.links, d => d.data[this.sourceAccessor] + d.data[this.targetAccessor]); this.enterLinks = dataBoundToLinks.enter().append('path'); this.exitLinks = dataBoundToLinks.exit(); this.updateLinks = dataBoundToLinks.merge(this.enterLinks).attr('data-offset-element', null); } const dataBoundToLabels = this.labelG.selectAll('text').data(this.preppedData.nodes, d => d[this.innerIDAccessor]); this.enteringLabels = dataBoundToLabels.enter().append('text'); this.exitingLabels = dataBoundToLabels.exit(); this.updatingLabels = dataBoundToLabels.merge(this.enteringLabels); } setTestingAttributes() { if (this.unitTest) { select(this.alluvialDiagramEl) .select('.visa-viz-d3-alluvial-container') .attr('data-testid', 'chart-container'); select(this.alluvialDiagramEl) .select('.alluvial-main-title') .attr('data-testid', 'main-title'); select(this.alluvialDiagramEl) .select('.alluvial-sub-title') .attr('data-testid', 'sub-title'); this.svg.attr('data-testid', 'root-svg'); this.root.attr('data-testid', 'margin-container'); this.rootG.attr('data-testid', 'padding-container'); // this.legendG.attr('data-testid', 'legend-container'); this.tooltipG.attr('data-testid', 'tooltip-container'); // add test attributes to nodes this.updateNodes.attr('data-testid', 'node').attr('data-id', d => `node-${d[this.innerIDAccessor]}`); // add test attributes to links if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { this.updateLinkGroups .attr('data-testid', 'alluvial-link-group') .attr('data-id', d => `link-group-${d[this.innerIDAccessor]}`); } this.updateLinks .attr('data-testid', 'link') .attr('data-id', d => `link-${d.source[this.innerIDAccessor]}-${d.target[this.innerIDAccessor]}`); // add test attributes to labels this.updatingLabels.attr('data-testid', 'dataLabel').attr('data-id', d => `dataLabel-${d[this.innerIDAccessor]}`); // this.svg.select('defs').attr('data-testid', 'pattern-defs'); } else { select(this.alluvialDiagramEl) .select('.visa-viz-d3-alluvial-container') .attr('data-testid', null); select(this.alluvialDiagramEl) .select('.alluvial-main-title') .attr('data-testid', null); select(this.alluvialDiagramEl) .select('.alluvial-sub-title') .attr('data-testid', null); this.svg.attr('data-testid', null); this.root.attr('data-testid', null); this.rootG.attr('data-testid', null); // this.legendG.attr('data-testid', null); this.tooltipG.attr('data-testid', null); // add test attributes to nodes this.updateNodes.attr('data-testid', null).attr('data-id', null); // add test attributes to links if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { this.updateLinkGroups.attr('data-testid', null).attr('data-id', null); } this.updateLinks.attr('data-testid', null).attr('data-id', null); // add test attributes to labels this.updatingLabels.attr('data-testid', null).attr('data-id', null); // this.svg.select('defs').attr('data-testid', null); } } newColumnInterpolationPosition() { return linkHorizontal() .source(d => d.target.layer <= this.previousMinNodeLayer ? [d.source.x0, d.y0] : d.source.layer >= this.previousMaxNodeLayer ? [d.target.x1, d.y0] : [d.source.x1, d.y0] ) .target(d => d.target.layer <= this.previousMinNodeLayer ? [d.source.x0, d.y0] : d.source.layer >= this.previousMaxNodeLayer ? [d.target.x1, d.y0] : [d.target.x0, d.y1] ); } enterLinkGeometries() { this.enterLinks.interrupt(); const linkOpacity = this.linkConfig.visible ? this.linkConfig.opacity : 0; if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { this.enterLinkGroups.attr('class', 'alluvial-link-wrapper'); } this.enterLinks .attr('class', 'alluvial-link') .classed('entering', true) .attr('d', this.newColumnInterpolationPosition()); this.enterLinks .attr('cursor', !this.suppressEvents ? this.cursor : null) .on('click', !this.suppressEvents ? d => this.onClickHandler(d) : null) .on('mouseover', !this.suppressEvents ? d => this.onHoverHandler(d) : null) .on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null) .attr('stroke-dasharray', (d, i, n) => { d.linelength = n[i].getTotalLength() - 2; // return d.linelength + ' ' + d.linelength; return d.target.layer <= this.previousMinNodeLayer || d.source.layer >= this.previousMaxNodeLayer ? '' : d.linelength + ' ' + d.linelength; }) // .attr('stroke-dashoffset', d => d.linelength) .attr('stroke-dashoffset', d => d.target.layer <= this.previousMinNodeLayer || d.source.layer >= this.previousMaxNodeLayer ? 0 : d.linelength ) .attr('stroke-width', d => d.target.layer <= this.previousMinNodeLayer || d.source.layer >= this.previousMaxNodeLayer ? Math.max(1, d.width) : 0.1 ) .attr('stroke-opacity', linkOpacity) .transition('enter') .duration(this.duration) .ease(easeCircleIn) .attr('d', sankeyLinkHorizontal()) .attr('stroke-width', d => d.target.layer <= this.previousMinNodeLayer || d.source.layer >= this.previousMaxNodeLayer ? Math.max(1, d.width) : 1 ) .attr('stroke-dashoffset', 0); // const test = select(this.svg.node()) // .selectAll('.duplicated-clicked-link'); // this.enterLinks.each((d, i, n) => { // const clicked = // this.clickHighlight && // this.clickHighlight.length > 0 && // checkClicked(d.data, this.clickHighlight, this.innerInteractionKeys); // if (clicked) { // // this.drawDuplicateClickedLink(n[i]); // // if (n[i].classed('duplicated-clicked-link')){ // // } // } // }); } updateLinkGeometries() { this.updateLinks.interrupt(); const linkOpacity = this.linkConfig.visible ? this.linkConfig.opacity : 0; this.updateLinks .transition('opacity') .ease(easeCircleIn) .duration(this.duration) .attr('stroke-opacity', d => { return checkInteraction( d.data, linkOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys // this.nodeIDAccessor ); }); } exitLinkGeometries() { this.exitLinks.interrupt(); const linkOpacity = this.linkConfig.visible ? this.linkConfig.opacity : 0; this.exitLinks .attr('stroke-dasharray', (d, i, n) => { d.linelength = n[i].getTotalLength(); return d.target.layer <= this.previousMinNodeLayer || d.source.layer >= this.previousMaxNodeLayer ? '' : d.linelength + ' ' + d.linelength; }) .transition('exit') .ease(easeCircleIn) .duration(this.duration) .attr('d', this.newColumnInterpolationPosition()) .attr('stroke-opacity', linkOpacity) .attr('stroke-dashoffset', d => d.linelength) .attr('stroke-width', d => d.target.layer <= this.currentMinNodeLayer || d.source.layer >= this.currentMaxNodeLayer ? Math.max(1, d.width) : 0.1 ) .remove(); } drawLinkGeometries() { this.removeTemporaryClickedLinks(this.svg.node()); // const linkOpacity = this.linkConfig.visible ? this.linkConfig.opacity : 0; if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { this.updateLinkGroups.classed('link-group offset-target', true); // .classed('entering', true) // .attr('cursor', !this.suppressEvents ? this.cursor : null); } this.updateLinks .attr('stroke', d => this.innerLinkFillMode === 'group' ? this.colorArr[this.groupKeys.indexOf(d[this.groupAccessor])] : this.innerLinkFillMode === 'none' ? this.colorArr[0] || '#E4E4E4' : this.innerLinkFillMode === 'path' ? this.colorArr[d.index] : this.innerLinkFillMode === 'source' ? this.colorArr[d.source.index] : this.colorArr[d.target.index] ) .attr('fill', 'none') .transition('update') .duration(this.duration) .ease(easeCircleIn) // .attr('stroke-opacity', d => { // return checkInteraction( // d.data, // linkOpacity, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys // // this.nodeIDAccessor // ); // }) .attr('d', sankeyLinkHorizontal()) .attr('stroke-width', d => Math.max(1, d.width)) .call(transitionEndAll, () => { this.removeTemporaryClickedLinks(this.svg.node()); this.updateLinks .classed('entering', false) .attr('d', sankeyLinkHorizontal()) .attr('stroke-dasharray', ''); this.updateLinks.each((d, i, n) => { const clicked = this.clickHighlight && this.clickHighlight.length > 0 && checkClicked(d.data, this.clickHighlight, this.innerInteractionKeys); if (clicked) { // this will add a non-interactive duplicate of each clicked link above the existing ones // so that the link visually appears above all other links, but the keyboard nav order does not change this.drawDuplicateClickedLink(n[i], d); } }); }); this.updateLinks .transition('accessibilityAfterExit') .duration(this.duration) .ease(easeCircleIn) .call(transitionEndAll, () => { // before we exit geometries, we need to check if a focus exists or not const focusDidExist = checkAccessFocus(this.rootG.node()); // then we must remove the exiting elements this.exitLinks.remove(); // then our util can count geometries this.setChartCountAccessibility(); // our group's label should update with new counts too this.setGroupAccessibilityID(); // since items exited, labels must receive updated values this.setGeometryAriaLabels(); // and also make sure the user's focus isn't lost retainAccessFocus({ parentGNode: this.rootG.node(), focusDidExist // recursive: true }); }); } // creates a clone of clicked links drawDuplicateClickedLink(inputElement, d) { const source = inputElement; const className = 'vcl-accessibility-focus'; const parent = source.parentNode; const sourceCopy = source.cloneNode(); select(sourceCopy) .classed('alluvial-link', false) .classed(className + '-highlight ' + className + '-hover', true) .classed('duplicated-clicked-link', true) .classed('entering', false) .data([d.data]) .attr('focusable', false) .attr('aria-label', null) .attr('aria-hidden', true) .attr('role', null) .style('pointer-events', 'none') .attr('tabindex', null); if (this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target') { const parentOfParent = parent.parentNode; const validSiblings = select(parentOfParent).selectAll('.link-group')._groups[0]; const lastGroup = validSiblings[validSiblings.length - 1]; lastGroup.appendChild(sourceCopy); } else { parent.appendChild(sourceCopy); } } removeTemporaryClickedLinks(root) { select(root) .selectAll('.duplicated-clicked-link') .remove(); } enterNodeGeometries() { this.enterNodes.interrupt(); if (!this.defaults) { this.enterNodes.classed('entering', true); } this.enterNodes .select('.alluvial-node') .attr('fill', (_, i) => (this.nodeConfig.fill ? this.colorArr[i] || this.colorArr[0] : '#E4E4E4')) .attr('stroke', '#717171') .attr('stroke-width', '1px') .attr('x', d => d.x0) .attr('y', d => d.y0) .attr('height', d => d.y1 - d.y0) .attr('opacity', 0) .attr('width', d => d.x1 - d.x0); // .transition('enter_nodes') // .delay(20 * this.duration) // .duration(this.duration) // .ease(easeCircleIn) // .attr('x', d => d.x0) // .attr('y', d => d.y0) // .attr('height', d => d.y1 - d.y0) // .attr('width', d => d.x1 - d.x0) // .attr('opacity', 1); // this.enterNodeGroups // .attr('class', 'node-wrapper') // .attr('data-offset-group', 'true'); // this.enterNodes // .attr('class', 'alluvial-node'); } updateNodeGeometries() { this.updateNodes.interrupt(); this.updateNodes .select('.alluvial-node') .transition('node_opacity') .duration((_, i, n) => { if (select(n[i].parentNode).classed('entering')) { // select(n[i].parentNode).classed('entering', false); return this.duration / 3; } return 0; }) // .duration(this.duration) .delay((_, i, n) => { return select(n[i].parentNode).classed('entering') ? this.duration / 1.2 : 0; }) .ease(easeCircleIn) .attr( 'opacity', 1 // d => { // return checkInteraction( // d.data, // 1, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys // // this.nodeIDAccessor // ); // } ); } exitNodeGeometries() { this.exitNodes.interrupt(); this.exitNodes .select('.alluvial-node') .transition('exit') .ease(easeCircleIn) .duration(this.duration / 3) .attr('opacity', 0) .attr('width', 0) .select(function() { return this.parentNode; }) .remove(); // this.exitNodes.remove(); // this.exitNodes // .select('.alluvial-node') // .transition('exit') // .ease(easeCircleIn) // .duration(this.duration) // // .attr('opacity', 0) // .attr('height', 0); } drawNodeGeometries() { this.updateNodes .select('.alluvial-node') // .on('click', !this.suppressEvents ? d => this.onClickHandler(d) : null) // .on('mouseover', !this.suppressEvents ? d => this.onHoverHandler(d) : null) // .on('mouseover', !this.suppressEvents ? d => this.onHoverHandler(d) : null) // .on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null) // .attr('cursor', !this.suppressEvents ? this.cursor : null) .transition('update_nodes') .duration((_, i, n) => { return select(n[i].parentNode).classed('entering') ? this.duration / 3 : this.duration; }) .delay((_, i, n) => { return select(n[i].parentNode).classed('entering') ? this.duration / 1.2 : 0; }) .ease(easeCircleIn) .attr('x', d => d.x0) .attr('y', d => d.y0) .attr('height', d => d.y1 - d.y0) .attr('width', d => d.x1 - d.x0) .attr('opacity', 1) .call(transitionEndAll, () => { this.updateNodes.classed('entering', false); // .attr('opacity', 1) // .attr('d', sankeyLinkHorizontal()) // .attr('stroke-dasharray', ''); }); // d => { // let matchHover = true; // if (d[this.sourceLinksString].length) { // matchHover = d[this.sourceLinksString].some( // linkData => // checkInteraction( // linkData, // 1, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys, // this.interactionKeysWithObjs, // this.nodeIDAccessor // ) >= 1 // ); // } // if (d[this.targetLinksString].length) { // matchHover = d[this.targetLinksString].some( // linkData => // checkInteraction( // linkData, // 1, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys, // this.interactionKeysWithObjs, // this.nodeIDAccessor // ) >= 1 // ); // } // return matchHover ? 1 : this.hoverOpacity; // }) // each item below should be their own functions when watchers are added // .attr('fill', (_, i) => (this.nodeConfig.fill ? this.colorArr[i] || this.colorArr[0] : '#E4E4E4')) // .attr('stroke', '#717171') // .attr('stroke-width', '1px'); } enterNodeLabels() { this.enteringLabels.interrupt(); const opacity = this.dataLabel.visible ? 1 : 0; const hiddenOpacity = this.dataLabel.visible ? Number.EPSILON : 0; this.widthAllNodesNoLinks = this.nodeCount * this.nodeConfig.width + this.nodeCount * this.nodeConfig.width; this.noLinksLeftPadding = (this.innerPaddedWidth - this.widthAllNodesNoLinks) / 2; this.enteringLabels .attr('class', 'alluvial-diagram-dataLabel entering') .attr('opacity', d => { if (this.linkConfig.visible) { let matchHover = true; if (d[this.sourceLinksString].length) { matchHover = d[this.sourceLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } if (d[this.targetLinksString].length) { matchHover = d[this.targetLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } return matchHover ? hiddenOpacity : 0; } else { return d.layer === 0 ? hiddenOpacity : d.layer === this.nodeCount ? hiddenOpacity : 0; } }) .attr('x', d => { if (this.linkConfig.visible) { return this.dataLabel.placement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0; } else { return d.x0 < this.innerPaddedWidth / 2 ? this.noLinksLeftPadding : this.noLinksLeftPadding + this.widthAllNodesNoLinks + this.nodeConfig.width; } }) .attr('y', d => (d.y1 + d.y0) / 2) .attr('dx', d => this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? '-0.5em' : '0.5em' : d.x0 < this.innerPaddedWidth / 2 ? '0.5em' : '-0.5em' ) .attr('dy', '0.4em') .attr('text-anchor', d => { return this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? 'end' : 'start' : d.x0 < this.innerPaddedWidth / 2 ? 'start' : 'end'; }); } updateNodeLabels() { this.updatingLabels.interrupt('label_opacity'); const opacity = this.dataLabel.visible ? 1 : 0; this.updatingLabels .transition('label_opacity') .ease(easeCircleIn) // .duration(this.duration) .duration((_, i, n) => { if (select(n[i]).classed('entering')) { return this.duration / 3; } return 0; }) // .duration(this.duration) .delay((_, i, n) => { return select(n[i]).classed('entering') ? this.duration / 1.2 : 0; }) .attr('opacity', d => { if (this.linkConfig.visible) { let matchHover = true; if (d[this.sourceLinksString].length) { matchHover = d[this.sourceLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } if (d[this.targetLinksString].length) { matchHover = d[this.targetLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } return matchHover ? 1 : 0; } else { return d.layer === 0 ? opacity : d.layer === this.nodeCount ? opacity : 0; } }); } exitNodeLabels() { this.exitingLabels.interrupt(); this.exitingLabels .transition('exit_labels') // .duration(this.duration) .duration(this.duration / 3) .ease(easeCircleIn) .attr('opacity', 0) .remove(); } addStrokeUnder() { const filter = createTextStrokeFilter({ root: this.svg.node(), id: this.chartID, color: '#ffffff' }); this.updatingLabels.attr('filter', filter); } drawNodeLabels() { // const opacity = this.dataLabel.visible ? 1 : 0; const hideOnly = this.dataLabel.placement !== 'auto' && this.dataLabel.collisionHideOnly; this.widthAllNodesNoLinks = this.nodeCount * this.nodeConfig.width + this.nodeCount * this.nodeConfig.width; this.noLinksLeftPadding = (this.innerPaddedWidth - this.widthAllNodesNoLinks) / 2; const nodeLabelUpdate = this.updatingLabels .text(d => this.dataLabel.format ? formatDataLabel(d, this.innerLabelAccessor, this.dataLabel.format) : d[this.innerLabelAccessor] ) .attr('data-x', d => { if (this.linkConfig.visible) { return this.dataLabel.placement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0; } else { return d.x0 < this.innerPaddedWidth / 2 ? this.noLinksLeftPadding : this.noLinksLeftPadding + this.widthAllNodesNoLinks + this.nodeConfig.width; } }) .attr('data-y', d => (d.y1 + d.y0) / 2) .attr('data-translate-x', this.padding.left + this.margin.left) .attr('data-translate-y', this.padding.top + this.margin.top) .attr('data-use-dx', hideOnly) .attr('data-use-dy', hideOnly) .attr('dx', d => this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? '-0.5em' : '0.5em' : d.x0 < this.innerPaddedWidth / 2 ? '0.5em' : '-0.5em' ) .attr('dy', '0.4em') .transition('update_labels') .duration((_, i, n) => { return select(n[i]).classed('entering') ? this.duration / 3 : this.duration; }) .delay((_, i, n) => { return select(n[i]).classed('entering') ? this.duration / 1.2 : 0; }) .ease(easeCircleIn); if (this.dataLabel.visible && (this.dataLabel.placement === 'auto' || this.dataLabel.collisionHideOnly)) { // we only need the node outlines and correct attributes on them const collisionPlacement = this.dataLabel && this.dataLabel.collisionPlacement; const nodeRects = this.updateNodes .select('.alluvial-node') .attr('data-x', d => d.x0) .attr('data-y', d => d.y0) .attr('data-translate-x', this.padding.left + this.margin.left) .attr('data-translate-y', this.padding.top + this.margin.top) .attr('data-height', d => d.y1 - d.y0) .attr('data-width', d => d.x1 - d.x0) .each((d, i, n) => { // for each node, we create a clone and place it // on either side of the rect to hack an inside/outside // placement from the collision util if (!hideOnly) { const source = n[i]; const parent = source.parentNode; const className = 'alluvial-node-collision-clone'; const sourceCopy = source.cloneNode(); select(sourceCopy) .classed('alluvial-node', false) .classed(className, true) .classed('entering', false) .data([d]) .attr('focusable', false) .attr('aria-label', null) .attr('aria-hidden', true) .attr('role', null) .style('pointer-events', 'none') .style('visibility', 'hidden') .attr('tabindex', null) .attr( 'data-x', collisionPlacement === 'all' ? d.x0 : collisionPlacement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0 ) .attr('data-width', collisionPlacement === 'all' ? d.x1 - d.x0 : 1); // temporarily append these to the parent parent.appendChild(sourceCopy); } }); const clonedRects = this.updateNodes.select('.alluvial-node-collision-clone'); this.bitmaps = resolveLabelCollision({ labelSelection: nodeLabelUpdate, avoidMarks: hideOnly ? [nodeRects] : [nodeRects, clonedRects], validPositions: hideOnly ? ['middle'] : ['left', 'right'], offsets: hideOnly ? [1] : [4, 4], accessors: [this.innerIDAccessor], size: [roundTo(this.width, 0), roundTo(this.height, 0)], // we need the whole width for series labels hideOnly: this.dataLabel.visible && hideOnly }); clonedRects.remove(); // if we are in hide only we need to add attributes back if (hideOnly) { nodeLabelUpdate .attr('text-anchor', d => { return this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? 'end' : 'start' : d.x0 < this.innerPaddedWidth / 2 ? 'start' : 'end'; }) .attr('x', d => { if (this.linkConfig.visible) { return this.dataLabel.placement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0; } else { return d.x0 < this.innerPaddedWidth / 2 ? this.noLinksLeftPadding : this.noLinksLeftPadding + this.widthAllNodesNoLinks + this.nodeConfig.width; } }) .attr('y', d => (d.y1 + d.y0) / 2) .attr('dx', d => this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? '-0.5em' : '0.5em' : d.x0 < this.innerPaddedWidth / 2 ? '0.5em' : '-0.5em' ) .attr('dy', '0.4em'); } } else { nodeLabelUpdate .attr('text-anchor', d => { return this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? 'end' : 'start' : d.x0 < this.innerPaddedWidth / 2 ? 'start' : 'end'; }) // .attr('opacity', d => { // if (this.linkConfig.visible) { // let matchHover = true; // if (d[this.sourceLinksString].length) { // matchHover = d[this.sourceLinksString].some( // linkData => // checkInteraction( // linkData.data, // opacity, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys // ) >= 1 // ); // } // if (d[this.targetLinksString].length) { // matchHover = d[this.targetLinksString].some( // linkData => // checkInteraction( // linkData.data, // opacity, // this.hoverOpacity, // this.hoverHighlight, // this.clickHighlight, // this.innerInteractionKeys // ) >= 1 // ); // } // return matchHover ? 1 : 0; // } else { // return d.layer === 0 ? opacity : d.layer === this.nodeCount ? opacity : 0; // } // }) .attr('x', d => { if (this.linkConfig.visible) { return this.dataLabel.placement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0; } else { return d.x0 < this.innerPaddedWidth / 2 ? this.noLinksLeftPadding : this.noLinksLeftPadding + this.widthAllNodesNoLinks + this.nodeConfig.width; } }) .attr('y', d => (d.y1 + d.y0) / 2) .attr('dx', d => this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? '-0.5em' : '0.5em' : d.x0 < this.innerPaddedWidth / 2 ? '0.5em' : '-0.5em' ) .attr('dy', '0.4em'); } // we need to call this after the transitions nodeLabelUpdate.call(transitionEndAll, () => { this.updatingLabels.classed('entering', false); this.addStrokeUnder(); }); } updateInteractionState() { // we created an "opacity" transition namespace in update's transition // we override it here to instantly display opacity state (below) this.removeTemporaryClickedLinks(this.svg.node()); this.updateLinks.interrupt('opacity'); this.updatingLabels.interrupt('label_opacity'); const linkOpacity = this.linkConfig.visible ? this.linkConfig.opacity : 0; const opacity = this.dataLabel.visible ? 1 : 0; const addCollisionClass = this.dataLabel.visible && (this.dataLabel.placement === 'auto' || this.dataLabel.collisionHideOnly); const hideOnly = this.dataLabel.placement !== 'auto' && this.dataLabel.collisionHideOnly; this.updateLinks.attr('stroke-opacity', d => { return checkInteraction( d.data, linkOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys // this.nodeIDAccessor ); }); this.updateLinks.each((d, i, n) => { const clicked = this.clickHighlight && this.clickHighlight.length > 0 && checkClicked(d.data, this.clickHighlight, this.innerInteractionKeys); if (clicked) { // this will add a non-interactive duplicate of each clicked link above the existing ones // so that the link visually appears above all other links, but the keyboard nav order does not change this.drawDuplicateClickedLink(n[i], d); } }); this.updatingLabels.attr('opacity', (d, i, n) => { const prevOpacity = +select(n[i]).attr('opacity'); const styleVisibility = select(n[i]).style('visibility'); let targetOpacity; if (this.linkConfig.visible) { let matchHover = true; if (d[this.sourceLinksString].length) { matchHover = d[this.sourceLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } if (d[this.targetLinksString].length) { matchHover = d[this.targetLinksString].some( linkData => checkInteraction( linkData.data, opacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) >= 1 ); } targetOpacity = matchHover ? opacity : 0; } else { targetOpacity = d.layer === 0 ? opacity : d.layer === this.nodeCount ? opacity : 0; } if ( ((targetOpacity === 1 && styleVisibility === 'hidden') || prevOpacity !== targetOpacity) && addCollisionClass ) { if (targetOpacity === 1) { select(n[i]) .classed('collision-added', true) .style('visibility', null); } else { select(n[i]).classed('collision-removed', true); } } return targetOpacity; }); if (addCollisionClass) { const labelsAdded = this.updatingLabels.filter((_, i, n) => select(n[i]).classed('collision-added')); const labelsRemoved = this.updatingLabels .filter((_, i, n) => select(n[i]).classed('collision-removed')) .attr('data-use-dx', hideOnly) // need to add this for remove piece of collision below .attr('data-use-dy', hideOnly); // we can now remove labels as well if we need to... if (labelsRemoved.size() > 0) { this.bitmaps = resolveLabelCollision({ bitmaps: this.bitmaps, labelSelection: labelsRemoved, avoidMarks: [], validPositions: ['middle'], offsets: [1], accessors: ['key'], size: [roundTo(this.width, 0), roundTo(this.height, 0)], hideOnly: false, removeOnly: true }); // remove temporary class now labelsRemoved.classed('collision-removed', false); } // we can now add labels as well if we need to... if (labelsAdded.size() > 0) { // we only need the node outlines and correct attributes on them const collisionPlacement = this.dataLabel && this.dataLabel.collisionPlacement; const nodeRects = this.updateNodes .select('.alluvial-node') .attr('data-x', d => d.x0) .attr('data-y', d => d.y0) .attr('data-translate-x', this.padding.left + this.margin.left) .attr('data-translate-y', this.padding.top + this.margin.top) .attr('data-height', d => d.y1 - d.y0) .attr('data-width', d => d.x1 - d.x0) .each((d, i, n) => { // for each node, we create a clone and place it // on either side of the rect to hack an inside/outside // placement from the collision util if (!hideOnly) { const source = n[i]; const parent = source.parentNode; const className = 'alluvial-node-collision-clone'; const sourceCopy = source.cloneNode(); select(sourceCopy) .classed('alluvial-node', false) .classed(className, true) .classed('entering', false) .data([d]) .attr('focusable', false) .attr('aria-label', null) .attr('aria-hidden', true) .attr('role', null) .style('pointer-events', 'none') .style('visibility', 'hidden') .attr('tabindex', null) .attr( 'data-x', collisionPlacement === 'all' ? d.x0 : collisionPlacement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0 ) .attr('data-width', collisionPlacement === 'all' ? d.x1 - d.x0 : 1); // temporarily append these to the parent parent.appendChild(sourceCopy); } }); const clonedRects = this.updateNodes.select('.alluvial-node-collision-clone'); this.bitmaps = resolveLabelCollision({ labelSelection: labelsAdded, bitmaps: this.bitmaps, avoidMarks: hideOnly ? [nodeRects] : [nodeRects, clonedRects], validPositions: hideOnly ? ['middle'] : ['left', 'right'], offsets: hideOnly ? [1] : [4, 4], accessors: [this.innerIDAccessor], size: [roundTo(this.width, 0), roundTo(this.height, 0)], // we need the whole width for series labels hideOnly: this.dataLabel.visible && hideOnly, suppressMarkDraw: true }); clonedRects.remove(); // if we are in hide only we need to add attributes back if (hideOnly) { labelsAdded .attr('text-anchor', d => { return this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? 'end' : 'start' : d.x0 < this.innerPaddedWidth / 2 ? 'start' : 'end'; }) .attr('x', d => { if (this.linkConfig.visible) { return this.dataLabel.placement === 'outside' ? d.x0 < this.innerPaddedWidth / 2 ? d.x0 : d.x1 : d.x0 < this.innerPaddedWidth / 2 ? d.x1 : d.x0; } else { return d.x0 < this.innerPaddedWidth / 2 ? this.noLinksLeftPadding : this.noLinksLeftPadding + this.widthAllNodesNoLinks + this.nodeConfig.width; } }) .attr('y', d => (d.y1 + d.y0) / 2) .attr('dx', d => this.dataLabel.placement === 'outside' || !this.linkConfig.visible ? d.x0 < this.innerPaddedWidth / 2 ? '-0.5em' : '0.5em' : d.x0 < this.innerPaddedWidth / 2 ? '0.5em' : '-0.5em' ) .attr('dy', '0.4em'); } // remove temporary class now labelsAdded.classed('collision-added', false); } } } drawAnnotations() { const positionData = this.preppedData; const preppedAnnotations = []; this.annotations.forEach((datum: any) => { const d = { ...datum }; let internalData = datum.data; if (positionData && internalData) { if (d.positionType === 'node' && d.data.hasOwnProperty(this.innerIDAccessor)) { const index = positionData.nodes.findIndex(x => x[this.innerIDAccessor] === d.data[this.innerIDAccessor]); internalData = positionData.nodes[index]; } else if ( d.positionType === 'source' || (d.positionType === 'target' && d.data.hasOwnProperty(this.sourceAccessor) && d.data.hasOwnProperty(this.targetAccessor)) ) { const index = positionData.links.findIndex( x => x.data[this.sourceAccessor] === d.data[this.sourceAccessor] && x.data[this.targetAccessor] === d.data[this.targetAccessor] ); internalData = positionData.links[index]; } } if (d.positionType && internalData) { if (d.positionType === 'target' && internalData.target) { d.x = internalData.target.x0; d.y = internalData.y1; } else if (d.positionType === 'source' && internalData.source) { d.x = internalData.source.x1; d.y = internalData.y0; } else if (d.positionType === 'node') { d.x = internalData.x1; d.y = (internalData.y1 + internalData.y0) / 2; } } // we need to wipe the data before we pass it in, so that the x and y are used instead! delete d.data; preppedAnnotations.push(d); }); annotate({ source: this.rootG.node(), data: preppedAnnotations, ignoreScales: true, // xScale: this.x, // xAccessor: this.layout !== 'horizontal' ? this.ordinalAccessor : this.valueAccessor, // yScale: this.y, // yAccessor: this.layout !== 'horizontal' ? this.valueAccessor : this.ordinalAccessor, width: this.width, height: this.height, padding: this.padding, margin: this.margin, bitmaps: this.bitmaps }); } setColors() { this.colorArr = this.colors ? convertVisaColor(this.colors) : getColors(this.colorPalette, this.nodeList.length); } setTagLevels() { this.topLevel = findTagLevel(this.highestHeadingLevel); this.bottomLevel = findTagLevel(this.highestHeadingLevel, 3); } setChartDescriptionWrapper() { // this initializes the accessibility description section of the chart initializeDescriptionRoot({ rootEle: this.alluvialDiagramEl, // this.lineChartEl, title: this.accessibility.title || this.mainTitle, chartTag: 'alluvial-diagram', uniqueID: this.chartID, highestHeadingLevel: this.highestHeadingLevel, redraw: this.shouldRedrawWrapper }); this.shouldRedrawWrapper = false; } setParentSVGAccessibility() { // this sets the accessibility features of the root SVG element const keys = scopeDataKeys(this, chartAccessors, 'alluvial-diagram'); setAccessibilityController({ node: this.svg.node(), // this.svg.node(), chartTag: 'alluvial-diagram', title: this.accessibility.title || this.mainTitle, description: this.subTitle, uniqueID: this.chartID, geomType: 'link', includeKeyNames: this.accessibility.includeDataKeyNames, dataKeys: keys, groupAccessor: this.innerIDAccessor, groupKeys: ['value'], groupName: 'node' }); } setGeometryAccessibilityAttributes() { // this makes sure every geom element has correct event handlers + semantics (role, tabindex, etc) this.updateLinks.each((_d, i, n) => { initializeElementAccess(n[i]); }); } setGeometryAriaLabels() { // this adds an ARIA label to each geom (a description read by screen readers) const keys = scopeDataKeys(this, chartAccessors, 'alluvial-diagram'); this.updateLinks.each((_d, i, n) => { setElementFocusHandler({ node: n[i], geomType: 'link', includeKeyNames: this.accessibility.includeDataKeyNames, dataKeys: keys, groupName: 'node', uniqueID: this.chartID, disableKeyNav: this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled }); setElementAccessID({ node: n[i], uniqueID: this.chartID }); }); } setGroupAccessibilityID() { // this sets an ARIA label on all the g elements in the chart this.updateNodes.each((_, i, n) => { setElementAccessID({ node: n[i], uniqueID: this.chartID }); }); } setChartCountAccessibility() { // this is our automated section that describes the chart contents // (like geometry and gorup counts, etc) setAccessChartCounts({ rootEle: this.alluvialDiagramEl, // this.lineChartEl, parentGNode: this.linkG.node(), // this.dotG.node(), // pass the wrapper to <g> or geometries here, should be single node selection chartTag: 'alluvial-diagram', geomType: 'link', groupName: 'node' // recursive: true }); } setSelectedClass() { this.updateLinks .classed('highlight', d => { const selected = checkInteraction(d.data, true, false, '', this.clickHighlight, this.innerInteractionKeys); return this.clickHighlight && this.clickHighlight.length ? selected : false; }) .each((d, i, n) => { let selected = checkInteraction(d.data, true, false, '', this.clickHighlight, this.innerInteractionKeys); selected = this.clickHighlight && this.clickHighlight.length ? selected : false; const selectable = this.accessibility.elementsAreInterface; setElementInteractionAccessState(n[i], selected, selectable); }); } setChartAccessibilityTitle() { setAccessTitle(this.alluvialDiagramEl, this.accessibility.title || this.mainTitle); } setChartAccessibilitySubtitle() { setAccessSubtitle(this.alluvialDiagramEl, this.subTitle); } setChartAccessibilityLongDescription() { setAccessLongDescription(this.alluvialDiagramEl, this.accessibility.longDescription); } setChartAccessibilityExecutiveSummary() { setAccessExecutiveSummary(this.alluvialDiagramEl, this.accessibility.executiveSummary); } setChartAccessibilityPurpose() { setAccessPurpose(this.alluvialDiagramEl, this.accessibility.purpose); } setChartAccessibilityContext() { setAccessContext(this.alluvialDiagramEl, this.accessibility.contextExplanation); } setChartAccessibilityStatisticalNotes() { setAccessStatistics(this.alluvialDiagramEl, this.accessibility.statisticalNotes); } setChartAccessibilityStructureNotes() { setAccessStructure(this.alluvialDiagramEl, this.accessibility.structureNotes); } setAnnotationAccessibility() { setAccessAnnotation(this.alluvialDiagramEl, this.annotations); } onClickHandler(d) { this.clickFunc.emit(d.data); } onHoverHandler(d) { overrideTitleTooltip(this.chartID, true); this.hoverFunc.emit(d.data); if (this.showTooltip) { this.eventsTooltip({ data: d, evt: event, isToShow: true }); } } onMouseOutHandler() { overrideTitleTooltip(this.chartID, false); this.mouseOutFunc.emit(); if (this.showTooltip) { this.eventsTooltip({ isToShow: false }); } } // set initial style (instead of copying css class across the lib) setTooltipInitialStyle() { initTooltipStyle(this.tooltipG); } // tooltip eventsTooltip({ data, evt, isToShow }: { data?: any; evt?: any; isToShow: boolean }) { drawTooltip({ root: this.tooltipG, data, event: evt, isToShow, tooltipLabel: this.tooltipLabel, groupAccessor: this.groupAccessor, // sourceAccessor: this.sourceAccessor, // targetAccessor: this.targetAccessor, valueAccessor: this.valueAccessor, // labelAccessor: this.labelAccessor, ordinalAccessor: this.innerIDAccessor, chartType: 'alluvial-diagram' }); } render() { // everything between this comment and the third should eventually // be moved into componentWillUpdate (if the stenicl bug is fixed) this.init(); if (this.shouldSetTagLevels) { this.setTagLevels(); this.shouldSetTagLevels = false; } // if (this.shouldSetDimensions) { this.setDimensions(); // this.shouldSetDimensions = false; // } // if (this.shouldUpdateData) { this.prepareData(); // this.shouldUpdateData = false; // } this.validateIdAccessor(); this.validateLabelText(); this.validateLinkFillMode(); this.validateInteractionKeys(); this.validateLinkGroups(); // if (this.shouldSetColors) { this.setColors(); // this.shouldSetColors = false; // } return ( // <div class="alluvial-diagram">alluvial-diagram</div>; <div> <div class="o-layout"> <div class="o-layout--chart"> <this.topLevel class="alluvial-main-title vcl-main-title">{this.mainTitle}</this.topLevel> <this.bottomLevel class="visa-ui-text--instructions alluvial-sub-title vcl-sub-title"> {this.subTitle} </this.bottomLevel> <keyboard-instructions uniqueID={this.chartID} geomType={'link'} groupName={'node'} // taken from initializeDescriptionRoot, on bar this should be "bar group", stacked bar is "stack", and clustered is "cluster" chartTag={'alluvial-diagram'} width={this.width - (this.margin ? this.margin.right || 0 : 0)} isInteractive={this.accessibility.elementsAreInterface} hasCousinNavigation={this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target'} cousinActionOverride={'on a link'} cousinResultOverride={ this.innerLinkFillMode === 'source' || this.innerLinkFillMode === 'target' ? "Drill up to link's Source or Target node" : '' } disabled={ this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled } // the chart is "simple" /> <div class="visa-viz-d3-alluvial-container" /> <div class="alluvial-tooltip vcl-tooltip" style={{ display: this.showTooltip ? 'block' : 'none' }} /> {/* <data-table uniqueID={this.chartID} isCompact tableColumns={this.tableColumns} data={this.tableData} padding={this.padding} margin={this.margin} hideDataTable={this.accessibility.hideDataTableButton} unitTest={this.unitTest} /> */} </div> </div> {/* <canvas id="bitmap-render" /> */} </div> ); } private init() { // reading properties const keys = Object.keys(AlluvialDiagramDefaultValues); let i = 0; const exceptions = { hoverOpacity: { exception: 0 }, showTooltip: { exception: false }, mainTitle: { exception: '' }, subTitle: { exception: '' }, linkConfig: { ...{ exception: false } } }; for (i = 0; i < keys.length; i++) { const exception = !exceptions[keys[i]] ? false : this[keys[i]] === exceptions[keys[i]].exception; this[keys[i]] = this[keys[i]] || exception ? this[keys[i]] : AlluvialDiagramDefaultValues[keys[i]]; } } }
the_stack
import 'colors'; import { ts } from '@ts-morph/common'; import cheerio = require('cheerio'); import fs = require('fs'); import glob = require('glob'); import request = require('request'); import { Project, Scope, SourceFile } from 'ts-morph'; import { Operator, ResourceTypes } from '../shared'; import { AccessLevelList } from '../shared/access-level'; import { Conditions } from './condition'; import { arnFixer, conditionFixer, fixes, serviceFixer } from './fixes'; export { indexManagedPolicies } from './managed-policies'; // tmp solution. the cheerio/types is currently not working type CheerioStatic = any; type CheerioElement = any; const project = new Project(); const modules: Module[] = []; const timeThreshold = new Date(); var threshold = 25; const thresholdOverride = process.env.NOCACHE; if (typeof thresholdOverride !== 'undefined' && thresholdOverride.length) { threshold += 999999999; } timeThreshold.setHours(timeThreshold.getHours() - threshold); type Stats = { actions: string[]; conditions: string[]; resources: string[]; }; const serviceStats: string[] = []; const conditionTypeDefaults: { [key: string]: { url: string; default: Operator; type: string[]; }; } = { string: { url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String', default: new Operator().stringLike(), type: ['string'], }, arn: { url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN', default: new Operator().arnLike(), type: ['string'], }, numeric: { url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric', default: new Operator().numericEquals(), type: ['number'], }, date: { url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Date', default: new Operator().dateEquals(), type: ['Date', 'string'], }, }; export interface Module { name?: string; servicePrefix?: string; filename: string; url?: string; actionList?: Actions; resourceTypes?: ResourceTypes; fixes?: { [key: string]: any; }; conditions?: Conditions; } export interface Actions { [key: string]: Action; } export interface Action { url: string; description: string; accessLevel: string; resourceTypes?: { [key: string]: ResourceTypeOnAction; }; conditions?: string[]; dependentActions?: string[]; } export interface ResourceTypeOnAction { required: boolean; conditions?: string[]; } export function getAwsServices(): Promise<string[]> { return getAwsServicesFromIamDocs(); } function getAwsServicesFromIamDocs(): Promise<string[]> { return new Promise((resolve, reject) => { const url = 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html'; requestWithRetry(url) .then((body) => { const re = /href=".\/list_(.*?)\.html"/g; var match: RegExpExecArray; const services: string[] = []; do { match = re.exec(body); if (match) { services.push(match[1]); } } while (match); if (!services.length) { return reject(`Unable to find services on ${url}`); } // set env `SERVICE` to generate only a single service for testing purpose const testOverride = process.env.SERVICE; if (typeof testOverride !== 'undefined' && testOverride.length) { return resolve([testOverride]); } const unique = services.filter((elem, pos) => { return services.indexOf(elem) == pos; }); resolve(unique.sort()); }) .catch((err) => { reject(err); }); }); } export function getContent(service: string): Promise<Module> { service = serviceFixer(service); process.stdout.write(`${service}: `.white); process.stdout.write('Fetching '.grey); const urlPattern = 'https://docs.aws.amazon.com/service-authorization/latest/reference/list_%s.html'; return new Promise(async (resolve, reject) => { const shortName = service.replace(/^(amazon|aws)/, ''); try { var module: Module = { filename: shortName.replace(/[^a-z0-9-]/i, '-'), }; const url = urlPattern.replace('%s', service); const cachedFile = `lib/generated/.cache/${module.filename}.ts`; if (fs.existsSync(cachedFile)) { const lastModified = await getLastModified(url); if (lastModified < timeThreshold) { console.log(`Skipping, last modified on ${lastModified}`.green); return resolve(module); } } requestWithRetry(url) .then((body) => { process.stdout.write('Parsing '.blue); const $ = cheerio.load(body); const servicePrefix = $('code').first().text().trim(); if (servicePrefix == '') { console.error(`PREFIX NOT FOUND FOR ${service} / ${url}`.red.bold); } module.name = servicePrefix; module.servicePrefix = servicePrefix; module.url = url; if (shortName in fixes) { module.fixes = fixes[shortName]; } module = addConditions($, module); module = addActions($, module); module = addResourceTypes($, module); resolve(module); }) .catch((err) => { reject(err); }); } catch (e) { reject(e); } }); } export function createModules(services: string[]): Promise<void> { createCache(); return new Promise(async (resolve, reject) => { for (const service of services) { await getContent(service).then(createModule).catch(reject); } writeServiceStats(); resolve(); }); } function writeStatsFile(file: string, data: string[]) { if (fs.existsSync(file)) { const contents = fs .readFileSync(file, 'utf8') .split('\n') .filter((n) => n); data.push(...contents); } const uniqueValues = data .filter(function (elem, pos) { return data.indexOf(elem) == pos; }) .sort(); const content = uniqueValues.join('\n') + '\n'; fs.writeFileSync(file, content); } function writeStats(module: string, stats: Stats) { process.stdout.write('Stats '.grey); Object.keys(stats).forEach(function (key) { const filePath = `./stats/${key}/${module}`; writeStatsFile(filePath, stats[key]); }); } function writeServiceStats() { writeStatsFile('./stats/services', serviceStats); } export function createModule(module: Module): Promise<void> { const stats: Stats = { actions: [], conditions: [], resources: [], }; if (typeof module.name === 'undefined') { //it was skipped, restore from cache const moduleFilePath = `lib/generated/${module.filename}.ts`; restoreFileFromCache(moduleFilePath); const moduleFile = new Project().addSourceFileAtPath(moduleFilePath); module.servicePrefix = moduleFile .getClasses()[0] .getProperty('servicePrefix') .getInitializer() .getText() .split("'") .join(''); } serviceStats.push(module.servicePrefix); if (typeof module.name === 'undefined') { restoreFileFromCache(`stats/actions/${module.servicePrefix}`); restoreFileFromCache(`stats/conditions/${module.servicePrefix}`); restoreFileFromCache(`stats/resources/${module.servicePrefix}`); modules.push(module); return Promise.resolve(); } process.stdout.write(`Generating `.cyan); if (module.fixes && 'name' in module.fixes) { module.name = module.fixes.name; } else if ( module.filename.endsWith('v2') && module.name.substr(-2).toLowerCase() != 'v2' ) { module.name += '-v2'; } modules.push(module); const sourceFile = project.createSourceFile( `./lib/generated/${module.filename}.ts` ); const description = `\nStatement provider for service [${module.name}](${module.url}).\n\n@param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement`; sourceFile.addImportDeclaration({ namedImports: ['AccessLevelList'], moduleSpecifier: '../shared/access-level', }); const classDeclaration = sourceFile.addClass({ name: camelCase(module.name), extends: 'PolicyStatement', isExported: true, }); classDeclaration.addJsDoc({ description: description, }); classDeclaration.addProperty({ name: 'servicePrefix', scope: Scope.Public, initializer: `'${module.servicePrefix}'`, }); const constructor = classDeclaration.addConstructor({}); constructor.addParameter({ name: 'sid', type: 'string', hasQuestionToken: true, }); constructor.setBodyText('super(sid);'); constructor.addJsDoc({ description: description, }); /** * We collect the access levels and their actions in this object */ const accessLevelList: AccessLevelList = {}; for (const [name, action] of Object.entries(module.actionList!)) { if (!(action.accessLevel in accessLevelList)) { accessLevelList[action.accessLevel] = []; } accessLevelList[action.accessLevel].push(name); stats.actions.push(`${module.servicePrefix}:${name};${action.accessLevel}`); const method = classDeclaration.addMethod({ name: `to${upperFirst(name)}`, scope: Scope.Public, }); method.setBodyText(`return this.to('${name}');`); var desc = `\n${action.description}\n\nAccess Level: ${action.accessLevel}`; if ('conditions' in action) { desc += '\n\nPossible conditions:'; action.conditions.forEach((condition) => { desc += `\n- .${createConditionName( module.conditions[condition].key, module.servicePrefix )}()`; }); } if ('dependentActions' in action) { desc += '\n\nDependent actions:'; action.dependentActions.forEach((dependentAction) => { desc += `\n- ${dependentAction}`; }); } if (action.url.length && action.url != 'https://docs.aws.amazon.com/') { desc += `\n\n${action.url}`; } method.addJsDoc({ description: desc, }); } classDeclaration.addProperty({ name: 'accessLevelList', scope: Scope.Protected, type: 'AccessLevelList', initializer: JSON.stringify(accessLevelList, null, 2), }); for (const [name, resourceType] of Object.entries(module.resourceTypes!)) { const method = classDeclaration.addMethod({ name: `on${camelCase(name)}`, scope: Scope.Public, }); stats.resources.push(`${module.servicePrefix}:${name}`); const params = getArnPlaceholders(resourceType.arn); params.forEach((param) => { method.addParameter({ name: lowerFirst(camelCase(param)), type: 'string', hasQuestionToken: /^(Partition|Region|Account(Id)?)$/.test(param), }); }); const methodBody: string[] = [`var arn = '${resourceType.arn}';`]; var paramDocs = ''; params.forEach((param) => { const paramName = lowerFirst(camelCase(param)); var orDefault = ''; if (param == 'Partition') { orDefault = " || 'aws'"; paramDocs += `\n@param ${paramName} - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to \`aws\`.`; } else if (param == 'Region') { orDefault = " || '*'"; paramDocs += `\n@param ${paramName} - Region of the resource; defaults to empty string: all regions.`; } else if (param.match(/^Account(Id)?$/)) { orDefault = " || '*'"; paramDocs += `\n@param ${paramName} - Account of the resource; defaults to empty string: all accounts.`; } else { paramDocs += `\n@param ${paramName} - Identifier for the ${paramName}.`; } methodBody.push( `arn = arn.replace('\${${param}}', ${paramName}${orDefault});` ); }); var desc = `\nAdds a resource of type ${resourceType.name} to the statement`; if ( resourceType.url.length && resourceType.url != 'https://docs.aws.amazon.com/' ) { desc += `\n\n${resourceType.url}`; } desc += `\n${paramDocs}`; if (resourceType.conditionKeys.length) { desc += '\n\nPossible conditions:'; resourceType.conditionKeys.forEach((key) => { desc += `\n- .${createConditionName( module.conditions[key].key, module.servicePrefix )}()`; }); } method.addJsDoc({ description: desc, }); methodBody.push('return this.on(arn);'); method.setBodyText(methodBody.join('\n')); } let hasConditions = false; for (let [key, condition] of Object.entries(module.conditions!)) { key = condition.key; const parts = key.split(':'); const name = parts[1].split(/\/(?=[$<]|$)/); stats.conditions.push(`${module.servicePrefix}:${parts[1]}`); // we have to skip global conditions, since we simply cannot override global conditions due to JSII limitations: https://github.com/aws/jsii/issues/1935 if (parts[0] == 'aws' && name[0] != 'FederatedProvider') { continue; } // boolean conditions don't take operators if (condition.type != 'boolean') { hasConditions = true; } var desc = ''; if (condition.description.length) { desc += `\n${condition.description}\n`; } if (condition.url.length) { desc += `\n${condition.url}\n`; } if ('relatedActions' in condition && condition.relatedActions.length) { desc += '\nApplies to actions:\n'; condition.relatedActions .filter((elem, pos) => { return condition.relatedActions.indexOf(elem) == pos; }) .forEach((relatedAction) => { desc += `- .to${camelCase(relatedAction)}()\n`; }); } if ( 'relatedResourceTypes' in condition && condition.relatedResourceTypes.length ) { desc += '\nApplies to resource types:\n'; condition.relatedResourceTypes .filter((elem, pos) => { return condition.relatedResourceTypes.indexOf(elem) == pos; }) .forEach((resourceType) => { desc += `- ${resourceType}\n`; }); } const type = condition.type.toLowerCase(); const methodBody: string[] = []; var methodName = createConditionName(key, module.servicePrefix); if (name.length > 1 && !name[1].length) { // special case for ec2:ResourceTag/ - not sure this is correct, the description makes zero sense... methodName += 'Exists'; } const method = classDeclaration.addMethod({ name: methodName, scope: Scope.Public, }); let propsKey = ''; if (parts[0] != module.servicePrefix) { propsKey += parts[0] + ':'; } propsKey += name[0]; if (name.length > 1) { // it is a parameterized condition propsKey += '/'; if (name[1].length) { const paramName = name[1].replace(/[^a-zA-Z0-9]/g, ''); desc += `\n@param ${lowerFirst(paramName)} The tag key to check`; method.addParameter({ name: lowerFirst(paramName), type: 'string', }); propsKey += `\${${lowerFirst(paramName)}}`; } } if (type in conditionTypeDefaults) { var types = [...conditionTypeDefaults[type].type]; if ('typeOverride' in condition) { types = condition.typeOverride; } if (types.length > 1) { types.push(`(${types.join('|')})[]`); } else { types.push(`${types}[]`); } desc += `\n@param value The value(s) to check`; method.addParameter({ name: 'value', type: types.join(' | '), }); desc += `\n@param operator Works with [${type} operators](${ conditionTypeDefaults[type].url }). **Default:** \`${conditionTypeDefaults[type].default.toString()}\``; method.addParameter({ name: 'operator', type: 'Operator | string', hasQuestionToken: true, }); if (type == 'date') { methodBody.push( 'if (typeof (value as Date).getMonth === "function") {', ' value = (value as Date).toISOString();', '} else if (Array.isArray(value)) {', ' value = value.map((item) => {', ' if (typeof (item as Date).getMonth === "function") {', ' item = (item as Date).toISOString();', ' }', ' return item;', ' });', '}' ); } methodBody.push( `return this.if(\`${propsKey}\`, value, operator || '${conditionTypeDefaults[ type ].default.toString()}')` ); } else if (type == 'boolean') { desc += '\n@param value `true` or `false`. **Default:** `true`'; method.addParameter({ name: 'value', type: type, hasQuestionToken: true, }); methodBody.push( `return this.if(\`${propsKey}\`, (typeof value !== 'undefined' ? value : true), 'Bool');` ); } else { throw new Error(`Unexpected condition type: ${type}`); } method.addJsDoc({ description: desc, }); method.setBodyText(methodBody.join('\n')); } const sharedClasses = ['PolicyStatement']; if (hasConditions) { sharedClasses.push('Operator'); } sourceFile.addImportDeclaration({ namedImports: sharedClasses, moduleSpecifier: '../shared', }); formatCode(sourceFile); const done = sourceFile.save(); writeStats(module.servicePrefix, stats); console.log('Done'.green); return done; } export function createIndex() { const filePath = './lib/generated/index.ts'; process.stdout.write('index: '.white); process.stdout.write('Generating '.cyan); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } const sourceFile = project.createSourceFile(filePath); modules.sort().forEach((module) => { const source = project.addSourceFileAtPath( `./lib/generated/${module.filename}.ts` ); const exports = []; source.getClasses().forEach((item) => { if (item.isExported()) { exports.push(item.getName()); } }); sourceFile.addExportDeclaration({ namedExports: exports, moduleSpecifier: `./${module.filename}`, }); }); formatCode(sourceFile); const done = sourceFile.save(); console.log('Done'.green); return done; } function cleanDescription(description: string): string { return description .replace(/[\r\n]+/g, ' ') .replace(/\s{2,}/g, ' ') .replace(/<code>(.*?)<\/code>/g, '`$1`') .trim(); } export function getArnPlaceholders(arn: string): RegExpMatchArray { const matches = arn.match(/(?<=\$\{)[a-z0-9_-]+(?=\})/gi); const toTheEnd = []; while (matches.length) { if (/^(Partition|Region|Account(Id)?)$/.test(matches[0])) { toTheEnd.push(matches.shift()); } else { break; } } matches.push(...toTheEnd.reverse()); return matches; } function upperFirst(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } export function lowerFirst(str: string): string { return str.charAt(0).toLowerCase() + str.slice(1); } export function camelCase(str: string) { return str .split(/[_-\s\./]/) .map((str) => { return upperFirst(str); }) .join(''); } function formatCode(file: SourceFile) { file.formatText({ ensureNewLineAtEndOfFile: true, insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, insertSpaceBeforeAndAfterBinaryOperators: true, insertSpaceAfterConstructor: true, insertSpaceAfterKeywordsInControlFlowStatements: true, insertSpaceAfterFunctionKeywordForAnonymousFunctions: true, insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: false, insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true, insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: true, insertSpaceAfterTypeAssertion: true, insertSpaceBeforeFunctionParenthesis: false, placeOpenBraceOnNewLineForFunctions: false, placeOpenBraceOnNewLineForControlBlocks: false, insertSpaceBeforeTypeAnnotation: false, indentMultiLineObjectLiteralBeginningOnBlankLine: true, semicolons: ts.SemicolonPreference.Insert, indentSize: 2, trimTrailingWhitespace: true, }); } function createCache() { createLibCache(); createStatsCache(); } function createLibCache() { const dir = 'lib/generated'; mkDirCache(dir, '*.ts'); } function createStatsCache() { ['actions', 'conditions', 'resources'].forEach((dirName) => { const dir = `stats/${dirName}`; mkDirCache(dir, '*'); }); } function mkDirCache(dir: string, pattern: string) { const cacheDir = `${dir}/.cache`; if (!fs.existsSync(cacheDir)) { fs.mkdirSync(cacheDir); } for (let file of glob.sync(`${dir}/${pattern}`)) { const fileName = (file as string).split('/').slice(-1)[0]; fs.renameSync(file, `${cacheDir}/${fileName}`); } } function restoreFileFromCache(filename: string) { const splitPath = filename.split('/'); const file = splitPath.pop(); splitPath.push('.cache'); splitPath.push(file); const cachedFile = splitPath.join('/'); if (!fs.existsSync(cachedFile)) { return; } fs.renameSync(cachedFile, filename); } function getLastModified(url: string): Promise<Date> { return new Promise((resolve, reject) => { requestWithRetry(url, { method: 'HEAD' }) .then((lastModified: string) => { var mod = new Date(); if (lastModified !== '') { mod = new Date(lastModified); } resolve(mod); }) .catch((err) => { reject(err); }); }); } function getTable($: CheerioStatic, title: string) { const table = $('.table-container table') .toArray() .filter((element) => { return $(element).find('th').first().text() == title; }); return $(table[0]); } function addActions($: CheerioStatic, module: Module): Module { const actions: Actions = {}; const tableActions = getTable($, 'Actions'); var action: string; tableActions.find('tr').each((_: number, element: CheerioElement) => { const tds = $(element).find('td'); const tdLength = tds.length; var first = tds.first(); if (tdLength == 6) { // it's a new action action = first.text().replace('[permission only]', '').trim(); actions[action] = { url: validateUrl(first.find('a[href]').attr('href')?.trim()), description: cleanDescription(first.next().text().trim()), accessLevel: first.next().next().text().trim(), }; first = first.next().next().next(); } if (tdLength != 6 && tdLength != 3) { const content = cleanDescription(tds.text()); if (content.length && !content.startsWith('SCENARIO:')) { console.warn( `skipping row due to unexpected number of fields: ${content}`.yellow ); } return; } var resourceType = first.text().trim(); var required = false; var conditionKeys = first.next().find('p'); const dependentActions = first.next().next().find('p'); const conditions: string[] = []; if (conditionKeys.length) { conditionKeys.each((_, conditionKey) => { const condition = cleanDescription($(conditionKey).text()); conditions.push(condition); if (!('relatedActions' in module.conditions[condition])) { module.conditions[condition].relatedActions = []; } module.conditions[condition].relatedActions.push(action); }); } if (dependentActions.length) { actions[action].dependentActions = []; dependentActions.each((_, dependentAction) => { actions[action].dependentActions.push( cleanDescription($(dependentAction).text()) ); }); } if (resourceType.length) { if (typeof actions[action].resourceTypes == 'undefined') { actions[action].resourceTypes = {}; } if (resourceType.indexOf('*') >= 0) { resourceType = resourceType.slice(0, -1); required = true; } actions[action].resourceTypes![resourceType] = { required: required, }; if (conditions.length) { actions[action].resourceTypes![resourceType].conditions = conditions; } } else if (conditions.length) { actions[action].conditions = conditions; } }); module.actionList = actions; return module; } function addResourceTypes($: CheerioStatic, module: Module): Module { const service = module.name; const resourceTypes: ResourceTypes = {}; const tableResourceTypes = getTable($, 'Resource types'); tableResourceTypes.find('tr').each((_: number, element: CheerioElement) => { const tds = $(element).find('td'); const name = tds.first().text().trim(); const url = validateUrl(tds.first().find('a[href]').attr('href')?.trim()); const arn = tds.first().next().text().trim(); if (!name.length && !arn.length) { return; } const conditionKeys = tds .first() .next() .next() .find('p') .toArray() .map((element) => { return $(element).text().trim(); }); conditionKeys.forEach((condition) => { if (!('relatedResourceTypes' in module.conditions[condition])) { module.conditions[condition].relatedResourceTypes = []; } module.conditions[condition].relatedResourceTypes.push(name); }); if (name.length) { resourceTypes[name] = { name: name, url: url, arn: arnFixer(module.servicePrefix, name, arn), conditionKeys: conditionKeys, }; } }); module.resourceTypes = resourceTypes; return module; } function addConditions($: CheerioStatic, module: Module): Module { const conditions: Conditions = {}; const table = getTable($, 'Condition keys'); table.find('tr').each((_: number, element: CheerioElement) => { const tds = $(element).find('td'); const key = tds.first().text().trim(); const url = validateUrl(tds.first().find('a[href]').attr('href')?.trim()); const description = cleanDescription(tds.first().next().text()); const type = tds.first().next().next().text().trim(); if (key.length) { const condition = conditionFixer(module.servicePrefix, { key: key, description: description, type: type, url: url, isGlobal: key.startsWith('aws:'), }); conditions[key] = condition; } }); module.conditions = conditions; return module; } function createConditionName(key: string, servicePrefix: string): string { let methodName = 'if'; const split = key.split(/:|\/(?=[$<]|$)/); // these are exceptions for the Security Token Service to: // - make it clear to which provider the condition is for // - avoid duplicate method names if (split[0] == 'accounts.google.com') { methodName += 'Google'; } else if (split[0] == 'cognito-identity.amazonaws.com') { methodName += 'Cognito'; } else if (split[0] == 'www.amazon.com') { methodName += 'Amazon'; } else if (split[0] == 'graph.facebook.com') { methodName += 'Facebook'; } else if (split[0] != servicePrefix) { // for global conditions and conditions related to other services methodName += upperFirst(split[0]); } methodName += upperFirst(camelCase(split[1])); return methodName; } function validateUrl(url: string) { if (typeof url == 'undefined') { return ''; } try { new URL(url); } catch (_) { console.warn(`Removed invalid URL ${url}`.red); return ''; } return url; } function requestWithRetry( url: string, options = {}, retries = 3, backoff = 300 ): Promise<any> { return new Promise((resolve, reject) => { const retry = (retries: number, backoff: number) => { request(url, options, (err, response, body) => { if (err) { const failDetails = retries > 0 ? `Retry in ${backoff * 2}` : 'Giving up'; console.log(`Failed to fetch ${url} - ${failDetails}`); if (retries > 0) { setTimeout(() => { retry(--retries, backoff * 2); }, backoff); } else { reject(err); } } else { if ('method' in options && options['method'] == 'HEAD') { if ('last-modified' in response.headers) { resolve(response.headers['last-modified']); } else resolve(''); } else { resolve(body); } } }); }; retry(retries, backoff); }); }
the_stack
import { Touch, SwipeEventArgs } from '../src/touch'; import { Browser } from '../src/browser'; import { createElement } from '../src/dom'; /*tslint:disable */ let touchTestObj: any; interface CommonArgs { changedTouches?: any[]; clientX?: number; clientY?: number; target?: Element | HTMLElement; type?: string; preventDefault(): void; } /*tslint:enable */ let node: Element; let direction: string; //Spy function for testing callback let tEvents: { tapEvent: Function, tapHold: Function, swipe: Function, scroll: Function, cancel: Function } = { tapEvent: (): void => { /** Do Nothing */ }, tapHold: (): void => { /** Do Nothing */ }, swipe: (e: SwipeEventArgs): void => { direction = e.swipeDirection }, scroll: (): void => { /** Do Nothing */ }, cancel: (): void => { /** Do Nothing */ } }; //Simulated MouseEvents Args let startMouseEventArs: CommonArgs = { clientX: 200, clientY: 200, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveMouseEventArs: CommonArgs = { clientX: 500, clientY: 400, target: node, type: 'touchmove', preventDefault: (): void => { /** Do Nothing */ } }; let endMouseEventArs: CommonArgs = { clientX: 200, clientY: 200, target: node, type: 'touchend', preventDefault: (): void => { /** Do Nothing */ } }; //Async Test For Tap Event // Tap delay is 300ms function TapEventTest(done: Function, delay: number): void { touchTestObj.startEvent(startMouseEventArs); touchTestObj.endEvent(endMouseEventArs); setTimeout( (): void => { done(); }, delay); } node = createElement('div', { id: 'test' }); touchTestObj = new Touch(<HTMLElement>node); touchTestObj.swipe = (e: SwipeEventArgs) => { tEvents.swipe(e); }; touchTestObj.scroll = () => { tEvents.scroll(); }; touchTestObj.tap = () => { tEvents.tapEvent(); }; // //Cover on property change. touchTestObj.onPropertyChanged(); // Spec for Touch Framework describe('Touch', () => { beforeEach(() => { spyOn(tEvents, 'tapEvent').and.callThrough(); spyOn(tEvents, 'tapHold').and.callThrough(); spyOn(tEvents, 'swipe').and.callThrough(); spyOn(tEvents, 'scroll').and.callThrough(); spyOn(tEvents, 'cancel').and.callThrough(); }); describe('Initialization of touch', () => { it('empty constructor', () => { let ele: HTMLElement = createElement('div', { id: 'test' }); let objTouch: Touch = new Touch(ele); expect(ele.classList.contains('e-touch')).toEqual(true); }); it('constructor with options', () => { let ele: HTMLElement = createElement('div', { id: 'test' }); let objTouch: Touch = new Touch(ele, { tap: (): void => {/** test */ } }); expect(typeof objTouch.tap).toEqual('function'); expect(ele.classList.contains('e-touch')).toEqual(true); }); it('ie browser constructor', () => { let ele: HTMLElement = createElement('div', { id: 'test' }); let myWindow: any = window; myWindow['browserDetails'].isIE = true; let objTouch: Touch = new Touch(ele, { tap: (): void => {/** test */ } }); expect(typeof objTouch.tap).toEqual('function'); expect(ele.classList.contains('e-block-touch')).toEqual(true); }); }); describe('Swipe', () => { it('event handler callback on swipe vertical', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; movedEnd.clientY = 400; let swipeFn: jasmine.Spy = jasmine.createSpy('clickEvent'); touchTestObj.swipe = swipeFn; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); //Asserts expect(swipeFn).toHaveBeenCalled(); touchTestObj.swipe = undefined; }); it('event handler callback on swipe horizontal', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; movedEnd.clientX = 400; let swipeFn: jasmine.Spy = jasmine.createSpy('swipeEvent'); touchTestObj.addEventListener('swipe', swipeFn); //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); //Asserts expect(swipeFn).toHaveBeenCalled(); }); it('swipe callback test on swipe down', () => { touchTestObj.swipe = (e: SwipeEventArgs) => { tEvents.swipe(e); }; let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; movedEnd.clientY = 400; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); //Asserts expect(direction).toBe('Down'); expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); }); it('swipe callback test on swipe up', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; movedEnd.clientY = 100; movedEnd.clientX = 200; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); //Asserts expect(direction).toBe('Up'); expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); }); it('swipe callback test on swipe direction right.', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; movedEnd.clientX = 400; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); //Asserts expect(direction).toBe('Right'); expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); }); it('swipe callback test on swipe left', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.clientX = 100; movedEnd.clientY = 200; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(movedEnd); touchTestObj.endEvent(movedEnd); //Asserts expect(direction).toBe('Left'); expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); }); it('swipe event callback test without handler.', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.clientX = 100; movedEnd.clientY = 200; touchTestObj.swipe = undefined; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(movedEnd); touchTestObj.endEvent(movedEnd); //Asserts expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); touchTestObj.addEventListener('swipe', (e: SwipeEventArgs) => { tEvents.swipe(e); }); }); }); describe('Scroll event', () => { it('event handler callback on scroll', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; moveArgs.clientY = 300; let scrollFn: jasmine.Spy = jasmine.createSpy('scrollEvt'); touchTestObj.scroll = scrollFn; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(scrollFn).toHaveBeenCalled(); }); it('scroll event callback test on vertical scrolling.', () => { touchTestObj.scroll = () => { tEvents.scroll(); }; let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; moveArgs.clientY = 300; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(tEvents.scroll).toHaveBeenCalled(); }); it('scroll event callback test on vertical scrolling.', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; moveArgs.clientY = 300; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(tEvents.scroll).toHaveBeenCalled(); }); it('scroll event callback test on horizontal scrolling.', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; moveArgs.clientX = 300; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(tEvents.scroll).toHaveBeenCalled(); }); it('scroll event callback test on without move action.', () => { //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(startMouseEventArs); touchTestObj.endEvent(startMouseEventArs); expect(tEvents.scroll).not.toHaveBeenCalled(); }); it('left and right scroll direction', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; let direction: string = ''; moveArgs.clientX = 400; touchTestObj.scroll = (e: any) => { direction = e.scrollDirection; }; //Actions touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(direction).toBe('Right'); moveArgs.clientX = 50; touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(direction).toBe('Left'); }); it('scroll event callback test without handler.', () => { let movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; let moveArgs: CommonArgs = moveMouseEventArs; moveArgs.clientX = 300; //Actions touchTestObj.scroll = undefined; touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveArgs); touchTestObj.endEvent(movedEnd); expect(tEvents.scroll).not.toHaveBeenCalled(); touchTestObj.addEventListener('scroll', () => { tEvents.scroll(); }); }); }); describe('TapHold event', () => { beforeEach((done: Function): void => { touchTestObj.startEvent(startMouseEventArs); setTimeout( () => { done(); }, 750); }); it('taphold event callback with handler', () => { expect(tEvents.tapHold).not.toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); }); }); describe('TapHold event', () => { beforeEach((done: Function): void => { touchTestObj.tapHold = () => { tEvents.tapHold(); }; touchTestObj.startEvent(startMouseEventArs); setTimeout( () => { done(); }, 750); }); it('taphold event callback with handler', () => { expect(tEvents.tapHold).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); }); }); describe('Touch cancel event', () => { beforeEach((done: Function): void => { touchTestObj.tapHold = () => { tEvents.tapHold(); }; touchTestObj.startEvent(startMouseEventArs); touchTestObj.cancelEvent(startMouseEventArs); setTimeout( () => { done(); }, 750); }); it('cancel event callback with handler', () => { expect(tEvents.tapHold).not.toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); expect(tEvents.cancel).not.toHaveBeenCalled(); }); }); describe('swipe trigger during cancel event', () => { beforeEach((done: Function): void => { touchTestObj.tapHold = () => { tEvents.tapHold(); }; touchTestObj.startEvent(startMouseEventArs); touchTestObj.cancelEvent(moveMouseEventArs); setTimeout( () => { done(); }, 750); }); it('cancel event callback', () => { expect(tEvents.tapHold).not.toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); expect(tEvents.cancel).not.toHaveBeenCalled(); }); }); describe('Tap event', () => { let tapFn: jasmine.Spy = jasmine.createSpy('tapEvent'); beforeEach((done: Function): void => { touchTestObj.tap = tapFn; TapEventTest(done, 500); }); it('event handler for tap event', () => { expect(tapFn).toHaveBeenCalled(); }); beforeEach((done: Function): void => { touchTestObj.tap = () => { tEvents.tapEvent(); }; TapEventTest(done, 500); }); it('tap event callback 500ms delay with doubletap.', () => { expect(tEvents.tapEvent).toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); }); beforeEach((done: Function): void => { TapEventTest(done, 0); }); it('tap event callback 0ms delay without doubletap.', () => { expect(tEvents.tapEvent).toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); expect(tEvents.swipe).not.toHaveBeenCalled(); expect(tEvents.scroll).not.toHaveBeenCalled(); }); }); describe('Tap Count', () => { let tapCount: number = 0; let tapFn = jasmine.createSpy('tapEvent'); beforeEach((done: Function): void => { tapCount++; touchTestObj.tap = tapFn; TapEventTest(done, 500); }); it('Count for tap event', () => { expect(tapFn).toHaveBeenCalled(); }); }); describe('Changed touches', () => { it('changed touches event argument', () => { let startEvt: CommonArgs = { changedTouches: [startMouseEventArs], preventDefault: (): void => { /** No Code */ } }; let moveEvt: CommonArgs = { changedTouches: [moveMouseEventArs], preventDefault: (): void => { /** No Code */ } }; //Actions touchTestObj.startEvent(startEvt); touchTestObj.moveEvent(moveEvt); touchTestObj.endEvent(moveEvt); //Asserts expect(tEvents.swipe).toHaveBeenCalled(); expect(tEvents.scroll).toHaveBeenCalled(); expect(tEvents.tapEvent).not.toHaveBeenCalled(); expect(tEvents.tapHold).not.toHaveBeenCalled(); }); }); describe('Method event', () => { it('destroy class test', () => { let ele: HTMLElement = createElement('div', { id: 'test' }); let objTouch: Touch = new Touch(ele); objTouch.tapHoldThreshold = 650; expect(ele.classList.contains('e-touch')).toEqual(true); objTouch.destroy(); expect(ele.classList.contains('e-touch')).toEqual(false); }); }); describe('swipe while scroll', () => { let inst: any; let element: HTMLElement; let spy: jasmine.Spy; let spy1: jasmine.Spy; beforeAll(() => { element = createElement('div', { // tslint:disable-next-line:no-multiline-string id: 'test', innerHTML: `Swipe while scroll India is a vast South Asian<br> Capital: New Delhi<br> President: Pranab Mukherjee<br> Prime minister: Narendra Modi<br> Population: 1.252 billion (2013) World Bank<br> Currency: Indian rupee<br> Gross domestic product: 1.877 trillion USD (2013) World Bank India is a vast South Asian country with<br> Capital: New Delhi<br> President: Pranab Mukherjee<br> Prime minister: Narendra Modi<br> Population: 1.252 billion (2013) World Bank<br> Currency: Indian rupee<br> Gross domestic product: 1.877 trillion USD (2013) World Bank India is a vast South Asian<br> Capital: New Delhi<br> President: Pranab Mukherjee<br> Prime minister: Narendra Modi<br> Population: 1.252 billion (2013) World Bank<br> Currency: Indian rupee<br> Gross domestic product: 1.877 trillion USD (2013) World Bank`, styles: 'overflow:auto;width:250px;height:350px' }); document.body.appendChild(element); inst = new Touch(element, {}); }); beforeEach(() => { spy = jasmine.createSpy('testSpy'); spy1 = jasmine.createSpy('tSpy'); }); afterAll(() => { let child: HTMLElement = document.getElementById('test'); document.removeChild(child); }); it('no swipe - Up', () => { inst.swipe = spy; inst.scroll = spy1; let startEvt: CommonArgs = { clientX: 100, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 100, clientY: 400, target: node, type: 'touchmove', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).not.toHaveBeenCalled(); expect(spy1).toHaveBeenCalled(); }); it('no swipe - Down', () => { inst.swipe = spy; inst.scroll = spy1; let startEvt: CommonArgs = { clientX: 100, clientY: 400, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 100, clientY: 420, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).not.toHaveBeenCalled(); expect(spy1).toHaveBeenCalled(); }); it('no swipe - Left', () => { inst.swipe = spy; inst.scroll = spy1; let startEvt: CommonArgs = { clientX: 150, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 100, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).not.toHaveBeenCalled(); expect(spy1).toHaveBeenCalled(); }); it('no swipe - Right', () => { inst.swipe = spy; inst.scroll = spy1; let startEvt: CommonArgs = { clientX: 100, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 150, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).not.toHaveBeenCalled(); expect(spy1).toHaveBeenCalled(); }); it('swipe - Up', () => { inst.swipe = spy; let startEvt: CommonArgs = { clientX: 100, clientY: 470, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 100, clientY: 410, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).toHaveBeenCalled(); }); it('swipe - Down', () => { inst.swipe = spy; let startEvt: CommonArgs = { clientX: 100, clientY: 410, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 105, clientY: 470, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).toHaveBeenCalled(); }); it('swipe - Right', () => { inst.swipe = spy; let startEvt: CommonArgs = { clientX: 100, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 170, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).toHaveBeenCalled(); }); it('swipe - Left', () => { inst.swipe = spy; let startEvt: CommonArgs = { clientX: 170, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; let moveEvt: CommonArgs = { clientX: 100, clientY: 450, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ } }; //Actions inst.startEvent(startEvt); inst.moveEvent(moveEvt); inst.endEvent(moveEvt); //Asserts expect(spy).toHaveBeenCalled(); }); }); });
the_stack
import React from 'react'; import {mount} from 'enzyme'; import {filter, JSONRender, FuncCustomerArgs} from 'rcre'; import {RCRETestUtil} from 'rcre-test-tools'; import moxios from 'moxios'; import axios from 'axios'; // import {CoreKind} from '../../../../packages/rcre/src/types'; describe('FormItem', () => { beforeEach(() => { moxios.install(axios); }); afterEach(() => { moxios.uninstall(axios); }); it('basicForm', () => { return new Promise((resolve, reject) => { let basicConfig = { body: [ { 'type': 'container', 'model': 'form', 'dataCustomer': { 'customers': [{ 'mode': 'submit', 'name': 'submitForm', 'config': { 'url': '/api/mock/submit', 'method': 'GET', 'data': '#ES{$trigger.submitForm}' } }, { 'name': 'asyncCallback', 'func': '#ES{asyncCallback}' }], 'groups': [{ 'name': 'asyncSubmit', 'steps': ['submitForm', 'asyncCallback'] }] }, 'data': { 'username': 'andycallandycal', 'max': 20 }, 'children': [ { 'type': 'form', 'name': 'basicForm', 'clearAfterSubmit': true, 'trigger': [ { 'event': 'onSubmit', 'targetCustomer': 'asyncSubmit', 'params': { 'username': '#ES{$args.username}' } } ], 'children': [ { 'type': 'formItem', 'label': '姓名', 'required': true, 'rules': [{ 'maxLength': '#ES{$data.max}', 'message': '长度不能超过#ES{$data.max}个字符' }, { 'required': true, 'message': '姓名是必填属性' }], 'control': { 'type': 'input', 'name': 'username', 'placeholder': '请输入姓名', className: 'test-username' }, 'extra': 'Extra Text' }, { 'type': 'formItem', 'label': '单价', 'required': true, 'rules': [{ 'max': 0, 'message': '不能大于0' }], 'control': { 'type': 'input', 'name': 'price' } }, { 'type': 'formItem', 'label': '动态控制验证', 'control': { 'type': 'input', 'name': 'max' } }, { 'type': 'formItem', 'wrapperCol': { 'offset': 4 }, 'control': { 'type': 'button', 'text': '提交', 'disabled': '#ES{!$form.valid}' } } ] } ] } ] }; let test = new RCRETestUtil(basicConfig); let wrapper = test.wrapper; let username = wrapper.find('input').at(0); let price = wrapper.find('input').at(1); let max = wrapper.find('input').at(2); username.simulate('change', { target: { value: 'andycall' } }); let state = test.getState(); let formState = test.getFormState('basicForm'); expect(state.container.form.username).toBe('andycall'); expect(formState.control.username.valid).toBe(true); username.simulate('change', { target: { value: '' } }); username.simulate('blur', {}); formState = test.getFormState('basicForm'); expect(formState.valid).toBe(false); price.simulate('change', { target: { value: 10 } }); state = test.getState(); formState = test.getFormState('basicForm'); let formControl = formState.control; let priceControl = formControl.price; expect(priceControl.valid).toBe(false); expect(priceControl.status).toBe('error'); expect(priceControl.errorMsg).toBe('不能大于0'); price.simulate('change', { target: { value: -10 } }); formState = test.getFormState('basicForm'); expect(formState.control.price.valid).toBe(true); const str = 'abfdeijwidjwijdwijdoqwijdqiodjqiwojdwoqijdqw'; username.simulate('change', { target: { value: str } }); state = test.getState(); formState = test.getFormState('basicForm'); expect(state.container.form.username).toBe(str); expect(formState.control.username.valid).toBe(false); expect(formState.control.username.errorMsg).toBe('长度不能超过20个字符'); max.simulate('change', { target: { value: str.length + 1 } }); expect(formState.control.username.valid).toBe(true); function asyncCallback($args: FuncCustomerArgs<any>) { let params = $args.params; try { expect(params.username).toBe('abfdeijwidjwijdwijdoqwijdqiodjqiwojdwoqijdqw'); resolve(); } catch (e) { reject(e); } } filter.setFilter('asyncCallback', asyncCallback); let form = wrapper.find('form').at(0); form.simulate('submit', {}); moxios.wait(async () => { let submitRequest = moxios.requests.mostRecent(); expect(JSON.parse(submitRequest.config.data)).toEqual({ username: 'abfdeijwidjwijdwijdoqwijdqiodjqiwojdwoqijdqw' }); await submitRequest.respondWith({ status: 200, response: { errno: 0 } }); }); }); }); describe('unexpected form config', () => { it('formItem required in outside', async () => { let config = { body: [{ type: 'container', model: 'testFormContainer', children: [ { type: 'form', name: 'testForm', children: [{ type: 'formItem', required: true, control: { type: 'input', name: 'username' } }] } ] }] }; let test = new RCRETestUtil(config); let wrapper = test.wrapper; await test.triggerFormValidate('testForm'); let formState = test.getFormState('testForm'); expect(formState.valid).toBe(false); expect(formState.control.username.valid).toBe(false); expect(formState.control.username.required).toBe(true); wrapper.unmount(); }); it('formItem required in rules', async () => { let config = { body: [{ type: 'container', model: 'testFormContainer', children: [ { type: 'form', name: 'nestTestForm', children: [{ type: 'formItem', rules: [{ required: true, message: '内容必填' }], control: { type: 'input', name: 'username' } }] } ] }] }; let test = new RCRETestUtil(config); let wrapper = test.wrapper; await test.triggerFormValidate('nestTestForm'); let formState = test.getFormState('nestTestForm'); expect(formState.valid).toBe(false); expect(formState.control.username.valid).toBe(false); expect(formState.control.username.required).toBe(true); let username = wrapper.find('input').at(0); username.simulate('blur', {}); formState = test.getFormState('nestTestForm'); expect(formState.control.username.errorMsg).toBe('内容必填'); wrapper.unmount(); }); }); it('sync FormItem Value in parent Container', async () => { const FORM_NAME = 'testForm'; let config = { body: [{ type: 'container', model: 'rootContainer', children: [ { type: 'button', text: 'setValue', trigger: [{ event: 'onClick', targetCustomer: '$this', params: { username: 'andycall' } }] }, { type: 'container', model: 'formContainer', props: { username: '#ES{$parent.username}' }, export: { username: '#ES{$data.username}' }, children: [ { type: 'form', name: FORM_NAME, children: [ { type: 'formItem', required: true, control: { type: 'input', name: 'username' } } ] } ] } ] }] }; let util = new RCRETestUtil(config); util.setContainer('rootContainer'); let button = util.getComponentByType('button'); await util.simulate(button, 'onClick'); let formState = util.getFormState(FORM_NAME); expect(formState.valid).toBe(true); expect(formState.control.username.valid).toBe(true); }); it('sync FormItem Value in parent Container using dataProvider', async () => { return new Promise(async (resolve, reject) => { const FORM_NAME = 'testForm'; let config = { body: [{ type: 'container', model: 'rootContainer', dataProvider: [{ mode: 'ajax', config: { url: '/api/mock/submit', method: 'GET', data: { username: '1' } }, namespace: 'submitData', responseRewrite: { username: '#ES{$output.data.username}' } }], children: [ { type: 'container', model: 'formContainer', props: { username: '#ES{$parent.username}' }, export: { username: '#ES{$data.username}' }, children: [ { type: 'form', name: FORM_NAME, children: [ { type: 'formItem', required: true, control: { type: 'input', name: 'username' } } ] } ] } ] }] }; let test = new RCRETestUtil(config); await test.triggerFormValidate(FORM_NAME); let formState = test.getFormState(FORM_NAME); expect(formState.valid).toBe(false); moxios.wait(async () => { let request = moxios.requests.mostRecent(); let requestData = request.config.data; expect(JSON.parse(requestData).username).toBe('1'); await request.respondWith({ status: 200, response: { errno: 0, errmsg: 'ok', data: { username: 'andycall' } } }); let state = test.getState(); formState = test.getFormState(FORM_NAME); expect(state.container.rootContainer.username).toBe('andycall'); expect(state.container.formContainer.username).toBe('andycall'); expect(formState.valid).toBe(true); resolve(); }); }); }); it('formItem is valid when change to disabled', async () => { let config = { body: [{ type: 'container', model: 'disabledContainer', data: { disabled: false }, children: [{ type: 'form', name: 'disabledForm', children: [ { type: 'formItem', required: true, rules: [ { minLength: 10 } ], control: { type: 'input', name: 'username', disabled: '#ES{$data.disabled}' } }, { type: 'button', text: 'text', trigger: [{ event: 'onClick', targetCustomer: '$this', params: { disabled: true } }] }, { type: 'button', text: 'text', trigger: [{ event: 'onClick', targetCustomer: '$this', params: { disabled: false } }] } ] }] }] }; let util = new RCRETestUtil(config); util.setContainer('disabledContainer'); let input = util.getComponentByType('input'); util.setData(input, 'aaa'); let formState = util.getFormState('disabledForm'); expect(formState.valid).toBe(false); expect(formState.control.username.valid).toBe(false); let button = util.getComponentByType('button'); await util.simulate(button, 'onClick'); formState = util.getFormState('disabledForm'); expect(formState.valid).toBe(true); expect(formState.control.username.valid).toBe(true); let enableButton = util.getComponentByType('button', 1); await util.simulate(enableButton, 'onClick'); formState = util.getFormState('disabledForm'); expect(formState.valid).toBe(false); expect(formState.control.username.valid).toBe(false); }); it('formItem with hidden or show should not be mounted', async () => { let config = { body: [{ type: 'container', model: 'showHiddenTest', data: { hideInput: true }, children: [{ type: 'form', name: 'hiddenTestForm', children: [ { type: 'formItem', required: true, label: 'UserName', control: { type: 'input', name: 'username', hidden: '#ES{$data.hideInput}' } }, { type: 'formItem', required: true, label: 'Password', control: { type: 'input', name: 'password' } } ] }] }] }; let test = new RCRETestUtil(config); let state = test.getState(); await test.triggerFormValidate('hiddenTestForm'); let formState = test.getFormState('hiddenTestForm'); expect(state.container.showHiddenTest.hideInput).toBe(true); expect(formState.control.username).toBe(undefined); expect(formState.control.password.valid).toBe(false); }); it('change formItem required will trigger validate', async () => { let config = { body: [{ type: 'container', model: 'requiredForm', children: [ { type: 'form', name: 'requiredForm', children: [ { type: 'formItem', required: '#ES{!$data.password}', control: { type: 'input', name: 'username' } }, { type: 'formItem', required: '#ES{!$data.username}', control: { type: 'input', name: 'password' } } ] } ] }] }; let test = new RCRETestUtil(config); let wrapper = test.wrapper; let userName = wrapper.find('input').at(0); let password = wrapper.find('input').at(1); await test.triggerFormValidate('requiredForm'); let formState = test.getFormState('requiredForm'); expect(formState.control.username.valid).toBe(false); expect(formState.control.username.required).toBe(true); expect(formState.control.password.valid).toBe(false); expect(formState.control.password.required).toBe(true); expect(formState.valid).toBe(false); userName.simulate('change', { target: { value: 'helloworld' } }); password.simulate('change', { target: { value: '' } }); formState = test.getFormState('requiredForm'); expect(formState.control.username.valid).toBe(true); expect(formState.control.username.required).toBe(true); expect(formState.control.password.valid).toBe(true); expect(formState.control.password.required).toBe(false); expect(formState.valid).toBe(true); userName.simulate('change', { target: { value: '' } }); password.simulate('change', { target: { value: 'helloworld' } }); formState = test.getFormState('requiredForm'); expect(formState.control.username.valid).toBe(true); expect(formState.control.username.required).toBe(false); expect(formState.control.password.valid).toBe(true); expect(formState.control.password.required).toBe(true); expect(formState.valid).toBe(true); }); it('formItem init value validate', async () => { let config = { body: [{ type: 'container', model: 'initFormValidate', data: { userName: 'lx', age: 27, gender: null, localPerson: true, edu: [], interest: {} }, children: [ { type: 'form', name: 'initFormValidate', children: [ { type: 'formItem', required: true, control: { type: 'input', name: 'userName' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'age' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'gender' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'localPerson' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'edu' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'interest' } } ] } ] }] }; let test = new RCRETestUtil(config); let wrapper = test.wrapper; await test.triggerFormValidate('initFormValidate'); let userName = wrapper.find('input').at(0); let age = wrapper.find('input').at(1); let formState = test.getFormState('initFormValidate'); let state = test.getState(); expect(state.container.initFormValidate.userName).toBe('lx'); expect(formState.control.userName.valid).toBe(true); expect(formState.control.age.valid).toBe(true); expect(formState.control.gender.valid).toBe(false); expect(formState.control.localPerson.valid).toBe(true); expect(formState.control.edu.valid).toBe(false); expect(formState.control.interest.valid).toBe(false); userName.simulate('change', { target: { value: '' } }); age.simulate('change', { target: { value: 0 } }); formState = test.getFormState('initFormValidate'); expect(formState.control.userName.valid).toBe(false); expect(formState.control.age.valid).toBe(true); expect(formState.valid).toBe(false); }); // it('formItem updateCount', () => { // let config = { // body: [{ // type: 'container', // model: 'formUpdateCount', // data: { // userName: 'lx', // age: '123', // age2: '123', // gender: 'male', // gender2: 'female', // edu: '123', // interest: '123' // }, // children: [ // { // type: 'form', // name: 'initFormValidate', // children: [ // { // type: 'formItem', // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // required: true, // control: { // type: 'input', // name: 'userName' // } // }, // { // type: 'formItem', // rules: [{ // maxLength: '#ES{$data.max1}', // message: '长度不能超过#ES{$data.max1}个字符' // }], // required: true, // control: { // type: 'input', // name: 'age' // } // }, // { // type: 'formItem', // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // required: true, // control: { // type: 'input', // name: 'gender' // } // } // ] // }, // { // type: 'form', // name: 'initFormValidate2', // children: [ // { // type: 'formItem', // required: true, // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // control: { // type: 'input', // name: 'userName2' // } // }, // { // type: 'formItem', // required: true, // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // control: { // type: 'input', // name: 'age2' // } // }, // { // type: 'formItem', // required: true, // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // control: { // type: 'input', // name: 'gender2' // } // } // ] // } // ] // }] // }; // // let component = <JSONRender code={JSON.stringify(config)}/>; // let wrapper = mount(component); // // // 同页面下的两个表单 // let firstForm = wrapper.find('RCREForm').at(0).find('RCREFormItem'); // let secondForm = wrapper.find('RCREForm').at(1).find('RCREFormItem'); // // let firstFormFirstItemInstance: any = firstForm.at(0).instance(); // let firstFormSecondItemInstance: any = firstForm.at(1).instance(); // let firstFormThirdItemInstance: any = firstForm.at(2).instance(); // // let secondFormFirstItemInstance: any = secondForm.at(0).instance(); // let secondFormSecondItemInstance: any = secondForm.at(1).instance(); // let secondFormThirdItemInstance: any = secondForm.at(2).instance(); // // let initFirstFormFirstItemCount = firstFormFirstItemInstance.TEST_UPDATECOUNT; // let initFirstFormSecondItemCount = firstFormSecondItemInstance.TEST_UPDATECOUNT; // let initFirstFormThirdItemCount = firstFormThirdItemInstance.TEST_UPDATECOUNT; // // let initSecondformfirstitemcount = secondFormFirstItemInstance.TEST_UPDATECOUNT; // let initSecondFormSecondItemCount = secondFormSecondItemInstance.TEST_UPDATECOUNT; // let initSecondFormThirdItemCount = secondFormThirdItemInstance.TEST_UPDATECOUNT; // // 当更改第一个form中的一个输入框时 // let firstFormFirstInput = firstForm.at(0).find('input').at(0); // firstFormFirstInput.simulate('change', { // target: { // value: 'helloworld' // } // }); // expect(firstFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormFirstItemCount + 1); // expect(firstFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormSecondItemCount); // expect(firstFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormThirdItemCount); // // expect(secondFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initSecondformfirstitemcount); // expect(secondFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormSecondItemCount); // expect(secondFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormThirdItemCount); // // // 当更改第一个form中的二个输入框时 // let firstFormSecondInput = wrapper.find('RCREForm').at(0).find('input').at(1); // firstFormSecondInput.simulate('change', { // target: { // value: '10' // } // }); // expect(firstFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormFirstItemCount + 1); // expect(firstFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormSecondItemCount + 1); // expect(firstFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormThirdItemCount); // // expect(secondFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initSecondformfirstitemcount); // expect(secondFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormSecondItemCount); // expect(secondFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormThirdItemCount); // // // 当更改第二个form中的一个输入框时 // let secondFormFirstInput = secondForm.at(0).find('input').at(0); // secondFormFirstInput.simulate('change', { // target: { // value: 'helloworld' // } // }); // expect(firstFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormFirstItemCount + 1); // expect(firstFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormSecondItemCount + 1); // expect(firstFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormThirdItemCount); // // expect(secondFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initSecondformfirstitemcount + 1); // expect(secondFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormSecondItemCount); // expect(secondFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormThirdItemCount); // // // 当更改第二个form中的二个输入框时 // let secondFormSecondInput = wrapper.find('RCREForm').at(1).find('input').at(1); // secondFormSecondInput.simulate('change', { // target: { // value: '10' // } // }); // expect(firstFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormFirstItemCount + 1); // expect(firstFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormSecondItemCount + 1); // expect(firstFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initFirstFormThirdItemCount); // // expect(secondFormFirstItemInstance.TEST_UPDATECOUNT).toBe(initSecondformfirstitemcount + 1); // expect(secondFormSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormSecondItemCount + 1); // expect(secondFormThirdItemInstance.TEST_UPDATECOUNT).toBe(initSecondFormThirdItemCount); // }); // it('formItem with name is ES expression', () => { // let config = { // body: [{ // type: 'container', // model: 'formUpdateCount', // data: { // userName: 'lx', // age: 27, // localPerson: '123', // }, // children: [ // { // type: 'form', // name: 'initFormValidate', // children: [ // { // type: 'formItem', // required: true, // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // control: { // type: 'input', // name: 'localPerson' // } // }, // { // type: 'formItem', // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // required: true, // control: { // type: 'input', // name: 'userName' // } // }, // { // type: 'formItem', // rules: [{ // maxLength: '#ES{$data.max}', // message: '长度不能超过#ES{$data.max}个字符' // }, { // required: true, // message: '姓名是必填属性' // }], // required: true, // control: { // type: 'input', // name: '#ES{$data.age}' // } // } // ] // } // ] // }] // }; // // let component = <JSONRender code={JSON.stringify(config)}/>; // let wrapper = mount(component); // // // 同页面下的两个表单 // let form = wrapper.find('RCREForm').at(0).find('RCREFormItem'); // // let formFirstItemInstance: any = form.at(0).instance(); // let formSecondItemInstance: any = form.at(1).instance(); // let formThirdItemInstance: any = form.at(2).instance(); // // // 不更改时 默认渲染次数 // // let initFirstItemCount = formFirstItemInstance.TEST_UPDATECOUNT; // // let initSecondItemCount = formSecondItemInstance.TEST_UPDATECOUNT; // // let initThirdItemCount = formThirdItemInstance.TEST_UPDATECOUNT; // // expect(formFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstItemCount); // // expect(formSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondItemCount); // // expect(formThirdItemInstance.TEST_UPDATECOUNT).toBe(initThirdItemCount); // // 当更改第一个form中的一个输入框时 // let firstFormFirstInput = form.at(0).find('input').at(0); // firstFormFirstInput.simulate('change', { // target: { // value: 'helloworld' // } // }); // expect(formFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstItemCount + 1); // expect(formSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondItemCount); // expect(formThirdItemInstance.TEST_UPDATECOUNT).toBe(initThirdItemCount + 2); // // // 当更改第一个form中的二个输入框时 // let firstFormSecondInput = wrapper.find('RCREForm').at(0).find('input').at(1); // firstFormSecondInput.simulate('change', { // target: { // value: '10' // } // }); // expect(formFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstItemCount + 1); // expect(formSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondItemCount + 1); // expect(formThirdItemInstance.TEST_UPDATECOUNT).toBe(initThirdItemCount + 4); // // // 当更改第一个form中的三个输入框时 // let firstFormThirdInput = wrapper.find('RCREForm').at(0).find('input').at(2); // firstFormThirdInput.simulate('change', { // target: { // value: '10' // } // }); // expect(formFirstItemInstance.TEST_UPDATECOUNT).toBe(initFirstItemCount + 1); // expect(formSecondItemInstance.TEST_UPDATECOUNT).toBe(initSecondItemCount + 1); // expect(formThirdItemInstance.TEST_UPDATECOUNT).toBe(initThirdItemCount + 6); // }); it('form with component not in formItem', () => { let config = { body: [ { type: 'container', model: 'loadingExample', data: { test: 'tst', testModal: 't123', placeholder: 'test' }, children: [ { type: 'form', name: 'testForm', children: [ { type: 'input', name: 'test' }, { type: 'formItem', control: { type: 'input', placeholder: '#ES{$data.placeholder}', name: 'testModal' } } ] } ] } ] }; let component = <JSONRender code={JSON.stringify(config)}/>; let wrapper = mount(component); let input = wrapper.find('RCREForm').at(0).find('input'); let firstInput = input.at(0); let secondInput = input.at(0); firstInput.simulate('change', { target: { value: 'first' } }); expect(firstInput.html()).toBe('<input name="test" value="first">'); secondInput.simulate('change', { target: { value: 'second' } }); expect(firstInput.html()).toBe('<input name="test" value="second">'); }); // it('upload error update', async () => { // return new Promise((resolve, reject) => { // let config = { // body: [ // { // type: 'container', // model: 'TextForm', // children: [ // { // type: 'form', // name: 'textForm', // children: [ // { // type: 'formItem', // required: true, // hasFeedBack: false, // control: { // type: 'upload', // name: 'upload', // action: 'http://127.0.0.1:8844/api/mock/gdUploadImgError', // responsePattern: '#ES{$output.errno === 0}', // responseErrMsg: '#ES{$output.errmsg}', // listType: 'picture-card', // uploadExt: ['.jpg', '.png'], // uploadSize: 100000 // } // }, // { // type: 'button', // text: '提交', // htmlType: 'submit', // disabled: '#ES{!$form.valid}' // } // ] // } // ] // } // ] // }; // // let component = <JSONRender code={JSON.stringify(config)}/>; // let wrapper = mount(component); // const fileList = [{ // uid: -1, // name: 'xxx.png', // status: 'done', // size: 100, // url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // thumbUrl: 'https://zos.alipayobjects.com/rmsportal/IQKRngzUuFzJzGzRJXUs.png', // }]; // // let upload = wrapper.find('input').at(0); // // upload.simulate('change', { // target: { // files: fileList // }, // }); // // setTimeout(() => { // wrapper.update(); // let uploadTxt = wrapper.find('.ant-form-explain').at(0); // expect(uploadTxt.html()).toBe('<div class="ant-form-explain">error</div>'); // resolve(); // }, 300); // }); // // }); it('FormItem rules pattern', () => { let config = { body: [{ type: 'container', model: 'demo', children: [ { type: 'form', name: 'demoForm', children: [{ type: 'formItem', rules: [{ pattern: /^\d+$/, message: 'ABC' }], control: { type: 'input', name: 'username' } }] } ] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); let username = test.getComponentByName('username'); test.setData(username, 'abc'); let formStatus = test.getFormItemState('demoForm', 'username'); expect(formStatus.valid).toBe(false); test.setData(username, '1'); formStatus = test.getFormItemState('demoForm', 'username'); expect(formStatus.valid).toBe(true); test.setData(username, 111); formStatus = test.getFormItemState('demoForm', 'username'); expect(formStatus.valid).toBe(true); test.setData(username, {}); formStatus = test.getFormItemState('demoForm', 'username'); expect(formStatus.valid).toBe(false); }); it('FormItem contains filterRule to be verified at initialization time', async () => { let config = { body: [{ type: 'container', model: 'demo', children: [{ type: 'form', name: 'form', children: [{ type: 'formItem', filterRule: '#ES{$args.value === "A" ? true : false}', filterErrMsg: 'got something wrong', control: { type: 'input', name: 'username' } }] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); await test.triggerFormValidate('form'); let formStatus = test.getFormItemState('form', 'username'); expect(formStatus.valid).toBe(false); expect(formStatus).toMatchSnapshot(); }); it('Container component updates will also trigger FormItem revalidation', async () => { filter.setFilter('isUserValid', (username: any) => { if (!username) { return false; } let keys = Object.keys(username); if (keys.some(key => !!username[key])) { return true; } return false; }); let config = { body: [{ type: 'container', model: 'demo', children: [{ type: 'form', name: 'form2', children: [{ type: 'foreach', dataSource: [1, 2, 3, 4, 5], control: { type: 'formItem', filterRule: '#ES{isUserValid($data.username)}', filterErrMsg: 'got something wrong', control: { type: 'input', name: 'username.#ES{$index}' } } }] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); await test.triggerFormValidate('form2'); let formState = test.getFormState('form2'); expect(formState.valid).toBe(false); expect(formState.control).toMatchSnapshot(); let firstUserName = test.getComponentByName('username.0'); test.setData(firstUserName, '123456'); formState = test.getFormState('form2'); expect(formState.valid).toBe(true); expect(formState.control).toMatchSnapshot(); }); it('Container component updates will also trigger FormItem revalidation with validation property', async () => { filter.setFilter('isUserValidWithValidation', (username: any) => { if (!username) { return { isValid: false, errmsg: '' }; } let keys = Object.keys(username); if (keys.some(key => !!username[key])) { return { isValid: true, errmsg: '' }; } return { isValid: false, errmsg: '' }; }); let config = { body: [{ type: 'container', model: 'demo', children: [{ type: 'form', name: 'form2', children: [{ type: 'foreach', dataSource: [1, 2, 3, 4, 5], control: { type: 'formItem', validation: '#ES{isUserValidWithValidation($data.username)}', control: { type: 'input', name: 'username.#ES{$index}' } } }] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); await test.triggerFormValidate('form2'); let formState = test.getFormState('form2'); expect(formState.valid).toBe(false); expect(formState.control).toMatchSnapshot(); let firstUserName = test.getComponentByName('username.0'); test.setData(firstUserName, '123456'); formState = test.getFormState('form2'); expect(formState.valid).toBe(true); expect(formState.control).toMatchSnapshot(); }); it('FormItem validate should be triggered after component mounted', async () => { let config = { body: [{ type: 'container', model: 'demo', data: { dataSource: [{ rowKey: 'A', id: '1' }, { rowKey: 'B', id: '2' }] }, children: [{ type: 'form', name: 'basicForm', children: [ { type: 'foreach', dataSource: '#ES{$data.dataSource}', rowKey: '#ES{$item.rowKey + $item.id}', control: { type: 'formItem', required: true, apiRule: { url: 'http://localhost:8844/static/table.json', method: 'GET', data: { name: '#ES{$args.value}' }, condition: '#ES{$item.rowKey === "B"}', validate: '#ES{$output.errno === 0}', export: { 'C': 'RESPONE' } }, control: { type: 'input', name: '#ES{$item.rowKey}', defaultValue: '#ES{$item.rowKey}' } } }, { type: 'button', text: 'update', trigger: [{ event: 'onClick', targetCustomer: '$this', params: { dataSource: [{ rowKey: 'B', id: '22' }, { rowKey: 'C', id: '33' }] } }, { event: 'onClick', targetCustomer: '$this', params: { C: '', B: '' } }] } ] }] }] }; moxios.uninstall(axios); let test = new RCRETestUtil(config); test.setContainer('demo'); await test.waitForDataProviderComplete(); let A = test.getComponentByName('A'); test.setData(A, 'test'); let B = test.getComponentByName('B'); test.setData(B, 'BBB'); await test.waitForDataProviderComplete(); let button = test.getComponentByType('button'); await test.simulate(button, 'onClick'); let C = test.getComponentByName('C'); test.setData(C, 'CCC'); await test.waitForDataProviderComplete(); let state = test.getContainerState(); expect(state.C).toBe('CCC'); }); it('FormItem control multi elements', async () => { let config = { body: [{ type: 'container', model: 'demo', children: [{ type: 'form', name: 'demo', children: [ { type: 'formItem', required: true, control: [ { type: 'text', text: '#ES{$formItem.errmsg}' }, { type: 'input', name: 'username' }, { type: 'input', name: 'password' } ] } ] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); await test.triggerFormValidate('demo'); let input = test.getComponentByName('username'); test.setData(input, 'helloworld'); let text = test.getComponentByType('text'); expect(text.text()).toBe('不能为空'); let password = test.getComponentByName('password'); test.setData(password, '123456'); text = test.getComponentByType('text'); expect(text.text()).toBe(''); }); it('name changed will trigger FormItem to revalidate', () => { let config = { body: [{ type: 'container', model: 'demo', data: { dynamicName: 'username', username: 'hello', password: 'eeieieieieieieieeieieieieieiwqweqweqweqwe' }, children: [ { type: 'form', name: 'demo', children: [ { type: 'formItem', required: true, rules: [{ maxLength: 5, message: '字数最大不能超过10' }], control: { type: 'input', name: '#ES{$data.dynamicName}' } }, { type: 'formItem', required: true, control: { type: 'input', name: 'dynamicName' } } ] }, ] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); let formState = test.getFormState('demo'); let state = test.getContainerState(); expect(formState.valid).toBe(true); expect(formState.control.dynamicName.valid).toBe(true); expect(formState.control.username.valid).toBe(true); expect(state.username).toBe('hello'); let dynamicName = test.getComponentByName('dynamicName'); test.setData(dynamicName, 'password'); formState = test.getFormState('demo'); expect(formState.control.password.valid).toBe(false); expect(formState.control.username).toBe(undefined); expect(formState.control.password.errorMsg).toBe('字数最大不能超过10'); expect(formState.valid).toBe(false); state = test.getContainerState(); expect(state.username).toBe(undefined); expect(state.password).toBe('eeieieieieieieieeieieieieieiwqweqweqweqwe'); }); it('disabled changed will trigger form revalidate', () => { let config = { body: [{ type: 'container', model: 'demo', data: { disabled: true, username: 'hello' }, children: [ { type: 'form', name: 'demo', children: [ { type: 'formItem', required: true, rules: [{ maxLength: 1 }], control: { type: 'input', name: 'username', disabled: '#ES{$data.disabled}' } }, { type: 'input', name: 'disabled' } ] } ] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); let formState = test.getFormState('demo'); expect(formState.valid).toBe(true); let disabled = test.getComponentByName('disabled'); test.setData(disabled, false); formState = test.getFormState('demo'); expect(formState.valid).toBe(false); expect(formState.control.username.valid).toBe(false); expect(formState.control.username.errorMsg).toBe('长度不能大于1'); }); it('change components value will trigger formItem revalidate', async () => { let config = { body: [{ type: 'container', model: 'demo', data: { username: 'helloworld' }, children: [{ type: 'form', name: 'demo', children: [ { type: 'formItem', required: true, rules: [{ maxLength: 10 }], control: { type: 'input', name: 'username' } }, { type: 'button', text: 'update', trigger: [{ event: 'onClick', targetCustomer: '$this', params: { username: '0000000000000000000000000000000000000000' } }] } ] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); let formStatus = test.getFormState('demo'); expect(formStatus.valid).toBe(true); let username = test.getComponentByName('username'); test.setData(username, '010101010101010101010101010110'); formStatus = test.getFormState('demo'); expect(formStatus.valid).toBe(false); expect(formStatus.control.username.valid).toBe(false); expect(formStatus.control.username.errorMsg).toBe('长度不能大于10'); test.setData(username, 'test'); formStatus = test.getFormState('demo'); expect(formStatus.valid).toBe(true); let button = test.getComponentByType('button'); await test.simulate(button, 'onClick'); formStatus = test.getFormState('demo'); expect(formStatus.valid).toBe(false); expect(formStatus.control.username.valid).toBe(false); expect(formStatus.control.username.errorMsg).toBe('长度不能大于10'); }); it('Form validation property', async () => { let config = { body: [{ type: 'container', model: 'demo', children: [{ type: 'form', name: 'test', children: [{ type: 'formItem', validation: ({$args}: any) => { return { isValid: $args.value === '12345', errmsg: 'error' }; }, control: { type: 'input', name: 'username' } }] }] }] }; let test = new RCRETestUtil(config); test.setContainer('demo'); await test.triggerFormValidate('test'); let formState = test.getFormState('test'); expect(formState.valid).toBe(false); let input = test.getComponentByName('username'); test.setData(input, 'helloworld'); formState = test.getFormState('test'); expect(formState.valid).toBe(false); test.setData(input, '12345'); formState = test.getFormState('test'); expect(formState.valid).toBe(true); }); });
the_stack
// ==================================================== // GraphQL mutation operation: updateBlockCellMutation // ==================================================== export interface updateBlockCellMutation_update_block_block_Channel_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Channel_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_Channel { __typename: "Channel"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Channel_user | null; source: updateBlockCellMutation_update_block_block_Channel_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; } export interface updateBlockCellMutation_update_block_block_Image_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Image_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_Image_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_Image { __typename: "Image"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Image_user | null; source: updateBlockCellMutation_update_block_block_Image_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; thumb_url: string | null; image_url: string | null; original_image_url: string | null; can: updateBlockCellMutation_update_block_block_Image_can | null; find_original_url: string | null; downloadable_image: string | null; } export interface updateBlockCellMutation_update_block_block_Text_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Text_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_Text_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_Text { __typename: "Text"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Text_user | null; source: updateBlockCellMutation_update_block_block_Text_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; content: string; can: updateBlockCellMutation_update_block_block_Text_can | null; find_original_url: string | null; editable_content: string; } export interface updateBlockCellMutation_update_block_block_Link_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Link_source { __typename: "ConnectableSource"; title: string | null; url: string | null; provider_name: string | null; provider_url: string | null; } export interface updateBlockCellMutation_update_block_block_Link_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_Link { __typename: "Link"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Link_user | null; source: updateBlockCellMutation_update_block_block_Link_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; source_url: string | null; image_url: string | null; image_updated_at: string | null; image_updated_at_unix_time: string | null; can: updateBlockCellMutation_update_block_block_Link_can | null; } export interface updateBlockCellMutation_update_block_block_Attachment_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Attachment_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_Attachment_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_Attachment { __typename: "Attachment"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Attachment_user | null; source: updateBlockCellMutation_update_block_block_Attachment_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; file_extension: string | null; file_url: string | null; file_size: string | null; file_content_type: string | null; image_url: string | null; image_updated_at: string | null; image_updated_at_unix_time: string | null; can: updateBlockCellMutation_update_block_block_Attachment_can | null; } export interface updateBlockCellMutation_update_block_block_Embed_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_Embed_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_Embed_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_Embed { __typename: "Embed"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_Embed_user | null; source: updateBlockCellMutation_update_block_block_Embed_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; embed_html: string | null; embed_width: number | null; embed_height: number | null; can: updateBlockCellMutation_update_block_block_Embed_can | null; } export interface updateBlockCellMutation_update_block_block_PendingBlock_user { __typename: "User"; id: number; name: string; href: string | null; } export interface updateBlockCellMutation_update_block_block_PendingBlock_source { __typename: "ConnectableSource"; title: string | null; url: string | null; } export interface updateBlockCellMutation_update_block_block_PendingBlock_can { __typename: "BlockCan"; manage: boolean | null; comment: boolean | null; mute: boolean | null; potentially_edit_thumbnail: boolean | null; edit_thumbnail: boolean | null; } export interface updateBlockCellMutation_update_block_block_PendingBlock { __typename: "PendingBlock"; id: number; title: string; href: string | null; created_at_unix_time: string | null; created_at_timestamp: string | null; created_at: string | null; updated_at: string | null; updated_at_timestamp: string | null; description: string | null; user: updateBlockCellMutation_update_block_block_PendingBlock_user | null; source: updateBlockCellMutation_update_block_block_PendingBlock_source | null; shareable_href: string | null; shareable_title: string; editable_title: string; editable_description: string | null; can: updateBlockCellMutation_update_block_block_PendingBlock_can | null; } export type updateBlockCellMutation_update_block_block = updateBlockCellMutation_update_block_block_Channel | updateBlockCellMutation_update_block_block_Image | updateBlockCellMutation_update_block_block_Text | updateBlockCellMutation_update_block_block_Link | updateBlockCellMutation_update_block_block_Attachment | updateBlockCellMutation_update_block_block_Embed | updateBlockCellMutation_update_block_block_PendingBlock; export interface updateBlockCellMutation_update_block { __typename: "UpdateBlockMutationPayload"; block: updateBlockCellMutation_update_block_block; } export interface updateBlockCellMutation { update_block: updateBlockCellMutation_update_block | null; } export interface updateBlockCellMutationVariables { id: string; title?: string | null; description?: string | null; content?: string | null; }
the_stack
* Tekton Hub * HTTP services for managing Tekton Hub * * The version of the OpenAPI document: 1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as globalImportUrl from 'url'; import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * Access Token for User * @export * @interface AccessToken */ export interface AccessToken { /** * * @type {Token} * @memberof AccessToken */ access?: Token; } /** * Auth tokens have access and refresh token for user * @export * @interface AuthTokens */ export interface AuthTokens { /** * * @type {Token} * @memberof AuthTokens */ access?: Token; /** * * @type {Token} * @memberof AuthTokens */ refresh?: Token; } /** * * @export * @interface AuthenticateResponseBody */ export interface AuthenticateResponseBody { /** * * @type {AuthTokens} * @memberof AuthenticateResponseBody */ data: AuthTokens; } /** * * @export * @interface Catalog */ export interface Catalog { /** * ID is the unique id of the catalog * @type {number} * @memberof Catalog */ id: number; /** * Name of catalog * @type {string} * @memberof Catalog */ name: string; /** * Type of catalog * @type {string} * @memberof Catalog */ type: CatalogTypeEnum; /** * URL of catalog * @type {string} * @memberof Catalog */ url: string; } /** * @export * @enum {string} */ export enum CatalogTypeEnum { Official = 'official', Community = 'community' } /** * * @export * @interface Category */ export interface Category { /** * ID is the unique id of the category * @type {number} * @memberof Category */ id: number; /** * Name of category * @type {string} * @memberof Category */ name: string; /** * List of tags associated with the category * @type {Array<Tag>} * @memberof Category */ tags: Array<Tag>; } /** * * @export * @interface GetResponseBody */ export interface GetResponseBody { /** * User rating for resource * @type {number} * @memberof GetResponseBody */ rating: number; } /** * Describes the services and their status * @export * @interface HubService */ export interface HubService { /** * Details of the error if any * @type {string} * @memberof HubService */ error?: string; /** * Name of the service * @type {string} * @memberof HubService */ name: string; /** * Status of the service * @type {string} * @memberof HubService */ status: HubServiceStatusEnum; } /** * @export * @enum {string} */ export enum HubServiceStatusEnum { Ok = 'ok', Error = 'error' } /** * * @export * @interface InfoResponseBody */ export interface InfoResponseBody { /** * * @type {UserData} * @memberof InfoResponseBody */ data: UserData; } /** * * @export * @interface Job */ export interface Job { /** * Name of the catalog * @type {string} * @memberof Job */ catalogName: string; /** * id of the job * @type {number} * @memberof Job */ id: number; /** * status of the job * @type {string} * @memberof Job */ status: string; } /** * * @export * @interface ListResponseBody */ export interface ListResponseBody { /** * * @type {Array<Category>} * @memberof ListResponseBody */ data?: Array<Category>; } /** * Invalid request body * @export * @interface ModelError */ export interface ModelError { /** * Is the error a server-side fault? * @type {boolean} * @memberof ModelError */ fault: boolean; /** * ID is a unique identifier for this particular occurrence of the problem. * @type {string} * @memberof ModelError */ id: string; /** * Message is a human-readable explanation specific to this occurrence of the problem. * @type {string} * @memberof ModelError */ message: string; /** * Name is the name of this class of errors. * @type {string} * @memberof ModelError */ name: string; /** * Is the error temporary? * @type {boolean} * @memberof ModelError */ temporary: boolean; /** * Is the error a timeout? * @type {boolean} * @memberof ModelError */ timeout: boolean; } /** * * @export * @interface NewRefreshTokenResponseBody */ export interface NewRefreshTokenResponseBody { /** * * @type {RefreshToken} * @memberof NewRefreshTokenResponseBody */ data: RefreshToken; } /** * * @export * @interface RefreshAccessTokenResponseBody */ export interface RefreshAccessTokenResponseBody { /** * * @type {AccessToken} * @memberof RefreshAccessTokenResponseBody */ data: AccessToken; } /** * * @export * @interface RefreshConfigResponseBody */ export interface RefreshConfigResponseBody { /** * Config file checksum * @type {string} * @memberof RefreshConfigResponseBody */ checksum: string; } /** * Refresh Token for User * @export * @interface RefreshToken */ export interface RefreshToken { /** * * @type {Token} * @memberof RefreshToken */ refresh?: Token; } /** * * @export * @interface Resource */ export interface Resource { /** * * @type {ResourceData} * @memberof Resource */ data: ResourceData; } /** * The resource type describes resource information. * @export * @interface ResourceData */ export interface ResourceData { /** * * @type {Catalog} * @memberof ResourceData */ catalog: Catalog; /** * ID is the unique id of the resource * @type {number} * @memberof ResourceData */ id: number; /** * Kind of resource * @type {string} * @memberof ResourceData */ kind: string; /** * * @type {ResourceVersionData} * @memberof ResourceData */ latestVersion: ResourceVersionData; /** * Name of resource * @type {string} * @memberof ResourceData */ name: string; /** * Rating of resource * @type {number} * @memberof ResourceData */ rating: number; /** * Tags related to resource * @type {Array<Tag>} * @memberof ResourceData */ tags: Array<Tag>; /** * List of all versions of a resource * @type {Array<ResourceVersionData>} * @memberof ResourceData */ versions: Array<ResourceVersionData>; } /** * * @export * @interface ResourceVersion */ export interface ResourceVersion { /** * * @type {ResourceVersionData} * @memberof ResourceVersion */ data: ResourceVersionData; } /** * The Version result type describes resource\'s version information. * @export * @interface ResourceVersionData */ export interface ResourceVersionData { /** * Description of version * @type {string} * @memberof ResourceVersionData */ description: string; /** * Display name of version * @type {string} * @memberof ResourceVersionData */ displayName: string; /** * ID is the unique id of resource\'s version * @type {number} * @memberof ResourceVersionData */ id: number; /** * Minimum pipelines version the resource\'s version is compatible with * @type {string} * @memberof ResourceVersionData */ minPipelinesVersion: string; /** * Raw URL of resource\'s yaml file of the version * @type {string} * @memberof ResourceVersionData */ rawURL: string; /** * * @type {ResourceData} * @memberof ResourceVersionData */ resource: ResourceData; /** * Timestamp when version was last updated * @type {string} * @memberof ResourceVersionData */ updatedAt: string; /** * Version of resource * @type {string} * @memberof ResourceVersionData */ version: string; /** * Web URL of resource\'s yaml file of the version * @type {string} * @memberof ResourceVersionData */ webURL: string; } /** * * @export * @interface ResourceVersions */ export interface ResourceVersions { /** * * @type {Versions} * @memberof ResourceVersions */ data: Versions; } /** * * @export * @interface Resources */ export interface Resources { /** * * @type {Array<ResourceData>} * @memberof Resources */ data: Array<ResourceData>; } /** * * @export * @interface StatusResponseBody */ export interface StatusResponseBody { /** * List of services and their status * @type {Array<HubService>} * @memberof StatusResponseBody */ services?: Array<HubService>; } /** * * @export * @interface Tag */ export interface Tag { /** * ID is the unique id of tag * @type {number} * @memberof Tag */ id: number; /** * Name of tag * @type {string} * @memberof Tag */ name: string; } /** * Token includes the JWT, Expire Duration & Time * @export * @interface Token */ export interface Token { /** * Time the token will expires at * @type {number} * @memberof Token */ expiresAt: number; /** * Duration the token will Expire In * @type {string} * @memberof Token */ refreshInterval: string; /** * JWT * @type {string} * @memberof Token */ token: string; } /** * * @export * @interface UpdateAgentRequestBody */ export interface UpdateAgentRequestBody { /** * Name of Agent * @type {string} * @memberof UpdateAgentRequestBody */ name: string; /** * Scopes required for Agent * @type {Array<string>} * @memberof UpdateAgentRequestBody */ scopes: Array<string>; } /** * * @export * @interface UpdateAgentResponseBody */ export interface UpdateAgentResponseBody { /** * Agent JWT * @type {string} * @memberof UpdateAgentResponseBody */ token: string; } /** * * @export * @interface UpdateRequestBody */ export interface UpdateRequestBody { /** * User rating for resource * @type {number} * @memberof UpdateRequestBody */ rating: number; } /** * Github user Information * @export * @interface UserData */ export interface UserData { /** * Github user\'s profile picture url * @type {string} * @memberof UserData */ avatarUrl: string; /** * Github id of User * @type {string} * @memberof UserData */ githubId: string; /** * Github user name * @type {string} * @memberof UserData */ name: string; } /** * The Versions type describes response for versions by resource id API. * @export * @interface Versions */ export interface Versions { /** * * @type {ResourceVersionData} * @memberof Versions */ latest: ResourceVersionData; /** * List of all versions of resource * @type {Array<ResourceVersionData>} * @memberof Versions */ versions: Array<ResourceVersionData>; } /** * AdminApi - axios parameter creator * @export */ export const AdminApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Refresh the changes in config file * @summary RefreshConfig admin * @param {*} [options] Override http request option. * @throws {RequiredError} */ adminRefreshConfig: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/system/config/refresh`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Create or Update an agent user with required scopes * @summary UpdateAgent admin * @param {UpdateAgentRequestBody} updateAgentRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ adminUpdateAgent: async (updateAgentRequestBody: UpdateAgentRequestBody, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'updateAgentRequestBody' is not null or undefined if (updateAgentRequestBody === null || updateAgentRequestBody === undefined) { throw new RequiredError('updateAgentRequestBody','Required parameter updateAgentRequestBody was null or undefined when calling adminUpdateAgent.'); } const localVarPath = `/system/user/agent`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof updateAgentRequestBody !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(updateAgentRequestBody !== undefined ? updateAgentRequestBody : {}) : (updateAgentRequestBody || ""); return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * AdminApi - functional programming interface * @export */ export const AdminApiFp = function(configuration?: Configuration) { return { /** * Refresh the changes in config file * @summary RefreshConfig admin * @param {*} [options] Override http request option. * @throws {RequiredError} */ async adminRefreshConfig(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<RefreshConfigResponseBody>> { const localVarAxiosArgs = await AdminApiAxiosParamCreator(configuration).adminRefreshConfig(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Create or Update an agent user with required scopes * @summary UpdateAgent admin * @param {UpdateAgentRequestBody} updateAgentRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ async adminUpdateAgent(updateAgentRequestBody: UpdateAgentRequestBody, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<UpdateAgentResponseBody>> { const localVarAxiosArgs = await AdminApiAxiosParamCreator(configuration).adminUpdateAgent(updateAgentRequestBody, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * AdminApi - factory interface * @export */ export const AdminApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Refresh the changes in config file * @summary RefreshConfig admin * @param {*} [options] Override http request option. * @throws {RequiredError} */ adminRefreshConfig(options?: any): AxiosPromise<RefreshConfigResponseBody> { return AdminApiFp(configuration).adminRefreshConfig(options).then((request) => request(axios, basePath)); }, /** * Create or Update an agent user with required scopes * @summary UpdateAgent admin * @param {UpdateAgentRequestBody} updateAgentRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ adminUpdateAgent(updateAgentRequestBody: UpdateAgentRequestBody, options?: any): AxiosPromise<UpdateAgentResponseBody> { return AdminApiFp(configuration).adminUpdateAgent(updateAgentRequestBody, options).then((request) => request(axios, basePath)); }, }; }; /** * AdminApi - object-oriented interface * @export * @class AdminApi * @extends {BaseAPI} */ export class AdminApi extends BaseAPI { /** * Refresh the changes in config file * @summary RefreshConfig admin * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AdminApi */ public adminRefreshConfig(options?: any) { return AdminApiFp(this.configuration).adminRefreshConfig(options).then((request) => request(this.axios, this.basePath)); } /** * Create or Update an agent user with required scopes * @summary UpdateAgent admin * @param {UpdateAgentRequestBody} updateAgentRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AdminApi */ public adminUpdateAgent(updateAgentRequestBody: UpdateAgentRequestBody, options?: any) { return AdminApiFp(this.configuration).adminUpdateAgent(updateAgentRequestBody, options).then((request) => request(this.axios, this.basePath)); } } /** * AuthApi - axios parameter creator * @export */ export const AuthApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Authenticates users against GitHub OAuth * @summary Authenticate auth * @param {string} code OAuth Authorization code of User * @param {*} [options] Override http request option. * @throws {RequiredError} */ authAuthenticate: async (code: string, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'code' is not null or undefined if (code === null || code === undefined) { throw new RequiredError('code','Required parameter code was null or undefined when calling authAuthenticate.'); } const localVarPath = `/auth/login`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; if (code !== undefined) { localVarQueryParameter['code'] = code; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * AuthApi - functional programming interface * @export */ export const AuthApiFp = function(configuration?: Configuration) { return { /** * Authenticates users against GitHub OAuth * @summary Authenticate auth * @param {string} code OAuth Authorization code of User * @param {*} [options] Override http request option. * @throws {RequiredError} */ async authAuthenticate(code: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<AuthenticateResponseBody>> { const localVarAxiosArgs = await AuthApiAxiosParamCreator(configuration).authAuthenticate(code, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * AuthApi - factory interface * @export */ export const AuthApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Authenticates users against GitHub OAuth * @summary Authenticate auth * @param {string} code OAuth Authorization code of User * @param {*} [options] Override http request option. * @throws {RequiredError} */ authAuthenticate(code: string, options?: any): AxiosPromise<AuthenticateResponseBody> { return AuthApiFp(configuration).authAuthenticate(code, options).then((request) => request(axios, basePath)); }, }; }; /** * AuthApi - object-oriented interface * @export * @class AuthApi * @extends {BaseAPI} */ export class AuthApi extends BaseAPI { /** * Authenticates users against GitHub OAuth * @summary Authenticate auth * @param {string} code OAuth Authorization code of User * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AuthApi */ public authAuthenticate(code: string, options?: any) { return AuthApiFp(this.configuration).authAuthenticate(code, options).then((request) => request(this.axios, this.basePath)); } } /** * CatalogApi - axios parameter creator * @export */ export const CatalogApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Refresh a Catalog by it\'s name * @summary Refresh catalog * @param {string} catalogName Name of catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ catalogRefresh: async (catalogName: string, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'catalogName' is not null or undefined if (catalogName === null || catalogName === undefined) { throw new RequiredError('catalogName','Required parameter catalogName was null or undefined when calling catalogRefresh.'); } const localVarPath = `/catalog/{catalogName}/refresh` .replace(`{${"catalogName"}}`, encodeURIComponent(String(catalogName))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Refresh all catalogs * @summary RefreshAll catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ catalogRefreshAll: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/catalog/refresh`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * CatalogApi - functional programming interface * @export */ export const CatalogApiFp = function(configuration?: Configuration) { return { /** * Refresh a Catalog by it\'s name * @summary Refresh catalog * @param {string} catalogName Name of catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ async catalogRefresh(catalogName: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Job>> { const localVarAxiosArgs = await CatalogApiAxiosParamCreator(configuration).catalogRefresh(catalogName, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Refresh all catalogs * @summary RefreshAll catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ async catalogRefreshAll(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<Job>>> { const localVarAxiosArgs = await CatalogApiAxiosParamCreator(configuration).catalogRefreshAll(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * CatalogApi - factory interface * @export */ export const CatalogApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Refresh a Catalog by it\'s name * @summary Refresh catalog * @param {string} catalogName Name of catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ catalogRefresh(catalogName: string, options?: any): AxiosPromise<Job> { return CatalogApiFp(configuration).catalogRefresh(catalogName, options).then((request) => request(axios, basePath)); }, /** * Refresh all catalogs * @summary RefreshAll catalog * @param {*} [options] Override http request option. * @throws {RequiredError} */ catalogRefreshAll(options?: any): AxiosPromise<Array<Job>> { return CatalogApiFp(configuration).catalogRefreshAll(options).then((request) => request(axios, basePath)); }, }; }; /** * CatalogApi - object-oriented interface * @export * @class CatalogApi * @extends {BaseAPI} */ export class CatalogApi extends BaseAPI { /** * Refresh a Catalog by it\'s name * @summary Refresh catalog * @param {string} catalogName Name of catalog * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CatalogApi */ public catalogRefresh(catalogName: string, options?: any) { return CatalogApiFp(this.configuration).catalogRefresh(catalogName, options).then((request) => request(this.axios, this.basePath)); } /** * Refresh all catalogs * @summary RefreshAll catalog * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CatalogApi */ public catalogRefreshAll(options?: any) { return CatalogApiFp(this.configuration).catalogRefreshAll(options).then((request) => request(this.axios, this.basePath)); } } /** * CategoryApi - axios parameter creator * @export */ export const CategoryApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ categoryList: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/categories`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ categoryList1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/v1/categories`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * CategoryApi - functional programming interface * @export */ export const CategoryApiFp = function(configuration?: Configuration) { return { /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ async categoryList(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListResponseBody>> { const localVarAxiosArgs = await CategoryApiAxiosParamCreator(configuration).categoryList(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ async categoryList1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListResponseBody>> { const localVarAxiosArgs = await CategoryApiAxiosParamCreator(configuration).categoryList1(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * CategoryApi - factory interface * @export */ export const CategoryApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ categoryList(options?: any): AxiosPromise<ListResponseBody> { return CategoryApiFp(configuration).categoryList(options).then((request) => request(axios, basePath)); }, /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} */ categoryList1(options?: any): AxiosPromise<ListResponseBody> { return CategoryApiFp(configuration).categoryList1(options).then((request) => request(axios, basePath)); }, }; }; /** * CategoryApi - object-oriented interface * @export * @class CategoryApi * @extends {BaseAPI} */ export class CategoryApi extends BaseAPI { /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CategoryApi */ public categoryList(options?: any) { return CategoryApiFp(this.configuration).categoryList(options).then((request) => request(this.axios, this.basePath)); } /** * List all categories along with their tags sorted by name * @summary list category * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CategoryApi */ public categoryList1(options?: any) { return CategoryApiFp(this.configuration).categoryList1(options).then((request) => request(this.axios, this.basePath)); } } /** * RatingApi - axios parameter creator * @export */ export const RatingApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Find user\'s rating for a resource * @summary Get rating * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ ratingGet: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling ratingGet.'); } const localVarPath = `/resource/{id}/rating` .replace(`{${"id"}}`, encodeURIComponent(String(id))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Update user\'s rating for a resource * @summary Update rating * @param {number} id ID of a resource * @param {UpdateRequestBody} updateRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ ratingUpdate: async (id: number, updateRequestBody: UpdateRequestBody, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling ratingUpdate.'); } // verify required parameter 'updateRequestBody' is not null or undefined if (updateRequestBody === null || updateRequestBody === undefined) { throw new RequiredError('updateRequestBody','Required parameter updateRequestBody was null or undefined when calling ratingUpdate.'); } const localVarPath = `/resource/{id}/rating` .replace(`{${"id"}}`, encodeURIComponent(String(id))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof updateRequestBody !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(updateRequestBody !== undefined ? updateRequestBody : {}) : (updateRequestBody || ""); return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * RatingApi - functional programming interface * @export */ export const RatingApiFp = function(configuration?: Configuration) { return { /** * Find user\'s rating for a resource * @summary Get rating * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async ratingGet(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GetResponseBody>> { const localVarAxiosArgs = await RatingApiAxiosParamCreator(configuration).ratingGet(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Update user\'s rating for a resource * @summary Update rating * @param {number} id ID of a resource * @param {UpdateRequestBody} updateRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ async ratingUpdate(id: number, updateRequestBody: UpdateRequestBody, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await RatingApiAxiosParamCreator(configuration).ratingUpdate(id, updateRequestBody, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * RatingApi - factory interface * @export */ export const RatingApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Find user\'s rating for a resource * @summary Get rating * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ ratingGet(id: number, options?: any): AxiosPromise<GetResponseBody> { return RatingApiFp(configuration).ratingGet(id, options).then((request) => request(axios, basePath)); }, /** * Update user\'s rating for a resource * @summary Update rating * @param {number} id ID of a resource * @param {UpdateRequestBody} updateRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} */ ratingUpdate(id: number, updateRequestBody: UpdateRequestBody, options?: any): AxiosPromise<void> { return RatingApiFp(configuration).ratingUpdate(id, updateRequestBody, options).then((request) => request(axios, basePath)); }, }; }; /** * RatingApi - object-oriented interface * @export * @class RatingApi * @extends {BaseAPI} */ export class RatingApi extends BaseAPI { /** * Find user\'s rating for a resource * @summary Get rating * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof RatingApi */ public ratingGet(id: number, options?: any) { return RatingApiFp(this.configuration).ratingGet(id, options).then((request) => request(this.axios, this.basePath)); } /** * Update user\'s rating for a resource * @summary Update rating * @param {number} id ID of a resource * @param {UpdateRequestBody} updateRequestBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof RatingApi */ public ratingUpdate(id: number, updateRequestBody: UpdateRequestBody, options?: any) { return RatingApiFp(this.configuration).ratingUpdate(id, updateRequestBody, options).then((request) => request(this.axios, this.basePath)); } } /** * ResourceApi - axios parameter creator * @export */ export const ResourceApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Find resources using name of catalog, resource name and kind of resource * @summary ByCatalogKindName resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name Name of resource * @param {string} [minpipelinesversion] To find resource compatible with a Tekton pipelines version, use this param * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByCatalogKindName: async (catalog: string, kind: 'task' | 'pipeline', name: string, minpipelinesversion?: string, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'catalog' is not null or undefined if (catalog === null || catalog === undefined) { throw new RequiredError('catalog','Required parameter catalog was null or undefined when calling resourceByCatalogKindName.'); } // verify required parameter 'kind' is not null or undefined if (kind === null || kind === undefined) { throw new RequiredError('kind','Required parameter kind was null or undefined when calling resourceByCatalogKindName.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('name','Required parameter name was null or undefined when calling resourceByCatalogKindName.'); } const localVarPath = `/resource/{catalog}/{kind}/{name}` .replace(`{${"catalog"}}`, encodeURIComponent(String(catalog))) .replace(`{${"kind"}}`, encodeURIComponent(String(kind))) .replace(`{${"name"}}`, encodeURIComponent(String(name))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; if (minpipelinesversion !== undefined) { localVarQueryParameter['minpipelinesversion'] = minpipelinesversion; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Find resource using name of catalog & name, kind and version of resource * @summary ByCatalogKindNameVersion resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name name of resource * @param {string} version version of resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByCatalogKindNameVersion: async (catalog: string, kind: 'task' | 'pipeline', name: string, version: string, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'catalog' is not null or undefined if (catalog === null || catalog === undefined) { throw new RequiredError('catalog','Required parameter catalog was null or undefined when calling resourceByCatalogKindNameVersion.'); } // verify required parameter 'kind' is not null or undefined if (kind === null || kind === undefined) { throw new RequiredError('kind','Required parameter kind was null or undefined when calling resourceByCatalogKindNameVersion.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('name','Required parameter name was null or undefined when calling resourceByCatalogKindNameVersion.'); } // verify required parameter 'version' is not null or undefined if (version === null || version === undefined) { throw new RequiredError('version','Required parameter version was null or undefined when calling resourceByCatalogKindNameVersion.'); } const localVarPath = `/resource/{catalog}/{kind}/{name}/{version}` .replace(`{${"catalog"}}`, encodeURIComponent(String(catalog))) .replace(`{${"kind"}}`, encodeURIComponent(String(kind))) .replace(`{${"name"}}`, encodeURIComponent(String(name))) .replace(`{${"version"}}`, encodeURIComponent(String(version))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Find a resource using it\'s id * @summary ById resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceById: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling resourceById.'); } const localVarPath = `/resource/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Find a resource using its version\'s id * @summary ByVersionId resource * @param {number} versionID Version ID of a resource\&#39;s version * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByVersionId: async (versionID: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'versionID' is not null or undefined if (versionID === null || versionID === undefined) { throw new RequiredError('versionID','Required parameter versionID was null or undefined when calling resourceByVersionId.'); } const localVarPath = `/resource/version/{versionID}` .replace(`{${"versionID"}}`, encodeURIComponent(String(versionID))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * List all resources sorted by rating and name * @summary List resource * @param {number} [limit] Maximum number of resources to be returned * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceList: async (limit?: number, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/resources`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; if (limit !== undefined) { localVarQueryParameter['limit'] = limit; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Find resources by a combination of name, kind , catalog and tags * @summary Query resource * @param {string} [name] Name of resource * @param {Array<string>} [catalogs] Catalogs of resource to filter by * @param {Array<string>} [kinds] Kinds of resource to filter by * @param {Array<string>} [tags] Tags associated with a resource to filter by * @param {number} [limit] Maximum number of resources to be returned * @param {'exact' | 'contains'} [match] Strategy used to find matching resources * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceQuery: async (name?: string, catalogs?: Array<string>, kinds?: Array<string>, tags?: Array<string>, limit?: number, match?: 'exact' | 'contains', categories?: Array<string>, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/query`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; if (name !== undefined) { localVarQueryParameter['name'] = name; } if (catalogs) { localVarQueryParameter['catalogs'] = catalogs; } if (kinds) { localVarQueryParameter['kinds'] = kinds; } if (tags) { localVarQueryParameter['tags'] = tags; } if (categories) { localVarQueryParameter['categories'] = categories; } if (limit !== undefined) { localVarQueryParameter['limit'] = limit; } if (match !== undefined) { localVarQueryParameter['match'] = match; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Find all versions of a resource by its id * @summary VersionsByID resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceVersionsByID: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling resourceVersionsByID.'); } const localVarPath = `/resource/{id}/versions` .replace(`{${"id"}}`, encodeURIComponent(String(id))); const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * ResourceApi - functional programming interface * @export */ export const ResourceApiFp = function(configuration?: Configuration) { return { /** * Find resources using name of catalog, resource name and kind of resource * @summary ByCatalogKindName resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name Name of resource * @param {string} [minpipelinesversion] To find resource compatible with a Tekton pipelines version, use this param * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceByCatalogKindName(catalog: string, kind: 'task' | 'pipeline', name: string, minpipelinesversion?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Resource>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceByCatalogKindName(catalog, kind, name, minpipelinesversion, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Find resource using name of catalog & name, kind and version of resource * @summary ByCatalogKindNameVersion resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name name of resource * @param {string} version version of resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceByCatalogKindNameVersion(catalog: string, kind: 'task' | 'pipeline', name: string, version: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ResourceVersion>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceByCatalogKindNameVersion(catalog, kind, name, version, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Find a resource using it\'s id * @summary ById resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceById(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Resource>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceById(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Find a resource using its version\'s id * @summary ByVersionId resource * @param {number} versionID Version ID of a resource\&#39;s version * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceByVersionId(versionID: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ResourceVersion>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceByVersionId(versionID, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * List all resources sorted by rating and name * @summary List resource * @param {number} [limit] Maximum number of resources to be returned * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceList(limit?: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Resources>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceList(limit, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Find resources by a combination of name, kind , catalog and tags * @summary Query resource * @param {string} [name] Name of resource * @param {Array<string>} [catalogs] Catalogs of resource to filter by * @param {Array<string>} [kinds] Kinds of resource to filter by * @param {Array<string>} [tags] Tags associated with a resource to filter by * @param {number} [limit] Maximum number of resources to be returned * @param {'exact' | 'contains'} [match] Strategy used to find matching resources * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceQuery(name?: string, catalogs?: Array<string>, kinds?: Array<string>, tags?: Array<string>, limit?: number, match?: 'exact' | 'contains', categories?: Array<string>, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Resources>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceQuery(name, catalogs, kinds, tags, limit, match, categories, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Find all versions of a resource by its id * @summary VersionsByID resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async resourceVersionsByID(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ResourceVersions>> { const localVarAxiosArgs = await ResourceApiAxiosParamCreator(configuration).resourceVersionsByID(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * ResourceApi - factory interface * @export */ export const ResourceApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Find resources using name of catalog, resource name and kind of resource * @summary ByCatalogKindName resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name Name of resource * @param {string} [minpipelinesversion] To find resource compatible with a Tekton pipelines version, use this param * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByCatalogKindName(catalog: string, kind: 'task' | 'pipeline', name: string, minpipelinesversion?: string, options?: any): AxiosPromise<Resource> { return ResourceApiFp(configuration).resourceByCatalogKindName(catalog, kind, name, minpipelinesversion, options).then((request) => request(axios, basePath)); }, /** * Find resource using name of catalog & name, kind and version of resource * @summary ByCatalogKindNameVersion resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name name of resource * @param {string} version version of resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByCatalogKindNameVersion(catalog: string, kind: 'task' | 'pipeline', name: string, version: string, options?: any): AxiosPromise<ResourceVersion> { return ResourceApiFp(configuration).resourceByCatalogKindNameVersion(catalog, kind, name, version, options).then((request) => request(axios, basePath)); }, /** * Find a resource using it\'s id * @summary ById resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceById(id: number, options?: any): AxiosPromise<Resource> { return ResourceApiFp(configuration).resourceById(id, options).then((request) => request(axios, basePath)); }, /** * Find a resource using its version\'s id * @summary ByVersionId resource * @param {number} versionID Version ID of a resource\&#39;s version * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceByVersionId(versionID: number, options?: any): AxiosPromise<ResourceVersion> { return ResourceApiFp(configuration).resourceByVersionId(versionID, options).then((request) => request(axios, basePath)); }, /** * List all resources sorted by rating and name * @summary List resource * @param {number} [limit] Maximum number of resources to be returned * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceList(limit?: number, options?: any): AxiosPromise<Resources> { return ResourceApiFp(configuration).resourceList(limit, options).then((request) => request(axios, basePath)); }, /** * Find resources by a combination of name, kind , catalog and tags * @summary Query resource * @param {string} [name] Name of resource * @param {Array<string>} [catalogs] Catalogs of resource to filter by * @param {Array<string>} [kinds] Kinds of resource to filter by * @param {Array<string>} [tags] Tags associated with a resource to filter by * @param {number} [limit] Maximum number of resources to be returned * @param {'exact' | 'contains'} [match] Strategy used to find matching resources * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceQuery(name?: string, catalogs?: Array<string>, kinds?: Array<string>, tags?: Array<string>, limit?: number, match?: 'exact' | 'contains', options?: any): AxiosPromise<Resources> { return ResourceApiFp(configuration).resourceQuery(name, catalogs, kinds, tags, limit, match, options).then((request) => request(axios, basePath)); }, /** * Find all versions of a resource by its id * @summary VersionsByID resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ resourceVersionsByID(id: number, options?: any): AxiosPromise<ResourceVersions> { return ResourceApiFp(configuration).resourceVersionsByID(id, options).then((request) => request(axios, basePath)); }, }; }; /** * ResourceApi - object-oriented interface * @export * @class ResourceApi * @extends {BaseAPI} */ export class ResourceApi extends BaseAPI { /** * Find resources using name of catalog, resource name and kind of resource * @summary ByCatalogKindName resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name Name of resource * @param {string} [minpipelinesversion] To find resource compatible with a Tekton pipelines version, use this param * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceByCatalogKindName(catalog: string, kind: 'task' | 'pipeline', name: string, minpipelinesversion?: string, options?: any) { return ResourceApiFp(this.configuration).resourceByCatalogKindName(catalog, kind, name, minpipelinesversion, options).then((request) => request(this.axios, this.basePath)); } /** * Find resource using name of catalog & name, kind and version of resource * @summary ByCatalogKindNameVersion resource * @param {string} catalog name of catalog * @param {'task' | 'pipeline'} kind kind of resource * @param {string} name name of resource * @param {string} version version of resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceByCatalogKindNameVersion(catalog: string, kind: 'task' | 'pipeline', name: string, version: string, options?: any) { return ResourceApiFp(this.configuration).resourceByCatalogKindNameVersion(catalog, kind, name, version, options).then((request) => request(this.axios, this.basePath)); } /** * Find a resource using it\'s id * @summary ById resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceById(id: number, options?: any) { return ResourceApiFp(this.configuration).resourceById(id, options).then((request) => request(this.axios, this.basePath)); } /** * Find a resource using its version\'s id * @summary ByVersionId resource * @param {number} versionID Version ID of a resource\&#39;s version * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceByVersionId(versionID: number, options?: any) { return ResourceApiFp(this.configuration).resourceByVersionId(versionID, options).then((request) => request(this.axios, this.basePath)); } /** * List all resources sorted by rating and name * @summary List resource * @param {number} [limit] Maximum number of resources to be returned * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceList(limit?: number, options?: any) { return ResourceApiFp(this.configuration).resourceList(limit, options).then((request) => request(this.axios, this.basePath)); } /** * Find resources by a combination of name, kind , catalog and tags * @summary Query resource * @param {string} [name] Name of resource * @param {Array<string>} [catalogs] Catalogs of resource to filter by * @param {Array<string>} [kinds] Kinds of resource to filter by * @param {Array<string>} [tags] Tags associated with a resource to filter by * @param {number} [limit] Maximum number of resources to be returned * @param {'exact' | 'contains'} [match] Strategy used to find matching resources * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceQuery(name?: string, catalogs?: Array<string>, kinds?: Array<string>, tags?: Array<string>, limit?: number, match?: 'exact' | 'contains', categories?: Array<string>,options?: any) { return ResourceApiFp(this.configuration).resourceQuery(name, catalogs, kinds, tags, limit, match, categories, options).then((request) => request(this.axios, this.basePath)); } /** * Find all versions of a resource by its id * @summary VersionsByID resource * @param {number} id ID of a resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResourceApi */ public resourceVersionsByID(id: number, options?: any) { return ResourceApiFp(this.configuration).resourceVersionsByID(id, options).then((request) => request(this.axios, this.basePath)); } } /** * StatusApi - axios parameter creator * @export */ export const StatusApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ statusStatus: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ statusStatus1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/v1`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * StatusApi - functional programming interface * @export */ export const StatusApiFp = function(configuration?: Configuration) { return { /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ async statusStatus(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<StatusResponseBody>> { const localVarAxiosArgs = await StatusApiAxiosParamCreator(configuration).statusStatus(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ async statusStatus1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<StatusResponseBody>> { const localVarAxiosArgs = await StatusApiAxiosParamCreator(configuration).statusStatus1(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * StatusApi - factory interface * @export */ export const StatusApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ statusStatus(options?: any): AxiosPromise<StatusResponseBody> { return StatusApiFp(configuration).statusStatus(options).then((request) => request(axios, basePath)); }, /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} */ statusStatus1(options?: any): AxiosPromise<StatusResponseBody> { return StatusApiFp(configuration).statusStatus1(options).then((request) => request(axios, basePath)); }, }; }; /** * StatusApi - object-oriented interface * @export * @class StatusApi * @extends {BaseAPI} */ export class StatusApi extends BaseAPI { /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StatusApi */ public statusStatus(options?: any) { return StatusApiFp(this.configuration).statusStatus(options).then((request) => request(this.axios, this.basePath)); } /** * Return status of the services * @summary Status status * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StatusApi */ public statusStatus1(options?: any) { return StatusApiFp(this.configuration).statusStatus1(options).then((request) => request(this.axios, this.basePath)); } } /** * SwaggerApi - axios parameter creator * @export */ export const SwaggerApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * JSON document containing the API swagger definition * @summary Download gen/http/openapi3.yaml * @param {*} [options] Override http request option. * @throws {RequiredError} */ swaggerSchemaSwaggerJson: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/schema/swagger.json`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * SwaggerApi - functional programming interface * @export */ export const SwaggerApiFp = function(configuration?: Configuration) { return { /** * JSON document containing the API swagger definition * @summary Download gen/http/openapi3.yaml * @param {*} [options] Override http request option. * @throws {RequiredError} */ async swaggerSchemaSwaggerJson(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await SwaggerApiAxiosParamCreator(configuration).swaggerSchemaSwaggerJson(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * SwaggerApi - factory interface * @export */ export const SwaggerApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * JSON document containing the API swagger definition * @summary Download gen/http/openapi3.yaml * @param {*} [options] Override http request option. * @throws {RequiredError} */ swaggerSchemaSwaggerJson(options?: any): AxiosPromise<void> { return SwaggerApiFp(configuration).swaggerSchemaSwaggerJson(options).then((request) => request(axios, basePath)); }, }; }; /** * SwaggerApi - object-oriented interface * @export * @class SwaggerApi * @extends {BaseAPI} */ export class SwaggerApi extends BaseAPI { /** * JSON document containing the API swagger definition * @summary Download gen/http/openapi3.yaml * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SwaggerApi */ public swaggerSchemaSwaggerJson(options?: any) { return SwaggerApiFp(this.configuration).swaggerSchemaSwaggerJson(options).then((request) => request(this.axios, this.basePath)); } } /** * UserApi - axios parameter creator * @export */ export const UserApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Get the user Info * @summary Info user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userInfo: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/user/info`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Get a new refresh token of User * @summary NewRefreshToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userNewRefreshToken: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/user/refresh/refreshtoken`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, /** * Refresh the access token of User * @summary RefreshAccessToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userRefreshAccessToken: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/user/refresh/accesstoken`; const localVarUrlObj = globalImportUrl.parse(localVarPath, true); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication jwt_header_Authorization required // http bearer authentication required if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === 'function' ? configuration.accessToken() : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + accessToken; } localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * UserApi - functional programming interface * @export */ export const UserApiFp = function(configuration?: Configuration) { return { /** * Get the user Info * @summary Info user * @param {*} [options] Override http request option. * @throws {RequiredError} */ async userInfo(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<InfoResponseBody>> { const localVarAxiosArgs = await UserApiAxiosParamCreator(configuration).userInfo(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Get a new refresh token of User * @summary NewRefreshToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ async userNewRefreshToken(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<NewRefreshTokenResponseBody>> { const localVarAxiosArgs = await UserApiAxiosParamCreator(configuration).userNewRefreshToken(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Refresh the access token of User * @summary RefreshAccessToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ async userRefreshAccessToken(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<RefreshAccessTokenResponseBody>> { const localVarAxiosArgs = await UserApiAxiosParamCreator(configuration).userRefreshAccessToken(options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * UserApi - factory interface * @export */ export const UserApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Get the user Info * @summary Info user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userInfo(options?: any): AxiosPromise<InfoResponseBody> { return UserApiFp(configuration).userInfo(options).then((request) => request(axios, basePath)); }, /** * Get a new refresh token of User * @summary NewRefreshToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userNewRefreshToken(options?: any): AxiosPromise<NewRefreshTokenResponseBody> { return UserApiFp(configuration).userNewRefreshToken(options).then((request) => request(axios, basePath)); }, /** * Refresh the access token of User * @summary RefreshAccessToken user * @param {*} [options] Override http request option. * @throws {RequiredError} */ userRefreshAccessToken(options?: any): AxiosPromise<RefreshAccessTokenResponseBody> { return UserApiFp(configuration).userRefreshAccessToken(options).then((request) => request(axios, basePath)); }, }; }; /** * UserApi - object-oriented interface * @export * @class UserApi * @extends {BaseAPI} */ export class UserApi extends BaseAPI { /** * Get the user Info * @summary Info user * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi */ public userInfo(options?: any) { return UserApiFp(this.configuration).userInfo(options).then((request) => request(this.axios, this.basePath)); } /** * Get a new refresh token of User * @summary NewRefreshToken user * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi */ public userNewRefreshToken(options?: any) { return UserApiFp(this.configuration).userNewRefreshToken(options).then((request) => request(this.axios, this.basePath)); } /** * Refresh the access token of User * @summary RefreshAccessToken user * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof UserApi */ public userRefreshAccessToken(options?: any) { return UserApiFp(this.configuration).userRefreshAccessToken(options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import SnippetProvider from "./SnippetProvider"; import Consts from './Consts'; import * as vscode from 'vscode'; const DOMParser = require('xmldom').DOMParser; export default class InsertCommands { static InsertClaimType() { let UserInputTypeList = ['TextBox', 'Radio Single Select', 'Dropdown Single Select', 'Checkbox Multi Select', 'DateTime Dropdown', 'Read only', 'Paragraph', 'Boolean', 'Integer', 'Long', 'String', 'String collection']; let name: string | undefined = 'Default'; let displayName: string | undefined = 'Default'; let userInputType: string | undefined = 'none'; vscode.window.showQuickPick(UserInputTypeList, { placeHolder: 'Select user input type' }) .then(result => { if (!result) return Promise.reject('user cancelled'); userInputType = result }).then(() => { return vscode.window.showInputBox({ prompt: "Provide a name" }) .then(result => { if (!result) return Promise.reject('user cancelled'); name = result; }); }) .then(() => { return vscode.window.showInputBox({ prompt: "Provide a display name that describes the claim type" }) .then(result => { if (!result) return Promise.reject('user cancelled'); displayName = result; }); }) .then(() => { switch (userInputType) { case "TextBox": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_TextBox, name, displayName)); case "Radio Single Select": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_RadioSingleSelect, name, displayName)); case "Dropdown Single Select": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_DropdownSingleSelect, name, displayName)); case "Checkbox Multi Select": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_CheckboxMultiSelect, name, displayName)); case "DateTime Dropdown": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_DateTimeDropdown, name, displayName)); case "Read only": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_Readonly, name, displayName)); case "Paragraph": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_Paragraph, name, displayName)); case "Boolean": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_Boolean, name, displayName)); case "Integer": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_Integer, name, displayName)); case "Long": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_Long, name, displayName)); case "String": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_String, name, displayName)); case "String collection": SnippetProvider.insertText(InsertCommands.GetClaimTypeWithParents(Consts.CLAIM_stringCollection, name, displayName)); } }) .then(() => { return vscode.window.showInformationMessage("For more information, see: [Modify sign up to add new claims and configure user input.](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-configure-signup-self-asserted-custom). To store a custom attributes in Azure AD directory, you need also to change the Claim type name to 'extension_" + name + "' and set the application. For more information, see [Creating and using custom attributes in a custom profile edit policy](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-create-custom-attributes-profile-edit-custom) ") }); } static GetClaimTypeWithParents(xml: string, name, displayName) { // Load the current XML document from the active text editor if (!vscode.window.activeTextEditor) { return xml; } var xmlDoc = new DOMParser().parseFromString(vscode.window.activeTextEditor.document.getText()); // Try to find the BuildingBlocks element in the target XML document. If not exists add a new one var docLookupList = xmlDoc.getElementsByTagName("BuildingBlocks"); if (docLookupList.length == 0) { xml = ' <BuildingBlocks>\r\n <ClaimsSchema>\r\n' + xml + ' </ClaimsSchema>\r\n </BuildingBlocks>\r\n'; } else { // Try to find the ClaimsSchema element in the target XML document. If not exists add a new one var docLookupList = xmlDoc.getElementsByTagName("ClaimsSchema"); if (docLookupList.length == 0) xml = ' <ClaimsSchema>\r\n' + xml + ' </ClaimsSchema>\r\n'; } return xml.replace(/\|/g, " ").replace("{name}", name).replace("{displayName}", displayName); } static InsertTechnicalProfileIdp() { let IdentityProviderList = ['Microsoft', 'Facebook', 'Azure AD', 'Azure AD Multi tenant', 'Google+' , 'LinkedIn', 'Twitter', 'AD-FS', 'Salesforce', 'Amazon']; let idp: string | undefined = 'default'; vscode.window.showQuickPick(IdentityProviderList.sort(), { placeHolder: 'Select an identity provider' }) .then(result => { idp = result; if (!result) return Promise.reject('user cancelled'); switch (idp) { case "Microsoft": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Microsoft)); case "Facebook": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Facebook)); case "Azure AD": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_AzureAD)); case "Azure AD Multi tenant": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_AzueADMulti)); case "Google+": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Google)); case "LinkedIn": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_LinkeIn)); case "Twitter": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Twitter)); case "AD-FS": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_ADFS)); case "Salesforce": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Saleforce)); case "VK": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_VK)); case "Amazon": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileIdpWithParents(Consts.TP_IDP_Amazon)); } }) .then(() => { let title: string = ''; let url: string = ''; switch (idp) { case "Microsoft": title = 'Add Microsoft Account (MSA) as an identity provider using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-msa-idp'; break; case "Facebook": title = ''; url = ''; break; case "Azure AD": title = 'Sign in by using Azure AD accounts'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-setup-aad-custom'; break; case "Azure AD Multi tenant": title = 'Allow users to sign in to a multi-tenant Azure AD identity provider using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-setup-commonaad-custom'; break; case "Google+": title = 'Add Google+ as an OAuth2 identity provider using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-goog-idp'; break; case "LinkedIn": title = 'Add LinkedIn as an identity provider by using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-li-idp'; break; case "Twitter": title = 'Add Twitter as an OAuth1 identity provider by using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-twitter-idp'; break; case "AD-FS": title = 'Add ADFS as a SAML identity provider using custom policies'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-adfs2016-idp'; break; case "Salesforce": title = 'Sign in by using Salesforce accounts via SAML'; url = 'https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-setup-sf-app-custom'; break; case "VK": title = ''; url = ''; break; case "Amazon": title = ''; url = ''; break; } if (title != '') return vscode.window.showInformationMessage("For more information, see: [" + title + "](" + url + ")"); }); } static GetTechnicalProfileIdpWithParents(xml: string) { // Load the current XML document from the active text editor if (!vscode.window.activeTextEditor) { return xml; } var xmlDoc = new DOMParser().parseFromString(vscode.window.activeTextEditor.document.getText()); // Try to find the ClaimsProviders element in the target XML document. If not exists add a new one var docLookupList = xmlDoc.getElementsByTagName("ClaimsProviders"); if (docLookupList.length == 0) { xml = ' <ClaimsProviders>\r\n' + xml + ' </ClaimsProviders>\r\n'; } return xml.replace(/\|/g, " "); } static InsertTechnicalProfileRESTAPI() { let authenticationTypeList = ['None', 'Basic', 'Client Certificate']; let name: string | undefined = 'Default'; let serviceUri: string | undefined = 'https://server-name/api/sign-up'; let authenticationType: string | undefined = 'none'; vscode.window.showInputBox({ prompt: "Provide a name" }) .then(result => { if (!result) return Promise.reject('user cancelled'); name = result; }) .then(() => { return vscode.window.showInputBox({ prompt: "Service URL" }) .then(result => { if (!result) return Promise.reject('user cancelled'); serviceUri = result; }); }) .then(() => { return vscode.window.showQuickPick(authenticationTypeList, { placeHolder: 'Select Authentication Type' }) .then(result => { if (!result) return Promise.reject('user cancelled'); authenticationType = result }); }) .then(() => { switch (authenticationType) { case "None": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileRESTAPIWithParents(Consts.TP_REST_None, name, serviceUri)); case "Basic": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileRESTAPIWithParents(Consts.TP_REST_Basic, name, serviceUri)); case "Client Certificate": SnippetProvider.insertText(InsertCommands.GetTechnicalProfileRESTAPIWithParents(Consts.TP_REST_ClientCertificate, name, serviceUri)); } }) .then(() => { return vscode.window.showInformationMessage("For more information, see: [Integrate REST API claims exchanges in your Azure AD B2C user journey as validation of user input](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-rest-api-netfw)") }); } static GetTechnicalProfileRESTAPIWithParents(xml: string, name: string | any, serviceUri: string | any) { // Load the current XML document from the active text editor if (!vscode.window.activeTextEditor) { return xml; } var xmlDoc = new DOMParser().parseFromString(vscode.window.activeTextEditor.document.getText()); // Check if the custom REST API claims provider already exists var RestClaimsProviderExists: boolean = false; var docLookupList = xmlDoc.getElementsByTagName("ClaimsProvider"); for (var i = 0; i < docLookupList.length; i++) { var subNode = docLookupList[i].getElementsByTagName("DisplayName"); if (subNode != null && subNode.length >0 && subNode[0].textContent === 'Custom REST API') { RestClaimsProviderExists = true; break; } } if (!RestClaimsProviderExists) { xml = '|<ClaimsProvider>\r\n' + '| <DisplayName>Custom REST API</DisplayName>\r\n' + '| <TechnicalProfiles>\r\n' + xml + '| </TechnicalProfiles>\r\n' + '|</ClaimsProvider>\r\n'; } // Try to find the ClaimsProviders element in the target XML document. If not exists add a new one docLookupList = xmlDoc.getElementsByTagName("ClaimsProviders"); if (docLookupList.length == 0) { xml = ' <ClaimsProviders>\r\n' + xml + ' </ClaimsProviders>\r\n'; } return xml.replace(/\|/g, " ").replace("{name}", name).replace("{serviceUri}", serviceUri); } static InsertApplicationInsights() { let instrumentationKey: string | undefined = 'Default'; try { var editor: vscode.TextEditor = vscode.window.activeTextEditor as vscode.TextEditor; var DOMParser = require('xmldom').DOMParser; //https://www.npmjs.com/package/xmldom var xmlDoc = new DOMParser().parseFromString(editor.document.getText(), "application/xml"); // Check if policy is a relying party var xmlRelyingParty = xmlDoc.getElementsByTagName("RelyingParty"); if (xmlRelyingParty.length == 0) { vscode.window.showWarningMessage("Application insights trace can not be added to this policy. You can add Application insights trace only to relying party policy."); return; } vscode.window.showInputBox({ prompt: "Type your Application Insights instrumentation key." }) .then(result => { if (!result) return Promise.reject('user cancelled'); instrumentationKey = result; }) .then(() => { SnippetProvider.insertText(Consts.ApplicationInsightsDebugMode.replace("{instrumentationKey}", instrumentationKey as string)); }) .then(() => { return vscode.window.showInformationMessage("See the commets how to set the policy deployment mode to debug, and user journey recorder endpoint. " + "For more information, see: [Azure Active Directory B2C: Collecting Logs](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-troubleshoot-custom)") }); } catch (e) { console.log(e.message) } } }
the_stack
import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as iam from '@aws-cdk/aws-iam'; import * as neptune from '@aws-cdk/aws-neptune'; import * as ecs from '@aws-cdk/aws-ecs'; import * as es from '@aws-cdk/aws-elasticsearch'; import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; import {Bucket} from '@aws-cdk/aws-s3'; export interface AmundsenStackProps extends cdk.StackProps { vpc: ec2.Vpc; ingressSecurityGroup: ec2.SecurityGroup; airflowS3Bucket: Bucket; } export class AmundsenStack extends cdk.Stack { readonly fargateCluster : ecs.Cluster; readonly esDomain: es.CfnDomain; readonly neptuneCluster: neptune.CfnDBCluster; constructor(scope: cdk.App, id: string, props: AmundsenStackProps) { super(scope, id, props); const application = this.node.tryGetContext('application'); const environment = this.node.tryGetContext('environment'); var subnets = props.vpc.privateSubnets.map((a) => { return a.subnetId; }); // Elasticsearch Cluster // Assumes Service Linked Role for Elasticsearch has been created. const iamPolicy = new iam.PolicyStatement({ resources: [ `arn:aws:es:${this.region}:${this.account}:domain/*` ], actions: [ "es:*" ], effect: iam.Effect.ALLOW, principals: [ new iam.AnyPrincipal() ] }); const iamPolicyDoc = new iam.PolicyDocument({statements: [iamPolicy]}); this.esDomain = new es.CfnDomain(this, 'AmundsenESDomain', { domainName: `${application}-${environment}-es-domain`, elasticsearchClusterConfig: { instanceCount: 1, instanceType: 't3.small.elasticsearch', }, ebsOptions: { ebsEnabled: true, volumeSize: 10, }, elasticsearchVersion: '6.7', vpcOptions: { securityGroupIds: [props.ingressSecurityGroup.securityGroupId], subnetIds: [props.vpc.privateSubnets[0].subnetId] }, accessPolicies: iamPolicyDoc, }); const NeptuneCloudWatchPolicyStatement = new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: [ 'logs:CreateLogGroup', 'logs:PutRetentionPolicy', 'logs:CreateLogStream', 'logs:PutLogEvents', 'logs:DescriptLogStreams', 'logs:GetLogEvents' ], resources: [ `arn:${this.partition}:logs:${this.account}:${this.region}:log-group:/aws/neptune/*`, `arn:${this.partition}:logs:${this.account}:${this.region}:log-group:/aws/neptune/*:log-stream:*` ] } ); const NeptuneCloudWatchPolicyDocument = new iam.PolicyDocument(); NeptuneCloudWatchPolicyDocument.addStatements(NeptuneCloudWatchPolicyStatement); const NeptuneCloudWatchPolicy = new iam.ManagedPolicy(this, 'NeptuneS3Policy', { description: 'An IAM Policy that allows Neptune cluster log events to be sent to CloudWatch', managedPolicyName: `${application}-${environment}-neptune-cloudwatch-policy`, document: NeptuneCloudWatchPolicyDocument }); const NeptuneS3PolicyStatement = new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: [ 's3:Get*', 's3:List*', "es:ESHttpGet", "es:ESHttpPut", "es:ESHttpPost", "es:ESHttpHead" ], resources: [ `arn:aws:s3:::*`, `arn:aws:es:${this.region}:${this.account}:domain/*`, ] } ); const NeptuneS3PolicyDocument = new iam.PolicyDocument(); NeptuneS3PolicyDocument.addStatements(NeptuneS3PolicyStatement); const NeptuneS3Policy = new iam.ManagedPolicy(this, 'NeptuneS3PolicyDocument', { description: 'An IAM Policy that allows s3 and elasticsearch access', managedPolicyName: `${application}-${environment}-neptune-s3-policy`, document: NeptuneS3PolicyDocument }); const neptuneRole = new iam.Role(this, 'NeptuneRole', { roleName: `${application}-${environment}-neptune-role`, assumedBy: new iam.ServicePrincipal('rds.amazonaws.com'), managedPolicies: [ NeptuneS3Policy, NeptuneCloudWatchPolicy ] }); const neptuneSubnetGroup = new neptune.CfnDBSubnetGroup(this, 'NeptuneSubnetGroup', { dbSubnetGroupDescription: 'private subnets', dbSubnetGroupName: `${application}-${environment}-neptune-subnet-group`, subnetIds: subnets }); const neptuneClusterParameterGroup = new neptune.CfnDBClusterParameterGroup(this, 'NeptuneClusterParameterGroup', { name: `${application}-${environment}-neptune-cluster-pg`, description: 'Neptune cluster parameter group', family: 'neptune1', parameters: { neptune_enable_audit_log: 1 }, }); new neptune.CfnDBClusterParameterGroup(this, 'NeptuneDBParameterGroup', { name: `${application}-${environment}-neptune-db-pg`, description: 'Neptune db parameter group', family: 'neptune1', parameters: { neptune_query_timeout: 120000 }, }); this.neptuneCluster = new neptune.CfnDBCluster(this, 'NeptuneCluster', { dbClusterParameterGroupName: neptuneClusterParameterGroup.name, backupRetentionPeriod: 7, associatedRoles: [ { roleArn: neptuneRole.roleArn, featureName: 'neptune-role' } ], dbClusterIdentifier: `${application}-${environment}-neptune-cluster`, dbSubnetGroupName: neptuneSubnetGroup.dbSubnetGroupName, iamAuthEnabled: true, port: 8182, preferredBackupWindow: '02:00-03:00', preferredMaintenanceWindow: 'mon:03:00-mon:04:00', storageEncrypted: true, vpcSecurityGroupIds: [ props.ingressSecurityGroup.securityGroupId ] }); new neptune.CfnDBInstance(this, 'NeptuneInstance', { dbInstanceClass: 'db.t3.medium', allowMajorVersionUpgrade: true, autoMinorVersionUpgrade: true, availabilityZone: props.vpc.availabilityZones[0], dbClusterIdentifier: `${application}-${environment}-neptune-cluster`, dbInstanceIdentifier: `${application}-${environment}-neptune-instance`, dbSubnetGroupName: neptuneSubnetGroup.dbSubnetGroupName, preferredMaintenanceWindow: 'mon:03:00-mon:04:00' }).addDependsOn(this.neptuneCluster); // Fargate Cluster this.fargateCluster = new ecs.Cluster(this, 'FargateCluster', { clusterName: `${application}-${environment}-amundsen-cluster`, vpc: props.vpc, containerInsights: true, }); const executionRole = new iam.Role(this, 'ExecutionRole', { roleName: `${application}-${environment}-amundsen-execution-role`, assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy') ] }); const taskRole = new iam.Role(this, 'TaskRole', { roleName: `${application}-${environment}-amundsen-task-role`, assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy') ] }); const taskPolicy = new iam.Policy(this, 'TaskPolicy', { policyName: `${application}-${environment}-amundsen-container-policy`, roles: [ taskRole ], }); taskPolicy.addStatements(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", ], resources: [ `arn:aws:logs:${this.region}:${this.account}:log-group:*:log-stream:*`, `arn:aws:logs:${this.region}:${this.account}:log-group:*`, ], })); // Add an ES policy to a Role taskPolicy.addStatements( new iam.PolicyStatement({ resources: [ `arn:aws:es:${this.region}:${this.account}:domain/*`, `arn:aws:rds:${this.region}:${this.account}:cluster/*`, `arn:aws:s3:::*`, `arn:aws:neptune-db:${this.region}:${this.account}:cluster-*`, ], actions: [ "es:ESHttpGet", "es:ESHttpPut", "es:ESHttpPost", "es:ESHttpHead", "s3:Get*", "s3:List*", "neptune-db:*" ], effect: iam.Effect.ALLOW, })); const amundsenFrontend = new ecs.FargateTaskDefinition(this, 'AmundsenFrontend', { cpu: 1024, executionRole: executionRole, memoryLimitMiB: 4096, taskRole: taskRole, }); const frontendContainer = amundsenFrontend.addContainer('AmundsenFrontendContainer', { image: ecs.ContainerImage.fromRegistry('amundsendev/amundsen-frontend:latest'), logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'amundsen-frontend' }), environment: { // LOG_LEVEL: 'DEBUG', // PORT: '5000', SEARCHSERVICE_BASE: 'http://localhost:5001', METADATASERVICE_BASE: 'http://localhost:5002', FRONTEND_SVC_CONFIG_MODULE_CLASS: 'amundsen_application.config.TestConfig', }, cpu: 256, memoryLimitMiB: 512, }); frontendContainer.addPortMappings({ containerPort: 5000 }); const metadataContainer = amundsenFrontend.addContainer('AmundsenMetadataContainer', { // image: ecs.ContainerImage.fromRegistry('amundsendev/amundsen-metadata:latest'), image: ecs.ContainerImage.fromRegistry('amundsendev/amundsen-metadata:3.5.0'), logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'amundsen-metadata' }), environment: { // LOG_LEVEL: 'DEBUG', // PORT: '5002', METADATA_SVC_CONFIG_MODULE_CLASS: 'metadata_service.config.NeptuneConfig', AWS_REGION: `${this.region}`, S3_BUCKET_NAME: props.airflowS3Bucket.bucketName, IGNORE_NEPTUNE_SHARD: 'True', PROXY_CLIENT: 'NEPTUNE', PROXY_PORT: '8182', PROXY_HOST: `wss://${this.neptuneCluster.attrEndpoint}:8182/gremlin`, PROXY_ENCRYPTED: 'True', PROXY_VALIDATE_SSL: 'False', }, cpu: 256, memoryLimitMiB: 512 }); metadataContainer.addPortMappings({ containerPort: 5002 }); const searchContainer = amundsenFrontend.addContainer('AmundsenSearchContainer', { image: ecs.ContainerImage.fromRegistry('amundsendev/amundsen-search:latest'), logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'amundsen-search' }), environment: { PROXY_CLIENT: 'ELASTICSEARCH', CREDENTIALS_PROXY_USER: '', CREDENTIALS_PROXY_PASSWORD: '', LOG_LEVEL: 'DEBUG', PORT: '5001', PROXY_PORT: '443', PROXY_ENDPOINT: `https://${this.esDomain.attrDomainEndpoint}`, }, cpu: 256, memoryLimitMiB: 512 }); searchContainer.addPortMappings({ containerPort: 5001 }); const alb = new elbv2.ApplicationLoadBalancer(this, 'LoadBalancer', { vpc: props.vpc, internetFacing: true, }); const amundsenListener = alb.addListener('Listener', { port: 80, defaultAction: elbv2.ListenerAction.fixedResponse(200) }); var ecsSecurityGroup = new ec2.SecurityGroup(this, 'ECS-Ingress', { vpc: props.vpc, allowAllOutbound: true, securityGroupName: 'EcsIngressSecurityGroup', }); ecsSecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.allTraffic()); const amundsenService = new ecs.FargateService(this, 'FargateFrontendService', { cluster: this.fargateCluster, serviceName: `${application}-${environment}-amundsen-frontend-service`, securityGroups: [ ecsSecurityGroup ], vpcSubnets: props.vpc.selectSubnets({ subnetType: ec2.SubnetType.PRIVATE }), taskDefinition: amundsenFrontend, assignPublicIp: false, desiredCount: 1, }); amundsenListener.addTargets('amundsenListener', { port: 80, priority: 1, healthCheck:{ path: '/healthcheck', protocol: elbv2.Protocol.HTTP, port: '5000', }, targets: [amundsenService], pathPattern: '/*', }); // create an Output new cdk.CfnOutput(this, 'amundsen-frontend-hostname', { value: alb.loadBalancerDnsName, description: 'Amundsen Frontend Hostname', exportName: 'amundsen-frontend-hostname', }); } }
the_stack
import { BaseResource } from 'ms-rest-azure'; import { CloudError } from 'ms-rest-azure'; import * as moment from 'moment'; export { BaseResource } from 'ms-rest-azure'; export { CloudError } from 'ms-rest-azure'; /** * @class * Initializes a new instance of the Resource class. * @constructor * The Resource model definition. * * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [location] Resource location * @member {object} [tags] Resource tags * @member {string} [etag] Resource etag */ export interface Resource extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; location?: string; tags?: { [propertyName: string]: string }; etag?: string; } /** * @class * Initializes a new instance of the LdapsSettings class. * @constructor * Secure LDAP Settings * * @member {string} [ldaps] A flag to determine whether or not Secure LDAP is * enabled or disabled. Possible values include: 'Enabled', 'Disabled' * @member {string} [pfxCertificate] The certificate required to configure * Secure LDAP. The parameter passed here should be a base64encoded * representation of the certificate pfx file. * @member {string} [pfxCertificatePassword] The password to decrypt the * provided Secure LDAP certificate pfx file. * @member {string} [publicCertificate] Public certificate used to configure * secure ldap. * @member {string} [certificateThumbprint] Thumbprint of configure ldaps * certificate. * @member {date} [certificateNotAfter] NotAfter DateTime of configure ldaps * certificate. * @member {string} [externalAccess] A flag to determine whether or not Secure * LDAP access over the internet is enabled or disabled. Possible values * include: 'Enabled', 'Disabled' * @member {string} [externalAccessIpAddress] External access ip address. */ export interface LdapsSettings { ldaps?: string; pfxCertificate?: string; pfxCertificatePassword?: string; readonly publicCertificate?: string; readonly certificateThumbprint?: string; readonly certificateNotAfter?: Date; externalAccess?: string; readonly externalAccessIpAddress?: string; } /** * @class * Initializes a new instance of the HealthMonitor class. * @constructor * Health Monitor Description * * @member {string} [id] Health Monitor Id * @member {string} [name] Health Monitor Name * @member {string} [details] Health Monitor Details */ export interface HealthMonitor { readonly id?: string; readonly name?: string; readonly details?: string; } /** * @class * Initializes a new instance of the HealthAlert class. * @constructor * Health Alert Description * * @member {string} [id] Health Alert Id * @member {string} [name] Health Alert Name * @member {string} [issue] Health Alert Issue * @member {string} [severity] Health Alert Severity * @member {date} [raised] Health Alert Raised DateTime * @member {date} [lastDetected] Health Alert Last Detected DateTime * @member {string} [resolutionUri] Health Alert TSG Link */ export interface HealthAlert { readonly id?: string; readonly name?: string; readonly issue?: string; readonly severity?: string; readonly raised?: Date; readonly lastDetected?: Date; readonly resolutionUri?: string; } /** * @class * Initializes a new instance of the NotificationSettings class. * @constructor * Settings for notification * * @member {string} [notifyGlobalAdmins] Should global admins be notified. * Possible values include: 'Enabled', 'Disabled' * @member {string} [notifyDcAdmins] Should domain controller admins be * notified. Possible values include: 'Enabled', 'Disabled' * @member {array} [additionalRecipients] The list of additional recipients */ export interface NotificationSettings { notifyGlobalAdmins?: string; notifyDcAdmins?: string; additionalRecipients?: string[]; } /** * @class * Initializes a new instance of the DomainSecuritySettings class. * @constructor * Domain Security Settings * * @member {string} [ntlmV1] A flag to determine whether or not NtlmV1 is * enabled or disabled. Possible values include: 'Enabled', 'Disabled' * @member {string} [tlsV1] A flag to determine whether or not TlsV1 is enabled * or disabled. Possible values include: 'Enabled', 'Disabled' * @member {string} [syncNtlmPasswords] A flag to determine whether or not * SyncNtlmPasswords is enabled or disabled. Possible values include: * 'Enabled', 'Disabled' */ export interface DomainSecuritySettings { ntlmV1?: string; tlsV1?: string; syncNtlmPasswords?: string; } /** * @class * Initializes a new instance of the DomainService class. * @constructor * Domain service. * * @member {string} [tenantId] Azure Active Directory tenant id * @member {string} [domainName] The name of the Azure domain that the user * would like to deploy Domain Services to. * @member {string} [vnetSiteId] Virtual network site id * @member {string} [subnetId] The name of the virtual network that Domain * Services will be deployed on. The id of the subnet that Domain Services will * be deployed on. /virtualNetwork/vnetName/subnets/subnetName. * @member {object} [ldapsSettings] Secure LDAP Settings * @member {string} [ldapsSettings.ldaps] A flag to determine whether or not * Secure LDAP is enabled or disabled. Possible values include: 'Enabled', * 'Disabled' * @member {string} [ldapsSettings.pfxCertificate] The certificate required to * configure Secure LDAP. The parameter passed here should be a base64encoded * representation of the certificate pfx file. * @member {string} [ldapsSettings.pfxCertificatePassword] The password to * decrypt the provided Secure LDAP certificate pfx file. * @member {string} [ldapsSettings.publicCertificate] Public certificate used * to configure secure ldap. * @member {string} [ldapsSettings.certificateThumbprint] Thumbprint of * configure ldaps certificate. * @member {date} [ldapsSettings.certificateNotAfter] NotAfter DateTime of * configure ldaps certificate. * @member {string} [ldapsSettings.externalAccess] A flag to determine whether * or not Secure LDAP access over the internet is enabled or disabled. Possible * values include: 'Enabled', 'Disabled' * @member {string} [ldapsSettings.externalAccessIpAddress] External access ip * address. * @member {date} [healthLastEvaluated] Last domain evaluation run DateTime * @member {array} [healthMonitors] List of Domain Health Monitors * @member {array} [healthAlerts] List of Domain Health Alerts * @member {object} [notificationSettings] Notification Settings * @member {string} [notificationSettings.notifyGlobalAdmins] Should global * admins be notified. Possible values include: 'Enabled', 'Disabled' * @member {string} [notificationSettings.notifyDcAdmins] Should domain * controller admins be notified. Possible values include: 'Enabled', * 'Disabled' * @member {array} [notificationSettings.additionalRecipients] The list of * additional recipients * @member {object} [domainSecuritySettings] DomainSecurity Settings * @member {string} [domainSecuritySettings.ntlmV1] A flag to determine whether * or not NtlmV1 is enabled or disabled. Possible values include: 'Enabled', * 'Disabled' * @member {string} [domainSecuritySettings.tlsV1] A flag to determine whether * or not TlsV1 is enabled or disabled. Possible values include: 'Enabled', * 'Disabled' * @member {string} [domainSecuritySettings.syncNtlmPasswords] A flag to * determine whether or not SyncNtlmPasswords is enabled or disabled. Possible * values include: 'Enabled', 'Disabled' * @member {string} [filteredSync] Enabled or Disabled flag to turn on * Group-based filtered sync. Possible values include: 'Enabled', 'Disabled' * @member {array} [domainControllerIpAddress] List of Domain Controller IP * Address * @member {string} [serviceStatus] Status of Domain Service instance * @member {string} [provisioningState] the current deployment or provisioning * state, which only appears in the response. */ export interface DomainService extends Resource { readonly tenantId?: string; domainName?: string; readonly vnetSiteId?: string; subnetId?: string; ldapsSettings?: LdapsSettings; readonly healthLastEvaluated?: Date; readonly healthMonitors?: HealthMonitor[]; readonly healthAlerts?: HealthAlert[]; notificationSettings?: NotificationSettings; domainSecuritySettings?: DomainSecuritySettings; filteredSync?: string; readonly domainControllerIpAddress?: string[]; readonly serviceStatus?: string; readonly provisioningState?: string; } /** * @class * Initializes a new instance of the OperationDisplayInfo class. * @constructor * The operation supported by Domain Services. * * @member {string} [description] The description of the operation. * @member {string} [operation] The action that users can perform, based on * their permission level. * @member {string} [provider] Service provider: Domain Services. * @member {string} [resource] Resource on which the operation is performed. */ export interface OperationDisplayInfo { description?: string; operation?: string; provider?: string; resource?: string; } /** * @class * Initializes a new instance of the OperationEntity class. * @constructor * The operation supported by Domain Services. * * @member {string} [name] Operation name: {provider}/{resource}/{operation}. * @member {object} [display] The operation supported by Domain Services. * @member {string} [display.description] The description of the operation. * @member {string} [display.operation] The action that users can perform, * based on their permission level. * @member {string} [display.provider] Service provider: Domain Services. * @member {string} [display.resource] Resource on which the operation is * performed. * @member {string} [origin] The origin of the operation. */ export interface OperationEntity { name?: string; display?: OperationDisplayInfo; origin?: string; } /** * @class * Initializes a new instance of the OperationEntityListResult class. * @constructor * The list of domain service operation response. * * @member {string} [nextLink] The continuation token for the next page of * results. */ export interface OperationEntityListResult extends Array<OperationEntity> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the DomainServiceListResult class. * @constructor * The response from the List Domain Services operation. * * @member {string} [nextLink] The continuation token for the next page of * results. */ export interface DomainServiceListResult extends Array<DomainService> { readonly nextLink?: string; }
the_stack
import * as DiscoveryError from "../../../../../main/js/generated/joynr/types/DiscoveryError"; import * as ProviderScope from "../../../../../main/js/generated/joynr/types/ProviderScope"; import Arbitrator from "../../../../../main/js/joynr/capabilities/arbitration/Arbitrator"; import DiscoveryEntryWithMetaInfo from "../../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import ProviderQos from "../../../../../main/js/generated/joynr/types/ProviderQos"; import CustomParameter from "../../../../../main/js/generated/joynr/types/CustomParameter"; import DiscoveryQos from "../../../../../main/js/joynr/proxy/DiscoveryQos"; import * as ArbitrationStrategyCollection from "../../../../../main/js/joynr/types/ArbitrationStrategyCollection"; import DiscoveryScope from "../../../../../main/js/generated/joynr/types/DiscoveryScope"; import DiscoveryException from "../../../../../main/js/joynr/exceptions/DiscoveryException"; import NoCompatibleProviderFoundException from "../../../../../main/js/joynr/exceptions/NoCompatibleProviderFoundException"; import Version from "../../../../../main/js/generated/joynr/types/Version"; import * as UtilInternal from "../../../../../main/js/joynr/util/UtilInternal"; import * as testUtil from "../../../testUtil"; import ApplicationException = require("../../../../../main/js/joynr/exceptions/ApplicationException"); import { FIXED_PARTICIPANT_PARAMETER } from "joynr/joynr/types/ArbitrationConstants"; let capabilities: any, fakeTime: number, staticArbitrationSettings: any, domain: any; let interfaceName: string, discoveryQos: DiscoveryQos, capDiscoverySpy: any, arbitrator: Arbitrator, discoveryEntries: DiscoveryEntryWithMetaInfo[], nrTimes: any; let fixedParticipantIdDiscoveryEntryWithMetaInfo: DiscoveryEntryWithMetaInfo; let discoveryEntryWithMajor47AndMinor0: any, discoveryEntryWithMajor47AndMinor1: any; let discoveryEntryWithMajor47AndMinor2: any, discoveryEntryWithMajor47AndMinor3: any; let discoveryEntryWithMajor48AndMinor2: any; // save values once before installing jasmine clock mocks async function increaseFakeTime(timeMs: number): Promise<void> { fakeTime = fakeTime + timeMs; jest.advanceTimersByTime(timeMs); await testUtil.multipleSetImmediate(); } function getDiscoveryEntry( domain: any, interfaceName: string, providerVersion: any, supportsOnChangeSubscriptions: any ) { return new DiscoveryEntryWithMetaInfo({ providerVersion, domain, interfaceName, qos: new ProviderQos({ customParameters: [new CustomParameter({ name: "theName", value: "theValue" })], priority: 123, scope: discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL, supportsOnChangeSubscriptions }), participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: true, expiryDateMs: Date.now() + 1e10 }); } describe("libjoynr-js.joynr.capabilities.arbitration.Arbitrator", () => { capabilities = [ { domain: "myDomain", interfaceName: "myInterface", participantId: 1, providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), qos: { supportsOnChangeSubscriptions: true } }, { domain: "myDomain", interfaceName: "myInterface", participantId: 2, providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), qos: { supportsOnChangeSubscriptions: false } }, { domain: "otherDomain", interfaceName: "otherInterface", participantId: 3, providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), qos: { supportsOnChangeSubscriptions: true } }, { domain: "thirdDomain", interfaceName: "otherInterface", participantId: 4, providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), qos: { supportsOnChangeSubscriptions: false } } ]; beforeEach(() => { domain = "myDomain"; interfaceName = "myInterface"; discoveryQos = new DiscoveryQos({ discoveryTimeoutMs: 5000, discoveryRetryDelayMs: 900, arbitrationStrategy: ArbitrationStrategyCollection.Nothing, cacheMaxAgeMs: 0, discoveryScope: DiscoveryScope.LOCAL_THEN_GLOBAL, additionalParameters: {} }); staticArbitrationSettings = { domains: [domain], interfaceName, discoveryQos, staticArbitration: true, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }; capDiscoverySpy = { lookup: jest.fn(), lookupByParticipantId: jest.fn() }; capDiscoverySpy.lookup.mockReturnValue(Promise.resolve([])); arbitrator = new Arbitrator(capDiscoverySpy, capabilities); discoveryEntries = []; for (let i = 0; i < 12; ++i) { discoveryEntries.push( getDiscoveryEntry( domain + i.toString(), interfaceName + i.toString(), new Version({ majorVersion: 47, minorVersion: 11 }), false ) ); } // prepare a number of similar discovery entries with different // provider versions const providerQos = new ProviderQos({ customParameters: [], priority: 123, scope: discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }); discoveryEntryWithMajor47AndMinor0 = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 0 }), domain, interfaceName, qos: providerQos, participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: true, expiryDateMs: Date.now() + 1e10 }); discoveryEntryWithMajor47AndMinor1 = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 1 }), domain, interfaceName, qos: providerQos, participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: false, expiryDateMs: Date.now() + 1e10 }); discoveryEntryWithMajor47AndMinor2 = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 2 }), domain, interfaceName, qos: providerQos, participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: true, expiryDateMs: Date.now() + 1e10 }); discoveryEntryWithMajor47AndMinor3 = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 3 }), domain, interfaceName, qos: providerQos, participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: false, expiryDateMs: Date.now() + 1e10 }); discoveryEntryWithMajor48AndMinor2 = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 48, minorVersion: 2 }), domain, interfaceName, qos: providerQos, participantId: "700", lastSeenDateMs: Date.now(), publicKeyId: "", isLocal: true, expiryDateMs: Date.now() + 1e10 }); nrTimes = 5; fakeTime = 0; jest.useFakeTimers(); jest.spyOn(Date, "now").mockImplementation(() => { return fakeTime; }); }); afterEach(() => { jest.useRealTimers(); }); describe("ArbitrationStrategy.FixedParticipant", () => { const expectedFixedParticipantId = "expectedFixedParticipantId"; beforeEach(() => { discoveryQos.arbitrationStrategy = ArbitrationStrategyCollection.FixedParticipant; discoveryQos.additionalParameters = { [FIXED_PARTICIPANT_PARAMETER]: expectedFixedParticipantId }; const expiryDateMs = Date.now() + 1e10; fixedParticipantIdDiscoveryEntryWithMetaInfo = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain, interfaceName, lastSeenDateMs: 111, qos: new ProviderQos({ customParameters: [], priority: 1, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: false }), participantId: expectedFixedParticipantId, isLocal: false, publicKeyId: "", expiryDateMs }); capDiscoverySpy.lookupByParticipantId.mockReturnValue( Promise.resolve(fixedParticipantIdDiscoveryEntryWithMetaInfo) ); }); it("calls lookup by participantId and returns entry with expected participantId", async () => { // start arbitration const result = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }); expect(capDiscoverySpy.lookupByParticipantId).toHaveBeenCalled(); expect(capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][0]).toEqual( expectedFixedParticipantId ); expect(capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][1].cacheMaxAge).toEqual( discoveryQos.cacheMaxAgeMs ); expect(capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][1].discoveryScope.name).toEqual( discoveryQos.discoveryScope.name ); expect(capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][1].discoveryTimeout).toEqual( discoveryQos.discoveryTimeoutMs ); expect( capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][1].providerMustSupportOnChange ).toEqual(discoveryQos.providerMustSupportOnChange); expect(capDiscoverySpy.lookupByParticipantId.mock.calls.slice(-1)[0][2]).toEqual([]); expect(result).toEqual([fixedParticipantIdDiscoveryEntryWithMetaInfo]); }); it("calls capabilityDiscovery with provided gbid array", async () => { const gbids = ["joynrtestgbid"]; // start arbitration await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }), gbids }); expect(capDiscoverySpy.lookupByParticipantId).toHaveBeenCalledWith( expectedFixedParticipantId, expect.any(Object), gbids ); }); }); it("is instantiable", () => { expect(new Arbitrator({} as any)).toBeDefined(); }); it("is of correct type and has all members", () => { expect(arbitrator).toBeDefined(); expect(arbitrator).not.toBeNull(); expect(typeof arbitrator === "object").toBeTruthy(); expect(arbitrator instanceof Arbitrator).toEqual(true); expect(arbitrator.startArbitration).toBeDefined(); expect(typeof arbitrator.startArbitration === "function").toEqual(true); }); it("calls capabilityDiscovery upon arbitration", async () => { // return some discoveryEntries so that arbitration is faster // (instantly instead of discoveryTimeout) capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(discoveryEntries)); jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue(discoveryEntries); arbitrator = new Arbitrator(capDiscoverySpy); // start arbitration await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }); expect(capDiscoverySpy.lookup).toHaveBeenCalled(); /* The arbitrator.startArbitration does a deep copy of its arguments. * Thus, two discoveryScope objects cannot be compared, as during deep copy * complex types are created as pure objects */ expect(capDiscoverySpy.lookup.mock.calls.slice(-1)[0][0]).toEqual([domain]); expect(capDiscoverySpy.lookup.mock.calls.slice(-1)[0][1]).toEqual(interfaceName); expect(capDiscoverySpy.lookup.mock.calls.slice(-1)[0][2].cacheMaxAge).toEqual(discoveryQos.cacheMaxAgeMs); expect(capDiscoverySpy.lookup.mock.calls.slice(-1)[0][2].discoveryScope.name).toEqual( discoveryQos.discoveryScope.name ); }); it("calls capabilityDiscovery with provided gbid array", async () => { capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(discoveryEntries)); jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue(discoveryEntries); const gbids = ["joynrdefaultgbid"]; // start arbitration await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }), gbids }); expect(capDiscoverySpy.lookup).toHaveBeenCalledWith([domain], interfaceName, expect.any(Object), gbids); }); it("calls capabilityDiscovery with empty gbid array when unspecified", async () => { capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(discoveryEntries)); jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue(discoveryEntries); // start arbitration await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }); expect(capDiscoverySpy.lookup).toHaveBeenCalledWith([domain], interfaceName, expect.any(Object), []); }); async function returnCapabilitiesFromDiscovery( providerMustSupportOnChange: boolean, discoveryEntries: any, expected: any ) { // return discoveryEntries to check whether these are eventually // returned by the arbitrator capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(discoveryEntries)); arbitrator = new Arbitrator(capDiscoverySpy); const result = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos: new DiscoveryQos(UtilInternal.extend(discoveryQos, { providerMustSupportOnChange })), proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }); expect(result).toEqual(expected); } function setSupportsOnChangeSubscriptionsToTrue(discoveryEntry: any) { discoveryEntry.qos = new ProviderQos( UtilInternal.extend(discoveryEntry.qos, { supportsOnChangeSubscriptions: true }) ); } it("returns capabilities from discovery", () => { return returnCapabilitiesFromDiscovery(false, discoveryEntries, discoveryEntries); }); it("returns filtered capabilities from discovery if discoveryQos.providerMustSupportOnChange is true", () => { setSupportsOnChangeSubscriptionsToTrue(discoveryEntries[1]); setSupportsOnChangeSubscriptionsToTrue(discoveryEntries[5]); setSupportsOnChangeSubscriptionsToTrue(discoveryEntries[11]); const filteredDiscoveryEntries = [discoveryEntries[1], discoveryEntries[5], discoveryEntries[11]]; return returnCapabilitiesFromDiscovery(true, discoveryEntries, filteredDiscoveryEntries); }); it("returns capabilities with matching provider version", async () => { const discoveryEntriesWithDifferentProviderVersions = [ discoveryEntryWithMajor47AndMinor0, discoveryEntryWithMajor47AndMinor1, discoveryEntryWithMajor47AndMinor2, discoveryEntryWithMajor47AndMinor3, discoveryEntryWithMajor48AndMinor2 ]; // return discoveryEntries to check whether these are eventually // returned by the arbitrator capDiscoverySpy.lookup.mockResolvedValue(discoveryEntriesWithDifferentProviderVersions); arbitrator = new Arbitrator(capDiscoverySpy); const returnedDiscoveryEntries = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 2 }) }); // remove lastSeenDateMs from object since it has been modified // by the lookup attempt // by providerVersion because of ArbitrationStrategyCollection.Nothing expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor47AndMinor0); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor47AndMinor1); expect(returnedDiscoveryEntries).toContain(discoveryEntryWithMajor47AndMinor2); expect(returnedDiscoveryEntries).toContain(discoveryEntryWithMajor47AndMinor3); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor48AndMinor2); }); it("rejects with NoCompatibleProviderFoundException including a list of incompatible provider version of latest lookup", async () => { const expectedMinimumMinorVersion = 2; const firstLookupResult = [ discoveryEntryWithMajor47AndMinor0, discoveryEntryWithMajor47AndMinor1, discoveryEntryWithMajor47AndMinor2, discoveryEntryWithMajor47AndMinor3, discoveryEntryWithMajor48AndMinor2 ]; const secondLookupResult = [discoveryEntryWithMajor47AndMinor0, discoveryEntryWithMajor48AndMinor2]; // return discoveryEntries to check whether these are eventually // returned by the arbitrator capDiscoverySpy.lookup.mockResolvedValue(firstLookupResult); arbitrator = new Arbitrator(capDiscoverySpy); const discoveryQosWithShortTimers = new DiscoveryQos({ discoveryTimeoutMs: 1000, discoveryRetryDelayMs: 600, arbitrationStrategy: ArbitrationStrategyCollection.Nothing, cacheMaxAgeMs: 0, discoveryScope: DiscoveryScope.LOCAL_THEN_GLOBAL, additionalParameters: {} }); // spy on and instrument arbitrationStrategy jest.spyOn(discoveryQosWithShortTimers, "arbitrationStrategy"); // call arbitrator const onFulfilledSpy = jest.fn(); const onRejectedSpy = jest.fn(); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos: discoveryQosWithShortTimers, proxyVersion: new Version({ majorVersion: 49, minorVersion: expectedMinimumMinorVersion }) }) .then(onFulfilledSpy) .catch(onRejectedSpy); await increaseFakeTime(1); expect(capDiscoverySpy.lookup.mock.calls.length).toBe(1); await increaseFakeTime(discoveryQosWithShortTimers.discoveryRetryDelayMs - 2); capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(secondLookupResult)); expect(capDiscoverySpy.lookup.mock.calls.length).toBe(1); await increaseFakeTime(2); expect(capDiscoverySpy.lookup.mock.calls.length).toBe(2); await increaseFakeTime(1000); expect(onRejectedSpy).toHaveBeenCalled(); expect(onFulfilledSpy).not.toHaveBeenCalled(); expect(onRejectedSpy.mock.calls[0][0] instanceof NoCompatibleProviderFoundException).toBeTruthy(); // discoverVersion should contain all not matching entries of only the last(!) lookup const discoveredVersions = onRejectedSpy.mock.calls[0][0].discoveredVersions; expect(discoveredVersions).toContain(discoveryEntryWithMajor47AndMinor0.providerVersion); expect(discoveredVersions).not.toContain(discoveryEntryWithMajor47AndMinor1.providerVersion); expect(discoveredVersions).not.toContain(discoveryEntryWithMajor47AndMinor2.providerVersion); expect(discoveredVersions).not.toContain(discoveryEntryWithMajor47AndMinor3.providerVersion); expect(discoveredVersions).toContain(discoveryEntryWithMajor48AndMinor2.providerVersion); }); it("timeouts when no retry is possible any more", async () => { const onRejectedSpy = jest.fn(); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(onRejectedSpy); // stop 1ms before last possible retry const delay = discoveryQos.discoveryTimeoutMs - discoveryQos.discoveryRetryDelayMs - 1; await increaseFakeTime(delay); expect(onRejectedSpy).not.toHaveBeenCalled(); // largest amount of possible retries has passed await increaseFakeTime(discoveryQos.discoveryRetryDelayMs); expect(onRejectedSpy).toHaveBeenCalled(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0] instanceof DiscoveryException).toBeTruthy(); }); it("use remaining discovery timeout in discoveryQos for lookupByParticipantId retries", async () => { const expectedFixedParticipantId = "expectedFixedParticipantId"; const ARBITRATION_TIMEOUT = 1000; const retryInterval: number = (ARBITRATION_TIMEOUT / 3) * 2; discoveryQos.discoveryTimeoutMs = ARBITRATION_TIMEOUT; discoveryQos.discoveryRetryDelayMs = retryInterval; discoveryQos.arbitrationStrategy = ArbitrationStrategyCollection.FixedParticipant; discoveryQos.additionalParameters = { [FIXED_PARTICIPANT_PARAMETER]: expectedFixedParticipantId }; // error could be DiscoveryError.NO_ENTRY_FOR_PARTICIPANT or DiscoveryError.NO_ENTRY_FOR_SELECTED_BACKENDS const fakeError = new ApplicationException({ detailMessage: "test", error: DiscoveryError.NO_ENTRY_FOR_SELECTED_BACKENDS }); capDiscoverySpy.lookupByParticipantId.mockReturnValue(Promise.reject(fakeError)); const onRejectedSpy = jest.fn(); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(onRejectedSpy); await testUtil.multipleSetImmediate(); // increase fake time to trigger retry await increaseFakeTime(700); // increase fake time for remaining time to reach the arbitration deadline await increaseFakeTime(300); expect(capDiscoverySpy.lookupByParticipantId).toHaveBeenCalledTimes(2); expect(onRejectedSpy).toHaveBeenCalled(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0] instanceof DiscoveryException).toBeTruthy(); // Args of first call const capturedLookupArgs1: any = capDiscoverySpy.lookupByParticipantId.mock.calls[0]; expect(capturedLookupArgs1[0]).toEqual(expectedFixedParticipantId); const capturedDiscoveryQos1 = capturedLookupArgs1[1]; expect(capturedDiscoveryQos1.cacheMaxAge).toEqual(discoveryQos.cacheMaxAgeMs); expect(capturedDiscoveryQos1.discoveryTimeout).toEqual(1000); // initial timeout // Args of second call const capturedLookupArgs2: any = capDiscoverySpy.lookupByParticipantId.mock.calls[1]; expect(capturedLookupArgs2[0]).toEqual(expectedFixedParticipantId); const capturedDiscoveryQos2 = capturedLookupArgs2[1]; expect(capturedDiscoveryQos2.cacheMaxAge).toEqual(discoveryQos.cacheMaxAgeMs); expect(capturedDiscoveryQos2.discoveryTimeout).toEqual(300); // remaining timeout }); it("use remaining discovery timeout in discoveryQos for lookup retries", async () => { const ARBITRATION_TIMEOUT = 1000; const retryInterval: number = (ARBITRATION_TIMEOUT / 3) * 2; discoveryQos.discoveryTimeoutMs = ARBITRATION_TIMEOUT; discoveryQos.discoveryRetryDelayMs = retryInterval; capDiscoverySpy.lookup.mockReturnValue(Promise.resolve([])); const onRejectedSpy = jest.fn(); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(onRejectedSpy); await testUtil.multipleSetImmediate(); // increase fake time to trigger retry await increaseFakeTime(700); // increase fake time for remaining time to reach the arbitration deadline await increaseFakeTime(300); expect(capDiscoverySpy.lookup).toHaveBeenCalledTimes(2); expect(onRejectedSpy).toHaveBeenCalled(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0] instanceof DiscoveryException).toBeTruthy(); // Args of first call const capturedLookupArgs1: any = capDiscoverySpy.lookup.mock.calls[0]; expect(capturedLookupArgs1[0]).toEqual([domain]); expect(capturedLookupArgs1[1]).toEqual(interfaceName); const capturedDiscoveryQos1 = capturedLookupArgs1[2]; expect(capturedDiscoveryQos1.cacheMaxAge).toEqual(discoveryQos.cacheMaxAgeMs); expect(capturedDiscoveryQos1.discoveryTimeout).toEqual(1000); // initial timeout // Args of second call const capturedLookupArgs2: any = capDiscoverySpy.lookup.mock.calls[1]; expect(capturedLookupArgs2[0]).toEqual([domain]); expect(capturedLookupArgs2[1]).toEqual(interfaceName); const capturedDiscoveryQos2 = capturedLookupArgs2[2]; expect(capturedDiscoveryQos2.cacheMaxAge).toEqual(discoveryQos.cacheMaxAgeMs); expect(capturedDiscoveryQos2.discoveryTimeout).toEqual(300); // remaining timeout }); it("timeouts after the given discoveryTimeoutMs when capabilityDiscoveryStub throws exceptions", async () => { const onRejectedSpy = jest.fn(); const fakeError = new Error("simulate discovery exception"); capDiscoverySpy.lookup.mockReturnValue(Promise.reject(fakeError)); discoveryQos.discoveryTimeoutMs = 500; discoveryQos.discoveryRetryDelayMs = 30; arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch((error: any) => { onRejectedSpy(error); }); const checkpointMs = discoveryQos.discoveryRetryDelayMs * 5; // let checkpoint ms pass await increaseFakeTime(checkpointMs); expect(onRejectedSpy).not.toHaveBeenCalled(); // let discoveryTimeoutMs pass await increaseFakeTime(discoveryQos.discoveryTimeoutMs - checkpointMs); expect(onRejectedSpy).toHaveBeenCalled(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0] instanceof DiscoveryException).toBeTruthy(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0].detailMessage).toMatch(fakeError.message); }); async function testDiscoveryRetryByDiscoveryError(discoveryError: DiscoveryError, expectedRetry: boolean) { const expectedCalls = expectedRetry ? 2 : 1; const onRejectedSpy = jest.fn(); const fakeError = new ApplicationException({ detailMessage: "test", error: discoveryError }); capDiscoverySpy.lookup.mockRejectedValue(fakeError); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(onRejectedSpy); await testUtil.multipleSetImmediate(); await increaseFakeTime(discoveryQos.discoveryTimeoutMs); expect(capDiscoverySpy.lookup).toHaveBeenCalledTimes(expectedCalls); expect(onRejectedSpy).toHaveBeenCalled(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0] instanceof DiscoveryException).toBeTruthy(); expect(onRejectedSpy.mock.calls.slice(-1)[0][0].detailMessage).toMatch(discoveryError.name); } [DiscoveryError.INTERNAL_ERROR, DiscoveryError.INVALID_GBID, DiscoveryError.UNKNOWN_GBID].forEach( discoveryError => { it(`won't retry lookup for DiscoveryError ${discoveryError.name}`, () => { return testDiscoveryRetryByDiscoveryError(discoveryError, false); }); } ); [DiscoveryError.NO_ENTRY_FOR_SELECTED_BACKENDS, DiscoveryError.NO_ENTRY_FOR_PARTICIPANT].forEach(discoveryError => { it(`retries lookup for DiscoveryError ${discoveryError.name}`, () => { return testDiscoveryRetryByDiscoveryError(discoveryError, true); }); }); it("reruns discovery for empty discovery results according to discoveryTimeoutMs and discoveryRetryDelayMs", async () => { //capDiscoverySpy.lookup.and.returnValue(Promise.resolve([])); capDiscoverySpy.lookup.mockImplementation(() => { return Promise.resolve([]); }); arbitrator = new Arbitrator(capDiscoverySpy); expect(capDiscoverySpy.lookup).not.toHaveBeenCalled(); jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue([]); let res: Function; const promise = new Promise(resolve => (res = resolve)); arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(() => { // startAbitration caught error [expected!] res(); }); await increaseFakeTime(1); for (let i = 1; i < nrTimes + 1; ++i) { await increaseFakeTime(discoveryQos.discoveryRetryDelayMs - 2); expect(capDiscoverySpy.lookup.mock.calls.length).toBe(i); await increaseFakeTime(2); expect(capDiscoverySpy.lookup.mock.calls.length).toBe(i + 1); } // this should trigger the done in the catch of startArbitration // above await increaseFakeTime(discoveryQos.discoveryTimeoutMs); await promise; }); it("uses arbitration strategy and returns its results", async () => { // just return some object so that arbitration is successful and // arbitration strategy is called capDiscoverySpy.lookup.mockReturnValue(Promise.resolve(discoveryEntries)); arbitrator = new Arbitrator(capDiscoverySpy); // spy on and instrument arbitrationStrategy to return discoveryEntries jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue(discoveryEntries); const discoveredEntries = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }); // the arbitrationStrategy was called with the discoveryEntries // returned by the discovery spy expect(discoveryQos.arbitrationStrategy).toHaveBeenCalled(); expect(discoveryQos.arbitrationStrategy).toHaveBeenCalledWith(discoveryEntries); expect(discoveredEntries).toEqual(discoveryEntries); // increaseFakeTime: is required for test purpose to ensure the // resolve/reject callbacks are called increaseFakeTime(1); }); it("is instantiable, of correct type and has all members", () => { expect(Arbitrator).toBeDefined(); expect(typeof Arbitrator === "function").toBeTruthy(); expect(arbitrator).toBeDefined(); expect(arbitrator instanceof Arbitrator).toBeTruthy(); expect(arbitrator.startArbitration).toBeDefined(); expect(typeof arbitrator.startArbitration === "function").toBeTruthy(); }); function arbitratesCorrectly(settings: any) { staticArbitrationSettings.domains = settings.domains; staticArbitrationSettings.interfaceName = settings.interfaceName; staticArbitrationSettings.discoveryQos = new DiscoveryQos( UtilInternal.extend(staticArbitrationSettings.discoveryQos, { providerMustSupportOnChange: settings.providerMustSupportOnChange || false }) ); return arbitrator.startArbitration(staticArbitrationSettings).then(discoveredEntries => { expect(discoveredEntries).toEqual(settings.expected); }); } it("arbitrates correctly static capabilities", async () => { jest.spyOn(discoveryQos, "arbitrationStrategy").mockImplementation((discoveredCaps: any) => { return discoveredCaps; }); await arbitratesCorrectly({ domains: ["myDomain"], interfaceName: "noneExistingInterface", expected: [] }); await arbitratesCorrectly({ domains: ["noneExistingDomain"], interfaceName: "myInterface", expected: [] }); await arbitratesCorrectly({ domains: ["myDomain"], interfaceName: "myInterface", expected: [capabilities[0], capabilities[1]] }); await arbitratesCorrectly({ domains: ["otherDomain"], interfaceName: "otherInterface", expected: [capabilities[2]] }); await arbitratesCorrectly({ domains: ["thirdDomain"], interfaceName: "otherInterface", expected: [capabilities[3]] }); }); it("Arbitrator supports discoveryQos.providerSupportsOnChange for static arbitration", async () => { jest.spyOn(discoveryQos, "arbitrationStrategy").mockImplementation((discoveredCaps: any) => { return discoveredCaps; }); await arbitratesCorrectly({ domains: ["myDomain"], interfaceName: "noneExistingInterface", providerMustSupportOnChange: true, expected: [] }); await arbitratesCorrectly({ domains: ["noneExistingDomain"], interfaceName: "myInterface", providerMustSupportOnChange: true, expected: [] }); await arbitratesCorrectly({ domains: ["myDomain"], interfaceName: "myInterface", providerMustSupportOnChange: false, expected: [capabilities[0], capabilities[1]] }); await arbitratesCorrectly({ domains: ["myDomain"], interfaceName: "myInterface", providerMustSupportOnChange: true, expected: [capabilities[0]] }); await arbitratesCorrectly({ domains: ["otherDomain"], interfaceName: "otherInterface", providerMustSupportOnChange: true, expected: [capabilities[2]] }); await arbitratesCorrectly({ domains: ["thirdDomain"], interfaceName: "otherInterface", providerMustSupportOnChange: true, expected: [] }); await arbitratesCorrectly({ domains: ["thirdDomain"], interfaceName: "otherInterface", providerMustSupportOnChange: false, expected: [capabilities[3]] }); }); it("uses the provided arbitrationStrategy", async () => { jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue(discoveryEntries); const discoveredEntries = await arbitrator.startArbitration(staticArbitrationSettings); expect(discoveredEntries).toEqual(discoveryEntries); expect(discoveryQos.arbitrationStrategy).toHaveBeenCalledWith([capabilities[0], capabilities[1]]); }); it("fails if arbitrationStrategy throws an exception", async () => { jest.spyOn(discoveryQos, "arbitrationStrategy").mockImplementation(() => { throw new Error("myError"); }); await expect(arbitrator.startArbitration(staticArbitrationSettings)).rejects.toBeInstanceOf(Error); }); it("rejects pending arbitrations when shutting down", async () => { capDiscoverySpy.lookup.mockReturnValue(Promise.resolve([])); jest.spyOn(discoveryQos, "arbitrationStrategy").mockReturnValue([]); arbitrator = new Arbitrator(capDiscoverySpy); const onRejectedSpy = jest.fn(); // start arbitration arbitrator .startArbitration({ domains: [domain], interfaceName, discoveryQos, proxyVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }) .catch(onRejectedSpy); arbitrator.shutdown(); await testUtil.multipleSetImmediate(); expect(onRejectedSpy).toHaveBeenCalled(); }); function arbitrationStrategyReturningFirstFoundEntry( capabilities: DiscoveryEntryWithMetaInfo[] ): DiscoveryEntryWithMetaInfo[] { const caps: DiscoveryEntryWithMetaInfo[] = []; if (!Array.isArray(capabilities)) { throw new Error("provided argument capabilities is not of type Array"); } for (const capId in capabilities) { if (capabilities.hasOwnProperty(capId)) { caps.push(capabilities[capId]); return caps; } } return caps; } it("filters capabilities properly and in order by version and arbitration strategy", async () => { const qosParam = new CustomParameter({ name: "keyword", value: "valid" }); const specificProviderQos = new ProviderQos({ customParameters: [qosParam], priority: 123, scope: discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL, supportsOnChangeSubscriptions: false }); UtilInternal.extend(discoveryEntryWithMajor47AndMinor3, { qos: specificProviderQos }); const discoveryEntriesWithDifferentProviderVersions = [ discoveryEntryWithMajor47AndMinor0, discoveryEntryWithMajor47AndMinor3, discoveryEntryWithMajor48AndMinor2 ]; const arbitrationStrategy = arbitrationStrategyReturningFirstFoundEntry; // return discoveryEntries to check whether these are eventually // returned by the arbitrator capDiscoverySpy.lookup.mockResolvedValue(discoveryEntriesWithDifferentProviderVersions); arbitrator = new Arbitrator(capDiscoverySpy); const returnedDiscoveryEntries = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos: new DiscoveryQos(UtilInternal.extend(discoveryQos, { arbitrationStrategy })), proxyVersion: new Version({ majorVersion: 47, minorVersion: 3 }) }); expect(returnedDiscoveryEntries.length).toEqual(1); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor47AndMinor0); expect(returnedDiscoveryEntries).toContain(discoveryEntryWithMajor47AndMinor3); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor48AndMinor2); }); it("filters capabilities properly by supportOnChangeSubscriptions and arbitration strategy", async () => { const qosParam = new CustomParameter({ name: "keyword", value: "valid" }); const specificProviderQos = new ProviderQos({ customParameters: [qosParam], priority: 123, scope: discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL, supportsOnChangeSubscriptions: false }); UtilInternal.extend(discoveryEntryWithMajor47AndMinor0, { qos: specificProviderQos }); UtilInternal.extend(discoveryEntryWithMajor48AndMinor2, { qos: specificProviderQos }); const discoveryEntries = [ discoveryEntryWithMajor47AndMinor0, discoveryEntryWithMajor47AndMinor3, discoveryEntryWithMajor48AndMinor2 ]; const arbitrationStrategy = arbitrationStrategyReturningFirstFoundEntry; //.bind(undefined, "valid"); // return discoveryEntries to check whether these are eventually // returned by the arbitrator capDiscoverySpy.lookup.mockResolvedValue(discoveryEntries); arbitrator = new Arbitrator(capDiscoverySpy); const returnedDiscoveryEntries = await arbitrator.startArbitration({ domains: [domain], interfaceName, discoveryQos: new DiscoveryQos( UtilInternal.extend(discoveryQos, { providerMustSupportOnChange: true, arbitrationStrategy }) ), proxyVersion: new Version({ majorVersion: 47, minorVersion: 0 }) }); expect(returnedDiscoveryEntries.length).toEqual(1); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor47AndMinor0); expect(returnedDiscoveryEntries).toContain(discoveryEntryWithMajor47AndMinor3); expect(returnedDiscoveryEntries).not.toContain(discoveryEntryWithMajor48AndMinor2); }); });
the_stack
import { IMethods, IIterator } from "../intefaces/index"; import { Utils } from '../utils/index'; import { WhereClause, SelectClause, SelectManyClause, JoinClause, LeftJoinClause, OrderByClause, OrderByDescendingClause, GroupByClause, GroupJoinClause, FirstClause, LastClause, CountClause, SumClause, AvarageClause, MinClause, MaxClause, SingleClause, TakeClause, SkipWhileClause, SkipClause, TakeWhileClause, AnyClause, ContainsClause, AllClause, DistinctClause, ConcatClause, UnionClause, ZipClause, ExceptClause, IntersectClasue, SequenceEqualClause, AggregateClause, } from "../methods/index"; import { Queryable } from './queryable'; export class IteratorMethods<T> implements IMethods<T> { // Contains all iterators _iteratorCollection: Array<IIterator<T>> = []; // Contains initial source _source: T[] | Promise<T[]>; _data: any[]; constructor(iteratorCollection: Array<IIterator<T>>, source: T[] | Promise<T[]>) { this._iteratorCollection = iteratorCollection; this._source = source; } clone(): IMethods<T> { const _cloneCollection = Object.assign([], this._iteratorCollection); return new IteratorMethods(_cloneCollection, this._source); } where(iterator: (entity: T) => boolean): IMethods<T> { this._iteratorCollection.push(new WhereClause(iterator)); return this; } select<S>(iterator: (entity: T) => S): IMethods<S> { this._iteratorCollection.push(new SelectClause(iterator)) return this as any; } selectMany<S>(iterator: (entity: T) => S): IMethods<S> { this._iteratorCollection.push(new SelectManyClause(iterator)) return this as any; } join<S, U>(source: S[] | Promise<S[]>, iterator: (aEntity: T, bEntity: S) => boolean): IMethods<U> { this._iteratorCollection.push(new JoinClause(source, iterator)); return this as any; } leftJoin<S, U>(source: S[] | Promise<S[]>, iterator: (aEntity: T, bEntity: S) => boolean): IMethods<U> { this._iteratorCollection.push(new LeftJoinClause(source, iterator)); return this as any; } orderBy(iterator: (entity: T) => void): IMethods<T> { this._iteratorCollection.push(new OrderByClause(iterator)); return this as any; } orderByDescending(iterator: (entity: T) => void): IMethods<T> { this._iteratorCollection.push(new OrderByDescendingClause(iterator)); return this as any; } groupBy(iterator: (entity: T) => any): IMethods<{ key: any; items: T[]; }> { this._iteratorCollection.push(new GroupByClause(iterator)); return this as any; } groupJoin<S>(source: S[], joinIterator: (aEntity: T, bEntity: S) => boolean, groupIterator: (entity: { x: T; y: S; }) => any): IMethods<{ key: any; items: T[]; }> { this._iteratorCollection.push(new GroupJoinClause(source, joinIterator, groupIterator)); return this as any; } distinct(comparer?: (aEntity: T, bEntity: T) => boolean): IMethods<T> { this._iteratorCollection.push(new DistinctClause(comparer)); return this; } concat(another: T[] | Promise<T[]>): IMethods<T> { this._iteratorCollection.push(new ConcatClause(another)); return this; } union(another: T[] | Promise<T[]>): IMethods<T> { this._iteratorCollection.push(new UnionClause(another as any)); return this; } zip<S>(another: S[] | Promise<S[]>, iterator?: (item1: T, item2: S) => any): IMethods<[T, S] | any> { this._iteratorCollection.push(new ZipClause(another as any, iterator)); return this; } except(another: T[] | Promise<T[]>): IMethods<T> { this._iteratorCollection.push(new ExceptClause(another as any)); return this; } intersect(another: T[] | Promise<T[]>): IMethods<T> { this._iteratorCollection.push(new IntersectClasue(another as any)); return this; } // Return S[] | Promise<S[]> toList<S>(): any { return this.runIterators(); } first(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { return new FirstClause(iterator).execute(data) as T; }); } firstOrDefault(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { return (new FirstClause(iterator).execute(data) || null) as T; }); } last(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { return new LastClause(iterator).execute(data) as T; }); } lastOrDefault(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { return (new LastClause(iterator).execute(data) || null) as T; }); } count(iterator?: (entity: T) => boolean): Promise<number> { return this.filterReturn(this.toList(), (data) => { return (new CountClause(iterator).execute(data) || null) as number; }) as any; } sum<S>(iterator: (entity: T) => S): Promise<number> { return this.filterReturn(this.toList(), (data) => { return (new SumClause(iterator).execute(data) || null) as number; }); } avarage<S>(iterator: (entity: T) => S): Promise<number> { return this.filterReturn(this.toList(), (data) => { return (new AvarageClause(iterator).execute(data) || 0) as number; }); } min<S>(iterator: (entity: T) => S): Promise<number> { return this.filterReturn(this.toList(), (data) => { return (new MinClause(iterator).execute(data) || null) as number; }); } max<S>(iterator: (entity: T) => S): Promise<number> { return this.filterReturn(this.toList(), (data) => { return (new MaxClause(iterator).execute(data) || null) as number; }); } single(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { if (!data) throw new Error("Single require source is not null"); return new SingleClause(iterator).execute(data); }); } singleOrDefault(iterator?: (entity: T) => boolean): Promise<T> { return this.filterReturn(this.toList(), (data) => { return new SingleClause(iterator).execute(data) || null; }); } take(value: number): IMethods<T> { this._iteratorCollection.push(new TakeClause(value)); return this; } skip(value: number): IMethods<T> { this._iteratorCollection.push(new SkipClause(value)); return this; } skipWhile(iterator: (entity: T) => boolean): IMethods<T> { this._iteratorCollection.push(new SkipWhileClause(iterator)); return this; } takeWhile(iterator: (entity: T) => boolean): IMethods<T> { this._iteratorCollection.push(new TakeWhileClause(iterator)); return this; } any<T>(iterator: (entity: T) => boolean): Promise<boolean> { return this.filterReturn(this.toList(), (data) => { return new AnyClause(iterator).execute(data); }); } all<T>(iterator: (entity: T) => boolean): Promise<boolean> { return this.filterReturn(this.toList(), (data) => { return new AllClause(iterator).execute(data); }); } contains(entity: T): Promise<boolean> { return this.filterReturn(this.toList(), (data) => { return new ContainsClause(entity).execute(data); }); } sequencyEqual(another: T[] | Promise<T[]>): Promise<boolean> { return this.filterReturn(this.toList(), (data) => { if (Utils.isPromise(another)) { return (another as Promise<T[]>).then(anotherData => { return new SequenceEqualClause(anotherData).execute(data); }); } return new SequenceEqualClause(another as T[]).execute(data); }); } aggregate(iterator: (accumulator: any, inital: T, index?: number) => any): Promise<any> { return this.filterReturn(this.toList(), (data) => { return (new AggregateClause<T>(iterator).execute(data)); }); } // Private functions // This function detect the input parameter is Promise or plain array data // if is promise => call promise and return from callback // opposite => return from callback private filterReturn(obj: T[] | Promise<T[]>, promiseCallback: Function) { if (Utils.isPromise(obj)) { return (obj as Promise<T[]>).then((data: T[]) => { return promiseCallback(data); }) } else return promiseCallback(obj); } runIterators(): Promise<T[]> | T[] { let _result: T[] = []; let _nextSources = {}; let _promises = []; for (let i = 0, li = this._iteratorCollection.length; i < li; i++) { let _iterator = this._iteratorCollection[i]; if (!_iterator.hasSource()) continue; if (Utils.isPromise(_iterator.nextSource)) _promises.push(_iterator.nextSource); else _promises.push(Promise.resolve(_iterator.nextSource)); } if (Utils.isPromise(this._source)) _promises.unshift(this._source); else _promises.unshift(Promise.resolve(this._source)); return Promise.all(_promises).then((responseDatas: any[]) => { let _index = 0; _result = responseDatas[0]; // Set from method's source for (let i = 0, li = this._iteratorCollection.length; i < li; i++) { let _iterator = this._iteratorCollection[i]; if (_iterator.hasSource()) { _iterator.replaceBySyncSource(responseDatas[_index + 1]); _index += 1; } } this._iteratorCollection.forEach((ite: IIterator<T>) => { _result = ite.execute(_result) as T[]; }); return _result; }); } }
the_stack
import { Promise } from "bluebird"; import Debug from "debug"; import { Kafka, Admin, Consumer, SASLMechanism, KafkaMessage } from "kafkajs"; import fs from "fs"; import { EventEmitter } from "events"; import { BatchConfig, LagStatus, JSKafkaConsumerConfig, KafkaLogger, ConsumerStats, AnalyticsConfig } from "../interfaces"; import { ConsumerAnalytics, ConsumerHealth, Metadata, Check, ConsumerRunResult } from "../shared"; const MESSAGE_CHARSET = "utf8"; export interface FormattedKafkaMessage extends Omit<KafkaMessage, "value"> { value: Buffer | string | Record<string, unknown>; } export interface ComittedOffsets { partition: number; offset: string; metadata: string | null; topic: string; } const DEFAULT_LOGGER = { debug: Debug("sinek:jsconsumer:debug"), info: Debug("sinek:jsconsumer:info"), warn: Debug("sinek:jsconsumer:warn"), error: Debug("sinek:jsconsumer:error") }; type Lag = { status: LagStatus[], at: number, took: number } type ConsumeCallback = ((messages, callback) => void) | null; const defaultLag = { status: [], at: 0, took: 0, }; /** * wrapper around kafkajs that immitates nconsumer * @extends EventEmitter */ export class JSConsumer extends EventEmitter { kafkaClient: Kafka; topics: string[]; config: JSKafkaConsumerConfig; asString = true; asJSON = false; asStream = false; consumer: Consumer | undefined; private _firstMessageConsumed = false; private _totalIncomingMessages = 0; private _lastReceived = 0; private _totalProcessedMessages = 0; private _lastProcessed = 0; private _isAutoCommitting = false; private _batchCount = 0; private _batchCommitts = 0; private _batchConfig: BatchConfig = {}; private _totalBatches = 0; private _lastLagStatus: Lag = defaultLag; private _lagCache: Lag = defaultLag; private _analyticsOptions: AnalyticsConfig | null = null; _analytics: ConsumerAnalytics | undefined; private _consumedSinceCommit = 0; private _emptyFetches = 0; private _avgBatchProcessingTime = 0; private _extCommitCallback: ((e: Error, partitions: any[]) => void) | undefined; private _errors = 0; private _groupId = ""; private _adminClient: Admin; private _health: ConsumerHealth; private _inClosing = false; /** * creates a new consumer instance * @param {string|Array} topics - topic or topics to subscribe to * @param {object} config - configuration object */ constructor(topics: string | string[], config: JSKafkaConsumerConfig) { super(); if (!config) { throw new Error("You are missing a config object."); } if (!config.logger || typeof config.logger !== "object") { config.logger = DEFAULT_LOGGER; } const { "metadata.broker.list": brokerList, "client.id": clientId, "security.protocol": securityProtocol, "ssl.ca.location": sslCALocation, "ssl.certificate.location": sslCertLocation, "ssl.key.location": sslKeyLocation, "ssl.key.password": sslKeyPassword, "sasl.mechanisms": mechanism, "sasl.username": username, "sasl.password": password, } = config.noptions; const brokers = brokerList.split(","); if (!brokers || !clientId) { throw new Error("You are missing a broker or group configs"); } if (securityProtocol) { this.kafkaClient = new Kafka({ brokers, clientId, ssl: { ca: [fs.readFileSync(sslCALocation as string, "utf-8")], cert: fs.readFileSync(sslCertLocation as string, "utf-8"), key: fs.readFileSync(sslKeyLocation as string, "utf-8"), passphrase: sslKeyPassword, }, sasl: { mechanism: mechanism as SASLMechanism, username: username as string, password: password as string, }, }); } else { this.kafkaClient = new Kafka({ brokers, clientId }); } this._adminClient = this.kafkaClient.admin(); this.topics = Array.isArray(topics) ? topics : [topics]; this.config = config; this._health = new ConsumerHealth(this, this.config.health); this.on("error", () => { this._errors++; }); this.on("batch", (messages, { resolveOffset, syncEvent }) => { const startBPT = Date.now(); this._totalIncomingMessages += messages.length; this._lastReceived = Date.now(); const messageOffsets: any[] = []; const mappedMessages = messages.map((message) => { this.config.logger!.debug(message); message.value = this._convertMessageValue(message.value, this.asString, this.asJSON); this.emit("message", message); messageOffsets.push(message.offset); return message; }); //execute sync event and wrap callback (in this mode the sync event recieves all messages as batch) syncEvent(mappedMessages, async (__error) => { /* ### sync event callback does not handle errors ### */ if (__error && this.config && this.config.logger && this.config.logger.warn) { this.config.logger.warn("Please dont pass errors to sinek consume callback", __error); } this._bumpVariableOfBatch(startBPT, mappedMessages.length); try { messageOffsets.forEach((offset) => { resolveOffset(offset); }); } catch (error) { this.emit("error", error); } }); }); } /** * connect to broker * @param {boolean} asStream - optional, if client should be started in streaming mode * @param {object} opts - optional, options asString, asJSON (booleans) * @returns {Promise.<*>} */ connect(asStream = false): Promise<any> { if (asStream) { return Promise.reject(new Error("JSConsumer does not support streaming mode.")); } const { logger, groupId } = this.config; let { noptions, tconf } = this.config; const config = { "broker.list": null, "group.id": typeof groupId === "string" ? groupId : "", "enable.auto.commit": false, // default in librdkafka is true - what makes this dangerous for our batching logic(s) }; const overwriteConfig = { "offset_commit_cb": this._onOffsetCommit.bind(this) }; if (noptions && noptions["offset_commit_cb"]) { if (typeof noptions["offset_commit_cb"] !== "function") { return Promise.reject(new Error("offset_commit_cb must be a function.")); } this._extCommitCallback = noptions["offset_commit_cb"]; } noptions = Object.assign({}, config, noptions, overwriteConfig); logger!.debug(JSON.stringify(noptions)); this._isAutoCommitting = noptions["enable.auto.commit"] || false; tconf = tconf || undefined; logger!.debug(JSON.stringify(tconf)); this._groupId = noptions["group.id"]; if (!this._groupId) { return Promise.reject(new Error("Group need to be configured on noptions['groupId.id']")); } return this._connectInFlow(logger as KafkaLogger); } /** * @private * event handler for async offset committs * @param {Error} error * @param {Array} partitions */ _onOffsetCommit(error: Error, partitions: any[]): void { if (this._extCommitCallback) { try { this._extCommitCallback(error, partitions); } catch (error) { this.emit("error", error); } } if (error) { return this.config.logger!.warn("commit request failed with an error: " + JSON.stringify(error)); } this.config.logger!.debug(JSON.stringify(partitions)); } /** * @private * connects in flow mode mode * @param {object} logger * @param {object} noptions * @param {object} tconf * @returns {Promise.<*>} */ _connectInFlow(logger: KafkaLogger): Promise { return new Promise(( resolve, reject ) => { this.consumer = this.kafkaClient.consumer({ groupId: this._groupId }); const { CONNECT, CRASH, DISCONNECT } = this.consumer.events; this.consumer.on(CRASH, error => { this.emit("error", error); }); this.consumer.on(DISCONNECT, () => { if (this._inClosing) { this._reset(); } logger.warn("Disconnected."); //auto-reconnect --> handled by consumer.consume(); }); this.consumer.on(CONNECT, payload => { logger.info(`KafkaJS consumer (flow) ready with group. Info: ${payload}.`); this.emit("ready"); }); logger.debug("Connecting.."); try { Promise.all([ this.consumer.connect(), this._adminClient.connect(), ]).then(resolve); } catch (error) { this.emit("error", error); return reject(error); } }); } /** * @private * runs (and calls itself) until it has successfully * read a certain size of messages from the broker * @returns {boolean} */ _consumerRun(syncEvent: ConsumeCallback): Promise<boolean> { if (!this.resume || !this.consumer) { return false; } this.consumer.run({ eachBatchAutoResolve: false, eachBatch: async ({ batch, uncommittedOffsets, resolveOffset, heartbeat, isRunning, isStale }) => { const messages = batch.messages; if (!isRunning() || isStale() || !messages.length) { //always ensure longer wait on consume error if (!isRunning() || isStale()) { if (this.config && this.config.logger && this.config.logger.debug) { // @todo - not sure where error comes from? // this.config.logger.debug(`Consumed recursively with error ${error.message}`); this.config.logger.debug(`Consumed recursively with error ${messages}`); } this.emit("error", Error); } //retry asap this._emptyFetches++; } else { if (this.config && this.config.logger && this.config.logger.debug) { this.config.logger.debug(`Consumed recursively with success ${messages.length}`); } this._emptyFetches = 0; //reset await uncommittedOffsets(); this.emit("batch", batch.messages, { resolveOffset, syncEvent }); } await heartbeat(); } }); } /** * @private * converts message value according to booleans * @param {Buffer} _value * @param {boolean} asString * @param {boolean} asJSON * @returns {Buffer|string|object} */ _convertMessageValue( _value: Buffer, asString = true, asJSON = false ): Buffer | string| Record<string, unknown> { if (!_value) { return _value; } if (!asString && !asJSON) { return _value; } let value; if (asString || asJSON) { value = _value.toString(MESSAGE_CHARSET); } if (asJSON) { try { value = JSON.parse(value); } catch (error) { this.config.logger!.warn(`Failed to parse message value as json: ${error.message}, ${value}`); } } return value; } _bumpVariableOfBatch(startBPT: number, batchLength: number): void { this._totalProcessedMessages += batchLength; this._lastProcessed = Date.now(); //when all messages from the batch are processed this._avgBatchProcessingTime = (this._avgBatchProcessingTime + (Date.now() - startBPT)) / 2; this._consumedSinceCommit += batchLength; this._totalBatches++; this._batchCount++; this.config.logger!.debug(`committing after ${this._batchCount}, batches, messages: ${this._consumedSinceCommit}`); this.emit("commit", this._consumedSinceCommit); this._batchCount = 0; this._batchCommitts++; this._consumedSinceCommit = 0; } async _consumeHandler(syncEvent: ConsumeCallback, { manualBatching }: { manualBatching: boolean }): Promise<void> { if (this._isAutoCommitting !== null && typeof this._isAutoCommitting !== "undefined") { this.config.logger!.warn("enable.auto.commit has no effect in 1:n consume-mode, set to null or undefined to remove this message." + "You can pass 'noBatchCommits' as true via options to .consume(), if you want to commit manually."); } if (this._isAutoCommitting) { throw new Error("Please disable enable.auto.commit when using 1:n consume-mode."); } if (!manualBatching) { this.config.logger!.warn("The consumer only allow manual batching for now"); } this.config.logger!.info("Batching manually.."); this._consumerRun(syncEvent); } /** * subscribe and start to consume, should be called only once after connection is successfull * options object supports the following fields: * batchSize amount of messages that is max. fetched per round * commitEveryNBatch amount of messages that should be processed before committing * concurrency the concurrency of the execution per batch * commitSync if the commit action should be blocking or non-blocking * noBatchCommits defaults to false, if set to true, no commits will be made for batches * * @param {function} syncEvent - callback (receives messages and callback as params) * @param {string} asString - optional, if message value should be decoded to utf8 * @param {boolean} asJSON - optional, if message value should be json deserialised * @param {object} options - optional object containing options for 1:n mode: * @returns {Promise.<*>} */ consume(syncEvent: ConsumeCallback = null, asString = true, asJSON = false, options: BatchConfig): Promise<void> { let { batchSize, commitEveryNBatch, concurrency, commitSync, noBatchCommits, manualBatching, sortedManualBatch, } = options; batchSize = batchSize || 1; commitEveryNBatch = commitEveryNBatch || 1; concurrency = concurrency || 1; commitSync = typeof commitSync === "undefined" ? true : commitSync; //default is true noBatchCommits = typeof noBatchCommits === "undefined" ? false : noBatchCommits; //default is false manualBatching = typeof manualBatching === "undefined" ? true : manualBatching; //default is true sortedManualBatch = typeof sortedManualBatch === "undefined" ? false : sortedManualBatch; //default is false this._batchConfig = { batchSize, commitEveryNBatch, concurrency, commitSync, noBatchCommits, manualBatching, sortedManualBatch } as BatchConfig; this.asString = asString; this.asJSON = asJSON; if (!this.consumer) { return Promise.reject(new Error("You must call and await .connect() before trying to consume messages.")); } if (syncEvent && this.asStream) { return Promise.reject(new Error("Usage of syncEvent is not permitted in streaming mode.")); } if (this.asStream) { return Promise.reject(new Error("Calling .consume() is not required in streaming mode.")); } if (sortedManualBatch && !manualBatching) { return Promise.reject(new Error("manualBatching batch option must be enabled, if you enable sortedManualBatch batch option.")); } if (this.config && this.config.logger) { this.config.logger.warn("batchSize is not supported by KafkaJS"); } const topics = this.topics; if (topics && topics.length) { this.config.logger!.info(`Subscribing to topics: ${topics.join(", ")}.`); topics.forEach(async (topic) => { await this.consumer!.subscribe({ topic }); }); } else { this.config.logger!.info("Not subscribing to any topics initially."); } if (!syncEvent) { return this.consumer.run({ eachMessage: async ({ message }) => { const m: FormattedKafkaMessage = message; this.config.logger!.debug(JSON.stringify(message)); this._totalIncomingMessages++; this._lastReceived = Date.now(); m.value = this._convertMessageValue(message.value, asString, asJSON); if (!this._firstMessageConsumed) { this._firstMessageConsumed = true; this.emit("first-drain-message", m); } this.emit("message", m); } }); } return this._consumeHandler(syncEvent, { manualBatching, }); } /** * pause the consumer for specific topics (partitions) * @param {Array.<{}>} topicPartitions * @throws {LibrdKafkaError} */ pause(topicPartitions = []): void { if (this.consumer) { return this.consumer.pause(topicPartitions); } } /** * resume the consumer for specific topic (partitions) * @param {Array.<{}>} topicPartitions * @throws {LibrdKafkaError} */ resume(topicPartitions = []): void { if (this.consumer) { return this.consumer.resume(topicPartitions); } } /** * returns consumer statistics * @todo - update type for consumer stats. * @returns {object} */ getStats(): ConsumerStats { return { totalIncoming: this._totalIncomingMessages, lastMessage: this._lastReceived, receivedFirstMsg: this._firstMessageConsumed, totalProcessed: this._totalProcessedMessages, lastProcessed: this._lastProcessed, queueSize: null, isPaused: false, drainStats: null, omittingQueue: true, autoComitting: this._isAutoCommitting, consumedSinceCommit: this._consumedSinceCommit, batch: { current: this._batchCount, committs: this._batchCommitts, total: this._totalBatches, currentEmptyFetches: this._emptyFetches, avgProcessingTime: this._avgBatchProcessingTime, config: this._batchConfig, }, lag: this._lagCache, //read from private cache totalErrors: this._errors }; } /** * @private * resets internal values */ _reset(): void { this._firstMessageConsumed = false; this._inClosing = false; this._totalIncomingMessages = 0; this._lastReceived = 0; this._totalProcessedMessages = 0; this._lastProcessed = 0; this.asStream = false; this._batchCount = 0; this._batchCommitts = 0; this._totalBatches = 0; this._lagCache = defaultLag; this._analytics = undefined; this._consumedSinceCommit = 0; this._emptyFetches = 0; this._avgBatchProcessingTime = 0; this._errors = 0; this._extCommitCallback = undefined; } /** * closes connection if open */ async close(): Promise { if (this.consumer) { this._inClosing = true; return Promise.all([ this.consumer.disconnect(), this._adminClient.disconnect(), ]); } } /** * gets the lowest and highest offset that is available * for a given kafka topic * @param {string} topic - name of the kafka topic * @param {number} partition - optional, default is 0 * @returns {Promise.<object>} */ async getOffsetForTopicPartition(topic: string, partition = 0): Promise<ComittedOffsets[]> { if (!this.consumer) { return Promise.reject(new Error("Consumer not yet connected.")); } if (this.config && this.config.logger && this.config.logger.debug) { this.config.logger.debug(`Fetching offsets for topic partition ${topic} ${partition}.`); } const offsetInfos = await this._adminClient.fetchOffsets({ groupId: this._groupId, topic }); return offsetInfos.filter((offsetInfo) => offsetInfo.partition === partition)[0]; } /** * gets all comitted offsets * @param {number} timeout - optional, default is 2500 * @returns {Promise.<Array>} */ async getComittedOffsets(timeout = 2500): Promise<ComittedOffsets[]> { if (!this.consumer) { return []; } if (this.config && this.config.logger && this.config.logger.debug) { this.config.logger.debug(`Fetching committed offsets ${timeout}`); } return [].concat([], await Promise.all( this.topics.map(async (topic) => { const offsets = await this._adminClient.fetchOffsets({ groupId: this._groupId, topic, }); return offsets.map((offsetInfo) => ({...offsetInfo, topic})); }) ) ); } /** * gets all topic-partitions which are assigned to this consumer * @returns {Array} */ async getAssignedPartitions(): Promise<[]> { try { return (await this.getComittedOffsets()); } catch (error) { this.emit("error", error); return []; } } /** * @static * return the offset that has been comitted for a given topic and partition * @param {string} topic - topic name * @param {number} partition - partition * @param {Array} offsets - commit offsets from getComittedOffsets() */ static findPartitionOffset(topic: string, partition: number, offsets: ComittedOffsets[]): string { for (let i = 0; i < offsets.length; i++) { if (offsets[i].topic === topic && offsets[i].partition === partition) { return offsets[i].offset; } } throw new Error(`no offset found for ${topic}:${partition} in comitted offsets.`); } /** * compares the local commit offset status with the remote broker * status for the topic partitions, for all assigned partitions of * the consumer * @param {boolean} noCache - when analytics are enabled the results can be taken from cache * @returns {Promise.<Array>} */ async getLagStatus(noCache = false): Promise<LagStatus[]> { if (!this.consumer) { return []; } //if allowed serve from cache if (!noCache && this._lagCache && this._lagCache.status!) { return this._lagCache.status; } if (this.config && this.config.logger && this.config.logger.debug) { this.config.logger.debug(`Getting lag status ${noCache}`); } const startT = Date.now(); const assigned = this.getAssignedPartitions(); const comitted = await this.getComittedOffsets(); const status = await Promise.all(assigned.map(async topicPartition => { try { const brokerState = await this.getOffsetForTopicPartition(topicPartition.topic, topicPartition.partition); // const comittedOffset = NConsumer.findPartitionOffset(topicPartition.topic, topicPartition.partition, comitted); // const topicOffset = await (await this._adminClient.fetchTopicOffsets(topicPartition.topic)).pop(); // const comittedOffset = topicOffset.offset; return { topic: topicPartition.topic, partition: topicPartition.partition, lowDistance: comitted - brokerState.lowOffset, highDistance: brokerState.highOffset - comitted, detail: { lowOffset: brokerState.lowOffset, highOffset: brokerState.highOffset, } }; } catch (error) { return { topic: topicPartition.topic, partition: topicPartition.partition, error }; } })); const duration = Date.now() - startT; this.config.logger!.info(`fetching and comparing lag status took: ${duration} ms.`); //store cached version if (status && Array.isArray(status)) { //keep last version if (this._lagCache && this._lagCache.status) { this._lastLagStatus = Object.assign({}, this._lagCache); } //cache new version this._lagCache = { status, at: startT, took: Date.now() - startT }; } return status; } /** * called in interval * @private */ _runAnalytics(): Promise<void> { if (!this._analytics) { this._analytics = new ConsumerAnalytics(this, this._analyticsOptions, this.config.logger as KafkaLogger); } return this._analytics.run() .then(res => this.emit("analytics", res)) .catch(error => this.emit("error", error)); } /** * returns the last computed analytics results * @throws * @returns {object} */ getAnalytics(): ConsumerRunResult | null { if (!this._analytics) { this.emit("error", new Error("You have not enabled analytics on this consumer instance.")); return null; } return this._analytics.getLastResult(); } /** * called in interval * @private */ _runLagCheck(): LagStatus[] { return this.getLagStatus(true).catch(error => this.emit("error", error)); } /** * runs a health check and returns object with status and message * @returns {Promise.<object>} */ checkHealth(): Promise<Check> { return this._health.check(); } /** * resolve the metadata information for a give topic * will create topic if it doesnt exist * @param {string} topic - name of the topic to query metadata for * @returns {Promise.<Metadata>} */ getTopicMetadata(topic: string): Promise<Metadata|Error> { return new Promise(( resolve, reject ) => { if (!this.consumer) { return reject(new Error("You must call and await .connect() before trying to get metadata.")); } if (this.config && this.config.logger && this.config.logger.debug) { this.config.logger.debug(`Fetching topic metadata ${topic}`); } this._adminClient.fetchTopicMetadata({ topics: [topic], }) .then((raw) => resolve(new Metadata(raw[0]))) .catch((e) => reject(e)); }); } /** * @alias getTopicMetadata * @param {number} timeout - optional, default is 2500 * @returns {Promise.<Metadata>} */ getMetadata(): Promise<Metadata|Error> { return this.getTopicMetadata(""); } /** * returns a list of available kafka topics on the connected brokers */ async getTopicList(): Promise<string[]> { const metadata: Metadata = await this.getMetadata(); return metadata.asTopicList(); } /** * Gets the last lag status * * @returns {Lag} */ getLastLagStatus(): Lag { return this._lastLagStatus; } /** * Gets the lag cache * * @returns {Lag} */ getLagCache(): Lag { return this._lagCache; } }
the_stack
import type { Renderer } from './compose_ts'; import type * as SDK from 'balena-sdk'; import type Dockerode = require('dockerode'); import * as path from 'path'; import type { Composition, ImageDescriptor } from 'resin-compose-parse'; import type { BuiltImage, ComposeOpts, ComposeProject, Release, TaggedImage, } from './compose-types'; import { getChalk } from './lazy'; import Logger = require('./logger'); import { ProgressCallback } from 'docker-progress'; export function generateOpts(options: { source?: string; projectName?: string; nologs: boolean; 'noconvert-eol': boolean; dockerfile?: string; 'multi-dockerignore': boolean; 'noparent-check': boolean; }): Promise<ComposeOpts> { const { promises: fs } = require('fs') as typeof import('fs'); return fs.realpath(options.source || '.').then((projectPath) => ({ projectName: options.projectName, projectPath, inlineLogs: !options.nologs, convertEol: !options['noconvert-eol'], dockerfilePath: options.dockerfile, multiDockerignore: !!options['multi-dockerignore'], noParentCheck: options['noparent-check'], })); } /** Parse the given composition and return a structure with info. Input is: * - composePath: the *absolute* path to the directory containing the compose file * - composeStr: the contents of the compose file, as a string */ export function createProject( composePath: string, composeStr: string, projectName = '', imageTag = '', ): ComposeProject { const yml = require('js-yaml') as typeof import('js-yaml'); const compose = require('resin-compose-parse') as typeof import('resin-compose-parse'); // both methods below may throw. const rawComposition = yml.load(composeStr); const composition = compose.normalize(rawComposition); projectName ||= path.basename(composePath); const descriptors = compose.parse(composition).map(function (descr) { // generate an image name based on the project and service names // if one is not given and the service requires a build if ( typeof descr.image !== 'string' && descr.image.context != null && descr.image.tag == null ) { const { makeImageName } = require('./compose_ts') as typeof import('./compose_ts'); descr.image.tag = makeImageName(projectName, descr.serviceName, imageTag); } return descr; }); return { path: composePath, name: projectName, composition, descriptors, }; } export const createRelease = async function ( apiEndpoint: string, auth: string, userId: number, appId: number, composition: Composition, draft: boolean, semver?: string, contract?: string, ): Promise<Release> { const _ = require('lodash') as typeof import('lodash'); const crypto = require('crypto') as typeof import('crypto'); const releaseMod = require('balena-release') as typeof import('balena-release'); const client = releaseMod.createClient({ apiEndpoint, auth }); const { release, serviceImages } = await releaseMod.create({ client, user: userId, application: appId, composition, source: 'local', commit: crypto.pseudoRandomBytes(16).toString('hex').toLowerCase(), semver, is_final: !draft, contract, }); return { client, release: _.pick(release, [ 'id', 'status', 'commit', 'composition', 'source', 'is_final', 'contract', 'semver', 'start_timestamp', 'end_timestamp', ]), serviceImages: _.mapValues( serviceImages, (serviceImage) => _.omit(serviceImage, [ 'created_at', 'is_a_build_of__service', '__metadata', ]) as Omit< typeof serviceImage, 'created_at' | 'is_a_build_of__service' | '__metadata' >, ), }; }; export const tagServiceImages = ( docker: Dockerode, images: BuiltImage[], serviceImages: Release['serviceImages'], ): Promise<TaggedImage[]> => Promise.all( images.map(function (d) { const serviceImage = serviceImages[d.serviceName]; const imageName = serviceImage.is_stored_at__image_location; const match = /(.*?)\/(.*?)(?::([^/]*))?$/.exec(imageName); if (match == null) { throw new Error(`Could not parse imageName: '${imageName}'`); } const [, registry, repo, tag = 'latest'] = match; const name = `${registry}/${repo}`; return docker .getImage(d.name) .tag({ repo: name, tag, force: true }) .then(() => docker.getImage(`${name}:${tag}`)) .then((localImage) => ({ serviceName: d.serviceName, serviceImage, localImage, registry, repo, logs: d.logs, props: d.props, })); }), ); export const getPreviousRepos = ( sdk: SDK.BalenaSDK, logger: Logger, appID: number, ): Promise<string[]> => sdk.pine .get<SDK.Release>({ resource: 'release', options: { $select: 'id', $filter: { belongs_to__application: appID, status: 'success', }, $expand: { contains__image: { $select: 'image', $expand: { image: { $select: 'is_stored_at__image_location' } }, }, }, $orderby: 'id desc', $top: 1, }, }) .then(function (release) { // grab all images from the latest release, return all image locations in the registry if (release.length > 0) { const images = release[0].contains__image as Array<{ image: [SDK.Image]; }>; const { getRegistryAndName } = require('resin-multibuild') as typeof import('resin-multibuild'); return Promise.all( images.map(function (d) { const imageName = d.image[0].is_stored_at__image_location || ''; const registry = getRegistryAndName(imageName); logger.logDebug( `Requesting access to previously pushed image repo (${registry.imageName})`, ); return registry.imageName; }), ); } else { return []; } }) .catch((e) => { logger.logDebug(`Failed to access previously pushed image repo: ${e}`); return []; }); export const authorizePush = function ( sdk: SDK.BalenaSDK, tokenAuthEndpoint: string, registry: string, images: string[], previousRepos: string[], ): Promise<string> { if (!Array.isArray(images)) { images = [images]; } images.push(...previousRepos); return sdk.request .send({ baseUrl: tokenAuthEndpoint, url: '/auth/v1/token', qs: { service: registry, scope: images.map((repo) => `repository:${repo}:pull,push`), }, }) .then(({ body }) => body.token) .catch(() => ''); }; // utilities const renderProgressBar = function (percentage: number, stepCount: number) { const _ = require('lodash') as typeof import('lodash'); percentage = _.clamp(percentage, 0, 100); const barCount = Math.floor((stepCount * percentage) / 100); const spaceCount = stepCount - barCount; const bar = `[${_.repeat('=', barCount)}>${_.repeat(' ', spaceCount)}]`; return `${bar} ${_.padStart(`${percentage}`, 3)}%`; }; export const pushProgressRenderer = function ( tty: ReturnType<typeof import('./tty')>, prefix: string, ): ProgressCallback & { end: () => void } { const fn: ProgressCallback & { end: () => void } = function (e) { const { error, percentage } = e; if (error != null) { throw new Error(error); } const bar = renderProgressBar(percentage, 40); return tty.replaceLine(`${prefix}${bar}\r`); }; fn.end = () => { tty.clearLine(); }; return fn; }; export class BuildProgressUI implements Renderer { public streams; private _prefix; private _prefixWidth; private _tty; private _services; private _startTime: undefined | number; private _ended; private _serviceToDataMap: Dictionary<{ status?: string; progress?: number; error?: Error; }> = {}; private _cancelled; private _spinner; private _runloop: | undefined | ReturnType<typeof import('./compose_ts').createRunLoop>; // these are to handle window wrapping private _maxLineWidth: undefined | number; private _lineWidths: number[] = []; constructor( tty: ReturnType<typeof import('./tty')>, descriptors: ImageDescriptor[], ) { this._handleEvent = this._handleEvent.bind(this); this.start = this.start.bind(this); this.end = this.end.bind(this); this._display = this._display.bind(this); const _ = require('lodash') as typeof import('lodash'); const through = require('through2') as typeof import('through2'); const eventHandler = this._handleEvent; const services = _.map(descriptors, 'serviceName'); const streams = _(services) .map(function (service) { const stream = through.obj(function (event, _enc, cb) { eventHandler(service, event); return cb(); }); stream.pipe(tty.stream, { end: false }); return [service, stream]; }) .fromPairs() .value(); this._tty = tty; this._services = services; // Logger magically prefixes the log line with [Build] etc., but it doesn't // work well with the spinner we're also showing. Manually build the prefix // here and bypass the logger. const prefix = getChalk().blue('[Build]') + ' '; const offset = 10; // account for escape sequences inserted for colouring this._prefixWidth = offset + prefix.length + _.max(_.map(services, (s) => s.length))!; this._prefix = prefix; this._ended = false; this._cancelled = false; this._spinner = ( require('./compose_ts') as typeof import('./compose_ts') ).createSpinner(); this.streams = streams; } _handleEvent( service: string, event: { status?: string; progress?: number; error?: Error }, ) { this._serviceToDataMap[service] = event; } start() { this._tty.hideCursor(); this._services.forEach((service) => { this.streams[service].write({ status: 'Preparing...' }); }); this._runloop = ( require('./compose_ts') as typeof import('./compose_ts') ).createRunLoop(this._display); this._startTime = Date.now(); } end(summary?: Dictionary<string>) { if (this._ended) { return; } this._ended = true; this._runloop?.end(); this._runloop = undefined; this._clear(); this._renderStatus(true); this._renderSummary(summary ?? this._getServiceSummary()); this._tty.showCursor(); } _display() { this._clear(); this._renderStatus(); this._renderSummary(this._getServiceSummary()); this._tty.cursorUp(this._services.length + 1); // for status line } _clear() { this._tty.deleteToEnd(); this._maxLineWidth = this._tty.currentWindowSize().width; } _getServiceSummary() { const _ = require('lodash') as typeof import('lodash'); const services = this._services; const serviceToDataMap = this._serviceToDataMap; return _(services) .map(function (service) { const { status, progress, error } = serviceToDataMap[service] ?? {}; if (error) { return `${error}`; } else if (progress) { const bar = renderProgressBar(progress, 20); if (status) { return `${bar} ${status}`; } return `${bar}`; } else if (status) { return `${status}`; } else { return 'Waiting...'; } }) .map((data, index) => [services[index], data]) .fromPairs() .value(); } _renderStatus(end = false) { const moment = require('moment') as typeof import('moment'); ( require('moment-duration-format') as typeof import('moment-duration-format') )(moment); this._tty.clearLine(); this._tty.write(this._prefix); if (end && this._cancelled) { this._tty.writeLine('Build cancelled'); } else if (end) { const serviceCount = this._services.length; const serviceStr = serviceCount === 1 ? '1 service' : `${serviceCount} services`; const durationStr = this._startTime == null ? 'unknown time' : moment .duration( Math.floor((Date.now() - this._startTime) / 1000), 'seconds', ) .format(); this._tty.writeLine(`Built ${serviceStr} in ${durationStr}`); } else { this._tty.writeLine(`Building services... ${this._spinner()}`); } } _renderSummary(serviceToStrMap: Dictionary<string>) { const _ = require('lodash') as typeof import('lodash'); const chalk = getChalk(); const truncate = require('cli-truncate') as typeof import('cli-truncate'); const strlen = require('string-width') as typeof import('string-width'); this._services.forEach((service, index) => { let str = _.padEnd(this._prefix + chalk.bold(service), this._prefixWidth); str += serviceToStrMap[service]; if (this._maxLineWidth != null) { str = truncate(str, this._maxLineWidth); } this._lineWidths[index] = strlen(str); this._tty.clearLine(); this._tty.writeLine(str); }); } } export class BuildProgressInline implements Renderer { public streams; private _prefixWidth; private _outStream; private _services; private _startTime: number | undefined; private _ended; constructor( outStream: NodeJS.ReadWriteStream, descriptors: Array<{ serviceName: string }>, ) { this.start = this.start.bind(this); this.end = this.end.bind(this); this._renderEvent = this._renderEvent.bind(this); const _ = require('lodash') as typeof import('lodash'); const through = require('through2') as typeof import('through2'); const services = _.map(descriptors, 'serviceName'); const eventHandler = this._renderEvent; const streams = _(services) .map(function (service) { const stream = through.obj(function (event, _enc, cb) { eventHandler(service, event); return cb(); }); stream.pipe(outStream, { end: false }); return [service, stream]; }) .fromPairs() .value(); const offset = 10; // account for escape sequences inserted for colouring this._prefixWidth = offset + _.max(_.map(services, (s) => s.length))!; this._outStream = outStream; this._services = services; this._ended = false; this.streams = streams; } start() { this._outStream.write('Building services...\n'); this._services.forEach((service) => { this.streams[service].write({ status: 'Preparing...' }); }); this._startTime = Date.now(); } end(summary?: Dictionary<string>) { const moment = require('moment') as typeof import('moment'); ( require('moment-duration-format') as typeof import('moment-duration-format') )(moment); if (this._ended) { return; } this._ended = true; if (summary != null) { this._services.forEach((service) => { this._renderEvent(service, { status: summary[service] }); }); } const serviceCount = this._services.length; const serviceStr = serviceCount === 1 ? '1 service' : `${serviceCount} services`; const durationStr = this._startTime == null ? 'unknown time' : moment .duration( Math.floor((Date.now() - this._startTime) / 1000), 'seconds', ) .format(); this._outStream.write(`Built ${serviceStr} in ${durationStr}\n`); } _renderEvent(service: string, event: { status?: string; error?: Error }) { const _ = require('lodash') as typeof import('lodash'); const str = (function () { const { status, error } = event; if (error) { return `${error}`; } else if (status) { return `${status}`; } else { return 'Waiting...'; } })(); const prefix = _.padEnd(getChalk().bold(service), this._prefixWidth); this._outStream.write(prefix); this._outStream.write(str); this._outStream.write('\n'); } }
the_stack
declare module com { export module google { export module android { export module gms { export module auth { export module api { export class Auth { public static class: java.lang.Class<com.google.android.gms.auth.api.Auth>; public static PROXY_API: com.google.android.gms.common.api.Api<com.google.android.gms.auth.api.AuthProxyOptions>; public static CREDENTIALS_API: com.google.android.gms.common.api.Api<com.google.android.gms.auth.api.Auth.AuthCredentialsOptions>; public static GOOGLE_SIGN_IN_API: com.google.android.gms.common.api.Api<com.google.android.gms.auth.api.signin.GoogleSignInOptions>; public static ProxyApi: com.google.android.gms.auth.api.proxy.ProxyApi; public static CredentialsApi: com.google.android.gms.auth.api.credentials.CredentialsApi; public static GoogleSignInApi: com.google.android.gms.auth.api.signin.GoogleSignInApi; // public static zba: com.google.android.gms.common.api.Api.ClientKey<com.google.android.gms.internal.auth-api.zbo>; // public static zbb: com.google.android.gms.common.api.Api.ClientKey<com.google.android.gms.auth.api.signin.internal.zbe>; } export module Auth { export class AuthCredentialsOptions extends com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.auth.api.Auth.AuthCredentialsOptions>; public zbd(): string; public equals(param0: any): boolean; public hashCode(): number; public zba(): globalAndroid.os.Bundle; public constructor(param0: com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder); } export module AuthCredentialsOptions { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder>; public zbb: string; public constructor(); public constructor(param0: com.google.android.gms.auth.api.Auth.AuthCredentialsOptions); public forceEnableSaveDialog(): com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder; public zba(param0: string): com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class Credential { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.Credential>; public static EXTRA_KEY: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.Credential>; public getProfilePictureUri(): globalAndroid.net.Uri; public getAccountType(): string; public getGivenName(): string; public getName(): string; public getPassword(): string; public equals(param0: any): boolean; public getFamilyName(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public getId(): string; public getIdTokens(): java.util.List<com.google.android.gms.auth.api.credentials.IdToken>; } export module Credential { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.Credential.Builder>; public setProfilePictureUri(param0: globalAndroid.net.Uri): com.google.android.gms.auth.api.credentials.Credential.Builder; public constructor(param0: string); public constructor(param0: com.google.android.gms.auth.api.credentials.Credential); public build(): com.google.android.gms.auth.api.credentials.Credential; public setName(param0: string): com.google.android.gms.auth.api.credentials.Credential.Builder; public setAccountType(param0: string): com.google.android.gms.auth.api.credentials.Credential.Builder; public setPassword(param0: string): com.google.android.gms.auth.api.credentials.Credential.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialPickerConfig { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialPickerConfig>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.CredentialPickerConfig>; /** @deprecated */ public isForNewAccount(): boolean; public shouldShowAddAccountButton(): boolean; public shouldShowCancelButton(): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module CredentialPickerConfig { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Builder>; public constructor(); public setShowAddAccountButton(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Builder; public setPrompt(param0: number): com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Builder; public build(): com.google.android.gms.auth.api.credentials.CredentialPickerConfig; /** @deprecated */ public setForNewAccount(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Builder; public setShowCancelButton(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Builder; } export class Prompt { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialPickerConfig.Prompt>; /** * Constructs a new instance of the com.google.android.gms.auth.api.credentials.CredentialPickerConfig$Prompt interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static SIGN_UP: number; public static CONTINUE: number; public static SIGN_IN: number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.CredentialRequest>; public getServerClientId(): string; public isPasswordLoginSupported(): boolean; public getIdTokenNonce(): string; public getCredentialPickerConfig(): com.google.android.gms.auth.api.credentials.CredentialPickerConfig; public getCredentialHintPickerConfig(): com.google.android.gms.auth.api.credentials.CredentialPickerConfig; /** @deprecated */ public getSupportsPasswordLogin(): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public isIdTokenRequested(): boolean; public getAccountTypesSet(): java.util.Set<string>; public getAccountTypes(): androidNative.Array<string>; } export module CredentialRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialRequest.Builder>; public setIdTokenNonce(param0: string): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public setIdTokenRequested(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; /** @deprecated */ public setSupportsPasswordLogin(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public setCredentialHintPickerConfig(param0: com.google.android.gms.auth.api.credentials.CredentialPickerConfig): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public constructor(); public setAccountTypes(param0: androidNative.Array<string>): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public setPasswordLoginSupported(param0: boolean): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public build(): com.google.android.gms.auth.api.credentials.CredentialRequest; public setServerClientId(param0: string): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; public setCredentialPickerConfig(param0: com.google.android.gms.auth.api.credentials.CredentialPickerConfig): com.google.android.gms.auth.api.credentials.CredentialRequest.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialRequestResponse extends com.google.android.gms.common.api.Response<com.google.android.gms.auth.api.credentials.CredentialRequestResult> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialRequestResponse>; public getCredential(): com.google.android.gms.auth.api.credentials.Credential; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialRequestResult { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialRequestResult>; /** * Constructs a new instance of the com.google.android.gms.auth.api.credentials.CredentialRequestResult interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getCredential(): com.google.android.gms.auth.api.credentials.Credential; }); public constructor(); public getCredential(): com.google.android.gms.auth.api.credentials.Credential; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class Credentials { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.Credentials>; public static getClient(param0: globalAndroid.app.Activity): com.google.android.gms.auth.api.credentials.CredentialsClient; public static getClient(param0: globalAndroid.app.Activity, param1: com.google.android.gms.auth.api.credentials.CredentialsOptions): com.google.android.gms.auth.api.credentials.CredentialsClient; public static getClient(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.credentials.CredentialsClient; public static getClient(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.credentials.CredentialsOptions): com.google.android.gms.auth.api.credentials.CredentialsClient; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialsApi { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialsApi>; /** * Constructs a new instance of the com.google.android.gms.auth.api.credentials.CredentialsApi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getHintPickerIntent(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.HintRequest): globalAndroid.app.PendingIntent; delete(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; disableAutoSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; request(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.CredentialRequest): com.google.android.gms.common.api.PendingResult<com.google.android.gms.auth.api.credentials.CredentialRequestResult>; save(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; }); public constructor(); public static ACTIVITY_RESULT_ADD_ACCOUNT: number; public static ACTIVITY_RESULT_OTHER_ACCOUNT: number; public static ACTIVITY_RESULT_NO_HINTS_AVAILABLE: number; public static CREDENTIAL_PICKER_REQUEST_CODE: number; public getHintPickerIntent(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.HintRequest): globalAndroid.app.PendingIntent; public request(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.CredentialRequest): com.google.android.gms.common.api.PendingResult<com.google.android.gms.auth.api.credentials.CredentialRequestResult>; public save(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public disableAutoSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public delete(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialsClient extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.auth.api.Auth.AuthCredentialsOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialsClient>; public disableAutoSignIn(): com.google.android.gms.tasks.Task<java.lang.Void>; public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public request(param0: com.google.android.gms.auth.api.credentials.CredentialRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.credentials.CredentialRequestResponse>; public save(param0: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.tasks.Task<java.lang.Void>; public delete(param0: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.tasks.Task<java.lang.Void>; public getHintPickerIntent(param0: com.google.android.gms.auth.api.credentials.HintRequest): globalAndroid.app.PendingIntent; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class CredentialsOptions extends com.google.android.gms.auth.api.Auth.AuthCredentialsOptions { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialsOptions>; public static DEFAULT: com.google.android.gms.auth.api.credentials.CredentialsOptions; } export module CredentialsOptions { export class Builder extends com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.CredentialsOptions.Builder>; public constructor(); public constructor(param0: com.google.android.gms.auth.api.Auth.AuthCredentialsOptions); public forceEnableSaveDialog(): com.google.android.gms.auth.api.Auth.AuthCredentialsOptions.Builder; public forceEnableSaveDialog(): com.google.android.gms.auth.api.credentials.CredentialsOptions.Builder; public build(): com.google.android.gms.auth.api.credentials.CredentialsOptions; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class HintRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.HintRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.HintRequest>; public getServerClientId(): string; public getHintPickerConfig(): com.google.android.gms.auth.api.credentials.CredentialPickerConfig; public getIdTokenNonce(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public isIdTokenRequested(): boolean; public getAccountTypes(): androidNative.Array<string>; public isEmailAddressIdentifierSupported(): boolean; } export module HintRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.HintRequest.Builder>; public setPhoneNumberIdentifierSupported(param0: boolean): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public constructor(); public setHintPickerConfig(param0: com.google.android.gms.auth.api.credentials.CredentialPickerConfig): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public setIdTokenNonce(param0: string): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public setIdTokenRequested(param0: boolean): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public setServerClientId(param0: string): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public setAccountTypes(param0: androidNative.Array<string>): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public setEmailAddressIdentifierSupported(param0: boolean): com.google.android.gms.auth.api.credentials.HintRequest.Builder; public build(): com.google.android.gms.auth.api.credentials.HintRequest; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class IdToken { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.IdToken>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.IdToken>; public getAccountType(): string; public constructor(param0: string, param1: string); public equals(param0: any): boolean; public getIdToken(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class IdentityProviders { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.IdentityProviders>; public static FACEBOOK: string; public static GOOGLE: string; public static LINKEDIN: string; public static MICROSOFT: string; public static PAYPAL: string; public static TWITTER: string; public static YAHOO: string; public static getIdentityProviderForAccount(param0: globalAndroid.accounts.Account): string; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zba extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.Credential> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zba>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zbb extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.CredentialPickerConfig> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zbb>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zbc extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.CredentialRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zbc>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zbd { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zbd>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zbe extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.HintRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zbe>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module credentials { export class zbf extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.credentials.IdToken> { public static class: java.lang.Class<com.google.android.gms.auth.api.credentials.zbf>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class BeginSignInRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest>; public static zba(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; public getPasswordRequestOptions(): com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions; public equals(param0: any): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getGoogleIdTokenRequestOptions(): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions; public hashCode(): number; public isAutoSelectEnabled(): boolean; public static builder(): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; } export module BeginSignInRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder>; public build(): com.google.android.gms.auth.api.identity.BeginSignInRequest; public constructor(); public zba(param0: string): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; public setAutoSelectEnabled(param0: boolean): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; public setGoogleIdTokenRequestOptions(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; public setPasswordRequestOptions(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions): com.google.android.gms.auth.api.identity.BeginSignInRequest.Builder; } export class GoogleIdTokenRequestOptions { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions>; public isSupported(): boolean; public hashCode(): number; public static builder(): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; public getLinkedServiceId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public equals(param0: any): boolean; public getServerClientId(): string; public getIdTokenDepositionScopes(): java.util.List<string>; public filterByAuthorizedAccounts(): boolean; public getNonce(): string; } export module GoogleIdTokenRequestOptions { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder>; public setServerClientId(param0: string): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; public setSupported(param0: boolean): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; public setNonce(param0: string): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; public associateLinkedAccounts(param0: string, param1: java.util.List<string>): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; public build(): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions; public constructor(); public setFilterByAuthorizedAccounts(param0: boolean): com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions.Builder; } } export class PasswordRequestOptions { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions>; public isSupported(): boolean; public hashCode(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public equals(param0: any): boolean; public static builder(): com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions.Builder; } export module PasswordRequestOptions { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions.Builder>; public setSupported(param0: boolean): com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions.Builder; public build(): com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions; public constructor(); } } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class BeginSignInResult { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.BeginSignInResult>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInResult>; public getPendingIntent(): globalAndroid.app.PendingIntent; public constructor(param0: globalAndroid.app.PendingIntent); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class CredentialSavingClient extends com.google.android.gms.common.api.HasApiKey<com.google.android.gms.auth.api.identity.zbc> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.CredentialSavingClient>; /** * Constructs a new instance of the com.google.android.gms.auth.api.identity.CredentialSavingClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { saveAccountLinkingToken(param0: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult>; savePassword(param0: com.google.android.gms.auth.api.identity.SavePasswordRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SavePasswordResult>; getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; }); public constructor(); public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public saveAccountLinkingToken(param0: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult>; public savePassword(param0: com.google.android.gms.auth.api.identity.SavePasswordRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SavePasswordResult>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class GetSignInIntentRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.GetSignInIntentRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.GetSignInIntentRequest>; public getServerClientId(): string; public static zba(param0: com.google.android.gms.auth.api.identity.GetSignInIntentRequest): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; public getHostedDomainFilter(): string; public getNonce(): string; public equals(param0: any): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public static builder(): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; } export module GetSignInIntentRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder>; public constructor(); public build(): com.google.android.gms.auth.api.identity.GetSignInIntentRequest; public filterByHostedDomain(param0: string): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; public setNonce(param0: string): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; public setServerClientId(param0: string): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; public zba(param0: string): com.google.android.gms.auth.api.identity.GetSignInIntentRequest.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class Identity { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.Identity>; public static getCredentialSavingClient(param0: globalAndroid.app.Activity): com.google.android.gms.auth.api.identity.CredentialSavingClient; public static getCredentialSavingClient(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.identity.CredentialSavingClient; public static getSignInClient(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.identity.SignInClient; public static getSignInClient(param0: globalAndroid.app.Activity): com.google.android.gms.auth.api.identity.SignInClient; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SaveAccountLinkingTokenRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest>; public static TOKEN_TYPE_AUTH_CODE: string; public static EXTRA_TOKEN: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest>; public static builder(): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public getTokenType(): string; public equals(param0: any): boolean; public getConsentPendingIntent(): globalAndroid.app.PendingIntent; public getServiceId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static zba(param0: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public hashCode(): number; public getScopes(): java.util.List<string>; } export module SaveAccountLinkingTokenRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder>; public setServiceId(param0: string): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public constructor(); public setTokenType(param0: string): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public build(): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest; public setConsentPendingIntent(param0: globalAndroid.app.PendingIntent): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public setScopes(param0: java.util.List<string>): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; public zba(param0: string): com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SaveAccountLinkingTokenResult { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult>; public getPendingIntent(): globalAndroid.app.PendingIntent; public hasResolution(): boolean; public equals(param0: any): boolean; public constructor(param0: globalAndroid.app.PendingIntent); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SavePasswordRequest { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SavePasswordRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SavePasswordRequest>; public equals(param0: any): boolean; public static builder(): com.google.android.gms.auth.api.identity.SavePasswordRequest.Builder; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static zba(param0: com.google.android.gms.auth.api.identity.SavePasswordRequest): com.google.android.gms.auth.api.identity.SavePasswordRequest.Builder; public hashCode(): number; public getSignInPassword(): com.google.android.gms.auth.api.identity.SignInPassword; } export module SavePasswordRequest { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SavePasswordRequest.Builder>; public constructor(); public zba(param0: string): com.google.android.gms.auth.api.identity.SavePasswordRequest.Builder; public setSignInPassword(param0: com.google.android.gms.auth.api.identity.SignInPassword): com.google.android.gms.auth.api.identity.SavePasswordRequest.Builder; public build(): com.google.android.gms.auth.api.identity.SavePasswordRequest; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SavePasswordResult { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SavePasswordResult>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SavePasswordResult>; public getPendingIntent(): globalAndroid.app.PendingIntent; public equals(param0: any): boolean; public constructor(param0: globalAndroid.app.PendingIntent); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SignInClient extends com.google.android.gms.common.api.HasApiKey<com.google.android.gms.auth.api.identity.zbl> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SignInClient>; /** * Constructs a new instance of the com.google.android.gms.auth.api.identity.SignInClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getSignInCredentialFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.identity.SignInCredential; beginSignIn(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.BeginSignInResult>; getSignInIntent(param0: com.google.android.gms.auth.api.identity.GetSignInIntentRequest): com.google.android.gms.tasks.Task<globalAndroid.app.PendingIntent>; signOut(): com.google.android.gms.tasks.Task<java.lang.Void>; getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; }); public constructor(); public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public getSignInIntent(param0: com.google.android.gms.auth.api.identity.GetSignInIntentRequest): com.google.android.gms.tasks.Task<globalAndroid.app.PendingIntent>; public getSignInCredentialFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.identity.SignInCredential; public beginSignIn(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.BeginSignInResult>; public signOut(): com.google.android.gms.tasks.Task<java.lang.Void>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SignInCredential { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SignInCredential>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SignInCredential>; public getProfilePictureUri(): globalAndroid.net.Uri; public getGoogleIdToken(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: globalAndroid.net.Uri, param5: string, param6: string); public getGivenName(): string; public getPassword(): string; public equals(param0: any): boolean; public getDisplayName(): string; public getFamilyName(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public getId(): string; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class SignInPassword { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.SignInPassword>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SignInPassword>; public constructor(param0: string, param1: string); public getPassword(): string; public equals(param0: any): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public getId(): string; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zba extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zba>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbb extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInResult> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbb>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbc extends com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbc>; public equals(param0: any): boolean; public constructor(); public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbd extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.GetSignInIntentRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbd>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbe extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbe>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbf extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbf>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbg extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbg>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbh extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbh>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbi extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SavePasswordRequest> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbi>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbj extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SavePasswordResult> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbj>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbk extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SignInCredential> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbk>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbl extends com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbl>; public equals(param0: any): boolean; public constructor(); public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module identity { export class zbm extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.identity.SignInPassword> { public static class: java.lang.Class<com.google.android.gms.auth.api.identity.zbm>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignIn { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignIn>; public static requestPermissions(param0: globalAndroid.app.Activity, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param3: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): void; public static getClient(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): com.google.android.gms.auth.api.signin.GoogleSignInClient; public static requestPermissions(param0: globalAndroid.app.Activity, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param3: androidNative.Array<com.google.android.gms.common.api.Scope>): void; public static getAccountForScopes(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Scope, param2: androidNative.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public static getSignedInAccountFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public static hasPermissions(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): boolean; public static getClient(param0: globalAndroid.app.Activity, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): com.google.android.gms.auth.api.signin.GoogleSignInClient; public static requestPermissions(param0: androidx.fragment.app.Fragment, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param3: androidNative.Array<com.google.android.gms.common.api.Scope>): void; public static getLastSignedInAccount(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public static hasPermissions(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: androidNative.Array<com.google.android.gms.common.api.Scope>): boolean; public static getAccountForExtension(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public static requestPermissions(param0: androidx.fragment.app.Fragment, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param3: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInAccount { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public getAccount(): globalAndroid.accounts.Account; public getGrantedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getGivenName(): string; public zaa(): string; public static createDefault(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public equals(param0: any): boolean; public getIdToken(): string; public getDisplayName(): string; public isExpired(): boolean; public zab(): string; public getFamilyName(): string; public getRequestedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static zaa(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public getPhotoUrl(): globalAndroid.net.Uri; public getEmail(): string; public getServerAuthCode(): string; public getId(): string; public hashCode(): number; public requestExtraScopes(param0: androidNative.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public static fromAccount(param0: globalAndroid.accounts.Account): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInApi { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInApi>; /** * Constructs a new instance of the com.google.android.gms.auth.api.signin.GoogleSignInApi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getSignInIntent(param0: com.google.android.gms.common.api.GoogleApiClient): globalAndroid.content.Intent; getSignInResultFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.signin.GoogleSignInResult; silentSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.OptionalPendingResult<com.google.android.gms.auth.api.signin.GoogleSignInResult>; revokeAccess(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; signOut(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; }); public constructor(); public static EXTRA_SIGN_IN_ACCOUNT: string; public getSignInIntent(param0: com.google.android.gms.common.api.GoogleApiClient): globalAndroid.content.Intent; public silentSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.OptionalPendingResult<com.google.android.gms.auth.api.signin.GoogleSignInResult>; public getSignInResultFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.signin.GoogleSignInResult; public signOut(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public revokeAccess(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInClient extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.auth.api.signin.GoogleSignInOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInClient>; public revokeAccess(): com.google.android.gms.tasks.Task<java.lang.Void>; public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public silentSignIn(): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public signOut(): com.google.android.gms.tasks.Task<java.lang.Void>; public getSignInIntent(): globalAndroid.content.Intent; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInOptions implements com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptions>; public static zab: com.google.android.gms.common.api.Scope; public static zac: com.google.android.gms.common.api.Scope; public static zad: com.google.android.gms.common.api.Scope; public static zae: com.google.android.gms.common.api.Scope; public static DEFAULT_SIGN_IN: com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static DEFAULT_GAMES_SIGN_IN: com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInOptions>; public getAccount(): globalAndroid.accounts.Account; public getServerClientId(): string; public zaa(): string; public isForceCodeForRefreshToken(): boolean; public equals(param0: any): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getLogSessionId(): string; public static zaa(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public getScopes(): java.util.ArrayList<com.google.android.gms.common.api.Scope>; public isServerAuthCodeRequested(): boolean; public getScopeArray(): androidNative.Array<com.google.android.gms.common.api.Scope>; public isIdTokenRequested(): boolean; public hashCode(): number; public getExtensions(): java.util.ArrayList<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; } export module GoogleSignInOptions { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder>; public requestServerAuthCode(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public constructor(); public requestIdToken(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public addExtension(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestEmail(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public setAccountName(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestServerAuthCode(param0: string, param1: boolean): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public setHostedDomain(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestScopes(param0: com.google.android.gms.common.api.Scope, param1: androidNative.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public constructor(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptions); public requestId(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestProfile(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public setLogSessionId(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public build(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInOptionsExtension { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension>; /** * Constructs a new instance of the com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getExtensionType(): number; toBundle(): globalAndroid.os.Bundle; getImpliedScopes(): java.util.List<com.google.android.gms.common.api.Scope>; }); public constructor(); public static FITNESS: number; public static GAMES: number; public toBundle(): globalAndroid.os.Bundle; public getImpliedScopes(): java.util.List<com.google.android.gms.common.api.Scope>; public getExtensionType(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInResult { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInResult>; public constructor(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status); public getStatus(): com.google.android.gms.common.api.Status; public getSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public isSuccess(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInStatusCodes { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes>; public static SIGN_IN_FAILED: number; public static SIGN_IN_CANCELLED: number; public static SIGN_IN_CURRENTLY_IN_PROGRESS: number; public static getStatusCodeString(param0: number): string; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class RevocationBoundService { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.RevocationBoundService>; public onBind(param0: globalAndroid.content.Intent): globalAndroid.os.IBinder; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class SignInAccount { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.SignInAccount>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.SignInAccount>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zba(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class GoogleSignInOptionsExtensionParcelable { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; public constructor(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getType(): number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class HashAccumulator { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.HashAccumulator>; public constructor(); public zaa(param0: boolean): com.google.android.gms.auth.api.signin.internal.HashAccumulator; public addObject(param0: any): com.google.android.gms.auth.api.signin.internal.HashAccumulator; public hash(): number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class SignInConfiguration { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.SignInConfiguration>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.SignInConfiguration>; public hashCode(): number; public constructor(param0: string, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public equals(param0: any): boolean; public zba(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class SignInHubActivity { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.SignInHubActivity>; public constructor(); public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onDestroy(): void; public dispatchPopulateAccessibilityEvent(param0: globalAndroid.view.accessibility.AccessibilityEvent): boolean; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class Storage { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.Storage>; public getSavedRefreshToken(): string; public getSavedDefaultGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public zaa(): void; public clear(): void; public getSavedDefaultGoogleSignInOptions(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static getInstance(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.signin.internal.Storage; public saveDefaultGoogleSignInAccount(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zaa>; public constructor(); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zba extends com.google.android.gms.auth.api.signin.internal.zbq { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zba>; public constructor(); public constructor(param0: string); public zbb(param0: com.google.android.gms.common.api.Status): void; public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; public zbc(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbb { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbb>; public static zba(param0: string): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public constructor(param0: string); public run(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbc extends androidx.loader.content.AsyncTaskLoader<java.lang.Void> implements com.google.android.gms.common.api.internal.SignInConnectionListener { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbc>; public onComplete(): void; public onStartLoading(): void; public constructor(param0: globalAndroid.content.Context, param1: java.util.Set<com.google.android.gms.common.api.GoogleApiClient>); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbd extends com.google.android.gms.auth.api.signin.GoogleSignInApi { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbd>; public constructor(); public getSignInIntent(param0: com.google.android.gms.common.api.GoogleApiClient): globalAndroid.content.Intent; public getSignInResultFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.signin.GoogleSignInResult; public revokeAccess(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public signOut(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public silentSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.OptionalPendingResult<com.google.android.gms.auth.api.signin.GoogleSignInResult>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbe extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.auth.api.signin.internal.zbs> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbe>; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public getSignInIntent(): globalAndroid.content.Intent; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getConnectionHint(): globalAndroid.os.Bundle; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public isConnecting(): boolean; public providesSignIn(): boolean; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.auth.api.signin.GoogleSignInOptions, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public zba(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public disconnect(): void; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public getEndpointPackageName(): string; public getMinApkVersion(): number; public getServiceDescriptor(): string; public disconnect(param0: string): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public requiresSignIn(): boolean; public requiresAccount(): boolean; public requiresGooglePlayServices(): boolean; public getStartServiceAction(): string; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public isConnected(): boolean; public getLastDisconnectMessage(): string; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbf extends com.google.android.gms.auth.api.signin.internal.zba { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbf>; public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; public zbb(param0: com.google.android.gms.common.api.Status): void; public zbc(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbg extends com.google.android.gms.auth.api.signin.internal.zbl<com.google.android.gms.auth.api.signin.GoogleSignInResult> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbg>; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; public setResult(param0: any): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbh extends com.google.android.gms.auth.api.signin.internal.zba { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbh>; public zbb(param0: com.google.android.gms.common.api.Status): void; public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; public zbc(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbi extends com.google.android.gms.auth.api.signin.internal.zbl<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbi>; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; public setResult(param0: any): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbj extends com.google.android.gms.auth.api.signin.internal.zba { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbj>; public zbb(param0: com.google.android.gms.common.api.Status): void; public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; public zbc(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbk extends com.google.android.gms.auth.api.signin.internal.zbl<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbk>; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; public setResult(param0: any): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export abstract class zbl<R> extends com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,com.google.android.gms.auth.api.signin.internal.zbe> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbl<any>>; public constructor(); public setFailedResult(param0: com.google.android.gms.common.api.Status): void; /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public setResult(param0: any): void; /** @deprecated */ public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbm { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbm>; public static zbe(param0: com.google.android.gms.common.api.GoogleApiClient, param1: globalAndroid.content.Context, param2: com.google.android.gms.auth.api.signin.GoogleSignInOptions, param3: boolean): com.google.android.gms.common.api.OptionalPendingResult<com.google.android.gms.auth.api.signin.GoogleSignInResult>; public static zbg(param0: com.google.android.gms.common.api.GoogleApiClient, param1: globalAndroid.content.Context, param2: boolean): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static zbc(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): globalAndroid.content.Intent; public static zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): globalAndroid.content.Intent; public static zbd(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.signin.GoogleSignInResult; public static zbf(param0: com.google.android.gms.common.api.GoogleApiClient, param1: globalAndroid.content.Context, param2: boolean): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static zbb(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): globalAndroid.content.Intent; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbn { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbn>; public zbe(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptions, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; public static zbc(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.signin.internal.zbn; public zbb(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public zbd(): void; public zba(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } } } } } } } } } // declare module com { // export module google { // export module android { // export module gms { // export module auth { // export module api { // export module signin { // export module internal { // export abstract class zbo extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.auth.api.signin.internal.zbp { // public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbo>; // public constructor(param0: string); // public constructor(); // public zbb(): void; // public zbc(): void; // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // } // } // } // } // } // } // } // } // } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbp { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbp>; /** * Constructs a new instance of the com.google.android.gms.auth.api.signin.internal.zbp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zbb(): void; zbc(): void; }); public constructor(); public zbb(): void; public zbc(): void; } } } } } } } } } // declare module com { // export module google { // export module android { // export module gms { // export module auth { // export module api { // export module signin { // export module internal { // export abstract class zbq extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.auth.api.signin.internal.zbr { // public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbq>; // public constructor(param0: string); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status): void; // public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module auth { // export module api { // export module signin { // export module internal { // export class zbr { // public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbr>; // /** // * Constructs a new instance of the com.google.android.gms.auth.api.signin.internal.zbr interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status): void; // zbc(param0: com.google.android.gms.common.api.Status): void; // zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status): void; // public zbd(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.common.api.Status): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module auth { // export module api { // export module signin { // export module internal { // export class zbs extends com.google.android.gms.internal.auth-api.zba { // public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbs>; // public zbd(param0: com.google.android.gms.auth.api.signin.internal.zbr, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): void; // public zbc(param0: com.google.android.gms.auth.api.signin.internal.zbr, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): void; // public zbe(param0: com.google.android.gms.auth.api.signin.internal.zbr, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): void; // } // } // } // } // } // } // } // } // } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbt extends com.google.android.gms.auth.api.signin.internal.zbo { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbt>; public constructor(); public constructor(param0: string); public constructor(param0: globalAndroid.content.Context); public zbb(): void; public zbc(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbu extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.SignInConfiguration> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbu>; public constructor(); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbv { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbv>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zbw extends androidx.loader.app.LoaderManager.LoaderCallbacks<java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zbw>; public onCreateLoader(param0: number, param1: globalAndroid.os.Bundle): androidx.loader.content.Loader<java.lang.Void>; public onLoaderReset(param0: androidx.loader.content.Loader<java.lang.Void>): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zaa { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zaa>; public compare(param0: any, param1: any): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zab extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInAccount> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zab>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zac extends java.util.Comparator<com.google.android.gms.common.api.Scope> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zac>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zad extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zad>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zba { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zba>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zbb extends com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<com.google.android.gms.auth.api.signin.GoogleSignInResult,com.google.android.gms.auth.api.signin.GoogleSignInAccount> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zbb>; public convert(param0: any): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zbc extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.SignInAccount> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zbc>; public constructor(); } } } } } } } } // declare module com { // export module google { // export module android { // export module gms { // export module auth { // export module api { // export class zba extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.internal.auth-api.zbo,com.google.android.gms.auth.api.Auth.AuthCredentialsOptions> { // public static class: java.lang.Class<com.google.android.gms.auth.api.zba>; // } // } // } // } // } // } // } declare module com { export module google { export module android { export module gms { export module auth { export module api { export class zbb extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.auth.api.signin.internal.zbe,com.google.android.gms.auth.api.signin.GoogleSignInOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.zbb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class ErrorDialogFragment { public static class: java.lang.Class<com.google.android.gms.common.ErrorDialogFragment>; public show(param0: globalAndroid.app.FragmentManager, param1: string): void; public constructor(); public static newInstance(param0: globalAndroid.app.Dialog): com.google.android.gms.common.ErrorDialogFragment; public onCancel(param0: globalAndroid.content.DialogInterface): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public static newInstance(param0: globalAndroid.app.Dialog, param1: globalAndroid.content.DialogInterface.OnCancelListener): com.google.android.gms.common.ErrorDialogFragment; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class GoogleApiAvailability { public static class: java.lang.Class<com.google.android.gms.common.GoogleApiAvailability>; public static GOOGLE_PLAY_SERVICES_VERSION_CODE: number; public static GOOGLE_PLAY_SERVICES_PACKAGE: string; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public getErrorDialog(param0: globalAndroid.app.Activity, param1: number, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public showErrorDialogFragment(param0: globalAndroid.app.Activity, param1: number, param2: number): boolean; public getErrorDialog(param0: androidx.fragment.app.Fragment, param1: number, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult, param2: number): boolean; public showErrorNotification(param0: globalAndroid.content.Context, param1: number): void; public getErrorResolutionPendingIntent(param0: globalAndroid.content.Context, param1: number, param2: number): globalAndroid.app.PendingIntent; public zaa(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.internal.LifecycleFragment, param2: number, param3: number, param4: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public setDefaultNotificationChannelId(param0: globalAndroid.content.Context, param1: string): void; public getErrorDialog(param0: globalAndroid.app.Activity, param1: number, param2: number): globalAndroid.app.Dialog; public checkApiAvailability(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: androidNative.Array<com.google.android.gms.common.api.GoogleApi<any>>): com.google.android.gms.tasks.Task<java.lang.Void>; public isGooglePlayServicesAvailable(param0: globalAndroid.content.Context): number; public isGooglePlayServicesAvailable(param0: globalAndroid.content.Context, param1: number): number; public makeGooglePlayServicesAvailable(param0: globalAndroid.app.Activity): com.google.android.gms.tasks.Task<java.lang.Void>; public constructor(); public showErrorNotification(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult): void; public getErrorResolutionPendingIntent(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult): globalAndroid.app.PendingIntent; public getClientVersion(param0: globalAndroid.content.Context): number; public checkApiAvailability(param0: com.google.android.gms.common.api.HasApiKey<any>, param1: androidNative.Array<com.google.android.gms.common.api.HasApiKey<any>>): com.google.android.gms.tasks.Task<java.lang.Void>; public static getInstance(): com.google.android.gms.common.GoogleApiAvailability; public zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zabm): com.google.android.gms.common.api.internal.zabk; public getErrorResolutionIntent(param0: globalAndroid.content.Context, param1: number, param2: string): globalAndroid.content.Intent; public showErrorDialogFragment(param0: globalAndroid.app.Activity, param1: number, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public getErrorString(param0: number): string; public getErrorDialog(param0: androidx.fragment.app.Fragment, param1: number, param2: number): globalAndroid.app.Dialog; public isUserResolvableError(param0: number): boolean; } export module GoogleApiAvailability { export class zaa extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.GoogleApiAvailability.zaa>; public constructor(); public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.GoogleApiAvailability, param1: globalAndroid.content.Context); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class GooglePlayServicesUtil { public static class: java.lang.Class<com.google.android.gms.common.GooglePlayServicesUtil>; public static GMS_ERROR_DIALOG: string; public static GOOGLE_PLAY_SERVICES_VERSION_CODE: number; public static GOOGLE_PLAY_SERVICES_PACKAGE: string; public static GOOGLE_PLAY_STORE_PACKAGE: string; /** @deprecated */ public static showErrorNotification(param0: number, param1: globalAndroid.content.Context): void; /** @deprecated */ public static isGooglePlayServicesAvailable(param0: globalAndroid.content.Context, param1: number): number; public static getRemoteContext(param0: globalAndroid.content.Context): globalAndroid.content.Context; /** @deprecated */ public static getErrorString(param0: number): string; public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: androidx.fragment.app.Fragment, param3: number, param4: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public static getRemoteResource(param0: globalAndroid.content.Context): globalAndroid.content.res.Resources; /** @deprecated */ public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): boolean; /** @deprecated */ public static getErrorPendingIntent(param0: number, param1: globalAndroid.content.Context, param2: number): globalAndroid.app.PendingIntent; /** @deprecated */ public static isUserRecoverableError(param0: number): boolean; /** @deprecated */ public static getErrorDialog(param0: number, param1: globalAndroid.app.Activity, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; /** @deprecated */ public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: number): boolean; /** @deprecated */ public static isGooglePlayServicesAvailable(param0: globalAndroid.content.Context): number; /** @deprecated */ public static getErrorDialog(param0: number, param1: globalAndroid.app.Activity, param2: number): globalAndroid.app.Dialog; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class SignInButton { public static class: java.lang.Class<com.google.android.gms.common.SignInButton>; public static SIZE_STANDARD: number; public static SIZE_WIDE: number; public static SIZE_ICON_ONLY: number; public static COLOR_DARK: number; public static COLOR_LIGHT: number; public static COLOR_AUTO: number; public setSize(param0: number): void; public constructor(param0: globalAndroid.content.Context); public setColorScheme(param0: number): void; /** @deprecated */ public setScopes(param0: androidNative.Array<com.google.android.gms.common.api.Scope>): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); public setOnClickListener(param0: globalAndroid.view.View.OnClickListener): void; public setStyle(param0: number, param1: number): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public setEnabled(param0: boolean): void; public onClick(param0: globalAndroid.view.View): void; /** @deprecated */ public setStyle(param0: number, param1: number, param2: androidNative.Array<com.google.android.gms.common.api.Scope>): void; } export module SignInButton { export class ButtonSize { public static class: java.lang.Class<com.google.android.gms.common.SignInButton.ButtonSize>; /** * Constructs a new instance of the com.google.android.gms.common.SignInButton$ButtonSize interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class ColorScheme { public static class: java.lang.Class<com.google.android.gms.common.SignInButton.ColorScheme>; /** * Constructs a new instance of the com.google.android.gms.common.SignInButton$ColorScheme 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 android { export module gms { export module common { export class SupportErrorDialogFragment { public static class: java.lang.Class<com.google.android.gms.common.SupportErrorDialogFragment>; public constructor(); public show(param0: androidx.fragment.app.FragmentManager, param1: string): void; public onCancel(param0: globalAndroid.content.DialogInterface): void; public static newInstance(param0: globalAndroid.app.Dialog, param1: globalAndroid.content.DialogInterface.OnCancelListener): com.google.android.gms.common.SupportErrorDialogFragment; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public static newInstance(param0: globalAndroid.app.Dialog): com.google.android.gms.common.SupportErrorDialogFragment; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class Api<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api<any>>; public constructor(param0: string, param1: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,any>, param2: com.google.android.gms.common.api.Api.ClientKey<any>); public zac(): com.google.android.gms.common.api.Api.AnyClientKey<any>; public zaa(): com.google.android.gms.common.api.Api.BaseClientBuilder<any,O>; public zab(): com.google.android.gms.common.api.Api.AbstractClientBuilder<any,O>; public zad(): string; } export module Api { export class AbstractClientBuilder<T, O> extends com.google.android.gms.common.api.Api.BaseClientBuilder<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AbstractClientBuilder<any,any>>; public constructor(); public buildClient(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: any, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener): any; /** @deprecated */ public buildClient(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: any, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): any; } export class AnyClient { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AnyClient>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$AnyClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class AnyClientKey<C> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AnyClientKey<any>>; public constructor(); } export class ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; } export module ApiOptions { export class HasAccountOptions implements com.google.android.gms.common.api.Api.ApiOptions.HasOptions, com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasAccountOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasAccountOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getAccount(): globalAndroid.accounts.Account; <clinit>(): void; <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; public getAccount(): globalAndroid.accounts.Account; } export class HasGoogleSignInAccountOptions extends com.google.android.gms.common.api.Api.ApiOptions.HasOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasGoogleSignInAccountOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasGoogleSignInAccountOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; public getGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } export class HasOptions extends com.google.android.gms.common.api.Api.ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; } export class NoOptions extends com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.NoOptions>; } export class NotRequiredOptions extends com.google.android.gms.common.api.Api.ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$NotRequiredOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; } export class Optional implements com.google.android.gms.common.api.Api.ApiOptions.HasOptions, com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.Optional>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$Optional interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { <clinit>(): void; <clinit>(): void; }); public constructor(); public static NO_OPTIONS: com.google.android.gms.common.api.Api.ApiOptions.NoOptions; } } export class BaseClientBuilder<T, O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api.BaseClientBuilder<any,any>>; public static API_PRIORITY_GAMES: number; public static API_PRIORITY_PLUS: number; public static API_PRIORITY_OTHER: number; public getImpliedScopes(param0: O): java.util.List<com.google.android.gms.common.api.Scope>; public getPriority(): number; public constructor(); } export class Client extends com.google.android.gms.common.api.Api.AnyClient { public static class: java.lang.Class<com.google.android.gms.common.api.Api.Client>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$Client interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; disconnect(param0: string): void; disconnect(): void; isConnected(): boolean; isConnecting(): boolean; getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; requiresSignIn(): boolean; onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; requiresAccount(): boolean; requiresGooglePlayServices(): boolean; providesSignIn(): boolean; getSignInIntent(): globalAndroid.content.Intent; dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; getServiceBrokerBinder(): globalAndroid.os.IBinder; getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; getEndpointPackageName(): string; getMinApkVersion(): number; getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; getLastDisconnectMessage(): string; }); public constructor(); public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public disconnect(param0: string): void; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public getLastDisconnectMessage(): string; public isConnected(): boolean; public requiresAccount(): boolean; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public getMinApkVersion(): number; public disconnect(): void; public isConnecting(): boolean; public providesSignIn(): boolean; } export class ClientKey<C> extends com.google.android.gms.common.api.Api.AnyClientKey<any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ClientKey<any>>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class AvailabilityException { public static class: java.lang.Class<com.google.android.gms.common.api.AvailabilityException>; public getMessage(): string; public constructor(param0: androidx.collection.ArrayMap<com.google.android.gms.common.api.internal.ApiKey<any>,com.google.android.gms.common.ConnectionResult>); public getConnectionResult(param0: com.google.android.gms.common.api.GoogleApi<any>): com.google.android.gms.common.ConnectionResult; public getConnectionResult(param0: com.google.android.gms.common.api.HasApiKey<any>): com.google.android.gms.common.ConnectionResult; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class Batch extends com.google.android.gms.common.api.internal.BasePendingResult<com.google.android.gms.common.api.BatchResult> { public static class: java.lang.Class<com.google.android.gms.common.api.Batch>; public cancel(): void; public createFailedResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.BatchResult; public createFailedResult(param0: com.google.android.gms.common.api.Status): any; } export module Batch { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.Batch.Builder>; public build(): com.google.android.gms.common.api.Batch; public add(param0: com.google.android.gms.common.api.PendingResult<any>): com.google.android.gms.common.api.BatchResultToken<any>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BatchResult { public static class: java.lang.Class<com.google.android.gms.common.api.BatchResult>; public getStatus(): com.google.android.gms.common.api.Status; public take(param0: com.google.android.gms.common.api.BatchResultToken<any>): com.google.android.gms.common.api.Result; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BatchResultToken<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.BatchResultToken<any>>; public mId: number; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BooleanResult { public static class: java.lang.Class<com.google.android.gms.common.api.BooleanResult>; public constructor(param0: com.google.android.gms.common.api.Status, param1: boolean); public getStatus(): com.google.android.gms.common.api.Status; public hashCode(): number; public getValue(): boolean; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class DataBufferResponse<T, R> extends com.google.android.gms.common.api.Response<any> implements com.google.android.gms.common.data.DataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.api.DataBufferResponse<any,any>>; public constructor(); public singleRefIterator(): java.util.Iterator<any>; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public isClosed(): boolean; public release(): void; /** @deprecated */ public isClosed(): boolean; public getCount(): number; public constructor(param0: any); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class GoogleApi<O> extends com.google.android.gms.common.api.HasApiKey<any> { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi<any>>; /** @deprecated */ public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public doRegisterEventListener(param0: com.google.android.gms.common.api.internal.RegistrationMethods<any,any>): com.google.android.gms.tasks.Task; public registerListener(param0: any, param1: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; public doWrite(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); /** @deprecated */ public getContextFeatureId(): string; public doBestEffortWrite(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public doUnregisterEventListener(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>): com.google.android.gms.tasks.Task<java.lang.Boolean>; public getLooper(): globalAndroid.os.Looper; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public createClientSettingsBuilder(): com.google.android.gms.common.internal.ClientSettings.Builder; /** @deprecated */ public doRegisterEventListener(param0: com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>, param1: com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>): com.google.android.gms.tasks.Task; public getApiOptions(): any; public doRead(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); public getApplicationContext(): globalAndroid.content.Context; public getContextAttributionTag(): string; public zaa(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): com.google.android.gms.common.api.Api.Client; public doWrite(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnectService(): com.google.android.gms.tasks.Task<java.lang.Boolean>; public zaa(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler): com.google.android.gms.common.api.internal.zace; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public doBestEffortWrite(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; public asGoogleApiClient(): com.google.android.gms.common.api.GoogleApiClient; public doUnregisterEventListener(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>, param1: number): com.google.android.gms.tasks.Task<java.lang.Boolean>; public zaa(): number; public doRead(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; } export module GoogleApi { export class Settings { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi.Settings>; public static DEFAULT_SETTINGS: com.google.android.gms.common.api.GoogleApi.Settings; public zaa: com.google.android.gms.common.api.internal.StatusExceptionMapper; public zab: globalAndroid.os.Looper; } export module Settings { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi.Settings.Builder>; public constructor(); public setLooper(param0: globalAndroid.os.Looper): com.google.android.gms.common.api.GoogleApi.Settings.Builder; public build(): com.google.android.gms.common.api.GoogleApi.Settings; public setMapper(param0: com.google.android.gms.common.api.internal.StatusExceptionMapper): com.google.android.gms.common.api.GoogleApi.Settings.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class GoogleApiActivity { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiActivity>; public constructor(); public onCancel(param0: globalAndroid.content.DialogInterface): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public onCreate(param0: globalAndroid.os.Bundle): void; public static zaa(param0: globalAndroid.content.Context, param1: globalAndroid.app.PendingIntent, param2: number): globalAndroid.app.PendingIntent; public static zaa(param0: globalAndroid.content.Context, param1: globalAndroid.app.PendingIntent, param2: number, param3: boolean): globalAndroid.content.Intent; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class GoogleApiClient { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient>; public static DEFAULT_ACCOUNT: string; public static SIGN_IN_MODE_REQUIRED: number; public static SIGN_IN_MODE_OPTIONAL: number; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public getLooper(): globalAndroid.os.Looper; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public zab(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public connect(): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public maybeSignOut(): void; public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public stopAutoManage(param0: androidx.fragment.app.FragmentActivity): void; public hasApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public zaa(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public constructor(); public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public getContext(): globalAndroid.content.Context; public disconnect(): void; public isConnected(): boolean; public reconnect(): void; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public isConnecting(): boolean; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public registerListener(param0: any): com.google.android.gms.common.api.internal.ListenerHolder<any>; public static dumpAll(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public static getAllClients(): java.util.Set<com.google.android.gms.common.api.GoogleApiClient>; public getClient(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>): com.google.android.gms.common.api.Api.Client; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public connect(param0: number): void; } export module GoogleApiClient { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.Builder>; public build(): com.google.android.gms.common.api.GoogleApiClient; public enableAutoManage(param0: androidx.fragment.app.FragmentActivity, param1: number, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public useDefaultAccount(): com.google.android.gms.common.api.GoogleApiClient.Builder; public addConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApiIfAvailable(param0: com.google.android.gms.common.api.Api<any>, param1: androidNative.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.api.GoogleApiClient.Builder; public buildClientSettings(): com.google.android.gms.common.internal.ClientSettings; public addScope(param0: com.google.android.gms.common.api.Scope): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApiIfAvailable(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions.HasOptions, param2: androidNative.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.api.GoogleApiClient.Builder; public addOnConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public setViewForPopups(param0: globalAndroid.view.View): com.google.android.gms.common.api.GoogleApiClient.Builder; public setHandler(param0: globalAndroid.os.Handler): com.google.android.gms.common.api.GoogleApiClient.Builder; public addScopeNames(param0: androidNative.Array<string>): com.google.android.gms.common.api.GoogleApiClient.Builder; public constructor(param0: globalAndroid.content.Context); public addApi(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApi(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions.HasOptions): com.google.android.gms.common.api.GoogleApiClient.Builder; public enableAutoManage(param0: androidx.fragment.app.FragmentActivity, param1: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public setGravityForPopups(param0: number): com.google.android.gms.common.api.GoogleApiClient.Builder; public setAccountName(param0: string): com.google.android.gms.common.api.GoogleApiClient.Builder; } export class ConnectionCallbacks extends com.google.android.gms.common.api.internal.ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks>; /** * Constructs a new instance of the com.google.android.gms.common.api.GoogleApiClient$ConnectionCallbacks interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnected(param0: globalAndroid.os.Bundle): void; onConnectionSuspended(param0: number): void; }); public constructor(); public static CAUSE_SERVICE_DISCONNECTED: number; public static CAUSE_NETWORK_LOST: number; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } export class OnConnectionFailedListener extends com.google.android.gms.common.api.internal.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.GoogleApiClient$OnConnectionFailedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; }); public constructor(); public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class HasApiKey<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.HasApiKey<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.HasApiKey<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getApiKey(): com.google.android.gms.common.api.internal.ApiKey<O>; }); public constructor(); public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<O>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class OptionalPendingResult<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.OptionalPendingResult<any>>; public constructor(); public get(): any; public isDone(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class PendingResult<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResult<any>>; public constructor(); public cancel(): void; public isCanceled(): boolean; public await(param0: number, param1: java.util.concurrent.TimeUnit): R; public await(): R; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; } export module PendingResult { export class StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResult.StatusListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.PendingResult$StatusListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class PendingResults { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults>; public static immediateFailedResult(param0: com.google.android.gms.common.api.Result, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static canceledPendingResult(param0: com.google.android.gms.common.api.Result): com.google.android.gms.common.api.PendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Result, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.OptionalPendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Result): com.google.android.gms.common.api.OptionalPendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static canceledPendingResult(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } export module PendingResults { export class zaa<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zaa<any>>; public constructor(param0: any); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); } export class zab<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zab<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); } export class zac<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zac<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient, param1: any); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class ResultTransform<R, S> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.ResultTransform<any,any>>; public constructor(); public onSuccess(param0: R): com.google.android.gms.common.api.PendingResult<S>; public createFailedResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.PendingResult<S>; public onFailure(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.Status; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class TransformedResult<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.TransformedResult<any>>; public constructor(); public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public andFinally(param0: com.google.android.gms.common.api.ResultCallbacks<any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class ActivityLifecycleObserver { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ActivityLifecycleObserver>; public onStopCallOnce(param0: java.lang.Runnable): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public static of(param0: globalAndroid.app.Activity): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ApiExceptionMapper { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ApiExceptionMapper>; public constructor(); public getException(param0: com.google.android.gms.common.api.Status): java.lang.Exception; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ApiKey<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ApiKey<any>>; public zaa(): string; public equals(param0: any): boolean; public static zaa(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions, param2: string): com.google.android.gms.common.api.internal.ApiKey<any>; public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class BaseImplementation { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation>; public constructor(); } export module BaseImplementation { export abstract class ApiMethodImpl<R, A> extends com.google.android.gms.common.api.internal.BasePendingResult<any> implements com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>>; public constructor(); public getApi(): com.google.android.gms.common.api.Api<any>; /** @deprecated */ public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public run(param0: any): void; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public setFailedResult(param0: com.google.android.gms.common.api.Status): void; /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); public getClientKey(): com.google.android.gms.common.api.Api.AnyClientKey<any>; public onSetFailedResult(param0: any): void; public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public doExecute(param0: any): void; public setResult(param0: any): void; public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); } export class ResultHolder<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.BaseImplementation$ResultHolder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { setResult(param0: R): void; setFailedResult(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public setResult(param0: R): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class BasePendingResult<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult<any>>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public setCancelToken(param0: com.google.android.gms.common.internal.ICancelToken): void; public zaa(): boolean; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public cancel(): void; public zaa(param0: com.google.android.gms.common.api.internal.zacq): void; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public zab(): void; public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(); public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); public setResult(param0: any): void; public await(): any; public static zaa(param0: com.google.android.gms.common.api.Result): void; public isCanceled(): boolean; public isReady(): boolean; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; /** @deprecated */ public forceFailureUnlessReady(param0: com.google.android.gms.common.api.Status): void; } export module BasePendingResult { export class CallbackHandler<R> extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>>; public constructor(); public zaa(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: any): void; public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(param0: globalAndroid.os.Looper); } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult.zaa>; public finalize(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ConnectionCallbacks>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.ConnectionCallbacks interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnected(param0: globalAndroid.os.Bundle): void; onConnectionSuspended(param0: number): void; }); public constructor(); public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class DataHolderNotifier<L> extends com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.DataHolderNotifier<any>>; public onNotifyListenerFailed(): void; public notifyListener(param0: any, param1: com.google.android.gms.common.data.DataHolder): void; public notifyListener(param0: any): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class DataHolderResult { public static class: java.lang.Class<com.google.android.gms.common.api.internal.DataHolderResult>; public mStatus: com.google.android.gms.common.api.Status; public mDataHolder: com.google.android.gms.common.data.DataHolder; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: com.google.android.gms.common.api.Status); public getStatus(): com.google.android.gms.common.api.Status; public release(): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class GoogleApiManager { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager>; public zab(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public zab(): number; public zac(): void; public handleMessage(param0: globalAndroid.os.Message): boolean; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>, param2: number): com.google.android.gms.tasks.Task; public zaa(param0: java.lang.Iterable<any>): com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.ApiKey<any>,string>>; public zab(param0: com.google.android.gms.common.api.GoogleApi<any>): com.google.android.gms.tasks.Task<java.lang.Boolean>; public static zaa(): com.google.android.gms.common.api.internal.GoogleApiManager; public static reportSignOut(): void; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>, param2: com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>, param3: java.lang.Runnable): com.google.android.gms.tasks.Task; public zaa(param0: com.google.android.gms.common.api.internal.zay): void; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>): void; public static zaa(param0: globalAndroid.content.Context): com.google.android.gms.common.api.internal.GoogleApiManager; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: number, param2: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): void; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: number, param2: com.google.android.gms.common.api.internal.TaskApiCall<any,any>, param3: com.google.android.gms.tasks.TaskCompletionSource, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper): void; } export module GoogleApiManager { export class zaa<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>>; public zai(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public zab(): com.google.android.gms.common.api.Api.Client; public zah(): boolean; public zaa(param0: com.google.android.gms.common.api.internal.zab): void; public zad(): void; public zal(): number; public onConnected(param0: globalAndroid.os.Bundle): void; public zag(): void; public constructor(param0: com.google.android.gms.common.api.GoogleApi<O>); public onConnectionSuspended(param0: number): void; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(): void; public zaa(param0: com.google.android.gms.common.api.internal.zaj): void; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public zae(): com.google.android.gms.common.ConnectionResult; public zak(): boolean; public zaf(): void; public zac(): java.util.Map<com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>,com.google.android.gms.common.api.internal.zabv>; } export class zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zab>; public hashCode(): number; public equals(param0: any): boolean; public toString(): string; } export class zac extends com.google.android.gms.common.api.internal.zach { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zac>; public onReportServiceBinding(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public constructor(param0: com.google.android.gms.common.api.Api.Client, param1: com.google.android.gms.common.api.internal.ApiKey<any>); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.IStatusCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onResult(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; } export module IStatusCallback { export abstract class Stub extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.api.internal.IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback.Stub>; public constructor(param0: string); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public static asInterface(param0: globalAndroid.os.IBinder): com.google.android.gms.common.api.internal.IStatusCallback; } export module Stub { export class zaa extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.api.internal.IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback.Stub.zaa>; public onResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ListenerHolder<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder<any>>; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public clear(): void; public notifyListener(param0: com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any>): void; public hasListener(): boolean; } export module ListenerHolder { export class ListenerKey<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>>; public hashCode(): number; public equals(param0: any): boolean; } export class Notifier<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.ListenerHolder$Notifier interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { notifyListener(param0: L): void; onNotifyListenerFailed(): void; }); public constructor(); public notifyListener(param0: L): void; public onNotifyListenerFailed(): void; } export class zaa extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.zaa>; public constructor(); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<any>, param1: globalAndroid.os.Looper); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ListenerHolders { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolders>; public zaa(): void; public static createListenerKey(param0: any, param1: string): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>; public constructor(); public static createListenerHolder(param0: any, param1: globalAndroid.os.Looper, param2: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; public zaa(param0: any, param1: globalAndroid.os.Looper, param2: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class NonGmsServiceBrokerClient extends com.google.android.gms.common.api.Api.Client { public static class: java.lang.Class<com.google.android.gms.common.api.internal.NonGmsServiceBrokerClient>; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: string, param3: string, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public getBinder(): globalAndroid.os.IBinder; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: globalAndroid.content.ComponentName, param3: com.google.android.gms.common.api.internal.ConnectionCallbacks, param4: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public requiresAccount(): boolean; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getMinApkVersion(): number; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public disconnect(param0: string): void; public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; public getLastDisconnectMessage(): string; public isConnected(): boolean; public zaa(param0: string): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public disconnect(): void; public isConnecting(): boolean; public providesSignIn(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.OnConnectionFailedListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.OnConnectionFailedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; }); public constructor(); public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class OptionalPendingResultImpl<R> extends com.google.android.gms.common.api.OptionalPendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.OptionalPendingResultImpl<any>>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public cancel(): void; public isCanceled(): boolean; public get(): any; public constructor(param0: com.google.android.gms.common.api.PendingResult<any>); public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public constructor(); public isDone(): boolean; public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public await(): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class PendingResultFacade<A, B> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.PendingResultFacade<any,any>>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class RegisterListenerMethod<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>>; public registerListener(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public clearListener(): void; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public zaa(): boolean; public zab(): number; public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>, param1: androidNative.Array<com.google.android.gms.common.Feature>, param2: boolean); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>, param1: androidNative.Array<com.google.android.gms.common.Feature>, param2: boolean, param3: number); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class RegistrationMethods<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegistrationMethods<any,any>>; public register: com.google.android.gms.common.api.internal.RegisterListenerMethod<A,L>; public zaa: com.google.android.gms.common.api.internal.UnregisterListenerMethod<A,L>; public zab: java.lang.Runnable; public static builder(): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<any,any>; } export module RegistrationMethods { export class Builder<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegistrationMethods.Builder<any,any>>; public onConnectionSuspended(param0: java.lang.Runnable): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public setAutoResolveMissingFeatures(param0: boolean): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public withHolder(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; /** @deprecated */ public register(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public unregister(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public register(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public build(): com.google.android.gms.common.api.internal.RegistrationMethods<A,L>; public setFeatures(param0: androidNative.Array<com.google.android.gms.common.Feature>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public setMethodKey(param0: number): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; /** @deprecated */ public unregister(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class RemoteCall<T, U> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RemoteCall<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.RemoteCall<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { accept(param0: T, param1: U): void; }); public constructor(); public accept(param0: T, param1: U): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class SignInConnectionListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.SignInConnectionListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.SignInConnectionListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(): void; }); public constructor(); public onComplete(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class StatusCallback extends com.google.android.gms.common.api.internal.IStatusCallback.Stub { public static class: java.lang.Class<com.google.android.gms.common.api.internal.StatusCallback>; public constructor(param0: com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<com.google.android.gms.common.api.Status>); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class StatusPendingResult extends com.google.android.gms.common.api.internal.BasePendingResult<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.StatusPendingResult>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class TaskApiCall<A, ResultT> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskApiCall<any,any>>; /** @deprecated */ public constructor(); public zaa(): androidNative.Array<com.google.android.gms.common.Feature>; public zab(): number; public doExecute(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<ResultT>): void; public constructor(param0: androidNative.Array<com.google.android.gms.common.Feature>, param1: boolean, param2: number); public shouldAutoResolveMissingFeatures(): boolean; public static builder(): com.google.android.gms.common.api.internal.TaskApiCall.Builder<any,any>; } export module TaskApiCall { export class Builder<A, ResultT> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskApiCall.Builder<any,any>>; public setMethodKey(param0: number): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public build(): com.google.android.gms.common.api.internal.TaskApiCall<A,ResultT>; public setFeatures(param0: androidNative.Array<com.google.android.gms.common.Feature>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public run(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<ResultT>>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public setAutoResolveMissingFeatures(param0: boolean): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; /** @deprecated */ public execute(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<ResultT>>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class TaskUtil { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskUtil>; public static setResultOrApiException(param0: com.google.android.gms.common.api.Status, param1: any, param2: com.google.android.gms.tasks.TaskCompletionSource): void; public static setResultOrApiException(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; public constructor(); /** @deprecated */ public static toVoidTaskThatFailsOnFalse(param0: com.google.android.gms.tasks.Task<java.lang.Boolean>): com.google.android.gms.tasks.Task<java.lang.Void>; public static trySetResultOrApiException(param0: com.google.android.gms.common.api.Status, param1: any, param2: com.google.android.gms.tasks.TaskCompletionSource): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class UnregisterListenerMethod<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>>; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public unregisterListener(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>): void; public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaa extends com.google.android.gms.common.api.internal.ActivityLifecycleObserver { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaa>; public onStopCallOnce(param0: java.lang.Runnable): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public constructor(param0: globalAndroid.app.Activity); public constructor(); } export module zaa { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaa.zaa>; public onStop(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaa extends com.google.android.gms.common.api.internal.zaaw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaa>; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public constructor(param0: com.google.android.gms.common.api.internal.zaaz); public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zaa(): void; public zaa(param0: globalAndroid.os.Bundle): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaab extends com.google.android.gms.common.api.GoogleApiClient { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaab>; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public constructor(); public connect(param0: number): void; public connect(): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public stopAutoManage(param0: androidx.fragment.app.FragmentActivity): void; public isConnected(): boolean; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public reconnect(): void; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public constructor(param0: string); public disconnect(): void; public isConnecting(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaac extends com.google.android.gms.common.api.internal.zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaac>; public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaad extends com.google.android.gms.common.api.internal.zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaad>; public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaae { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaae>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaf extends com.google.android.gms.common.api.internal.zaaw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaf>; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public constructor(param0: com.google.android.gms.common.api.internal.zaaz, param1: com.google.android.gms.common.internal.ClientSettings, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param3: com.google.android.gms.common.GoogleApiAvailabilityLight, param4: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param5: java.util.concurrent.locks.Lock, param6: globalAndroid.content.Context); public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zaa(): void; public zaa(param0: globalAndroid.os.Bundle): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaag extends com.google.android.gms.common.api.internal.zaap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaag>; public zaa(): void; public constructor(param0: java.util.Map<com.google.android.gms.common.api.Api.Client,com.google.android.gms.common.api.internal.zaah>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaah { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaah>; public constructor(param0: com.google.android.gms.common.api.internal.zaaf, param1: com.google.android.gms.common.api.Api<any>, param2: boolean); public onReportServiceBinding(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaai extends com.google.android.gms.common.api.internal.zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaai>; public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaj extends com.google.android.gms.common.api.internal.zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaj>; public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaak extends com.google.android.gms.signin.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaak>; public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.signin.internal.zai): void; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public zab(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; public zaa(param0: com.google.android.gms.signin.internal.zak): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaal extends com.google.android.gms.common.api.internal.zaap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaal>; public constructor(param0: java.util.ArrayList<com.google.android.gms.common.api.Api.Client>); public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaam implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaam>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaan extends com.google.android.gms.common.api.internal.zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaan>; public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaao extends com.google.android.gms.common.api.internal.zaaw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaao>; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public constructor(param0: com.google.android.gms.common.api.internal.zaaz); public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zaa(): void; public zaa(param0: globalAndroid.os.Bundle): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zaap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaap>; public zaa(): void; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaq extends com.google.android.gms.common.internal.zak { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaq>; public getConnectionHint(): globalAndroid.os.Bundle; public isConnected(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaar extends com.google.android.gms.common.api.GoogleApiClient implements com.google.android.gms.common.api.internal.zabn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaar>; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public getClient(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>): com.google.android.gms.common.api.Api.Client; public zaa(param0: number, param1: boolean): void; public zab(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public zaa(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public getContext(): globalAndroid.content.Context; public connect(param0: number): void; public connect(): void; public static zaa(param0: java.lang.Iterable<com.google.android.gms.common.api.Api.Client>, param1: boolean): number; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public constructor(param0: globalAndroid.content.Context, param1: java.util.concurrent.locks.Lock, param2: globalAndroid.os.Looper, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.GoogleApiAvailability, param5: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param6: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param7: java.util.List<com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks>, param8: java.util.List<com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener>, param9: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param10: number, param11: number, param12: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>); public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public constructor(); public zaa(param0: globalAndroid.os.Bundle): void; public maybeSignOut(): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public stopAutoManage(param0: androidx.fragment.app.FragmentActivity): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public isConnected(): boolean; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public reconnect(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public hasApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public isConnecting(): boolean; public registerListener(param0: any): com.google.android.gms.common.api.internal.ListenerHolder<any>; public getLooper(): globalAndroid.os.Looper; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaas extends com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaas>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaat extends com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaat>; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaau extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaau>; public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaav extends com.google.android.gms.common.api.ResultCallback<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaav>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaw>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zaaw interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(): void; zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; zab(): boolean; zac(): void; zaa(param0: globalAndroid.os.Bundle): void; zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; zaa(param0: number): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zaa(): void; public zaa(param0: globalAndroid.os.Bundle): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaax extends com.google.android.gms.common.api.internal.zabm { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaax>; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zaay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaay>; public constructor(param0: com.google.android.gms.common.api.internal.zaaw); public zaa(param0: com.google.android.gms.common.api.internal.zaaz): void; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaz implements com.google.android.gms.common.api.internal.zabo, com.google.android.gms.common.api.internal.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaz>; public zaf(): void; public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zad(): boolean; public zaa(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public zae(): boolean; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zaar, param2: java.util.concurrent.locks.Lock, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.GoogleApiAvailabilityLight, param5: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param6: com.google.android.gms.common.internal.ClientSettings, param7: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param8: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param9: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>, param10: com.google.android.gms.common.api.internal.zabn); public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): com.google.android.gms.common.ConnectionResult; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public zag(): void; public onConnected(param0: globalAndroid.os.Bundle): void; public zaa(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public zaa(): void; public zaa(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public zaa(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zab>; public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: java.lang.Exception): void; public constructor(param0: number); public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zaa(param0: com.google.android.gms.common.api.internal.zav, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaba { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaba>; public static zaa(): java.util.concurrent.ExecutorService; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabb extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabb>; public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabc { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabc>; public execute(param0: java.lang.Runnable): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabd>; public onBackgroundStateChanged(param0: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabe { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabe>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabf>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabg { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabg>; public onSignOutComplete(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabh { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabh>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabi { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabi>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabj { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabj>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabk { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabk>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; public zaa(param0: globalAndroid.content.Context): void; public zaa(): void; public constructor(param0: com.google.android.gms.common.api.internal.zabm); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabl<O> extends com.google.android.gms.common.api.internal.zaab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabl<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApi<any>); public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public zaa(param0: com.google.android.gms.common.api.internal.zacn<any>): void; public constructor(); public constructor(param0: string); public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public getContext(): globalAndroid.content.Context; public getLooper(): globalAndroid.os.Looper; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zabm { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabm>; public zaa(): void; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabn>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zabn interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: globalAndroid.os.Bundle): void; zaa(param0: com.google.android.gms.common.ConnectionResult): void; zaa(param0: number, param1: boolean): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: number, param1: boolean): void; public zaa(param0: globalAndroid.os.Bundle): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabo { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabo>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zabo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; zaa(): void; zab(): com.google.android.gms.common.ConnectionResult; zaa(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; zac(): void; zaa(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; zad(): boolean; zae(): boolean; zaa(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; zag(): void; zaa(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; zaf(): void; }); public constructor(); public zaf(): void; public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zad(): boolean; public zaa(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public zae(): boolean; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): com.google.android.gms.common.ConnectionResult; public zag(): void; public zaa(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public zaa(): void; public zaa(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public zaa(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabp extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabp>; public static zaa(param0: globalAndroid.app.Activity): com.google.android.gms.common.api.internal.zabp; public zac(): com.google.android.gms.tasks.Task<java.lang.Void>; public zaa(): void; public onDestroy(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabq { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabq>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabr<T> extends com.google.android.gms.tasks.OnCompleteListener<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabr<any>>; public onComplete(param0: com.google.android.gms.tasks.Task<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabs>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabt { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabt>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabu { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabu>; public zaa: com.google.android.gms.common.api.internal.zab; public zab: number; public zac: com.google.android.gms.common.api.GoogleApi<any>; public constructor(param0: com.google.android.gms.common.api.internal.zab, param1: number, param2: com.google.android.gms.common.api.GoogleApi<any>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabv { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabv>; public zaa: com.google.android.gms.common.api.internal.RegisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>; public zab: com.google.android.gms.common.api.internal.UnregisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>; public zac: java.lang.Runnable; public constructor(param0: com.google.android.gms.common.api.internal.RegisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>, param1: com.google.android.gms.common.api.internal.UnregisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>, param2: java.lang.Runnable); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabw>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabx extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabx>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaby { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaby>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabz extends com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabz>; public registerListener(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zac<T> extends com.google.android.gms.common.api.internal.zad { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zac<any>>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: java.lang.Exception): void; public constructor(param0: number); public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zaa(param0: com.google.android.gms.common.api.internal.zav, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaca extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaca>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacb extends com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacb>; public unregisterListener(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacc<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacc<any>>; public constructor(param0: com.google.android.gms.common.api.Status); public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public cancel(): void; public isCanceled(): boolean; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public constructor(); public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public await(): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacd>; public static zaa(): java.util.concurrent.ExecutorService; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zace extends com.google.android.gms.signin.internal.zab implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zace>; public zaa(param0: com.google.android.gms.signin.internal.zai): void; public zaa(param0: com.google.android.gms.common.api.internal.zach): void; public zab(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; public constructor(); public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public onConnected(param0: globalAndroid.os.Bundle): void; public zaa(): void; public constructor(param0: string); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.ClientSettings); public zaa(param0: com.google.android.gms.signin.internal.zak): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacf>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacg { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacg>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zach { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zach>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zach interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.ConnectionResult): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaci { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaci>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacj extends com.google.android.gms.common.api.internal.TaskApiCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacj>; public doExecute(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zack extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zack>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacl extends com.google.android.gms.tasks.Continuation<java.lang.Boolean,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacl>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacm { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacm>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacn<R> extends com.google.android.gms.common.api.TransformedResult<any> implements com.google.android.gms.common.api.ResultCallback<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacn<any>>; public constructor(param0: java.lang.ref.WeakReference<com.google.android.gms.common.api.GoogleApiClient>); public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public zaa(param0: com.google.android.gms.common.api.PendingResult<any>): void; public constructor(); public onResult(param0: any): void; public andFinally(param0: com.google.android.gms.common.api.ResultCallbacks<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaco { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaco>; public zaa(): void; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacp extends com.google.android.gms.internal.base.zas { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacp>; public constructor(param0: com.google.android.gms.common.api.internal.zacn<any>, param1: globalAndroid.os.Looper); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(); public constructor(param0: globalAndroid.os.Looper); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacq { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacq>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zacq interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacr extends com.google.android.gms.common.api.internal.zacq { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacr>; public zaa(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zad extends com.google.android.gms.common.api.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zad>; public constructor(param0: number); public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): androidNative.Array<com.google.android.gms.common.Feature>; public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zae extends com.google.android.gms.common.api.internal.zac<java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zae>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public constructor(param0: number); public constructor(param0: com.google.android.gms.common.api.internal.zabv, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>); public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): androidNative.Array<com.google.android.gms.common.Feature>; public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaf<A> extends com.google.android.gms.common.api.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaf<any>>; public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: java.lang.Exception): void; public constructor(param0: number); public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zaa(param0: com.google.android.gms.common.api.internal.zav, param1: boolean): void; public constructor(param0: number, param1: any); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zag extends com.google.android.gms.common.api.internal.zac<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zag>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public constructor(param0: number); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>); public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): androidNative.Array<com.google.android.gms.common.Feature>; public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zah<ResultT> extends com.google.android.gms.common.api.internal.zad { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zah<any>>; public zaa(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: java.lang.Exception): void; public constructor(param0: number); public constructor(param0: number, param1: com.google.android.gms.common.api.internal.TaskApiCall<com.google.android.gms.common.api.Api.AnyClient,any>, param2: com.google.android.gms.tasks.TaskCompletionSource<any>, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): androidNative.Array<com.google.android.gms.common.Feature>; public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; public zaa(param0: com.google.android.gms.common.api.internal.zav, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zai extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zai>; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleActivity): com.google.android.gms.common.api.internal.zai; public zaa(): void; public zaa(param0: number, param1: com.google.android.gms.common.api.GoogleApiClient, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public zaa(param0: number): void; public onStop(): void; public onStart(): void; } export module zai { export class zaa extends com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zai.zaa>; public zaa: number; public zab: com.google.android.gms.common.api.GoogleApiClient; public zac: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public constructor(param0: com.google.android.gms.common.api.internal.zai, param1: number, param2: com.google.android.gms.common.api.GoogleApiClient, param3: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaj { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaj>; public zaa(): java.util.Set<com.google.android.gms.common.api.internal.ApiKey<any>>; public zab(): com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.ApiKey<any>,string>>; public constructor(param0: java.lang.Iterable<any>); public zaa(param0: com.google.android.gms.common.api.internal.ApiKey<any>, param1: com.google.android.gms.common.ConnectionResult, param2: string): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zak { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zak>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zal>; public zac: com.google.android.gms.common.GoogleApiAvailability; public zab(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public zaa(): void; public zab(): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onCancel(param0: globalAndroid.content.DialogInterface): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public onStop(): void; public constructor(param0: com.google.android.gms.common.api.internal.LifecycleFragment); public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public onStart(): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zam extends com.google.android.gms.common.api.internal.zabm { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zam>; public zaa(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zan { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zan>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zao extends java.lang.ThreadLocal<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zao>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zap extends com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zap>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zap interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; onConnected(param0: globalAndroid.os.Bundle): void; onConnectionSuspended(param0: number): void; }); public constructor(); public static CAUSE_SERVICE_DISCONNECTED: number; public static CAUSE_NETWORK_LOST: number; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaq implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaq>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public onConnected(param0: globalAndroid.os.Bundle): void; public zaa(param0: com.google.android.gms.common.api.internal.zap): void; public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: boolean); public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zar { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zar>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zas extends com.google.android.gms.common.api.internal.zabo { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zas>; public zaf(): void; public zab(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zac(): void; public zad(): boolean; public zaa(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public zae(): boolean; public zaa(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(): com.google.android.gms.common.ConnectionResult; public zag(): void; public zaa(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public zaa(): void; public zaa(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public static zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zaar, param2: java.util.concurrent.locks.Lock, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.GoogleApiAvailabilityLight, param5: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param6: com.google.android.gms.common.internal.ClientSettings, param7: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param8: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param9: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>): com.google.android.gms.common.api.internal.zas; public zaa(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zat extends com.google.android.gms.common.api.internal.zabn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zat>; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: number, param1: boolean): void; public zaa(param0: globalAndroid.os.Bundle): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zau extends com.google.android.gms.common.api.internal.zabn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zau>; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: number, param1: boolean): void; public zaa(param0: globalAndroid.os.Bundle): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zav { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zav>; public zab(): void; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaw extends com.google.android.gms.tasks.OnCompleteListener<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaw>; public onComplete(param0: com.google.android.gms.tasks.Task<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zax extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zax>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zay extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zay>; public onResume(): void; public zaa(): void; public static zaa(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.internal.GoogleApiManager, param2: com.google.android.gms.common.api.internal.ApiKey<any>): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public onStop(): void; public onStart(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaz { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaz>; public zaa(): com.google.android.gms.common.api.internal.ApiKey<any>; public constructor(param0: com.google.android.gms.common.api.internal.ApiKey<any>); public zab(): com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.api.zaa>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zab extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.zab>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zac { public static class: java.lang.Class<com.google.android.gms.common.api.zac>; public run(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zad { public static class: java.lang.Class<com.google.android.gms.common.api.zad>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export abstract class AbstractDataBuffer<T> extends com.google.android.gms.common.data.DataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.AbstractDataBuffer<any>>; public mDataHolder: com.google.android.gms.common.data.DataHolder; public singleRefIterator(): java.util.Iterator<any>; public close(): void; public getMetadata(): globalAndroid.os.Bundle; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public release(): void; /** @deprecated */ public isClosed(): boolean; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class BitmapTeleporter { public static class: java.lang.Class<com.google.android.gms.common.data.BitmapTeleporter>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.BitmapTeleporter>; public constructor(param0: globalAndroid.graphics.Bitmap); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public release(): void; public setTempDir(param0: java.io.File): void; public get(): globalAndroid.graphics.Bitmap; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBuffer<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.data.DataBuffer<any>>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBuffer<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getCount(): number; get(param0: number): T; getMetadata(): globalAndroid.os.Bundle; close(): void; isClosed(): boolean; iterator(): java.util.Iterator<T>; singleRefIterator(): java.util.Iterator<T>; release(): void; }); public constructor(); public get(param0: number): T; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public release(): void; /** @deprecated */ public isClosed(): boolean; public singleRefIterator(): java.util.Iterator<T>; public getCount(): number; public iterator(): java.util.Iterator<T>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferIterator<T> extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferIterator<any>>; public zaa: com.google.android.gms.common.data.DataBuffer<any>; public zab: number; public constructor(param0: com.google.android.gms.common.data.DataBuffer<any>); public hasNext(): boolean; public remove(): void; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferObserver { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserver>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBufferObserver interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onDataChanged(): void; onDataRangeChanged(param0: number, param1: number): void; onDataRangeInserted(param0: number, param1: number): void; onDataRangeRemoved(param0: number, param1: number): void; onDataRangeMoved(param0: number, param1: number, param2: number): void; }); public constructor(); public onDataRangeInserted(param0: number, param1: number): void; public onDataChanged(): void; public onDataRangeChanged(param0: number, param1: number): void; public onDataRangeRemoved(param0: number, param1: number): void; public onDataRangeMoved(param0: number, param1: number, param2: number): void; } export module DataBufferObserver { export class Observable { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserver.Observable>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBufferObserver$Observable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; }); public constructor(); public removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferObserverSet implements com.google.android.gms.common.data.DataBufferObserver, com.google.android.gms.common.data.DataBufferObserver.Observable { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserverSet>; public constructor(); public addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public hasObservers(): boolean; public onDataRangeInserted(param0: number, param1: number): void; public clear(): void; public onDataChanged(): void; public onDataRangeChanged(param0: number, param1: number): void; public onDataRangeRemoved(param0: number, param1: number): void; public onDataRangeMoved(param0: number, param1: number, param2: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferRef { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferRef>; public mDataHolder: com.google.android.gms.common.data.DataHolder; public mDataRow: number; public getInteger(param0: string): number; public hasColumn(param0: string): boolean; public hashCode(): number; public getFloat(param0: string): number; public parseUri(param0: string): globalAndroid.net.Uri; public getByteArray(param0: string): androidNative.Array<number>; public copyToBuffer(param0: string, param1: globalAndroid.database.CharArrayBuffer): void; public getDouble(param0: string): number; public hasNull(param0: string): boolean; public isDataValid(): boolean; public getLong(param0: string): number; public zaa(param0: number): void; public getString(param0: string): string; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: number); public getDataRow(): number; public equals(param0: any): boolean; public getBoolean(param0: string): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferSafeParcelable<T> extends com.google.android.gms.common.data.AbstractDataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferSafeParcelable<any>>; public singleRefIterator(): java.util.Iterator<any>; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: globalAndroid.os.Parcelable.Creator<any>); public getMetadata(): globalAndroid.os.Bundle; public close(): void; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public static addValue(param0: com.google.android.gms.common.data.DataHolder.Builder, param1: com.google.android.gms.common.internal.safeparcel.SafeParcelable): void; public release(): void; /** @deprecated */ public isClosed(): boolean; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; public static buildDataHolder(): com.google.android.gms.common.data.DataHolder.Builder; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferUtils { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferUtils>; public static KEY_NEXT_PAGE_TOKEN: string; public static KEY_PREV_PAGE_TOKEN: string; public static freezeAndClose(param0: com.google.android.gms.common.data.DataBuffer<any>): java.util.ArrayList; public static hasData(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; public static hasPrevPage(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; public static hasNextPage(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataHolder { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.DataHolder>; public getString(param0: string, param1: number, param2: number): string; public close(): void; public static empty(param0: number): com.google.android.gms.common.data.DataHolder; public hasColumn(param0: string): boolean; public hasNull(param0: string, param1: number, param2: number): boolean; public constructor(param0: globalAndroid.database.Cursor, param1: number, param2: globalAndroid.os.Bundle); public zaa(): void; public finalize(): void; public getLong(param0: string, param1: number, param2: number): number; public static builder(param0: androidNative.Array<string>): com.google.android.gms.common.data.DataHolder.Builder; public isClosed(): boolean; public zab(param0: string, param1: number, param2: number): number; public getCount(): number; public zaa(param0: string, param1: number, param2: number, param3: globalAndroid.database.CharArrayBuffer): void; public getStatusCode(): number; public constructor(param0: androidNative.Array<string>, param1: androidNative.Array<globalAndroid.database.CursorWindow>, param2: number, param3: globalAndroid.os.Bundle); public getMetadata(): globalAndroid.os.Bundle; public getInteger(param0: string, param1: number, param2: number): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zaa(param0: string, param1: number, param2: number): number; public getBoolean(param0: string, param1: number, param2: number): boolean; public getByteArray(param0: string, param1: number, param2: number): androidNative.Array<number>; public getWindowIndex(param0: number): number; } export module DataHolder { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder.Builder>; public build(param0: number, param1: globalAndroid.os.Bundle): com.google.android.gms.common.data.DataHolder; public zaa(param0: java.util.HashMap<string,any>): com.google.android.gms.common.data.DataHolder.Builder; public build(param0: number): com.google.android.gms.common.data.DataHolder; public withRow(param0: globalAndroid.content.ContentValues): com.google.android.gms.common.data.DataHolder.Builder; } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder.zaa>; public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export abstract class EntityBuffer<T> extends com.google.android.gms.common.data.AbstractDataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.EntityBuffer<any>>; public singleRefIterator(): java.util.Iterator<any>; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public getChildDataMarkerColumn(): string; public iterator(): java.util.Iterator<any>; public getPrimaryDataMarkerColumn(): string; public get(param0: number): any; public release(): void; /** @deprecated */ public isClosed(): boolean; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; public getEntry(param0: number, param1: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class Freezable<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.data.Freezable<any>>; /** * Constructs a new instance of the com.google.android.gms.common.data.Freezable<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { freeze(): T; isDataValid(): boolean; }); public constructor(); public isDataValid(): boolean; public freeze(): T; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class FreezableUtils { public static class: java.lang.Class<com.google.android.gms.common.data.FreezableUtils>; public constructor(); public static freeze(param0: androidNative.Array<com.google.android.gms.common.data.Freezable<any>>): java.util.ArrayList; public static freezeIterable(param0: java.lang.Iterable): java.util.ArrayList; public static freeze(param0: java.util.ArrayList): java.util.ArrayList; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class SingleRefDataBufferIterator<T> extends com.google.android.gms.common.data.DataBufferIterator<any> { public static class: java.lang.Class<com.google.android.gms.common.data.SingleRefDataBufferIterator<any>>; public constructor(param0: com.google.android.gms.common.data.DataBuffer<any>); public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.BitmapTeleporter> { public static class: java.lang.Class<com.google.android.gms.common.data.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zab extends com.google.android.gms.common.data.DataHolder.Builder { public static class: java.lang.Class<com.google.android.gms.common.data.zab>; public withRow(param0: globalAndroid.content.ContentValues): com.google.android.gms.common.data.DataHolder.Builder; public zaa(param0: java.util.HashMap<string,any>): com.google.android.gms.common.data.DataHolder.Builder; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zac extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.DataHolder> { public static class: java.lang.Class<com.google.android.gms.common.data.zac>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class ImageManager { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager>; public loadImage(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri): void; public loadImage(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri, param2: number): void; public loadImage(param0: globalAndroid.widget.ImageView, param1: number): void; public loadImage(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri): void; public loadImage(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri, param2: number): void; public static create(param0: globalAndroid.content.Context): com.google.android.gms.common.images.ImageManager; } export module ImageManager { export class ImageReceiver { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.ImageReceiver>; public zab(param0: com.google.android.gms.common.images.zab): void; public zaa(): void; public zaa(param0: com.google.android.gms.common.images.zab): void; public onReceiveResult(param0: number, param1: globalAndroid.os.Bundle): void; } export class OnImageLoadedListener { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.OnImageLoadedListener>; /** * Constructs a new instance of the com.google.android.gms.common.images.ImageManager$OnImageLoadedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onImageLoaded(param0: globalAndroid.net.Uri, param1: globalAndroid.graphics.drawable.Drawable, param2: boolean): void; }); public constructor(); public onImageLoaded(param0: globalAndroid.net.Uri, param1: globalAndroid.graphics.drawable.Drawable, param2: boolean): void; } export class zaa extends androidx.collection.LruCache<com.google.android.gms.common.images.zaa,globalAndroid.graphics.Bitmap> { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zaa>; } export class zab { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zab>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: com.google.android.gms.common.images.zab); public run(): void; } export class zac { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zac>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: globalAndroid.net.Uri, param2: globalAndroid.os.ParcelFileDescriptor); public run(): void; } export class zad { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zad>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: globalAndroid.net.Uri, param2: globalAndroid.graphics.Bitmap, param3: boolean, param4: java.util.concurrent.CountDownLatch); public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class Size { public static class: java.lang.Class<com.google.android.gms.common.images.Size>; public getWidth(): number; public getHeight(): number; public constructor(param0: number, param1: number); public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public static parseSize(param0: string): com.google.android.gms.common.images.Size; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class WebImage { public static class: java.lang.Class<com.google.android.gms.common.images.WebImage>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.images.WebImage>; public getWidth(): number; public getHeight(): number; public constructor(param0: globalAndroid.net.Uri); public getUrl(): globalAndroid.net.Uri; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.net.Uri, param1: number, param2: number); public constructor(param0: org.json.JSONObject); public hashCode(): number; public toJson(): org.json.JSONObject; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.images.zaa>; public zaa: globalAndroid.net.Uri; public constructor(param0: globalAndroid.net.Uri); public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export abstract class zab { public static class: java.lang.Class<com.google.android.gms.common.images.zab>; public zab: number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public zaa(param0: boolean, param1: boolean): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zac extends com.google.android.gms.common.images.zab { public static class: java.lang.Class<com.google.android.gms.common.images.zac>; public hashCode(): number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public equals(param0: any): boolean; public constructor(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri); public zaa(param0: boolean, param1: boolean): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zad extends com.google.android.gms.common.images.zab { public static class: java.lang.Class<com.google.android.gms.common.images.zad>; public constructor(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri); public hashCode(): number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public equals(param0: any): boolean; public zaa(param0: boolean, param1: boolean): boolean; public constructor(param0: globalAndroid.widget.ImageView, param1: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zae extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.images.WebImage> { public static class: java.lang.Class<com.google.android.gms.common.images.zae>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ApiExceptionUtil { public static class: java.lang.Class<com.google.android.gms.common.internal.ApiExceptionUtil>; public constructor(); public static fromStatus(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ClientIdentity { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientIdentity>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ClientIdentity>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public constructor(param0: number, param1: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ClientSettings { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings>; public zaa(param0: java.lang.Integer): void; public getGravityForPopups(): number; public getRealClientPackageName(): string; public zad(): java.lang.Integer; public zac(): com.google.android.gms.signin.SignInOptions; public static createDefault(param0: globalAndroid.content.Context): com.google.android.gms.common.internal.ClientSettings; public zaa(): java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.zaa>; public getViewForPopups(): globalAndroid.view.View; public constructor(param0: globalAndroid.accounts.Account, param1: java.util.Set<com.google.android.gms.common.api.Scope>, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.zaa>, param3: number, param4: globalAndroid.view.View, param5: string, param6: string, param7: com.google.android.gms.signin.SignInOptions); public getRequiredScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getAccountOrDefault(): globalAndroid.accounts.Account; public getApplicableScopes(param0: com.google.android.gms.common.api.Api<any>): java.util.Set<com.google.android.gms.common.api.Scope>; /** @deprecated */ public getAccountName(): string; public getAccount(): globalAndroid.accounts.Account; public getAllRequestedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public constructor(param0: globalAndroid.accounts.Account, param1: java.util.Set<com.google.android.gms.common.api.Scope>, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.zaa>, param3: number, param4: globalAndroid.view.View, param5: string, param6: string, param7: com.google.android.gms.signin.SignInOptions, param8: boolean); public zab(): string; } export module ClientSettings { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings.Builder>; public zaa(param0: globalAndroid.accounts.Account): com.google.android.gms.common.internal.ClientSettings.Builder; public zaa(param0: java.util.Collection<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.internal.ClientSettings.Builder; public zaa(param0: string): com.google.android.gms.common.internal.ClientSettings.Builder; public build(): com.google.android.gms.common.internal.ClientSettings; public constructor(); public setRealClientPackageName(param0: string): com.google.android.gms.common.internal.ClientSettings.Builder; } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings.zaa>; public zaa: java.util.Set<com.google.android.gms.common.api.Scope>; public constructor(param0: java.util.Set<com.google.android.gms.common.api.Scope>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class FallbackServiceBroker { public static class: java.lang.Class<com.google.android.gms.common.internal.FallbackServiceBroker>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class GmsClient<T> extends com.google.android.gms.common.internal.BaseGmsClient<any> { public static class: java.lang.Class<com.google.android.gms.common.internal.GmsClient<any>>; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public validateScopes(param0: java.util.Set<com.google.android.gms.common.api.Scope>): java.util.Set<com.google.android.gms.common.api.Scope>; public getAccount(): globalAndroid.accounts.Account; public getClientSettings(): com.google.android.gms.common.internal.ClientSettings; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getEndpointPackageName(): string; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getSignInIntent(): globalAndroid.content.Intent; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getConnectionHint(): globalAndroid.os.Bundle; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public requiresAccount(): boolean; public getScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public disconnect(): void; public isConnected(): boolean; public providesSignIn(): boolean; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public isConnecting(): boolean; public getLastDisconnectMessage(): string; public disconnect(param0: string): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public getMinApkVersion(): number; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class PendingResultUtil { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil>; public constructor(); public static toVoidTask(param0: com.google.android.gms.common.api.PendingResult<any>): com.google.android.gms.tasks.Task; public static toTask(param0: com.google.android.gms.common.api.PendingResult<any>, param1: com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any>): com.google.android.gms.tasks.Task; public static toResponseTask(param0: com.google.android.gms.common.api.PendingResult<any>, param1: com.google.android.gms.common.api.Response): com.google.android.gms.tasks.Task; } export module PendingResultUtil { export class ResultConverter<R, T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.internal.PendingResultUtil$ResultConverter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { convert(param0: R): T; }); public constructor(); public convert(param0: R): T; } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil.zaa>; /** * Constructs a new instance of the com.google.android.gms.common.internal.PendingResultUtil$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; }); public constructor(); public zaa(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class Common { public static class: java.lang.Class<com.google.android.gms.common.internal.service.Common>; public static CLIENT_KEY: com.google.android.gms.common.api.Api.ClientKey<com.google.android.gms.common.internal.service.zah>; public static API: com.google.android.gms.common.api.Api<com.google.android.gms.common.api.Api.ApiOptions.NoOptions>; public static zaa: com.google.android.gms.common.internal.service.zab; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaa extends com.google.android.gms.common.internal.service.zal { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaa>; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public constructor(); public constructor(param0: string); public zaa(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zab { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zab>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zab interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; }); public constructor(); public zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zac extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.common.internal.service.zah,com.google.android.gms.common.api.Api.ApiOptions.NoOptions> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zac>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zad extends com.google.android.gms.common.internal.service.zai { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zad>; public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zae extends com.google.android.gms.common.internal.service.zab { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zae>; public constructor(); public zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zaf<R> extends com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,com.google.android.gms.common.internal.service.zah> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaf<any>>; public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(); /** @deprecated */ public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zag extends com.google.android.gms.common.internal.service.zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zag>; public constructor(param0: com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<com.google.android.gms.common.api.Status>); public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public constructor(); public constructor(param0: string); public zaa(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zah extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.common.internal.service.zao> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zah>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param4: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public requiresAccount(): boolean; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getMinApkVersion(): number; public getServiceDescriptor(): string; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public getConnectionHint(): globalAndroid.os.Bundle; public disconnect(param0: string): void; public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public getLastDisconnectMessage(): string; public isConnected(): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public getStartServiceAction(): string; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public disconnect(): void; public isConnecting(): boolean; public providesSignIn(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zai extends com.google.android.gms.common.internal.service.zaf<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zai>; public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(); /** @deprecated */ public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); /** @deprecated */ public constructor(param0: globalAndroid.os.Looper); public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaj extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.internal.service.zak { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaj>; public zaa(): globalAndroid.os.Parcel; public zaa(param0: com.google.android.gms.common.internal.zaaa): void; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zak { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zak>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zak interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.internal.zaaa): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.internal.zaaa): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zal extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.internal.service.zam { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zal>; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public constructor(); public constructor(param0: string); public zaa(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zam { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zam>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zam interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: number): void; }); public constructor(); public zaa(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zan extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.internal.service.zao { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zan>; public zaa(): globalAndroid.os.Parcel; public zaa(param0: com.google.android.gms.common.internal.service.zam): void; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zao { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zao>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zao interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.internal.service.zam): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.internal.service.zam): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zap extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zap>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaq extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.common.api.Api.ApiOptions.NoOptions> implements com.google.android.gms.common.internal.zaac { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaq>; public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; public zaa(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): com.google.android.gms.common.api.Api.Client; public zaa(param0: com.google.android.gms.common.internal.zaaa): com.google.android.gms.tasks.Task<java.lang.Void>; /** @deprecated */ public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public zaa(): number; public constructor(param0: globalAndroid.content.Context); public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public zaa(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler): com.google.android.gms.common.api.internal.zace; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zar extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.common.internal.service.zak> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zar>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.internal.ConnectionCallbacks, param4: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public requiresAccount(): boolean; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getMinApkVersion(): number; public getServiceDescriptor(): string; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public getConnectionHint(): globalAndroid.os.Bundle; public disconnect(param0: string): void; public getApiFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public getLastDisconnectMessage(): string; public isConnected(): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public getStartServiceAction(): string; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getUseDynamicLookup(): boolean; public disconnect(): void; public isConnecting(): boolean; public providesSignIn(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zas extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.common.internal.service.zar,com.google.android.gms.common.api.Api.ApiOptions.NoOptions> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zas>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ClientIdentity> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaaa { public static class: java.lang.Class<com.google.android.gms.common.internal.zaaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zaaa>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zab(): java.util.List<com.google.android.gms.common.internal.zao>; public constructor(param0: number, param1: java.util.List<com.google.android.gms.common.internal.zao>); public zaa(): number; public zaa(param0: com.google.android.gms.common.internal.zao): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaab { public static class: java.lang.Class<com.google.android.gms.common.internal.zaab>; public zaa(param0: globalAndroid.content.res.Resources, param1: number, param2: number): void; public constructor(param0: globalAndroid.content.Context); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaac extends com.google.android.gms.common.api.HasApiKey<com.google.android.gms.common.api.Api.ApiOptions.NoOptions> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaac>; /** * Constructs a new instance of the com.google.android.gms.common.internal.zaac interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.internal.zaaa): com.google.android.gms.tasks.Task<java.lang.Void>; getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; }); public constructor(); public zaa(param0: com.google.android.gms.common.internal.zaaa): com.google.android.gms.tasks.Task<java.lang.Void>; public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaad extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zaaa> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaad>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class zab { public static class: java.lang.Class<com.google.android.gms.common.internal.zab>; public constructor(); public static zaa(param0: androidx.fragment.app.Fragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public zaa(): void; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleFragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public onClick(param0: globalAndroid.content.DialogInterface, param1: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zac { public static class: java.lang.Class<com.google.android.gms.common.internal.zac>; public static zad(param0: globalAndroid.content.Context, param1: number): string; public static zaa(param0: globalAndroid.content.Context): string; public static zae(param0: globalAndroid.content.Context, param1: number): string; public static zab(param0: globalAndroid.content.Context, param1: number): string; public static zac(param0: globalAndroid.content.Context, param1: number): string; public static zaa(param0: globalAndroid.content.Context, param1: number): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zad extends com.google.android.gms.common.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.internal.zad>; public static zaa(param0: androidx.fragment.app.Fragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public zaa(): void; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleFragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zae extends com.google.android.gms.common.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.internal.zae>; public static zaa(param0: androidx.fragment.app.Fragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public zaa(): void; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleFragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaf extends com.google.android.gms.common.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.internal.zaf>; public static zaa(param0: androidx.fragment.app.Fragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; public zaa(): void; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleFragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.zab; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zag { public static class: java.lang.Class<com.google.android.gms.common.internal.zag>; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zah { public static class: java.lang.Class<com.google.android.gms.common.internal.zah>; public constructor(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.internal.zak); public zaa(): void; public zab(): void; public zac(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public zab(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public zaa(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public zab(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public zaa(param0: globalAndroid.os.Bundle): void; public zaa(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: number): void; public zac(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public handleMessage(param0: globalAndroid.os.Message): boolean; public zaa(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zai { public static class: java.lang.Class<com.google.android.gms.common.internal.zai>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaj { public static class: java.lang.Class<com.google.android.gms.common.internal.zaj>; public constructor(); public zaa(): void; public zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api.Client): number; public constructor(param0: com.google.android.gms.common.GoogleApiAvailabilityLight); public zaa(param0: globalAndroid.content.Context, param1: number): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zak { public static class: java.lang.Class<com.google.android.gms.common.internal.zak>; /** * Constructs a new instance of the com.google.android.gms.common.internal.zak interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isConnected(): boolean; getConnectionHint(): globalAndroid.os.Bundle; }); public constructor(); public isConnected(): boolean; public getConnectionHint(): globalAndroid.os.Bundle; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zal extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.internal.zam { public static class: java.lang.Class<com.google.android.gms.common.internal.zal>; public zaa(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.zaw): com.google.android.gms.dynamic.IObjectWrapper; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; public zaa(): globalAndroid.os.Parcel; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zam { public static class: java.lang.Class<com.google.android.gms.common.internal.zam>; /** * Constructs a new instance of the com.google.android.gms.common.internal.zam interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.zaw): com.google.android.gms.dynamic.IObjectWrapper; }); public constructor(); public zaa(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.zaw): com.google.android.gms.dynamic.IObjectWrapper; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zan extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zao> { public static class: java.lang.Class<com.google.android.gms.common.internal.zan>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zao { public static class: java.lang.Class<com.google.android.gms.common.internal.zao>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zao>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: number, param2: number, param3: number, param4: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zap extends com.google.android.gms.common.internal.PendingResultUtil.zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.zap>; public zaa(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaq extends com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaq>; public convert(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zar extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.internal.zar>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zas extends com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.internal.zas>; public convert(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zat { public static class: java.lang.Class<com.google.android.gms.common.internal.zat>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zat>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.accounts.Account, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zau { public static class: java.lang.Class<com.google.android.gms.common.internal.zau>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zau>; public zaa(): com.google.android.gms.common.internal.IAccountAccessor; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zac(): boolean; public zad(): boolean; public equals(param0: any): boolean; public zab(): com.google.android.gms.common.ConnectionResult; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zav extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zat> { public static class: java.lang.Class<com.google.android.gms.common.internal.zav>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaw { public static class: java.lang.Class<com.google.android.gms.common.internal.zaw>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zaw>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: number, param2: androidNative.Array<com.google.android.gms.common.api.Scope>); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zax extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zau> { public static class: java.lang.Class<com.google.android.gms.common.internal.zax>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zay extends com.google.android.gms.dynamic.RemoteCreator<com.google.android.gms.common.internal.zam> { public static class: java.lang.Class<com.google.android.gms.common.internal.zay>; public static zaa(param0: globalAndroid.content.Context, param1: number, param2: number): globalAndroid.view.View; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaz extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.zaw> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaz>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export class FavaDiagnosticsEntity { public static class: java.lang.Class<com.google.android.gms.common.server.FavaDiagnosticsEntity>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.FavaDiagnosticsEntity>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: string, param2: number); public constructor(param0: string, param1: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class StringToIntConverter extends com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable implements com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<string,java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.StringToIntConverter>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter>; public zab(): number; public add(param0: string, param1: number): com.google.android.gms.common.server.converter.StringToIntConverter; public zab(param0: any): any; public zaa(param0: any): any; public zaa(): number; public constructor(); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module StringToIntConverter { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.server.converter.StringToIntConverter.zaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter.zaa>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.zab> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zaa>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zab { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zab>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.zab>; public zaa(): com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>; public static zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>): com.google.android.gms.common.server.converter.zab; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zac extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter.zaa> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zac>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zad extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zad>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export abstract class FastJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse>; public toString(): string; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.Map): void; public setIntegerInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Integer>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigInteger): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Float>): void; public addConcreteTypeInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: com.google.android.gms.common.server.response.FastJsonResponse): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: number): void; public static zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: any): any; public setStringsInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<string>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigDecimal): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigDecimal): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setLongInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Long>): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Boolean>): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: boolean): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: androidNative.Array<number>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigInteger): void; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigInteger>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public setStringMapInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.Map<string,string>): void; public constructor(); public zah(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public getFieldMappings(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public setDecodedBytesInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: androidNative.Array<number>): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Double>): void; public isPrimitiveFieldSet(param0: string): boolean; public addConcreteTypeArrayInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList): void; public isFieldSet(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>): boolean; public getValueObject(param0: string): any; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigDecimal>): void; public setBooleanInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: boolean): void; public getFieldValue(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>): any; public setStringInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: string): void; } export module FastJsonResponse { export class Field<I, O> extends com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zae: string; public zaf: number; public zag: java.lang.Class<any>; public static CREATOR: com.google.android.gms.common.server.response.zai; public zad(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static forConcreteTypeArray(param0: string, param1: number, param2: java.lang.Class): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public zab(param0: any): any; public static forBoolean(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Boolean,java.lang.Boolean>; public toString(): string; public static forLong(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Long,java.lang.Long>; public static forStrings(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.util.ArrayList<string>,java.util.ArrayList<string>>; public zac(): com.google.android.gms.common.server.response.FastJsonResponse; public static forFloat(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Float,java.lang.Float>; public getSafeParcelableFieldId(): number; public static forString(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<string,string>; public static forStringMap(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.util.HashMap<string,string>,java.util.HashMap<string,string>>; public zaa(param0: com.google.android.gms.common.server.response.zaj): void; public static forDouble(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Double,java.lang.Double>; public static forBase64(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<androidNative.Array<number>,androidNative.Array<number>>; public zab(): boolean; public static forConcreteType(param0: string, param1: number, param2: java.lang.Class): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public zaa(param0: any): any; public static forInteger(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Integer,java.lang.Integer>; public static withConverter(param0: string, param1: number, param2: com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>, param3: boolean): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public zaa(): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; } export class FieldConverter<I, O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.server.response.FastJsonResponse$FieldConverter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(): number; zab(): number; zab(param0: I): O; zaa(param0: O): I; }); public constructor(); public zab(param0: I): O; public zaa(param0: O): I; public zab(): number; public zaa(): number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class FastParser<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser<any>>; public constructor(); public parse(param0: java.io.InputStream, param1: T): void; } export module FastParser { export class ParseException { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser.ParseException>; public constructor(param0: java.lang.Throwable); public constructor(param0: string); public constructor(param0: string, param1: java.lang.Throwable); } export class zaa<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser.zaa<any>>; /** * Constructs a new instance of the com.google.android.gms.common.server.response.FastParser$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): O; }); public constructor(); public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): O; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export abstract class FastSafeParcelableJsonResponse extends com.google.android.gms.common.server.response.FastJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastSafeParcelableJsonResponse>; public describeContents(): number; public isPrimitiveFieldSet(param0: string): boolean; public equals(param0: any): boolean; public toByteArray(): androidNative.Array<number>; public getValueObject(param0: string): any; public constructor(); public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class SafeParcelResponse extends com.google.android.gms.common.server.response.FastSafeParcelableJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.SafeParcelResponse>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.SafeParcelResponse>; public toString(): string; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.Map): void; public setIntegerInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Integer>): void; public static from(param0: com.google.android.gms.common.server.response.FastJsonResponse): com.google.android.gms.common.server.response.SafeParcelResponse; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigInteger): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Float>): void; public addConcreteTypeInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: com.google.android.gms.common.server.response.FastJsonResponse): void; public constructor(param0: com.google.android.gms.common.server.response.zaj, param1: string); public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: number): void; public static zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: any): any; public setStringsInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<string>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigDecimal): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigDecimal): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setLongInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Long>): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Boolean>): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: boolean): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: androidNative.Array<number>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigInteger): void; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigInteger>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public setStringMapInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.Map<string,string>): void; public constructor(); public getFieldMappings(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public setDecodedBytesInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: androidNative.Array<number>): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Double>): void; public isPrimitiveFieldSet(param0: string): boolean; public addConcreteTypeArrayInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList): void; public getValueObject(param0: string): any; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigDecimal>): void; public setBooleanInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: boolean): void; public setStringInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: string): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaa extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Long> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaa>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zab extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zab>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zac extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Double> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zac>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zad extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Float> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zad>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zae extends com.google.android.gms.common.server.response.FastParser.zaa<string> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zae>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaf extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaf>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zag extends com.google.android.gms.common.server.response.FastParser.zaa<java.math.BigDecimal> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zag>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zah extends com.google.android.gms.common.server.response.FastParser.zaa<java.math.BigInteger> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zah>; public zaa(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zai extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zai>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaj { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaj>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zaj>; public zaa(param0: java.lang.Class<any>): boolean; public toString(): string; public zac(): string; public zaa(): void; public zab(): void; public zaa(param0: string): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zaa(param0: java.lang.Class<any>, param1: java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>): void; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: java.lang.Class<any>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zak extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zal> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zak>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zal { public static class: java.lang.Class<com.google.android.gms.common.server.response.zal>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zal>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zam { public static class: java.lang.Class<com.google.android.gms.common.server.response.zam>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zam>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zan extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zam> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zan>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zao extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zaj> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zao>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zap extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.SafeParcelResponse> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zap>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.FavaDiagnosticsEntity> { public static class: java.lang.Class<com.google.android.gms.common.server.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.zaa>; public then(param0: any): com.google.android.gms.tasks.Task; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class zab { public static class: java.lang.Class<com.google.android.gms.common.zab>; public then(param0: any): com.google.android.gms.tasks.Task; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export abstract class DeferredLifecycleHelper<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.dynamic.DeferredLifecycleHelper<any>>; public constructor(); public onResume(): void; public createDelegate(param0: com.google.android.gms.dynamic.OnDelegateCreatedListener<T>): void; public handleGooglePlayUnavailable(param0: globalAndroid.widget.FrameLayout): void; public onStop(): void; public onLowMemory(): void; public onPause(): void; public onDestroyView(): void; public onDestroy(): void; public onInflate(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle, param2: globalAndroid.os.Bundle): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onCreateView(param0: globalAndroid.view.LayoutInflater, param1: globalAndroid.view.ViewGroup, param2: globalAndroid.os.Bundle): globalAndroid.view.View; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public static showGooglePlayUnavailableMessage(param0: globalAndroid.widget.FrameLayout): void; public onStart(): void; public getDelegate(): T; } export module DeferredLifecycleHelper { export class zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa>; /** * Constructs a new instance of the com.google.android.gms.dynamic.DeferredLifecycleHelper$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(): number; zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; }); public constructor(); public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; public zaa(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zaa extends com.google.android.gms.dynamic.OnDelegateCreatedListener<any> { public static class: java.lang.Class<com.google.android.gms.dynamic.zaa>; public onDelegateCreated(param0: any): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zab extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zab>; public zaa(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zac extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zac>; public zaa(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zad { public static class: java.lang.Class<com.google.android.gms.dynamic.zad>; public onClick(param0: globalAndroid.view.View): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zae extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zae>; public zaa(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zaf extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zaf>; public zaa(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zag extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zag>; public zaa(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zba { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zba>; // public constructor(param0: globalAndroid.os.IBinder, param1: string); // public zbb(param0: number, param1: globalAndroid.os.Parcel): void; // public asBinder(): globalAndroid.os.IBinder; // public zba(): globalAndroid.os.Parcel; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbaa extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.internal.auth-api.zbab { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbaa>; // public constructor(); // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public zbb(param0: com.google.android.gms.common.api.Status, param1: globalAndroid.app.PendingIntent): void; // public constructor(param0: string); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbab { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbab>; // /** // * Constructs a new instance of the com.google.android.gms.internal.auth-api.zbab interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status, param1: globalAndroid.app.PendingIntent): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: globalAndroid.app.PendingIntent): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbac extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.internal.auth-api.zbad { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbac>; // public constructor(); // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public constructor(param0: string); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbad { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbad>; // /** // * Constructs a new instance of the com.google.android.gms.internal.auth-api.zbad interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbae extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.internal.auth-api.zbaf { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbae>; // public constructor(); // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public constructor(param0: string); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SavePasswordResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbaf { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbaf>; // /** // * Constructs a new instance of the com.google.android.gms.internal.auth-api.zbaf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SavePasswordResult): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SavePasswordResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbag extends com.google.android.gms.internal.auth-api.zba { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbag>; // public zbd(param0: com.google.android.gms.internal.auth-api.zbab, param1: com.google.android.gms.auth.api.identity.GetSignInIntentRequest): void; // public zbc(param0: com.google.android.gms.internal.auth-api.zby, param1: com.google.android.gms.auth.api.identity.BeginSignInRequest): void; // public zbe(param0: com.google.android.gms.common.api.internal.IStatusCallback, param1: string): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbah extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbah>; // public accept(param0: any, param1: any): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbai extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbai>; // public accept(param0: any, param1: any): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbaj extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.internal.auth-api.zbw,com.google.android.gms.auth.api.identity.zbc> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbaj>; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbak extends com.google.android.gms.internal.auth-api.zbac { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbak>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbal extends com.google.android.gms.internal.auth-api.zbae { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbal>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.SavePasswordResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbam extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.auth.api.identity.zbc> implements com.google.android.gms.auth.api.identity.CredentialSavingClient { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbam>; // /** @deprecated */ // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public savePassword(param0: com.google.android.gms.auth.api.identity.SavePasswordRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SavePasswordResult>; // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public saveAccountLinkingToken(param0: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenResult>; // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.auth.api.identity.zbc); // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.identity.zbc); // public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zban extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zban>; // public accept(param0: any, param1: any): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbao extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbao>; // public accept(param0: any, param1: any): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbap extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbap>; // public accept(param0: any, param1: any): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbaq extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.internal.auth-api.zbav,com.google.android.gms.auth.api.identity.zbl> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbaq>; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbar extends com.google.android.gms.internal.auth-api.zbx { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbar>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.BeginSignInResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbas extends com.google.android.gms.common.api.internal.IStatusCallback.Stub { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbas>; // public onResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbat extends com.google.android.gms.internal.auth-api.zbaa { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbat>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: globalAndroid.app.PendingIntent): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbau extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.auth.api.identity.zbl> implements com.google.android.gms.auth.api.identity.SignInClient { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbau>; // /** @deprecated */ // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.auth.api.identity.zbl); // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.identity.zbl); // public signOut(): com.google.android.gms.tasks.Task<java.lang.Void>; // public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); // public getSignInCredentialFromIntent(param0: globalAndroid.content.Intent): com.google.android.gms.auth.api.identity.SignInCredential; // public getSignInIntent(param0: com.google.android.gms.auth.api.identity.GetSignInIntentRequest): com.google.android.gms.tasks.Task<globalAndroid.app.PendingIntent>; // public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); // public beginSignIn(param0: com.google.android.gms.auth.api.identity.BeginSignInRequest): com.google.android.gms.tasks.Task<com.google.android.gms.auth.api.identity.BeginSignInResult>; // public getApiKey(): com.google.android.gms.common.api.internal.ApiKey<any>; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbav extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.internal.auth-api.zbag> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbav>; // public getStartServiceAction(): string; // public requiresGooglePlayServices(): boolean; // public getServiceBrokerBinder(): globalAndroid.os.IBinder; // public getServiceDescriptor(): string; // public usesClientTelemetry(): boolean; // public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getEndpointPackageName(): string; // public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getSignInIntent(): globalAndroid.content.Intent; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public getConnectionHint(): globalAndroid.os.Bundle; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.auth.api.identity.zbl, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); // public getGetServiceRequestExtraArgs(): globalAndroid.os.Bundle; // public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; // public requiresAccount(): boolean; // public disconnect(): void; // public isConnected(): boolean; // public providesSignIn(): boolean; // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); // public isConnecting(): boolean; // public getLastDisconnectMessage(): string; // public getUseDynamicLookup(): boolean; // public disconnect(param0: string): void; // public getMinApkVersion(): number; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); // public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; // public getApiFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; // public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; // public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; // public requiresSignIn(): boolean; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbaw { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbaw>; // public static zba: com.google.android.gms.common.Feature; // public static zbb: com.google.android.gms.common.Feature; // public static zbc: com.google.android.gms.common.Feature; // public static zbd: com.google.android.gms.common.Feature; // public static zbe: com.google.android.gms.common.Feature; // public static zbf: com.google.android.gms.common.Feature; // public static zbg: com.google.android.gms.common.Feature; // public static zbh: androidNative.Array<com.google.android.gms.common.Feature>; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbax { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbax>; // public static zba(): string; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbay { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbay>; // public static zba(param0: globalAndroid.content.Context, param1: number, param2: globalAndroid.content.Intent, param3: number): globalAndroid.app.PendingIntent; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbb { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbb>; // public asBinder(): globalAndroid.os.IBinder; // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public constructor(param0: string); // public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbc { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbc>; // public static zbb(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable): void; // public static zbc(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.IInterface): void; // public static zba(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable.Creator): globalAndroid.os.Parcelable; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbd extends com.google.android.gms.internal.auth-api.zbr { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbd>; // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // public constructor(param0: string); // public zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbe extends com.google.android.gms.auth.api.credentials.CredentialRequestResult { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbe>; // public getStatus(): com.google.android.gms.common.api.Status; // public getCredential(): com.google.android.gms.auth.api.credentials.Credential; // public constructor(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbf extends com.google.android.gms.internal.auth-api.zbd { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbf>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // public zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbg extends com.google.android.gms.internal.auth-api.zbm<com.google.android.gms.auth.api.credentials.CredentialRequestResult> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbg>; // public setResult(param0: any): void; // public zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.internal.auth-api.zbt): void; // public setFailedResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbh extends com.google.android.gms.internal.auth-api.zbm<com.google.android.gms.common.api.Status> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbh>; // public setResult(param0: any): void; // public zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.internal.auth-api.zbt): void; // public setFailedResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbi extends com.google.android.gms.internal.auth-api.zbm<com.google.android.gms.common.api.Status> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbi>; // public setResult(param0: any): void; // public zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.internal.auth-api.zbt): void; // public setFailedResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbj extends com.google.android.gms.internal.auth-api.zbm<com.google.android.gms.common.api.Status> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbj>; // public setResult(param0: any): void; // public zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.internal.auth-api.zbt): void; // public setFailedResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbk extends com.google.android.gms.internal.auth-api.zbd { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbk>; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // public zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbl extends com.google.android.gms.auth.api.credentials.CredentialsApi { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbl>; // public constructor(); // public save(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; // public request(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.CredentialRequest): com.google.android.gms.common.api.PendingResult<com.google.android.gms.auth.api.credentials.CredentialRequestResult>; // public delete(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.Credential): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; // public disableAutoSignIn(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; // public getHintPickerIntent(param0: com.google.android.gms.common.api.GoogleApiClient, param1: com.google.android.gms.auth.api.credentials.HintRequest): globalAndroid.app.PendingIntent; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbm<R> extends com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,com.google.android.gms.internal.auth-api.zbo> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbm<any>>; // public setResult(param0: any): void; // public zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.internal.auth-api.zbt): void; // public setFailedResult(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbn { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbn>; // public static zba(param0: globalAndroid.content.Context, param1: com.google.android.gms.auth.api.Auth.AuthCredentialsOptions, param2: com.google.android.gms.auth.api.credentials.HintRequest, param3: string): globalAndroid.app.PendingIntent; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbo extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.internal.auth-api.zbt> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbo>; // public getStartServiceAction(): string; // public requiresGooglePlayServices(): boolean; // public getServiceBrokerBinder(): globalAndroid.os.IBinder; // public getServiceDescriptor(): string; // public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getEndpointPackageName(): string; // public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getSignInIntent(): globalAndroid.content.Intent; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public getConnectionHint(): globalAndroid.os.Bundle; // public getGetServiceRequestExtraArgs(): globalAndroid.os.Bundle; // public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; // public requiresAccount(): boolean; // public disconnect(): void; // public isConnected(): boolean; // public providesSignIn(): boolean; // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.auth.api.Auth.AuthCredentialsOptions, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); // public isConnecting(): boolean; // public getLastDisconnectMessage(): string; // public disconnect(param0: string): void; // public getMinApkVersion(): number; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); // public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; // public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; // public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; // public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; // public requiresSignIn(): boolean; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbp { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbp>; // public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.auth-api.zbp>; // public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; // public constructor(param0: com.google.android.gms.auth.api.credentials.Credential); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbq extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.auth-api.zbp> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbq>; // public constructor(); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbr extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.internal.auth-api.zbs { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbr>; // public constructor(); // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // public constructor(param0: string); // public zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbs { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbs>; // /** // * Constructs a new instance of the com.google.android.gms.internal.auth-api.zbs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // zbc(param0: com.google.android.gms.common.api.Status): void; // zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.credentials.Credential): void; // public zbd(param0: com.google.android.gms.common.api.Status, param1: string): void; // public zbc(param0: com.google.android.gms.common.api.Status): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbt extends com.google.android.gms.internal.auth-api.zba { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbt>; // public zbc(param0: com.google.android.gms.internal.auth-api.zbs, param1: com.google.android.gms.internal.auth-api.zbp): void; // public zbd(param0: com.google.android.gms.internal.auth-api.zbs, param1: com.google.android.gms.auth.api.credentials.CredentialRequest): void; // public zbe(param0: com.google.android.gms.internal.auth-api.zbs, param1: com.google.android.gms.internal.auth-api.zbu): void; // public zbf(param0: com.google.android.gms.internal.auth-api.zbs): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbu { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbu>; // public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.auth-api.zbu>; // public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; // public constructor(param0: com.google.android.gms.auth.api.credentials.Credential); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbv extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.auth-api.zbu> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbv>; // public constructor(); // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbw extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.internal.auth-api.zbz> { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbw>; // public getStartServiceAction(): string; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.auth.api.identity.zbc, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); // public requiresGooglePlayServices(): boolean; // public getServiceBrokerBinder(): globalAndroid.os.IBinder; // public getServiceDescriptor(): string; // public usesClientTelemetry(): boolean; // public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getEndpointPackageName(): string; // public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public getSignInIntent(): globalAndroid.content.Intent; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); // public getConnectionHint(): globalAndroid.os.Bundle; // public getGetServiceRequestExtraArgs(): globalAndroid.os.Bundle; // public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; // public requiresAccount(): boolean; // public disconnect(): void; // public isConnected(): boolean; // public providesSignIn(): boolean; // /** @deprecated */ // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); // public isConnecting(): boolean; // public getLastDisconnectMessage(): string; // public getUseDynamicLookup(): boolean; // public disconnect(param0: string): void; // public getMinApkVersion(): number; // public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); // public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; // public getApiFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; // public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; // public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; // public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; // public requiresSignIn(): boolean; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export abstract class zbx extends com.google.android.gms.internal.auth-api.zbb implements com.google.android.gms.internal.auth-api.zby { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbx>; // public constructor(); // public zba(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; // public constructor(param0: string); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.BeginSignInResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zby { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zby>; // /** // * Constructs a new instance of the com.google.android.gms.internal.auth-api.zby interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. // */ // public constructor(implementation: { // zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.BeginSignInResult): void; // }); // public constructor(); // public zbb(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.identity.BeginSignInResult): void; // } // } // } // } // } // } // } // declare module com { // export module google { // export module android { // export module gms { // export module internal { // export module auth-api { // export class zbz extends com.google.android.gms.internal.auth-api.zba { // public static class: java.lang.Class<com.google.android.gms.internal.auth-api.zbz>; // public zbd(param0: com.google.android.gms.internal.auth-api.zbaf, param1: com.google.android.gms.auth.api.identity.SavePasswordRequest): void; // public zbc(param0: com.google.android.gms.internal.auth-api.zbad, param1: com.google.android.gms.auth.api.identity.SaveAccountLinkingTokenRequest): void; // } // } // } // } // } // } // } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaa { public static class: java.lang.Class<com.google.android.gms.internal.base.zaa>; public asBinder(): globalAndroid.os.IBinder; public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public constructor(param0: string); public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zab { public static class: java.lang.Class<com.google.android.gms.internal.base.zab>; public constructor(param0: globalAndroid.os.IBinder, param1: string); public asBinder(): globalAndroid.os.IBinder; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; public zac(param0: number, param1: globalAndroid.os.Parcel): void; public zaa(): globalAndroid.os.Parcel; public zab(param0: number, param1: globalAndroid.os.Parcel): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zac { public static class: java.lang.Class<com.google.android.gms.internal.base.zac>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zac 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 android { export module gms { export module internal { export module base { export class zad { public static class: java.lang.Class<com.google.android.gms.internal.base.zad>; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable.Creator): globalAndroid.os.Parcelable; public static zaa(param0: globalAndroid.os.Parcel, param1: boolean): void; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable): void; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.IInterface): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zae { public static class: java.lang.Class<com.google.android.gms.internal.base.zae>; public static zaa: com.google.android.gms.common.Feature; public static zab: androidNative.Array<com.google.android.gms.common.Feature>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaf { public static class: java.lang.Class<com.google.android.gms.internal.base.zaf>; public invalidateDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public getConstantState(): globalAndroid.graphics.drawable.Drawable.ConstantState; public unscheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable): void; public onBoundsChange(param0: globalAndroid.graphics.Rect): void; public draw(param0: globalAndroid.graphics.Canvas): void; public setColorFilter(param0: globalAndroid.graphics.ColorFilter): void; public getIntrinsicHeight(): number; public scheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable, param2: number): void; public getChangingConfigurations(): number; public mutate(): globalAndroid.graphics.drawable.Drawable; public setAlpha(param0: number): void; public zaa(param0: number): void; public constructor(param0: globalAndroid.graphics.drawable.Drawable, param1: globalAndroid.graphics.drawable.Drawable); public getIntrinsicWidth(): number; public getOpacity(): number; public zaa(): globalAndroid.graphics.drawable.Drawable; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zag { public static class: java.lang.Class<com.google.android.gms.internal.base.zag>; public setAlpha(param0: number): void; public getConstantState(): globalAndroid.graphics.drawable.Drawable.ConstantState; public draw(param0: globalAndroid.graphics.Canvas): void; public getOpacity(): number; public setColorFilter(param0: globalAndroid.graphics.ColorFilter): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zah { public static class: java.lang.Class<com.google.android.gms.internal.base.zah>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zai { public static class: java.lang.Class<com.google.android.gms.internal.base.zai>; public newDrawable(): globalAndroid.graphics.drawable.Drawable; public getChangingConfigurations(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaj { public static class: java.lang.Class<com.google.android.gms.internal.base.zaj>; public newDrawable(): globalAndroid.graphics.drawable.Drawable; public getChangingConfigurations(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zak extends androidx.collection.LruCache<any,globalAndroid.graphics.drawable.Drawable> { public static class: java.lang.Class<com.google.android.gms.internal.base.zak>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zal { public static class: java.lang.Class<com.google.android.gms.internal.base.zal>; public static zaa(param0: number): void; public static zaa(): number; public onMeasure(param0: number, param1: number): void; public onDraw(param0: globalAndroid.graphics.Canvas): void; public static zaa(param0: globalAndroid.net.Uri): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zam { public static class: java.lang.Class<com.google.android.gms.internal.base.zam>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zam interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: number, param1: number): java.util.concurrent.ExecutorService; zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; zaa(param0: java.util.concurrent.ThreadFactory, param1: number): java.util.concurrent.ExecutorService; }); public constructor(); public zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; public zaa(param0: java.util.concurrent.ThreadFactory, param1: number): java.util.concurrent.ExecutorService; public zaa(param0: number, param1: number): java.util.concurrent.ExecutorService; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zan { public static class: java.lang.Class<com.google.android.gms.internal.base.zan>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zao { public static class: java.lang.Class<com.google.android.gms.internal.base.zao>; public static zaa(): com.google.android.gms.internal.base.zam; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zap extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.base.zap>; public static zaa: number; public static zab: number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaq extends com.google.android.gms.internal.base.zam { public static class: java.lang.Class<com.google.android.gms.internal.base.zaq>; public zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; public zaa(param0: java.util.concurrent.ThreadFactory, param1: number): java.util.concurrent.ExecutorService; public zaa(param0: number, param1: number): java.util.concurrent.ExecutorService; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zar { public static class: java.lang.Class<com.google.android.gms.internal.base.zar>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zar 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 android { export module gms { export module internal { export module base { export class zas { public static class: java.lang.Class<com.google.android.gms.internal.base.zas>; public constructor(); public constructor(param0: globalAndroid.os.Looper); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class SignInOptions extends com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.signin.SignInOptions>; public static zaa: com.google.android.gms.signin.SignInOptions; public equals(param0: any): boolean; public hashCode(): number; } export module SignInOptions { export class zaa { public static class: java.lang.Class<com.google.android.gms.signin.SignInOptions.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class SignInClientImpl extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.signin.internal.zag> implements com.google.android.gms.signin.zae { public static class: java.lang.Class<com.google.android.gms.signin.internal.SignInClientImpl>; public getStartServiceAction(): string; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public zab(): void; public getServiceDescriptor(): string; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getEndpointPackageName(): string; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getSignInIntent(): globalAndroid.content.Intent; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public static createBundleFromClientSettings(param0: com.google.android.gms.common.internal.ClientSettings): globalAndroid.os.Bundle; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: boolean, param3: com.google.android.gms.common.internal.ClientSettings, param4: globalAndroid.os.Bundle, param5: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param6: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getConnectionHint(): globalAndroid.os.Bundle; public getGetServiceRequestExtraArgs(): globalAndroid.os.Bundle; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public requiresAccount(): boolean; public disconnect(): void; public zaa(): void; public isConnected(): boolean; public providesSignIn(): boolean; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public zaa(param0: com.google.android.gms.signin.internal.zae): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: boolean, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.signin.SignInOptions, param5: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param6: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public isConnecting(): boolean; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; public getLastDisconnectMessage(): string; public disconnect(param0: string): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.internal.ConnectionCallbacks, param5: com.google.android.gms.common.api.internal.OnConnectionFailedListener); public getMinApkVersion(): number; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaa { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaa>; public constructor(); public getStatus(): com.google.android.gms.common.api.Status; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zab extends com.google.android.gms.signin.internal.zad { public static class: java.lang.Class<com.google.android.gms.signin.internal.zab>; public constructor(); public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public zaa(param0: com.google.android.gms.signin.internal.zak): void; public constructor(param0: string); public zaa(param0: com.google.android.gms.signin.internal.zai): void; public zaa(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zac extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaa> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zac>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export abstract class zad extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.signin.internal.zae { public static class: java.lang.Class<com.google.android.gms.signin.internal.zad>; public constructor(); public zaa(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public zaa(param0: com.google.android.gms.signin.internal.zak): void; public constructor(param0: string); public zaa(param0: com.google.android.gms.signin.internal.zai): void; public zaa(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zae { public static class: java.lang.Class<com.google.android.gms.signin.internal.zae>; /** * Constructs a new instance of the com.google.android.gms.signin.internal.zae interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; zaa(param0: com.google.android.gms.common.api.Status): void; zab(param0: com.google.android.gms.common.api.Status): void; zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; zaa(param0: com.google.android.gms.signin.internal.zak): void; zaa(param0: com.google.android.gms.signin.internal.zai): void; }); public constructor(); public zaa(param0: com.google.android.gms.signin.internal.zak): void; public zaa(param0: com.google.android.gms.signin.internal.zai): void; public zaa(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaf extends com.google.android.gms.internal.base.zab implements com.google.android.gms.signin.internal.zag { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaf>; public zaa(param0: com.google.android.gms.signin.internal.zaj, param1: com.google.android.gms.signin.internal.zae): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; public zaa(): globalAndroid.os.Parcel; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zag { public static class: java.lang.Class<com.google.android.gms.signin.internal.zag>; /** * Constructs a new instance of the com.google.android.gms.signin.internal.zag interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: number): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; zaa(param0: com.google.android.gms.signin.internal.zaj, param1: com.google.android.gms.signin.internal.zae): void; }); public constructor(); public zaa(param0: com.google.android.gms.signin.internal.zaj, param1: com.google.android.gms.signin.internal.zae): void; public zaa(param0: number): void; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zah extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zai> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zah>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zai { public static class: java.lang.Class<com.google.android.gms.signin.internal.zai>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zai>; public getStatus(): com.google.android.gms.common.api.Status; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: java.util.List<string>, param1: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaj { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaj>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaj>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: com.google.android.gms.common.internal.zat); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zak { public static class: java.lang.Class<com.google.android.gms.signin.internal.zak>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zak>; public zaa(): com.google.android.gms.common.ConnectionResult; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zab(): com.google.android.gms.common.internal.zau; public constructor(param0: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zal extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaj> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zal>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zam extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zak> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zam>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zaa extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,com.google.android.gms.signin.SignInOptions> { public static class: java.lang.Class<com.google.android.gms.signin.zaa>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zab { public static class: java.lang.Class<com.google.android.gms.signin.zab>; public static zaa: com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,com.google.android.gms.signin.SignInOptions>; public static zab: com.google.android.gms.common.api.Api<com.google.android.gms.signin.SignInOptions>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zac extends com.google.android.gms.common.api.Api.ApiOptions.HasOptions { public static class: java.lang.Class<com.google.android.gms.signin.zac>; public static zaa(): globalAndroid.os.Bundle; public equals(param0: any): boolean; public hashCode(): number; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zad extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,com.google.android.gms.signin.zac> { public static class: java.lang.Class<com.google.android.gms.signin.zad>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zae extends com.google.android.gms.common.api.Api.Client { public static class: java.lang.Class<com.google.android.gms.signin.zae>; /** * Constructs a new instance of the com.google.android.gms.signin.zae interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.signin.internal.zae): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; zaa(): void; zab(): void; connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; disconnect(param0: string): void; disconnect(): void; isConnected(): boolean; isConnecting(): boolean; getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; requiresSignIn(): boolean; onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; requiresAccount(): boolean; requiresGooglePlayServices(): boolean; providesSignIn(): boolean; getSignInIntent(): globalAndroid.content.Intent; dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; getServiceBrokerBinder(): globalAndroid.os.IBinder; getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; getEndpointPackageName(): string; getMinApkVersion(): number; getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; getLastDisconnectMessage(): string; }); public constructor(); public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public requiresGooglePlayServices(): boolean; public zaa(param0: com.google.android.gms.signin.internal.zae): void; public requiresAccount(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public providesSignIn(): boolean; public zab(): void; public isConnected(): boolean; public getEndpointPackageName(): string; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public getRequiredFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public getMinApkVersion(): number; public isConnecting(): boolean; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public zaa(): void; public disconnect(): void; public getAvailableFeatures(): androidNative.Array<com.google.android.gms.common.Feature>; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public requiresSignIn(): boolean; public disconnect(param0: string): void; public getScopesForConnectionlessNonSignIn(): java.util.Set<com.google.android.gms.common.api.Scope>; public getLastDisconnectMessage(): string; } } } } } } //Generics information: //com.google.android.gms.auth.api.signin.internal.zbl:1 //com.google.android.gms.common.api.Api:1 //com.google.android.gms.common.api.Api.AbstractClientBuilder:2 //com.google.android.gms.common.api.Api.AnyClientKey:1 //com.google.android.gms.common.api.Api.BaseClientBuilder:2 //com.google.android.gms.common.api.Api.ClientKey:1 //com.google.android.gms.common.api.BatchResultToken:1 //com.google.android.gms.common.api.DataBufferResponse:2 //com.google.android.gms.common.api.GoogleApi:1 //com.google.android.gms.common.api.HasApiKey:1 //com.google.android.gms.common.api.OptionalPendingResult:1 //com.google.android.gms.common.api.PendingResult:1 //com.google.android.gms.common.api.PendingResults.zaa:1 //com.google.android.gms.common.api.PendingResults.zab:1 //com.google.android.gms.common.api.PendingResults.zac:1 //com.google.android.gms.common.api.ResultTransform:2 //com.google.android.gms.common.api.TransformedResult:1 //com.google.android.gms.common.api.internal.ApiKey:1 //com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl:2 //com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder:1 //com.google.android.gms.common.api.internal.BasePendingResult:1 //com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler:1 //com.google.android.gms.common.api.internal.DataHolderNotifier:1 //com.google.android.gms.common.api.internal.GoogleApiManager.zaa:1 //com.google.android.gms.common.api.internal.ListenerHolder:1 //com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey:1 //com.google.android.gms.common.api.internal.ListenerHolder.Notifier:1 //com.google.android.gms.common.api.internal.OptionalPendingResultImpl:1 //com.google.android.gms.common.api.internal.PendingResultFacade:2 //com.google.android.gms.common.api.internal.RegisterListenerMethod:2 //com.google.android.gms.common.api.internal.RegistrationMethods:2 //com.google.android.gms.common.api.internal.RegistrationMethods.Builder:2 //com.google.android.gms.common.api.internal.RemoteCall:2 //com.google.android.gms.common.api.internal.TaskApiCall:2 //com.google.android.gms.common.api.internal.TaskApiCall.Builder:2 //com.google.android.gms.common.api.internal.UnregisterListenerMethod:2 //com.google.android.gms.common.api.internal.zabl:1 //com.google.android.gms.common.api.internal.zabr:1 //com.google.android.gms.common.api.internal.zac:1 //com.google.android.gms.common.api.internal.zacc:1 //com.google.android.gms.common.api.internal.zacn:1 //com.google.android.gms.common.api.internal.zaf:1 //com.google.android.gms.common.api.internal.zah:1 //com.google.android.gms.common.data.AbstractDataBuffer:1 //com.google.android.gms.common.data.DataBuffer:1 //com.google.android.gms.common.data.DataBufferIterator:1 //com.google.android.gms.common.data.DataBufferSafeParcelable:1 //com.google.android.gms.common.data.EntityBuffer:1 //com.google.android.gms.common.data.Freezable:1 //com.google.android.gms.common.data.SingleRefDataBufferIterator:1 //com.google.android.gms.common.internal.GmsClient:1 //com.google.android.gms.common.internal.PendingResultUtil.ResultConverter:2 //com.google.android.gms.common.internal.service.zaf:1 //com.google.android.gms.common.server.response.FastJsonResponse.Field:2 //com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter:2 //com.google.android.gms.common.server.response.FastParser:1 //com.google.android.gms.common.server.response.FastParser.zaa:1 //com.google.android.gms.dynamic.DeferredLifecycleHelper:1 //com.google.android.gms.internal.auth-api.zbm:1
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormPublisher_Information { interface tab__70098AD5_4956_11DD_982E_00188B01DCE6_Sections { _70098AD6_4956_11DD_982E_00188B01DCE6: DevKit.Controls.Section; _EAF2EDB4_7C5E_DD11_940F_00155D8AC303: DevKit.Controls.Section; description: DevKit.Controls.Section; } interface tab__E1F7A9C9_A0E6_4C8B_ACBD_C6610FBD2343_Sections { _6FE75F79_0CA8_4DBE_8C7B_6E68C17DE013: DevKit.Controls.Section; _CBF04024_5749_444C_BC51_CFAF839688BF: DevKit.Controls.Section; } interface tab_solutions_marketplace_Sections { marketplacesection: DevKit.Controls.Section; } interface tab__70098AD5_4956_11DD_982E_00188B01DCE6 extends DevKit.Controls.ITab { Section: tab__70098AD5_4956_11DD_982E_00188B01DCE6_Sections; } interface tab__E1F7A9C9_A0E6_4C8B_ACBD_C6610FBD2343 extends DevKit.Controls.ITab { Section: tab__E1F7A9C9_A0E6_4C8B_ACBD_C6610FBD2343_Sections; } interface tab_solutions_marketplace extends DevKit.Controls.ITab { Section: tab_solutions_marketplace_Sections; } interface Tabs { _70098AD5_4956_11DD_982E_00188B01DCE6: tab__70098AD5_4956_11DD_982E_00188B01DCE6; _E1F7A9C9_A0E6_4C8B_ACBD_C6610FBD2343: tab__E1F7A9C9_A0E6_4C8B_ACBD_C6610FBD2343; solutions_marketplace: tab_solutions_marketplace; } interface Body { Tab: Tabs; /** City name for address 1. */ Address1_City: DevKit.Controls.String; /** Country/region name for address 1. */ Address1_Country: DevKit.Controls.String; /** First line for entering address 1 information. */ Address1_Line1: DevKit.Controls.String; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.Controls.String; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.Controls.String; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.Controls.String; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.Controls.String; /** Default option value prefix used for newly created options for solutions associated with this publisher. */ CustomizationOptionValuePrefix: DevKit.Controls.Integer; /** Prefix used for new entities, attributes, and entity relationships for solutions associated with this publisher. */ CustomizationPrefix: DevKit.Controls.String; /** Description of the solution. */ Description: DevKit.Controls.String; /** Email address for the publisher. */ EMailAddress: DevKit.Controls.String; /** User display name for this publisher. */ FriendlyName: DevKit.Controls.String; IFRAME_SolutionsMarketplace: DevKit.Controls.IFrame; /** URL for the supporting website of this publisher. */ SupportingWebsiteUrl: DevKit.Controls.String; /** The unique name of this publisher. */ UniqueName: DevKit.Controls.String; } } class FormPublisher_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Publisher_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 Publisher_Information */ Body: DevKit.FormPublisher_Information.Body; } class PublisherApi { /** * DynamicsCrm.DevKit PublisherApi * @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 for address 1. */ Address1_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 1, such as billing, shipping, or primary address. */ Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 1. */ Address1_City: DevKit.WebApi.StringValue; /** Country/region name for address 1. */ Address1_Country: DevKit.WebApi.StringValue; /** County name for address 1. */ Address1_County: DevKit.WebApi.StringValue; /** Fax number for address 1. */ Address1_Fax: DevKit.WebApi.StringValue; /** Latitude for address 1. */ Address1_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 1 information. */ Address1_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.WebApi.StringValue; /** Longitude for address 1. */ Address1_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 1. */ Address1_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 1. */ Address1_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 1. */ Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 1. */ Address1_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 1. This is the difference between local time and standard Coordinated Universal Time. */ Address1_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier for address 2. */ Address2_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 2. such as billing, shipping, or primary address. */ Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 2. */ Address2_City: DevKit.WebApi.StringValue; /** Country/region name for address 2. */ Address2_Country: DevKit.WebApi.StringValue; /** County name for address 2. */ Address2_County: DevKit.WebApi.StringValue; /** Fax number for address 2. */ Address2_Fax: DevKit.WebApi.StringValue; /** Latitude for address 2. */ Address2_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 2 information. */ Address2_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 2 information. */ Address2_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 2 information. */ Address2_Line3: DevKit.WebApi.StringValue; /** Longitude for address 2. */ Address2_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 2. */ Address2_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 2. */ Address2_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 2. */ Address2_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 2. */ Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 2. */ Address2_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 2. */ Address2_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 2. */ Address2_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 2. */ Address2_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 2. */ Address2_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 2. This is the difference between local time and standard Coordinated Universal Time. */ Address2_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who created the publisher. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the publisher was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the publisher. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Default option value prefix used for newly created options for solutions associated with this publisher. */ CustomizationOptionValuePrefix: DevKit.WebApi.IntegerValue; /** Prefix used for new entities, attributes, and entity relationships for solutions associated with this publisher. */ CustomizationPrefix: DevKit.WebApi.StringValue; /** Description of the solution. */ Description: DevKit.WebApi.StringValue; /** Email address for the publisher. */ EMailAddress: DevKit.WebApi.StringValue; /** Shows the default image for the record. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** User display name for this publisher. */ FriendlyName: DevKit.WebApi.StringValue; /** Indicates whether the publisher was created as part of a managed solution installation. */ IsReadonly: DevKit.WebApi.BooleanValueReadonly; /** Unique identifier of the user who last modified the publisher. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the publisher was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the publisher. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the organization associated with the publisher. */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Default locale of the publisher in Microsoft Pinpoint. */ PinpointPublisherDefaultLocale: DevKit.WebApi.StringValueReadonly; /** Identifier of the publisher in Microsoft Pinpoint. */ PinpointPublisherId: DevKit.WebApi.BigIntValueReadonly; /** Unique identifier of the publisher. */ PublisherId: DevKit.WebApi.GuidValue; /** URL for the supporting website of this publisher. */ SupportingWebsiteUrl: DevKit.WebApi.StringValue; /** The unique name of this publisher. */ UniqueName: DevKit.WebApi.StringValue; VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Publisher { enum Address1_AddressTypeCode { /** 1 */ Default_Value } enum Address1_ShippingMethodCode { /** 1 */ Default_Value } enum Address2_AddressTypeCode { /** 1 */ Default_Value } enum Address2_ShippingMethodCode { /** 1 */ Default_Value } 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':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack