text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { EventEmitter } from "events"; import _ from "lodash"; import { SCLangError } from "../Errors"; type JSONObjectType = object; export enum State { NULL = "null", BOOTING = "booting", COMPILED = "compiled", COMPILING = "compiling", COMPILE_ERROR = "compileError", READY = "ready", } export class SclangCompileResult { version = ""; stdout = ""; errors: CompileError[] = []; extensionErrors: ExtensionError[] = []; duplicateClasses: DuplicateClass[] = []; dirs: string[] = []; } interface CompileError { msg: string; file: string; line: number; char: number; } interface ExtensionError { forClass: string; file: string; } interface DuplicateClass { forClass: string; files: string[]; } interface SCSyntaxError { msg: string | null; file: string | null; line: number | null; charPos: number | null; code: string; } interface StateChangeHandlers { [name: string]: StateChangeHandler[]; } interface StateChangeHandler { re: RegExp; // A handler can return true to stop further processing fn: (match: RegExpExecArray, text: string) => void | true; } interface Response { type: string; chunks: string[]; } interface ResponseCollectors { [guid: string]: Response; } /** * Captures STDOUT */ interface Capturing { [guid: string]: string[]; } /** * Stores calls */ interface Calls { [guid: string]: ResolveReject; } interface ResolveReject<R = any> { resolve: (result: R) => void; reject: (error: Error | SCLangError) => void; } /** * This parses the stdout of sclang and detects changes of the * interpreter state and converts compilation errors into js objects. * * Also detects runtime errors and results posted when sc code * is evaluated from supercollider.js * * Convert errors and responses into JavaScript objects * * Emit events when state changes * * @private */ export class SclangIO extends EventEmitter { states: StateChangeHandlers; responseCollectors: ResponseCollectors = {}; capturing: Capturing = {}; calls: Calls = {}; state: State = State.NULL; output: string[] = []; result: SclangCompileResult; constructor() { super(); this.result = new SclangCompileResult(); this.states = this.makeStates(); this.reset(); } reset(): void { this.responseCollectors = {}; this.capturing = {}; this.calls = {}; this.state = State.NULL; // these are stored on the object // and are sent with compile error/success event this.output = []; this.result = new SclangCompileResult(); } /** * @param {string} input - parse the stdout of supercollider */ parse(input: string): void { let echo = true, last = 0; const startState = this.state; this.states[this.state].forEach((stf: StateChangeHandler): void => { let match: RegExpExecArray | null = null; if (this.state === startState) { while ((match = stf.re.exec(input)) !== null) { last = match.index + match[0].length; // do not post if any handler returns true if (stf.fn(match, input) === true) { echo = false; } // break if its not a /g regex with multiple results if (!stf.re.global) { break; } } } }); if (echo) { this.emit("stdout", input); } // anything left over should be emitted to stdout ? // This might result in some content being emitted twice. // Currently if there is anything after SUPERCOLLIDERJS.interpret // it is emitted. // if (last < input.length && (startState === this.state)) { // console.log('leftovers:', input.substr(last)); // // this.parse(input.substr(last)); // } // state has changed and there is still text to parse if (last < input.length && startState !== this.state) { // parse remainder with new state this.parse(input.substr(last)); } } setState(newState: State): void { if (newState !== this.state) { this.state = newState; this.emit("state", this.state); } } makeStates(): StateChangeHandlers { return { booting: [ { re: /^compiling class library/m, fn: (match, text: string): void => { this.reset(); this.setState(State.COMPILING); this.pushOutputText(text); }, }, ], compiling: [ { re: /^compile done/m, fn: (): void => { this.processOutput(); this.setState(State.COMPILED); }, }, { re: /^Library has not been compiled successfully/m, fn: (match, text: string): void => { this.pushOutputText(text); this.processOutput(); this.setState(State.COMPILE_ERROR); }, }, { re: /^ERROR: There is a discrepancy\./m, fn: (/*match*/): void => { this.processOutput(); this.setState(State.COMPILE_ERROR); }, }, { // it may go directly into initClasses without posting compile done re: /Welcome to SuperCollider ([0-9A-Za-z\-.]+)\. /m, fn: (match): void => { this.result.version = match[1]; this.processOutput(); this.setState(State.READY); }, }, { // it sometimes posts this sc3> even when compile failed re: /^[\s]*sc3>[\s]*$/m, fn: (match, text: string): void => { this.pushOutputText(text); this.processOutput(); this.setState(State.COMPILE_ERROR); }, }, { // another case of just trailing off re: /^error parsing/m, fn: (match, text: string): void => { this.pushOutputText(text); this.processOutput(); this.setState(State.COMPILE_ERROR); }, }, { // collect all output re: /(.+)/m, fn: (match, text: string): void => { this.pushOutputText(text); }, }, ], compileError: [], compiled: [ { re: /Welcome to SuperCollider ([0-9A-Za-z\-.]+)\. /m, fn: (match): void => { this.result.version = match[1]; this.setState(State.READY); }, }, { re: /^[\s]*sc3>[\s]*$/m, fn: (/*match:RegExMatchType, text*/): void => { this.setState(State.READY); }, }, ], // REPL is now active ready: [ { // There may be multiple SUPERCOLLIDERJS matches in a block of text. // ie. this is a multi-line global regex // This fn is called for each of them with a different match each time // but the same text body. re: /^SUPERCOLLIDERJS:([0-9A-Za-z-]+):([A-Za-z]+):(.*)$/gm, fn: (match, text: string): void | true => { const guid = match[1], type = match[2], body = match[3]; let response: Response, stdout: string, obj: JSONObjectType, lines: string[], started = false, stopped = false; switch (type) { case "CAPTURE": if (body === "START") { this.capturing[guid] = []; lines = []; // yuck _.each(text.split("\n"), (l: string): void => { if (l.match(/SUPERCOLLIDERJS:([0-9A-Za-z-]+):CAPTURE:START/)) { started = true; } else if (l.match(/SUPERCOLLIDERJS:([0-9A-Za-z-]+):CAPTURE:END/)) { stopped = true; } else { if (started && !stopped) { lines.push(l); } } }); this.capturing[guid].push(lines.join("\n")); } return true; case "START": this.responseCollectors[guid] = { type: body, chunks: [], }; return true; case "CHUNK": this.responseCollectors[guid].chunks.push(body); return true; case "END": response = this.responseCollectors[guid]; stdout = response.chunks.join(""); obj = JSON.parse(stdout); if (guid in this.calls) { if (response.type === "Result") { // anything posted during CAPTURE should be forwarded // to stdout stdout = this.capturing[guid].join("\n"); delete this.capturing[guid]; if (stdout) { this.emit("stdout", stdout); } this.calls[guid].resolve(obj); } else { // response.type === "Error" let err: SCSyntaxError | undefined = undefined; if (response.type === "SyntaxError") { stdout = this.capturing[guid].join("\n"); err = this.parseSyntaxErrors(stdout); delete this.capturing[guid]; } this.calls[guid].reject( new SCLangError(`Interpret error: ${obj && obj["errorString"]}`, response.type, err || obj), ); } delete this.calls[guid]; } else { // I hope sc doesn't post multiple streams at the same time if (guid === "0") { // out of band error this.emit("error", { type: response.type, error: obj }); } } delete this.responseCollectors[guid]; return true; default: } }, }, { re: /^SUPERCOLLIDERJS.interpreted$/gm, fn: (match, text: string): true => { let rest = text.substr(match.index + 28); // remove the prompt -> rest = rest.replace(/-> \r?\n?/, ""); this.emit("stdout", rest); return true; }, }, { // user compiled programmatically eg. with Quarks.gui button re: /^compiling class library/m, fn: (match, text: string): void => { this.reset(); this.setState(State.COMPILING); this.pushOutputText(text); }, }, ], }; } /** * Register resolve and reject callbacks for a block of code that is being sent * to sclang to be interpreted. * * callbacks - an object with reject, resolve */ registerCall(guid: string, callbacks: ResolveReject): void { this.calls[guid] = callbacks; } /** * Parse syntax error from STDOUT runtime errors. */ parseSyntaxErrors(text: string): SCSyntaxError { const msgRe = /^ERROR: syntax error, (.+)$/m, msgRe2 = /^ERROR: (.+)$/m, fileRe = /in file '(.+)'/m, lineRe = /line ([0-9]+) char ([0-9]+):$/m; const msg = msgRe.exec(text) || msgRe2.exec(text), line = lineRe.exec(text), file = fileRe.exec(text), code = text .split("\n") .slice(4, -3) .join("\n") .trim(); return { msg: msg && msg[1], file: file && file[1], line: line && parseInt(line[1], 10), charPos: line && parseInt(line[2], 10), code: code, }; } /** * Push text posted by sclang during library compilation * to the .output stack for later procesing */ pushOutputText(text: string): void { this.output.push(text); } /** * Consume the compilation output stack, merging any results * into this.result and resetting the stack. */ processOutput(): void { const parsed = this.parseCompileOutput((this.output || []).join("\n")); // merge with any previously processed _.each(parsed, (value, key): void => { if (_.isArray(value)) { this.result[key] = (this.result[key] || []).concat(value); } if (_.isString(value)) { this.result[key] = (this.result[key] || "") + value; } }); this.output = []; } /** * Parse library compile errors and information * collected from sclang STDOUT. */ parseCompileOutput(text: string): SclangCompileResult { const errors = new SclangCompileResult(); // NumPrimitives = 688 // multiple: // compiling dir: '' const dirsRe = /^[\s]+compiling dir:[\s]+'(.+)'$/gm; let match: RegExpExecArray | null = null; let end = 0; while ((match = dirsRe.exec(text))) { errors.dirs.push(match[1]); end = match.index + match[0].length; } // the rest are the error blocks const rest = text.substr(end), // split on --------------------- // blocks = rest.split(/^\-+$/m), // message // in file 'path' line x char y: errRe = /([^\n]+)\n\s+in file '([^']+)'\n\s+line ([0-9]+) char ([0-9]+)/gm, nonExistentRe = /Class extension for nonexistent class '([A-Za-z0-9_]+)[\s\S]+In file:'(.+)'/gm, duplicateRe = /^ERROR: duplicate Class found: '([A-Za-z0-9_]+)'\n([^\n]+)\n([^\n]+)\n/gm, commonPath = /^\/Common/; while ((match = errRe.exec(rest))) { let file = match[2]; // errors in Common library are posted as '/Common/...' if (commonPath.exec(file)) { file = errors.dirs[0] + file; } errors.errors.push({ msg: match[1], file: file, line: parseInt(match[3], 10), char: parseInt(match[4], 10), }); } while ((match = nonExistentRe.exec(text))) { errors.extensionErrors.push({ forClass: match[1], file: match[2], }); } while ((match = duplicateRe.exec(text)) !== null) { errors.duplicateClasses.push({ forClass: match[1], files: [match[2], match[3]], }); } return errors; } }
the_stack
import * as types from './types'; import httpClient from 'adapters/http/httpClient'; const ENDPOINT = 'https://cloud.feedly.com'; // Authentication API: export function createAuthUrl(input: types.AuthenticateInput): string { return ENDPOINT + '/v3/auth/auth?' + new URLSearchParams({ client_id: input.client_id, redirect_uri: input.redirect_uri, response_type: input.response_type, scope: input.scope }).toString(); } export function authCallback(urlString: string): types.AuthenticateResponse { const paramsString = urlString.slice(urlString.indexOf('?') + 1); const params = new URLSearchParams(paramsString); return { code: params.get('code')!, state: params.get('state') ?? undefined, error: params.get('error') ?? undefined }; } export function exchangeToken(input: types.ExchangeTokenInput): Promise<types.ExchangeTokenResponse> { return httpClient.postJson(ENDPOINT, '/v3/auth/token', input) .then<types.ExchangeTokenResponse>(handleJsonResponse); } export function refreshToken(input: types.RefreshTokenInput): Promise<types.RefreshTokenResponse> { return httpClient.postJson(ENDPOINT, '/v3/auth/token', input) .then<types.RefreshTokenResponse>(handleJsonResponse); } export function logout(accessToken: string): Promise<Response> { return httpClient.post( ENDPOINT, '/v3/auth/logout', null, createAuthHeader(accessToken) ).then(handleResponse); } // Categories API: export function getCategories(accessToken: string): Promise<types.Category[]> { return httpClient.get(ENDPOINT, '/v3/categories', null, createAuthHeader(accessToken)) .then<types.Category[]>(handleJsonResponse); } export function changeCategoryLabel(accessToken: string, categoryId: string, label: string): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/categories/' + encodeURIComponent(categoryId), { label }, createAuthHeader(accessToken) ).then(handleResponse); } export function deleteCategory(accessToken: string, categoryId: string): Promise<Response> { return httpClient.deleteJson( ENDPOINT, '/v3/categories/' + encodeURIComponent(categoryId), null, createAuthHeader(accessToken) ).then(handleResponse); } // Feeds API: export function getFeed(accessToken: string, feedId: string): Promise<types.Feed> { return httpClient.get( ENDPOINT, '/v3/feeds/' + encodeURIComponent(feedId), null, createAuthHeader(accessToken) ).then<types.Feed>(handleJsonResponse); } // Markers API: export function getUnreadCounts(accessToken: string, input: types.GetUnreadCountsInput = {}): Promise<types.GetUnreadCountsResponce> { return httpClient.get( ENDPOINT, '/v3/markers/counts', input, createAuthHeader(accessToken) ).then<types.GetUnreadCountsResponce>(handleJsonResponse); } export function markAsReadForEntries(accessToken: string, entryIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'markAsRead', type: 'entries', entryIds: Array.isArray(entryIds) ? entryIds : [entryIds] }, createAuthHeader(accessToken) ).then(handleResponse); } export function markAsReadForFeeds(accessToken: string, feedIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'markAsRead', type: 'feeds', feedIds: Array.isArray(feedIds) ? feedIds : [feedIds] }, createAuthHeader(accessToken) ).then(handleResponse); } export function markAsReadForCategories(accessToken: string, categoryIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'markAsRead', type: 'categories', categoryIds: Array.isArray(categoryIds) ? categoryIds : [categoryIds] }, createAuthHeader(accessToken) ).then(handleResponse); } export function keepUnreadForEntries(accessToken: string, entryIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'keepUnread', type: 'entries', entryIds: Array.isArray(entryIds) ? entryIds : [entryIds] }, createAuthHeader(accessToken) ).then(handleResponse); } export function keepUnreadForFeeds(accessToken: string, feedIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'keepUnread', type: 'feeds', feedIds: Array.isArray(feedIds) ? feedIds : [feedIds] }, createAuthHeader(accessToken) ).then(handleResponse); } export function keepUnreadForCategories(accessToken: string, categoryIds: string | string[]): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/markers', { action: 'keepUnread', type: 'categories', categoryIds: Array.isArray(categoryIds) ? categoryIds : [categoryIds] }, createAuthHeader(accessToken) ).then(handleResponse); } // OPML API export function createExportOpmlUrl(accessToken: string): string { return ENDPOINT + 'v3/opml?' + new URLSearchParams({ feedlyToken: accessToken }).toString(); } export function importOpml(accessToken: string, xmlString: string): Promise<Response> { return httpClient.postXml( ENDPOINT, '/v3/opml', xmlString, createAuthHeader(accessToken) ).then(handleResponse); } // Profile API: export function getProfile(accessToken: string): Promise<types.Profile> { return httpClient.get( ENDPOINT, '/v3/profile', null, createAuthHeader(accessToken) ).then<types.Profile>(handleJsonResponse); } export function updateProfile(accessToken: string, input: types.UpdateProfileInput): Promise<Response> { return httpClient.putJson( ENDPOINT, '/v3/profile', null, createAuthHeader(accessToken) ).then(handleResponse); } // Search API: export function searchFeeds(accessToken: string, input: types.SearchInput): Promise<types.SearchResponse> { return httpClient.get( ENDPOINT, '/v3/search/feeds', input, createAuthHeader(accessToken) ).then<types.SearchResponse>(handleJsonResponse); } // Streams API: export function getStreamIds(accessToken: string, input: types.GetStreamInput): Promise<types.GetEntryIdsResponse> { return httpClient.get( ENDPOINT, '/v3/streams/ids', input, createAuthHeader(accessToken) ).then<types.GetEntryIdsResponse>(handleJsonResponse); } export function getStreamContents(accessToken: string, input: types.GetStreamInput): Promise<types.Contents> { return httpClient.get( ENDPOINT, '/v3/streams/contents', input, createAuthHeader(accessToken) ).then<types.Contents>(handleJsonResponse); } // Subscriptions API: export function getSubscriptions(accessToken: string): Promise<types.Subscription[]> { return httpClient.get( ENDPOINT, '/v3/subscriptions', null, createAuthHeader(accessToken) ).then<types.Subscription[]>(handleJsonResponse); } export function subscribeFeed(accessToken: string, input: types.SubscribeFeedInput): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/subscriptions', input, createAuthHeader(accessToken) ).then(handleResponse); } export function unsubscribeFeed(accessToken: string, feedId: string): Promise<Response> { return httpClient.deleteJson( ENDPOINT, '/v3/subscriptions/' + encodeURIComponent(feedId), null, createAuthHeader(accessToken) ).then(handleResponse); } // Tags API: export function getTags(accessToken: string): Promise<types.Tag[]> { return httpClient.get( ENDPOINT, '/v3/tags', null, createAuthHeader(accessToken) ).then<types.Tag[]>(handleJsonResponse); } export function changeTagLabel(accessToken: string, tagId: string, label: string): Promise<Response> { return httpClient.postJson( ENDPOINT, '/v3/tags/' + encodeURIComponent(tagId), { label }, createAuthHeader(accessToken) ).then(handleResponse); } export function setTag(accessToken: string, entryIds: string[], tagIds: string[]): Promise<Response> { return httpClient.putJson( ENDPOINT, '/v3/tags/' + encodeURIComponent(tagIds.join(',')), { entryIds }, createAuthHeader(accessToken) ).then(handleResponse); } export function unsetTag(accessToken: string, entryIds: string[], tagIds: string[]): Promise<Response> { return httpClient.deleteJson( ENDPOINT, '/v3/tags/' + encodeURIComponent(tagIds.join(',')) + '/' + encodeURIComponent(entryIds.join(',')), null, createAuthHeader(accessToken) ).then(handleResponse); } export function deleteTag(accessToken: string, tagIds: string[]): Promise<Response> { return httpClient.deleteJson( ENDPOINT, '/v3/tags/' + encodeURIComponent(tagIds.join(',')), null, createAuthHeader(accessToken) ).then(handleResponse); } // Utils: function createAuthHeader(accessToken: string): { [key: string]: string } { return { 'Authorization': 'OAuth ' + accessToken }; } function handleResponse(response: Response): Promise<Response> { if (response.ok) { return Promise.resolve(response); } else { return handleError(response); } } function handleJsonResponse<T>(response: Response): Promise<T> { if (response.ok) { return response.json(); } else { return handleError(response); } } function handleError<T>(response: Response): Promise<T> { return response.json() .then( (error) => Promise.reject(new Error(`${error.errorMessage} (errorCode: ${error.errorCode}) (errorId: ${error.errorId})`)), () => Promise.reject(new Error(`(status: ${response.status}) (statusText: ${response.statusText}) (url: ${response.url})`)) ); }
the_stack
import {SapDriver} from "../../../../src/driver/sap/SapDriver.ts"; import {closeTestingConnections, createTestingConnections, reloadTestingDatabases, allSettled} from "../../../utils/test-utils.ts"; import {Connection} from "../../../../src/connection/Connection.ts"; import {PostWithVersion} from "./entity/PostWithVersion.ts"; import {runIfMain} from "../../../deps/mocha.ts"; import {expect} from "../../../deps/chai.ts"; import {PostWithoutVersionAndUpdateDate} from "./entity/PostWithoutVersionAndUpdateDate.ts"; import {PostWithUpdateDate} from "./entity/PostWithUpdateDate.ts"; import {PostWithVersionAndUpdatedDate} from "./entity/PostWithVersionAndUpdatedDate.ts"; import {OptimisticLockVersionMismatchError} from "../../../../src/error/OptimisticLockVersionMismatchError.ts"; import {OptimisticLockCanNotBeUsedError} from "../../../../src/error/OptimisticLockCanNotBeUsedError.ts"; import {NoVersionOrUpdateDateColumnError} from "../../../../src/error/NoVersionOrUpdateDateColumnError.ts"; import {PessimisticLockTransactionRequiredError} from "../../../../src/error/PessimisticLockTransactionRequiredError.ts"; import {MysqlDriver} from "../../../../src/driver/mysql/MysqlDriver.ts"; import {PostgresDriver} from "../../../../src/driver/postgres/PostgresDriver.ts"; import {SqlServerDriver} from "../../../../src/driver/sqlserver/SqlServerDriver.ts"; import {AbstractSqliteDriver} from "../../../../src/driver/sqlite-abstract/AbstractSqliteDriver.ts"; import {OracleDriver} from "../../../../src/driver/oracle/OracleDriver.ts"; import {LockNotSupportedOnGivenDriverError} from "../../../../src/error/LockNotSupportedOnGivenDriverError.ts"; describe("query builder > locking", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ entities: [PostWithoutVersionAndUpdateDate, PostWithUpdateDate, PostWithVersion, PostWithVersionAndUpdatedDate], enabledDrivers: ["postgres", "mysql", "mariadb", "cockroachdb", "mssql", "oracle", "sap"] // TODO(uki00a) Remove `enabledDrivers when deno-sqlite supports `datetime('now')`. })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("should not attach pessimistic read lock statement on query if locking is not used", () => Promise.all(connections.map(async connection => { if (connection.driver instanceof AbstractSqliteDriver || connection.driver instanceof SapDriver) return; const sql = connection.createQueryBuilder(PostWithVersion, "post") .where("post.id = :id", { id: 1 }) .getSql(); expect(sql.indexOf("LOCK IN SHARE MODE") === -1).to.be.true; expect(sql.indexOf("FOR SHARE") === -1).to.be.true; expect(sql.indexOf("WITH (HOLDLOCK, ROWLOCK)") === -1).to.be.true; }))); it("should throw error if pessimistic lock used without transaction", () => Promise.all(connections.map(async connection => { if (connection.driver instanceof AbstractSqliteDriver || connection.driver instanceof SapDriver) return; const results = await allSettled([ connection.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_read") .where("post.id = :id", { id: 1 }) .getOne(), connection.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_write") .where("post.id = :id", { id: 1 }) .getOne() ]); expect(results[0].status).to.equal('rejected'); expect(results[0].reason).to.be.instanceOf(PessimisticLockTransactionRequiredError); expect(results[1].status).to.equal('rejected'); expect(results[1].reason).to.be.instanceOf(PessimisticLockTransactionRequiredError); }))); it("should not throw error if pessimistic lock used with transaction", () => Promise.all(connections.map(async connection => { // TODO(uki00a) uncomment this when CockroachDriver is implemented. if (connection.driver instanceof AbstractSqliteDriver/* || connection.driver instanceof CockroachDriver*/ || connection.driver instanceof SapDriver) return; return connection.manager.transaction(entityManager => { return Promise.all([ entityManager.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_read") .where("post.id = :id", { id: 1 }) .getOne(), entityManager.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_write") .where("post.id = :id", { id: 1 }) .getOne() ]); }); }))); it("should attach pessimistic read lock statement on query if locking enabled", () => Promise.all(connections.map(async connection => { // TODO(uki00a) uncomment this when CockroachDriver is implemented. if (connection.driver instanceof AbstractSqliteDriver /*|| connection.driver instanceof CockroachDriver*/ || connection.driver instanceof SapDriver) return; const sql = connection.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_read") .where("post.id = :id", { id: 1 }) .getSql(); if (connection.driver instanceof MysqlDriver) { expect(sql.indexOf("LOCK IN SHARE MODE") !== -1).to.be.true; } else if (connection.driver instanceof PostgresDriver) { expect(sql.indexOf("FOR SHARE") !== -1).to.be.true; } else if (connection.driver instanceof OracleDriver) { expect(sql.indexOf("FOR UPDATE") !== -1).to.be.true; } else if (connection.driver instanceof SqlServerDriver) { expect(sql.indexOf("WITH (HOLDLOCK, ROWLOCK)") !== -1).to.be.true; } }))); it("should attach dirty read lock statement on query if locking enabled", () => Promise.all(connections.map(async connection => { if (!(connection.driver instanceof SqlServerDriver)) return; const sql = connection.createQueryBuilder(PostWithVersion, "post") .setLock("dirty_read") .where("post.id = :id", { id: 1 }) .getSql(); expect(sql.indexOf("WITH (NOLOCK)") !== -1).to.be.true; }))); it("should not attach pessimistic write lock statement on query if locking is not used", () => Promise.all(connections.map(async connection => { if (connection.driver instanceof AbstractSqliteDriver || connection.driver instanceof SapDriver) return; const sql = connection.createQueryBuilder(PostWithVersion, "post") .where("post.id = :id", { id: 1 }) .getSql(); expect(sql.indexOf("FOR UPDATE") === -1).to.be.true; expect(sql.indexOf("WITH (UPDLOCK, ROWLOCK)") === -1).to.be.true; }))); it("should attach pessimistic write lock statement on query if locking enabled", () => Promise.all(connections.map(async connection => { // TODO(uki00a) uncomment this when CockroachDriver is implemented. if (connection.driver instanceof AbstractSqliteDriver /*|| connection.driver instanceof CockroachDriver*/ || connection.driver instanceof SapDriver) return; const sql = connection.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_write") .where("post.id = :id", { id: 1 }) .getSql(); if (connection.driver instanceof MysqlDriver || connection.driver instanceof PostgresDriver || connection.driver instanceof OracleDriver) { expect(sql.indexOf("FOR UPDATE") !== -1).to.be.true; } else if (connection.driver instanceof SqlServerDriver) { expect(sql.indexOf("WITH (UPDLOCK, ROWLOCK)") !== -1).to.be.true; } }))); it("should throw error if optimistic lock used with getMany method", () => Promise.all(connections.map(async connection => { try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .getMany(); expect.fail('an error not to be thrown'); } catch (err) {{ expect(err).to.be.instanceOf(OptimisticLockCanNotBeUsedError); }} }))); it("should throw error if optimistic lock used with getCount method", () => Promise.all(connections.map(async connection => { try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .getCount(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockCanNotBeUsedError); } }))); it("should throw error if optimistic lock used with getManyAndCount method", () => Promise.all(connections.map(async connection => { try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .getManyAndCount(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockCanNotBeUsedError); } }))); it("should throw error if optimistic lock used with getRawMany method", () => Promise.all(connections.map(async connection => { try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .getRawMany(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockCanNotBeUsedError); } }))); it("should throw error if optimistic lock used with getRawOne method", () => Promise.all(connections.map(async connection => { try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .where("post.id = :id", { id: 1 }) .getRawOne(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockCanNotBeUsedError); } }))); it("should not throw error if optimistic lock used with getOne method", () => Promise.all(connections.map(async connection => { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .where("post.id = :id", { id: 1 }) .getOne(); }))); it.skip("should throw error if entity does not have version and update date columns", () => Promise.all(connections.map(async connection => { const post = new PostWithoutVersionAndUpdateDate(); post.title = "New post"; await connection.manager.save(post); try { await connection.createQueryBuilder(PostWithoutVersionAndUpdateDate, "post") .setLock("optimistic", 1) .where("post.id = :id", { id: 1 }) .getOne(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(NoVersionOrUpdateDateColumnError); } }))); // skipped because inserted milliseconds are not always equal to what we say it to insert, unskip when needed it.skip("should throw error if actual version does not equal expected version", () => Promise.all(connections.map(async connection => { const post = new PostWithVersion(); post.title = "New post"; await connection.manager.save(post); try { await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 2) .where("post.id = :id", { id: 1 }) .getOne(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockVersionMismatchError); } }))); // skipped because inserted milliseconds are not always equal to what we say it to insert, unskip when needed it.skip("should not throw error if actual version and expected versions are equal", () => Promise.all(connections.map(async connection => { const post = new PostWithVersion(); post.title = "New post"; await connection.manager.save(post); await connection.createQueryBuilder(PostWithVersion, "post") .setLock("optimistic", 1) .where("post.id = :id", { id: 1 }) .getOne(); }))); // skipped because inserted milliseconds are not always equal to what we say it to insert, unskip when needed it.skip("should throw error if actual updated date does not equal expected updated date", () => Promise.all(connections.map(async connection => { const post = new PostWithUpdateDate(); post.title = "New post"; await connection.manager.save(post); try { await connection.createQueryBuilder(PostWithUpdateDate, "post") .setLock("optimistic", new Date(2017, 1, 1)) .where("post.id = :id", { id: 1 }) .getOne(); expect.fail("an error not to be thrown"); } catch (err) { expect(err).to.be.instanceOf(OptimisticLockVersionMismatchError); } }))); // skipped because inserted milliseconds are not always equal to what we say it to insert, unskip when needed it.skip("should not throw error if actual updated date and expected updated date are equal", () => Promise.all(connections.map(async connection => { if (connection.driver instanceof SqlServerDriver) return; const post = new PostWithUpdateDate(); post.title = "New post"; await connection.manager.save(post); return connection.createQueryBuilder(PostWithUpdateDate, "post") .setLock("optimistic", post.updateDate) .where("post.id = :id", {id: 1}) .getOne(); }))); // skipped because inserted milliseconds are not always equal to what we say it to insert, unskip when needed it.skip("should work if both version and update date columns applied", () => Promise.all(connections.map(async connection => { const post = new PostWithVersionAndUpdatedDate(); post.title = "New post"; await connection.manager.save(post); return Promise.all([ connection.createQueryBuilder(PostWithVersionAndUpdatedDate, "post") .setLock("optimistic", post.updateDate) .where("post.id = :id", { id: 1 }) .getOne(), connection.createQueryBuilder(PostWithVersionAndUpdatedDate, "post") .setLock("optimistic", 1) .where("post.id = :id", { id: 1 }) .getOne() ]); }))); it("should throw error if pessimistic locking not supported by given driver", () => Promise.all(connections.map(async connection => { // TODO(uki00a) uncomment if CockroachDriver is implemented. if (connection.driver instanceof AbstractSqliteDriver /*|| connection.driver instanceof CockroachDriver*/ || connection.driver instanceof SapDriver) return connection.manager.transaction(async entityManager => { const results = await allSettled([ entityManager.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_read") .where("post.id = :id", { id: 1 }) .getOne(), entityManager.createQueryBuilder(PostWithVersion, "post") .setLock("pessimistic_write") .where("post.id = :id", { id: 1 }) .getOne() ]); expect(results[0].status).to.equal('rejected'); expect(results[1].reason).to.be.instanceOf(LockNotSupportedOnGivenDriverError); expect(results[1].status).to.equal('rejected'); expect(results[1].reason).to.be.instanceOf(LockNotSupportedOnGivenDriverError); }); return; }))); }); runIfMain(import.meta);
the_stack
import React, { FunctionComponent, useEffect, useMemo, useState } from 'react'; import ReactDOM from 'react-dom'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import QRCode from 'qrcode.react'; import { isAndroid as checkIsAndroid, isMobile as checkIsMobile, saveMobileLinkInfo, } from '@walletconnect/browser-utils'; import { observer } from 'mobx-react-lite'; import { action, makeObservable, observable } from 'mobx'; import { Keplr } from '@keplr-wallet/types'; import { KeplrWalletConnectV1 } from '@keplr-wallet/wc-client'; import WalletConnect from '@walletconnect/client'; import { BroadcastMode, StdTx } from '@cosmjs/launchpad'; import { EmbedChainInfos } from 'src/config'; import Axios from 'axios'; import { Buffer } from 'buffer/'; import { wrapBaseDialog } from './base'; import { AccountStore, getKeplrFromWindow, WalletStatus } from '@keplr-wallet/stores'; import { ChainStore } from 'src/stores/chain'; import { AccountWithCosmosAndOsmosis } from 'src/stores/osmosis/account'; import { useStore } from 'src/stores'; import { IJsonRpcRequest, IRequestOptions } from '@walletconnect/types'; // Make sure that this asset is depolyed. require('../../public/assets/osmosis-wallet-connect.png'); const walletList = [ { name: 'Keplr Wallet', description: 'Keplr Browser Extension', logoUrl: '/public/assets/other-logos/keplr.png', type: 'extension', }, { name: 'WalletConnect', description: 'Keplr Mobile', logoUrl: '/public/assets/other-logos/wallet-connect.png', type: 'wallet-connect', }, ]; async function sendTx(chainId: string, tx: StdTx | Uint8Array, mode: BroadcastMode): Promise<Uint8Array> { const restInstance = Axios.create({ baseURL: EmbedChainInfos.find(chainInfo => chainInfo.chainId === chainId)!.rest, }); const isProtoTx = Buffer.isBuffer(tx) || tx instanceof Uint8Array; const params = isProtoTx ? { tx_bytes: Buffer.from(tx as any).toString('base64'), mode: (() => { switch (mode) { case 'async': return 'BROADCAST_MODE_ASYNC'; case 'block': return 'BROADCAST_MODE_BLOCK'; case 'sync': return 'BROADCAST_MODE_SYNC'; default: return 'BROADCAST_MODE_UNSPECIFIED'; } })(), } : { tx, mode: mode, }; const result = await restInstance.post(isProtoTx ? '/cosmos/tx/v1beta1/txs' : '/txs', params); const txResponse = isProtoTx ? result.data['tx_response'] : result.data; if (txResponse.code != null && txResponse.code !== 0) { throw new Error(txResponse['raw_log']); } return Buffer.from(txResponse.txhash, 'hex'); } class WalletConnectQRCodeModalV1Renderer { constructor() {} open(uri: string, cb: any) { const wrapper = document.createElement('div'); wrapper.setAttribute('id', 'wallet-connect-qrcode-modal-v1'); document.body.appendChild(wrapper); ReactDOM.render( <WalletConnectQRCodeModal uri={uri} close={() => { this.close(); cb(); }} />, wrapper ); } close() { const wrapper = document.getElementById('wallet-connect-qrcode-modal-v1'); if (wrapper) { document.body.removeChild(wrapper); } } } export type WalletType = 'true' | 'extension' | 'wallet-connect' | null; export const KeyConnectingWalletType = 'connecting_wallet_type'; export const KeyAutoConnectingWalletType = 'account_auto_connect'; export class ConnectWalletManager { // We should set the wallet connector when the `getKeplr()` method should return the `Keplr` for wallet connect. // But, account store request the `getKeplr()` method whenever that needs the `Keplr` api. // Thus, we should return the `Keplr` api persistently if the wallet connect is connected. // And, when the wallet is disconnected, we should clear this field. // In fact, `WalletConnect` itself is persistent. // But, in some cases, it acts inproperly. // So, handle that in the store logic too. protected walletConnector: WalletConnect | undefined; @observable autoConnectingWalletType: WalletType; constructor( protected readonly chainStore: ChainStore, protected accountStore?: AccountStore<AccountWithCosmosAndOsmosis> ) { this.autoConnectingWalletType = localStorage?.getItem(KeyAutoConnectingWalletType) as WalletType; makeObservable(this); } // The account store needs to reference the `getKeplr()` method this on the constructor. // But, this store also needs to reference the account store. // To solve this problem, just set the account store field lazily. setAccountStore(accountStore: AccountStore<AccountWithCosmosAndOsmosis>) { this.accountStore = accountStore; } protected onBeforeSendRequest = (request: Partial<IJsonRpcRequest>): void => { if (!checkIsMobile()) { return; } const deepLink = checkIsAndroid() ? 'intent://wcV1#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;' : 'keplrwallet://wcV1'; switch (request.method) { case 'keplr_enable_wallet_connect_v1': // Keplr mobile requests another per-chain permission for each wallet connect session. // By the current logic, `enable()` is requested immediately after wallet connect is connected. // However, in this case, two requests are made consecutively. // So in ios, the deep link modal pops up twice and confuses the user. // To solve this problem, enable on the osmosis chain does not open deep links. if (request.params && request.params.length === 1 && request.params[0] === this.chainStore.current.chainId) { break; } window.location.href = deepLink; break; case 'keplr_sign_amino_wallet_connect_v1': window.location.href = deepLink; break; } return; }; getKeplr = (): Promise<Keplr | undefined> => { const connectingWalletType = localStorage?.getItem(KeyAutoConnectingWalletType) || localStorage?.getItem(KeyConnectingWalletType); if (connectingWalletType === 'wallet-connect') { if (!this.walletConnector) { this.walletConnector = new WalletConnect({ bridge: 'https://bridge.walletconnect.org', signingMethods: [], qrcodeModal: new WalletConnectQRCodeModalV1Renderer(), }); // XXX: I don't know why they designed that the client meta options in the constructor should be always ingored... // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.walletConnector._clientMeta = { name: 'Osmosis', description: 'Osmosis is the first IBC-native Cosmos interchain AMM', url: 'https://app.osmosis.zone', icons: [window.location.origin + '/public/assets/osmosis-wallet-connect.png'], }; this.walletConnector!.on('disconnect', this.onWalletConnectDisconnected); } if (!this.walletConnector.connected) { return new Promise<Keplr | undefined>((resolve, reject) => { this.walletConnector!.connect() .then(() => { localStorage?.removeItem(KeyConnectingWalletType); localStorage?.setItem(KeyAutoConnectingWalletType, 'wallet-connect'); this.autoConnectingWalletType = 'wallet-connect'; resolve( new KeplrWalletConnectV1(this.walletConnector!, { sendTx, onBeforeSendRequest: this.onBeforeSendRequest, }) ); }) .catch(e => { console.log(e); // XXX: Due to the limitation of cureent account store implementation. // We shouldn't throw an error (reject) on the `getKeplr()` method. // So return the `undefined` temporarily. // In this case, the wallet will be considered as `NotExist` resolve(undefined); }); }); } else { localStorage?.removeItem(KeyConnectingWalletType); localStorage?.setItem(KeyAutoConnectingWalletType, 'wallet-connect'); this.autoConnectingWalletType = 'wallet-connect'; return Promise.resolve( new KeplrWalletConnectV1(this.walletConnector, { sendTx, onBeforeSendRequest: this.onBeforeSendRequest, }) ); } } else { localStorage?.removeItem(KeyConnectingWalletType); localStorage?.setItem(KeyAutoConnectingWalletType, 'extension'); this.autoConnectingWalletType = 'extension'; return getKeplrFromWindow(); } }; onWalletConnectDisconnected = (error: Error | null) => { if (error) { console.log(error); } else { this.disableAutoConnect(); this.disconnect(); } }; /** * Disconnect the wallet regardless of wallet type (extension, wallet connect) */ disconnect() { if (this.walletConnector) { if (this.walletConnector.connected) { this.walletConnector.killSession(); } this.walletConnector = undefined; } if (this.accountStore) { for (const chainInfo of this.chainStore.chainInfos) { const account = this.accountStore.getAccount(chainInfo.chainId); // Clear all account. if (account.walletStatus !== WalletStatus.NotInit) { account.disconnect(); } } } } @action disableAutoConnect() { localStorage?.removeItem(KeyAutoConnectingWalletType); this.autoConnectingWalletType = null; } } export const ConnectWalletDialog = wrapBaseDialog( observer(({ initialFocus, close }: { initialFocus: React.RefObject<HTMLDivElement>; close: () => void }) => { const { chainStore, accountStore } = useStore(); const [isMobile] = useState(() => checkIsMobile()); useEffect(() => { if (isMobile) { // Skip the selection of wallet type if mobile const wallet = walletList[1]; localStorage.setItem(KeyConnectingWalletType, wallet.type); accountStore.getAccount(chainStore.current.chainId).init(); close(); } }, [isMobile]); return ( <div ref={initialFocus}> <h4 className="text-lg md:text-xl text-white-high">Connect Wallet</h4> {walletList .filter(wallet => { if (isMobile && wallet.type == 'extension') { return false; } return true; }) .map(wallet => ( <button key={wallet.name} className="w-full text-left p-3 md:p-5 rounded-2xl bg-background flex items-center mt-4 md:mt-5" onClick={() => { localStorage.setItem(KeyConnectingWalletType, wallet.type); accountStore.getAccount(chainStore.current.chainId).init(); close(); }}> <img src={wallet.logoUrl} className="w-12 mr-3 md:w-16 md:mr-5" /> <div> <h5 className="text-base md:text-lg mb-1 text-white-high">{wallet.name}</h5> <p className="text-xs md:text-sm text-iconDefault">{wallet.description}</p> </div> </button> ))} </div> ); }) ); export const WalletConnectQRCodeModal: FunctionComponent<{ uri: string; close: () => void; }> = ({ uri, close }) => { const [isMobile] = useState(() => checkIsMobile()); const [isAndroid] = useState(() => checkIsAndroid()); const navigateToAppURL = useMemo(() => { if (isMobile) { if (isAndroid) { // Save the mobile link. saveMobileLinkInfo({ name: 'Keplr', href: 'intent://wcV1#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;', }); return `intent://wcV1?${uri}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`; } else { // Save the mobile link. saveMobileLinkInfo({ name: 'Keplr', href: 'keplrwallet://wcV1', }); return `keplrwallet://wcV1?${uri}`; } } }, [isMobile, isAndroid, uri]); useEffect(() => { if (navigateToAppURL) { window.location.href = navigateToAppURL; } }, [navigateToAppURL]); const [isTimeout, setIsTimeout] = useState(false); useEffect(() => { const timeoutId = setTimeout(() => { setIsTimeout(true); }, 2000); return () => { clearTimeout(timeoutId); }; }, []); // Perhaps there is no way to know whether the app is installed or launched in the web browser. // For now, if users are still looking at the screen after 2 seconds, assume that the app isn't installed. if (isMobile) { if (isTimeout) { return ( <div className="fixed inset-0 z-100 overflow-y-auto"> <div className="p-5 flex items-center justify-center min-h-screen"> <div className="fixed inset-0 bg-black opacity-20 flex justify-center items-center" onClick={e => { e.preventDefault(); e.stopPropagation(); close(); }} /> <div className="relative md:max-w-modal px-4 py-5 md:p-8 bg-surface shadow-elevation-24dp rounded-2xl z-10" onClick={e => { e.preventDefault(); e.stopPropagation(); }}> {isAndroid ? ( <button className="px-6 py-2.5 rounded-xl bg-primary-400 flex items-center justify-center mx-auto hover:opacity-75" onClick={e => { e.preventDefault(); e.stopPropagation(); window.location.href = navigateToAppURL!; }}> <h6 className="text-white-high">Open Keplr</h6> </button> ) : ( <button className="px-6 py-2.5 rounded-xl bg-primary-400 flex items-center justify-center mx-auto hover:opacity-75" onClick={e => { e.preventDefault(); e.stopPropagation(); window.location.href = 'itms-apps://itunes.apple.com/app/1567851089'; }}> <h6 className="text-white-high">Install Keplr</h6> </button> )} </div> </div> </div> ); } else { return ( <div className="fixed inset-0 z-100 overflow-y-auto"> <div className="p-5 flex items-center justify-center min-h-screen"> <div className="fixed inset-0 bg-black opacity-20 flex justify-center items-center" onClick={e => { e.preventDefault(); e.stopPropagation(); close(); }} /> <div className="relative md:max-w-modal px-4 py-5 md:p-8 bg-surface shadow-elevation-24dp rounded-2xl z-10" onClick={e => { e.preventDefault(); e.stopPropagation(); }}> <img alt="ldg" className="s-spin w-7 h-7" src="/public/assets/Icons/Loading.png" /> </div> </div> </div> ); } } return ( <div className="fixed inset-0 z-100 overflow-y-auto"> <div className="p-5 flex items-center justify-center min-h-screen"> <div className="fixed inset-0 bg-black opacity-20 flex justify-center items-center" onClick={e => { e.preventDefault(); e.stopPropagation(); close(); }} /> <div className="relative md:max-w-modal px-4 py-5 md:p-8 bg-surface shadow-elevation-24dp rounded-2xl z-10" onClick={e => { e.preventDefault(); e.stopPropagation(); }}> <h4 className="text-lg md:text-xl mb-3 md:mb-5 text-white-high">Scan QR Code</h4> <div className="p-3.5 bg-white-high"> <QRCode size={500} value={uri} /> </div> <img onClick={() => close()} className="absolute cursor-pointer top-3 md:top-5 right-3 md:right-5 w-8 md:w-10" src="/public/assets/Icons/Close.svg" /> </div> </div> </div> ); };
the_stack
import axios from 'axios'; import BigNumber from 'bignumber.js'; import { credentials, ServiceError } from 'grpc'; import SHA3 from 'sha3'; import { AccountStateBlob, AccountStateWithProof } from '../__generated__/account_state_blob_pb'; import { AdmissionControlClient } from '../__generated__/admission_control_grpc_pb'; import { AdmissionControlStatus, SubmitTransactionRequest, SubmitTransactionResponse, } from '../__generated__/admission_control_pb'; import { GetAccountStateRequest, GetAccountStateResponse, GetAccountTransactionBySequenceNumberRequest, GetAccountTransactionBySequenceNumberResponse, RequestItem, ResponseItem, UpdateToLatestLedgerRequest, } from '../__generated__/get_with_proof_pb'; import * as mempool_status_pb from '../__generated__/mempool_status_pb'; import { RawTransaction, SignedTransaction, SignedTransactionWithProof } from '../__generated__/transaction_pb'; import HashSaltValues from '../constants/HashSaltValues'; import ServerHosts from '../constants/ServerHosts'; import { KeyPair, Signature } from '../crypto/Eddsa'; import { LibraAdmissionControlStatus, LibraMempoolTransactionStatus, LibraSignedTransaction, LibraSignedTransactionWithProof, LibraTransaction, LibraTransactionResponse, } from '../transaction'; import { Account, AccountAddress, AccountAddressLike, AccountState, AccountStates } from '../wallet/Accounts'; import { ClientDecoder } from './Decoder'; import { ClientEncoder } from './Encoder'; interface LibraLibConfig { port?: string; host?: string; network?: LibraNetwork; faucetServerHost?: string; validatorSetFile?: string; } export enum LibraNetwork { Testnet = 'testnet', // Mainnet = 'mainnet' } export class LibraClient { private readonly config: LibraLibConfig; private readonly client: AdmissionControlClient; private readonly decoder: ClientDecoder; private readonly encoder: ClientEncoder; constructor(config: LibraLibConfig) { this.config = config; if (config.host === undefined) { // since only testnet for now this.config.host = ServerHosts.DefaultTestnet; } if (config.port === undefined) { this.config.port = '80'; } const connectionAddress = `${this.config.host}:${this.config.port}`; this.client = new AdmissionControlClient(connectionAddress, credentials.createInsecure()); this.decoder = new ClientDecoder(); this.encoder = new ClientEncoder(this); } /** * Fetch the current state of an account. * * * @param {string} address Accounts address */ public async getAccountState(address: AccountAddressLike): Promise<AccountState> { const result = await this.getAccountStates([address]); return result[0]; } /** * Fetches the current state of multiple accounts. * * @param {AccountAddressLike[]} addresses Array of users addresses */ public async getAccountStates(addresses: AccountAddressLike[]): Promise<AccountStates> { const accountAddresses = addresses.map(address => new AccountAddress(address)); const request = new UpdateToLatestLedgerRequest(); accountAddresses.forEach(address => { const requestItem = new RequestItem(); const getAccountStateRequest = new GetAccountStateRequest(); getAccountStateRequest.setAddress(address.toBytes()); requestItem.setGetAccountStateRequest(getAccountStateRequest); request.addRequestedItems(requestItem); }); return new Promise<AccountStates>((resolve, reject) => { this.client.updateToLatestLedger(request, (error, response) => { if (error) { return reject(error); } resolve( response.getResponseItemsList().map((item: ResponseItem, index: number) => { const stateResponse = item.getGetAccountStateResponse() as GetAccountStateResponse; const stateWithProof = stateResponse.getAccountStateWithProof() as AccountStateWithProof; if (stateWithProof.hasBlob()) { const stateBlob = stateWithProof.getBlob() as AccountStateBlob; const blob = stateBlob.getBlob_asU8(); return this.decoder.decodeAccountStateBlob(blob); } return AccountState.default(accountAddresses[index].toHex()); }), ); }); }); } /** * Returns the Accounts transaction done with sequenceNumber. * */ public async getAccountTransaction( address: AccountAddressLike, sequenceNumber: BigNumber | string | number, fetchEvents: boolean = true, ): Promise<LibraSignedTransactionWithProof | null> { const accountAddress = new AccountAddress(address); const parsedSequenceNumber = new BigNumber(sequenceNumber); const request = new UpdateToLatestLedgerRequest(); const requestItem = new RequestItem(); const getTransactionRequest = new GetAccountTransactionBySequenceNumberRequest(); getTransactionRequest.setAccount(accountAddress.toBytes()); getTransactionRequest.setSequenceNumber(parsedSequenceNumber.toString(10)); getTransactionRequest.setFetchEvents(fetchEvents); requestItem.setGetAccountTransactionBySequenceNumberRequest(getTransactionRequest); request.addRequestedItems(requestItem); return new Promise<LibraSignedTransactionWithProof | null>((resolve, reject) => { this.client.updateToLatestLedger(request, (error, response) => { if (error) { return reject(error); } const responseItems = response.getResponseItemsList(); if (responseItems.length === 0) { return resolve(null); } const r = responseItems[0].getGetAccountTransactionBySequenceNumberResponse() as GetAccountTransactionBySequenceNumberResponse; const signedTransactionWP = r.getSignedTransactionWithProof() as SignedTransactionWithProof; resolve(this.decoder.decodeSignedTransactionWithProof(signedTransactionWP)); }); }); } /** * Uses the faucetService on testnet to mint coins to be sent * to receiver. * * Returns the sequence number for the transaction used to mint * * Note: `numCoins` should be in base unit i.e microlibra (10^6 I believe). */ public async mintWithFaucetService( receiver: AccountAddress | string, numCoins: BigNumber | string | number, waitForConfirmation: boolean = true, ): Promise<string> { const serverHost = this.config.faucetServerHost || ServerHosts.DefaultFaucet; const coins = new BigNumber(numCoins).toString(10); const address = receiver.toString(); const response = await axios.post(`http://${serverHost}?amount=${coins}&address=${address}`); if (response.status !== 200) { throw new Error(`Failed to query faucet service. Code: ${response.status}, Err: ${response.data.toString()}`); } const sequenceNumber = response.data as string; if (waitForConfirmation) { await this.waitForConfirmation(AccountAddress.default(), sequenceNumber); } return sequenceNumber; } /** * Keeps polling the account state of address till sequenceNumber is computed. * */ public async waitForConfirmation( accountAddress: AccountAddress | string, transactionSequenceNumber: number | string | BigNumber, ): Promise<void> { const sequenceNumber = new BigNumber(transactionSequenceNumber); const address = accountAddress.toString(); let maxIterations = 50; const poll = (resolve: (value?: void | PromiseLike<void>) => void, reject: (reason?: Error) => void) => { setTimeout(() => { maxIterations--; this.getAccountState(address) .then(accountState => { if (accountState.sequenceNumber.gte(sequenceNumber)) { return resolve(); } if (maxIterations === -1) { reject(new Error(`Confirmation timeout for [${address}]:[${sequenceNumber.toString(10)}]`)); } else { poll(resolve, reject); } }) .catch(reject); }, 1000); }; return new Promise((resolve, reject) => { poll(resolve, reject); }); } /** * Sign the transaction with keyPair and returns a promise that resolves to a LibraSignedTransaction * * */ public async signTransaction(transaction: LibraTransaction, keyPair: KeyPair): Promise<LibraSignedTransaction> { const rawTxn = await this.encoder.encodeLibraTransaction(transaction, transaction.sendersAddress); const signature = this.signRawTransaction(rawTxn, keyPair); return new LibraSignedTransaction(transaction, keyPair.getPublicKey(), signature); } /** * Transfer coins from sender to receipient. * numCoins should be in libraCoins based unit. * */ public async transferCoins( sender: Account, recipientAddress: string, numCoins: number | string | BigNumber, ): Promise<LibraTransactionResponse> { return this.execute(LibraTransaction.createTransfer(recipientAddress, new BigNumber(numCoins)), sender); } /** * Execute a transaction by sender. * */ public async execute(transaction: LibraTransaction, sender: Account): Promise<LibraTransactionResponse> { const rawTransaction = await this.encoder.encodeLibraTransaction(transaction, sender.getAddress()); const signedTransaction = new SignedTransaction(); const request = new SubmitTransactionRequest(); const senderSignature = this.signRawTransaction(rawTransaction, sender.keyPair); signedTransaction.setRawTxnBytes(rawTransaction.serializeBinary()); signedTransaction.setSenderPublicKey(sender.keyPair.getPublicKey()); signedTransaction.setSenderSignature(senderSignature); request.setSignedTxn(signedTransaction); return new Promise((resolve, reject) => { this.client.submitTransaction(request, (error: ServiceError | null, response: SubmitTransactionResponse) => { if (error) { // TBD: should this fail with only service error // or should it fail if transaction is not acknowledged return reject(error); } const vmStatus = this.decoder.decodeVMStatus(response.getVmStatus()); resolve( new LibraTransactionResponse( new LibraSignedTransaction(transaction, sender.keyPair.getPublicKey(), senderSignature), response.getValidatorId_asU8(), response.hasAcStatus() ? (response.getAcStatus() as AdmissionControlStatus).getCode() : LibraAdmissionControlStatus.UNKNOWN, response.hasMempoolStatus() ? (response.getMempoolStatus() as mempool_status_pb.MempoolAddTransactionStatus).getCode() : LibraMempoolTransactionStatus.UNKNOWN, vmStatus, ), ); }); }); } private signRawTransaction(rawTransaction: RawTransaction, keyPair: KeyPair): Signature { const rawTxnBytes = rawTransaction.serializeBinary(); const hash = new SHA3(256) .update(Buffer.from(HashSaltValues.rawTransactionHashSalt, 'hex')) .update(Buffer.from(rawTxnBytes.buffer)) .digest(); return keyPair.sign(hash); } } export default LibraClient;
the_stack
import EventSource from 'eventsource'; import { startTServer, startDisposableServer } from './utils/tserver'; import { eventStream } from './utils/eventStream'; import { createClient, createHandler } from '../index'; import { TOKEN_HEADER_KEY, TOKEN_QUERY_KEY } from '../common'; import http from 'http'; import { schema } from './fixtures/simple'; import fetch from 'node-fetch'; import express from 'express'; import Fastify from 'fastify'; // just does nothing function noop(): void { /**/ } it('should only accept valid accept headers', async () => { const { request } = await startTServer(); const { data: token } = await request('PUT'); let res = await request('GET', { accept: 'gibberish', [TOKEN_HEADER_KEY]: token, }); expect(res.statusCode).toBe(406); res = await request('GET', { accept: 'application/graphql+json', [TOKEN_HEADER_KEY]: token, }); expect(res.statusCode).toBe(400); expect(res.statusMessage).toBe('Missing query'); res = await request('GET', { accept: 'application/json', [TOKEN_HEADER_KEY]: token, }); expect(res.statusCode).toBe(400); expect(res.statusMessage).toBe('Missing query'); res = await request('GET', { accept: 'text/event-stream' }); expect(res.statusCode).toBe(400); expect(res.statusMessage).toBe('Missing query'); res = await request('POST', { accept: 'text/event-stream' }, { query: '' }); expect(res.statusCode).toBe(400); expect(res.statusMessage).toBe('Missing query'); }); it.todo('should throw all unexpected errors from the handler'); it.todo('should use the string body argument from the handler'); it.todo('should use the object body argument from the handler'); describe('single connection mode', () => { it('should respond with 404s when token was not previously registered', async () => { const { request } = await startTServer(); // maybe POST gql request let res = await request('POST'); expect(res.statusCode).toBe(404); expect(res.statusMessage).toBe('Stream not found'); // maybe GET gql request res = await request('GET'); expect(res.statusCode).toBe(404); expect(res.statusMessage).toBe('Stream not found'); // completing/ending an operation res = await request('DELETE'); expect(res.statusCode).toBe(404); expect(res.statusMessage).toBe('Stream not found'); }); it('should get a token with PUT request', async () => { const { request } = await startTServer({ authenticate: () => 'token' }); const { statusCode, headers, data } = await request('PUT'); expect(statusCode).toBe(201); expect(headers['content-type']).toBe('text/plain; charset=utf-8'); expect(data).toBe('token'); }); it('should allow event streams on reservations only', async () => { const { url, request } = await startTServer(); // no reservation no connect let es = new EventSource(url); await new Promise<void>((resolve) => { es.onerror = () => { resolve(); es.close(); // no retry }; }); // token can be sent through the header let res = await request('PUT'); es = new EventSource(url, { headers: { [TOKEN_HEADER_KEY]: res.data }, }); await new Promise<void>((resolve, reject) => { es.onopen = () => resolve(); es.onerror = (e) => { reject(e); es.close(); // no retry }; }); es.close(); // token can be sent through the url res = await request('PUT'); es = new EventSource(url + '?' + TOKEN_QUERY_KEY + '=' + res.data); await new Promise<void>((resolve, reject) => { es.onopen = () => resolve(); es.onerror = (e) => { reject(e); es.close(); // no retry }; }); es.close(); }); it('should not allow operations without providing an operation id', async () => { const { request } = await startTServer(); const { data: token } = await request('PUT'); const { statusCode, statusMessage } = await request( 'POST', { [TOKEN_HEADER_KEY]: token }, { query: '{ getValue }' }, ); expect(statusCode).toBe(400); expect(statusMessage).toBe('Operation ID is missing'); }); it('should stream query operations to connected event stream', async (done) => { const { url, request } = await startTServer(); const { data: token } = await request('PUT'); const es = new EventSource(url + '?' + TOKEN_QUERY_KEY + '=' + token); es.addEventListener('next', (event) => { expect((event as any).data).toMatchSnapshot(); }); es.addEventListener('complete', () => { es.close(); done(); }); const { statusCode } = await request( 'POST', { [TOKEN_HEADER_KEY]: token }, { query: '{ getValue }', extensions: { operationId: '1' } }, ); expect(statusCode).toBe(202); }); it.todo('should stream query operations even if event stream connects later'); it('should stream subscription operations to connected event stream', async (done) => { const { url, request } = await startTServer(); const { data: token } = await request('PUT'); const es = new EventSource(url + '?' + TOKEN_QUERY_KEY + '=' + token); es.addEventListener('next', (event) => { // called 5 times expect((event as any).data).toMatchSnapshot(); }); es.addEventListener('complete', () => { es.close(); done(); }); const { statusCode } = await request( 'POST', { [TOKEN_HEADER_KEY]: token }, { query: 'subscription { greetings }', extensions: { operationId: '1' } }, ); expect(statusCode).toBe(202); }); it('should report operation validation issues to request', async () => { const { url, request } = await startTServer(); const { data: token } = await request('PUT'); const es = new EventSource(url + '?' + TOKEN_QUERY_KEY + '=' + token); es.addEventListener('next', () => { fail('Shouldnt have omitted'); }); es.addEventListener('complete', () => { fail('Shouldnt have omitted'); }); const { statusCode, data } = await request( 'POST', { [TOKEN_HEADER_KEY]: token }, { query: '{ notExists }', extensions: { operationId: '1' } }, ); expect(statusCode).toBe(400); expect(data).toMatchSnapshot(); es.close(); }); it('should bubble errors thrown in onNext to the handler', async (done) => { const onNextErr = new Error('Woops!'); const handler = createHandler({ schema, onNext: () => { throw onNextErr; }, }); const [, url, dispose] = await startDisposableServer( http.createServer(async (req, res) => { try { await handler(req, res); } catch (err) { expect(err).toBe(onNextErr); await dispose(); done(); } }), ); const client = createClient({ singleConnection: true, url, fetchFn: fetch, retryAttempts: 0, }); client.subscribe( { query: '{ getValue }', }, { next: noop, error: noop, complete: noop, }, ); }); }); describe('distinct connections mode', () => { it('should stream query operations to connected event stream and then disconnect', async () => { const { url, waitForDisconnect } = await startTServer(); const control = new AbortController(); // POST let msgs = await eventStream({ signal: control.signal, url, body: { query: '{ getValue }' }, }); for await (const msg of msgs) { expect(msg).toMatchSnapshot(); } await waitForDisconnect(); // GET const urlQuery = new URL(url); urlQuery.searchParams.set('query', '{ getValue }'); msgs = await eventStream({ signal: control.signal, url: urlQuery.toString(), }); for await (const msg of msgs) { expect(msg).toMatchSnapshot(); } await waitForDisconnect(); }); it('should stream subscription operations to connected event stream and then disconnect', async () => { const { url, waitForDisconnect } = await startTServer(); const control = new AbortController(); // POST let msgs = await eventStream({ signal: control.signal, url, body: { query: 'subscription { greetings }' }, }); for await (const msg of msgs) { expect(msg).toMatchSnapshot(); } await waitForDisconnect(); // GET const urlQuery = new URL(url); urlQuery.searchParams.set('query', 'subscription { greetings }'); msgs = await eventStream({ signal: control.signal, url: urlQuery.toString(), }); for await (const msg of msgs) { expect(msg).toMatchSnapshot(); } await waitForDisconnect(); }); it('should report operation validation issues by streaming them', async () => { const { url, waitForDisconnect } = await startTServer(); const control = new AbortController(); const msgs = await eventStream({ signal: control.signal, url, body: { query: '{ notExists }' }, }); for await (const msg of msgs) { expect(msg).toMatchSnapshot(); } await waitForDisconnect(); }); it('should complete subscription operations after client disconnects', async () => { const { url, waitForOperation, waitForComplete } = await startTServer(); const control = new AbortController(); await eventStream({ signal: control.signal, url, body: { query: 'subscription { ping }' }, }); await waitForOperation(); control.abort(); await waitForComplete(); }); it('should bubble errors thrown in onNext to the handler', async (done) => { const onNextErr = new Error('Woops!'); const handler = createHandler({ schema, onNext: () => { throw onNextErr; }, }); const [, url, dispose] = await startDisposableServer( http.createServer(async (req, res) => { try { await handler(req, res); } catch (err) { expect(err).toBe(onNextErr); await dispose(); done(); } }), ); const client = createClient({ url, fetchFn: fetch, retryAttempts: 0, }); client.subscribe( { query: '{ getValue }', }, { next: noop, error: noop, complete: noop, }, ); }); }); describe('express', () => { it('should work as advertised in the readme', async () => { const app = express(); const handler = createHandler({ schema }); app.use('/graphql/stream', handler); const [, url, dispose] = await startDisposableServer( http.createServer(app), ); const client = createClient({ url: url + '/graphql/stream', fetchFn: fetch, retryAttempts: 0, }); const next = jest.fn(); await new Promise<void>((resolve, reject) => { client.subscribe( { query: 'subscription { greetings }', }, { next: next, error: reject, complete: resolve, }, ); }); expect(next).toBeCalledTimes(5); expect(next.mock.calls).toMatchSnapshot(); await dispose(); }); }); describe('fastify', () => { it('should work as advertised in the readme', async () => { const handler = createHandler({ schema }); const fastify = Fastify(); fastify.all('/graphql/stream', (req, res) => handler(req.raw, res.raw, req.body), ); const url = await fastify.listen(0); const client = createClient({ url: url + '/graphql/stream', fetchFn: fetch, retryAttempts: 0, }); const next = jest.fn(); await new Promise<void>((resolve, reject) => { client.subscribe( { query: 'subscription { greetings }', }, { next: next, error: reject, complete: resolve, }, ); }); expect(next).toBeCalledTimes(5); expect(next.mock.calls).toMatchSnapshot(); await fastify.close(); }); });
the_stack
import { browser, by, element, ExpectedConditions } from 'protractor'; import randomIpv6 from "random-ipv6"; import { BasePage } from './BasePage.po'; import { SideNavigationPage } from '../PageObjects/SideNavigationPage.po'; import { randomize } from '../config'; interface CreateServer { Status: string; Hostname: string; Domainname: string; CDN: string; CacheGroup: string; Type: string; Profile: string; PhysLocation: string; InterfaceName: string; validationMessage?: string; } interface ServerCapability { ServerCapability: string; validationMessage?: string; } interface UpdateServer { description: string; CDN: string; Profile: string; validationMessage?: string; } interface DeleteServer { Name: string; validationMessage?: string; } export class ServersPage extends BasePage { private btnMore = element(by.xpath("//button[contains(text(),'More')]")); private btnDelete = element(by.buttonText('Delete')); private txtStatus = element(by.name('status')); private txtHostName = element(by.xpath("//ol[@class='breadcrumb pull-left']//li[@class='active ng-binding']")) private txtDomainName = element(by.name('domainName')); private txtProfile = element(by.name('profile')); private txtPhysLocation = element(by.name('physLocation')); private lblInputError = element(by.className("input-error")); private txtHostname = element(by.name('hostName')); private txtCDN = element(by.name('cdn')); private txtCacheGroup = element(by.name('cachegroup')); private txtType = element(by.name('type')); private txtConfirmServerName = element(by.name('confirmWithNameInput')); private btnYesRemoveSC = element(by.buttonText("Yes")) private btnManageCapabilities = element(by.linkText('Manage Capabilities')); private btnAddCapabilities = element(by.name('addCapabilityBtn')); private selectCapabilities = element(by.name('selectFormDropdown')); private searchFilter = element(by.id('serverCapabilitiesTable_filter')).element(by.css('label input')); private btnManageDeliveryService = element(by.linkText('Manage Delivery Services')); private btnLinkDStoServer = element(by.xpath("//button[@title='Link Delivery Services to Server']")); private txtDSSearch = element(by.id('assignDSTable_filter')).element(by.css('label input')); private txtInterfaceName = element(by.id("-name")); private btnMoreCreateServer = element(by.name("moreBtn")) private btnCreateServer = element(by.name("createServerMenuItem")) private txtQuickSearch = element(by.id("quickSearch")); private btnTableColumn = element(by.className("caret")) private randomize = randomize; public async OpenServerPage() { let snp = new SideNavigationPage(); await snp.NavigateToServersPage(); } public async OpenConfigureMenu() { let snp = new SideNavigationPage(); await snp.ClickConfigureMenu(); } public GetInputErrorDisplayed() { return this.lblInputError.getText() } public IsServersItemPresent(): PromiseLike<boolean> { return element(by.xpath("//table[@id='serversTable']//tr/td[text()='" + "']")).isPresent() } public async ClickAddServer() { await this.btnCreateServer.click() } public async CreateServer(server: CreateServer): Promise<boolean> { let result = false; let basePage = new BasePage(); let ipv6 = randomIpv6(); await this.btnMoreCreateServer.click(); await this.btnCreateServer.click(); await this.txtStatus.sendKeys(server.Status); await this.txtHostname.sendKeys(server.Hostname + this.randomize); await this.txtDomainName.sendKeys(server.Domainname); await this.txtCDN.sendKeys("ALL"); await this.txtCDN.sendKeys(server.CDN + this.randomize); await this.txtCacheGroup.sendKeys(server.CacheGroup + this.randomize); await this.txtType.sendKeys(server.Type); await this.txtProfile.sendKeys(server.Profile + this.randomize); await this.txtPhysLocation.sendKeys(server.PhysLocation); await this.txtInterfaceName.sendKeys(server.InterfaceName); await element(by.id("" + server.InterfaceName + "-")).sendKeys(ipv6.toString()); if (!await basePage.ClickCreate()) result = false; await basePage.GetOutputMessage().then(function (value) { if (server.validationMessage == value) { result = true; } else { result = false; } }) await this.OpenServerPage(); return result; } public async SearchServer(nameServer: string) { let name = nameServer + this.randomize; await this.txtQuickSearch.clear(); await this.txtQuickSearch.sendKeys(name); await browser.actions().click(element(by.cssContainingText("span", name))).perform(); } public async SearchDeliveryServiceFromServerPage(name: string): Promise<boolean> { await this.txtDSSearch.clear(); await this.txtDSSearch.sendKeys(name); if (await browser.isElementPresent(element(by.xpath("//td[@data-search='^" + name + "$']"))) == true) { await element(by.xpath("//td[@data-search='^" + name + "$']")).click(); return true; } return false; } public async AddDeliveryServiceToServer(deliveryServiceName: string, outputMessage: string): Promise<boolean> { let result = false; let basePage = new BasePage(); let deliveryService = deliveryServiceName + this.randomize; const serverNameRandomized = await this.txtHostName.getText(); let serverName = serverNameRandomized.replace(this.randomize, "") if (outputMessage.includes("delivery services assigned")) { outputMessage = outputMessage.replace(serverName, serverNameRandomized) } if (outputMessage.includes("cannot assign")) { let dsCapRequired = outputMessage.slice(112, 118); outputMessage = outputMessage.replace(dsCapRequired, dsCapRequired + this.randomize) outputMessage = outputMessage.replace(serverName, serverNameRandomized) } await this.btnMore.click(); if (await this.btnManageDeliveryService.isPresent() == true) { await this.btnManageDeliveryService.click(); await this.btnLinkDStoServer.click(); if (await this.SearchDeliveryServiceFromServerPage(deliveryService) == true) { await basePage.ClickSubmit(); result = await basePage.GetOutputMessage().then(function (value) { if (value == outputMessage) { return true; } else { return false; } }) } } else { result = false; } return result; } public async AddServerCapabilitiesToServer(serverCapabilities: ServerCapability): Promise<boolean> { let result = false; let basePage = new BasePage(); let serverCapabilitiesName = serverCapabilities.ServerCapability + this.randomize; await this.btnMore.click(); if ((await this.btnManageCapabilities.isPresent()) == true) { await this.btnManageCapabilities.click(); await this.btnAddCapabilities.click(); await this.selectCapabilities.sendKeys(serverCapabilitiesName); await basePage.ClickSubmit(); result = await basePage.GetOutputMessage().then(function (value) { if (serverCapabilities.validationMessage === value || serverCapabilities.validationMessage && value.includes(serverCapabilities.validationMessage)) { result = true; } else { result = false; } return result; }) } else { result = false; } await this.OpenServerPage(); return result; } public async SearchServerServerCapabilities(name: string) { let result = false; await this.searchFilter.clear(); await this.searchFilter.sendKeys(name); result = await element.all(by.repeater('sc in ::serverCapabilities')).filter(function (row) { return row.element(by.name('name')).getText().then(function (val) { return val === name; }); }).first().getText().then(function (value) { if (value == name) { return true; } else { return false; } }) return result; } public async RemoveServerCapabilitiesFromServer(serverCapabilities: string, outputMessage: string): Promise<boolean> { let result = false; let basePage = new BasePage(); let serverCapabilitiesname = serverCapabilities + this.randomize; const url = (await browser.getCurrentUrl()).toString(); let serverNumber = url.substring(url.lastIndexOf('/') + 1); if (outputMessage.includes("cannot remove")) { outputMessage = outputMessage.replace(serverCapabilities, serverCapabilitiesname) outputMessage = outputMessage.slice(0, 56) + serverNumber + " " + outputMessage.slice(56); } await this.btnMore.click(); if ((await this.btnManageCapabilities.isPresent()) == true) { await this.btnManageCapabilities.click(); if (await this.SearchServerServerCapabilities(serverCapabilitiesname) == true) { await element(by.xpath("//td[text()='" + serverCapabilitiesname + "']/following-sibling::td/a[@title='Remove Server Capability']")).click(); } await this.btnYesRemoveSC.click(); result = await basePage.GetOutputMessage().then(function (value) { if (outputMessage == value) { return true; } else if (value.includes(outputMessage)) { return true; } else { return false; } }) } else { result = false; } await this.OpenServerPage(); return result; } public async UpdateServer(server: UpdateServer): Promise<boolean> { let result = false; let basePage = new BasePage(); if (server.description.includes('change the cdn of a Server')) { await this.txtCDN.sendKeys(server.CDN + this.randomize); await this.txtProfile.sendKeys(server.Profile + this.randomize) await basePage.ClickUpdate(); result = await basePage.GetOutputMessage().then(function (value) { if (server.validationMessage == value) { return true; } else { return false; } }) } return result; } public async DeleteServer(server: DeleteServer) { let result = false; let basePage = new BasePage(); let name = server.Name + this.randomize await this.btnDelete.click(); await browser.wait(ExpectedConditions.visibilityOf(this.txtConfirmServerName), 1000); await this.txtConfirmServerName.sendKeys(name); if (await basePage.ClickDeletePermanently() == true) { result = await basePage.GetOutputMessage().then(function (value) { if (server.validationMessage == value) { return true } else { return false; } }) } else { await basePage.ClickCancel(); } await this.OpenServerPage(); return result; } public async ToggleTableColumn(name: string): Promise<boolean> { await this.btnTableColumn.click(); const result = await element(by.cssContainingText("th", name)).isPresent(); await element(by.cssContainingText("label", name)).click(); await this.btnTableColumn.click(); return !result; } }
the_stack
import assert from 'assert' import isUndefined from 'lodash/isUndefined' import mapValues from 'lodash/mapValues' import omit from 'lodash/omit' import omitBy from 'lodash/omitBy' import flow from 'lodash/flow' import { getLabwareV1Def, getPipetteNameSpecs } from '@opentrons/shared-data' import { FileLabware, FilePipette, ProtocolFile, } from '@opentrons/shared-data/protocol/types/schemaV1' import { FormPatch } from '../../steplist/actions' import { FormData } from '../../form-types' export interface PDMetadata { pipetteTiprackAssignments: Record<string, string> dismissedWarnings: { form: Record<string, string[] | null | undefined> timeline: Record<string, string[] | null | undefined> } ingredients: Record< string, { name: string | null | undefined description: string | null | undefined serialize: boolean } > ingredLocations: { [labwareId: string]: { [wellId: string]: { [liquidId: string]: { volume: number } } } } savedStepForms: Record< string, { stepType: 'moveLiquid' | 'mix' | 'pause' | 'manualIntervention' id: string [key: string]: any } > orderedStepIds: string[] } export type PDProtocolFile = ProtocolFile<PDMetadata> type LegacyPipetteEntities = Record< string, { id: string tiprackModel: string mount: string name?: string model?: string } > function getPipetteCapacityLegacy( pipette: LegacyPipetteEntities[keyof LegacyPipetteEntities] ): number { // hacky model to name ('p10_single_v1.3' -> 'p10_single') fallback const pipetteName = pipette.name || (pipette.model || '').split('_v')[0] if (!pipetteName) { throw new Error( `expected pipette name or model in migration. Pipette: "${JSON.stringify( pipette )}"` ) } // @ts-expect-error unable to cast type string from manipulation above to type PipetteName const specs = getPipetteNameSpecs(pipetteName) const tiprackDef = getLabwareV1Def(pipette.tiprackModel) if (specs && tiprackDef && tiprackDef.metadata.tipVolume) { return Math.min(specs.maxVolume, tiprackDef.metadata.tipVolume) } assert(specs, `Expected spec for pipette ${JSON.stringify(pipette)}`) assert( tiprackDef, `expected tiprack def for pipette ${JSON.stringify(pipette)}` ) assert( tiprackDef?.metadata?.tipVolume, `expected tiprack volume for tiprack def ${JSON.stringify( tiprackDef?.metadata || 'undefined' )}` ) return NaN } // NOTE: these constants are copied here because // the default-values key did not exist for most protocols // pre 1.1.0 in later migration files many of these values // should be taken from the default-values key export const INITIAL_DECK_SETUP_STEP_ID: '__INITIAL_DECK_SETUP_STEP__' = '__INITIAL_DECK_SETUP_STEP__' export const initialDeckSetupStepForm: FormData = { stepType: 'manualIntervention', id: INITIAL_DECK_SETUP_STEP_ID, labwareLocationUpdate: { trashId: '12', }, pipetteLocationUpdate: {}, } // NOTE: this function was copied on 2019-2-7 from // formLevel/handleFormChange/dependentFieldsUpdateMoveLiquid.js // in order to avoid further inadvertent changes to this migration function _updatePatchPathField( patch: FormPatch, rawForm: FormData, pipetteEntities: LegacyPipetteEntities ): FormPatch { const appliedPatch = { ...rawForm, ...patch } const { path, changeTip } = appliedPatch if (!path) { console.warn( `No path for form: ${String(rawForm.id)}. Falling back to "single" path` ) // sanity check - fall back to 'single' if no path specified return { ...patch, path: 'single' } } const numericVolume = Number(appliedPatch.volume) || 0 const pipetteCapacity = getPipetteCapacityLegacy( pipetteEntities[appliedPatch.pipette] ) let pipetteCapacityExceeded = numericVolume > pipetteCapacity if ( appliedPatch.volume && appliedPatch.pipette && appliedPatch.pipette in pipetteEntities ) { if (pipetteCapacity) { if ( !pipetteCapacityExceeded && ['multiDispense', 'multiAspirate'].includes(appliedPatch.path) ) { const disposalVolume = appliedPatch.disposalVolume_checkbox && appliedPatch.disposalVolume_volume ? appliedPatch.disposalVolume_volume : 0 pipetteCapacityExceeded = numericVolume * 2 + disposalVolume > pipetteCapacity } } } if (pipetteCapacityExceeded) { return { ...patch, path: 'single' } } // changeTip value incompatible with next path value const incompatiblePath = (changeTip === 'perSource' && path === 'multiAspirate') || (changeTip === 'perDest' && path === 'multiDispense') if (pipetteCapacityExceeded || incompatiblePath) { return { ...patch, path: 'single' } } return patch } export function renameOrderedSteps(fileData: PDProtocolFile): PDProtocolFile { const { data } = fileData['designer-application'] return { ...fileData, 'designer-application': { ...fileData['designer-application'], data: { ...data, // @ts-expect-error orderedSteps doesn't exist on PDMetaData orderedStepIds: data.orderedStepIds || data.orderedSteps, // @ts-expect-error orderedSteps doesn't exist on PDMetaData orderedSteps: undefined, }, }, } } // builds the initial deck setup step for older protocols that didn't have one. export function addInitialDeckSetupStep( fileData: PDProtocolFile ): PDProtocolFile { const savedStepForms = fileData['designer-application'].data.savedStepForms // already has deck setup step, pass thru if (savedStepForms[INITIAL_DECK_SETUP_STEP_ID]) return fileData const additionalLabware = mapValues( fileData.labware, (labware: FileLabware) => labware.slot ) const pipetteLocations = mapValues( fileData.pipettes, (pipette: FilePipette) => pipette.mount ) // TODO(IL, 2020-06-08): should be FormData but Flow get confused // (Since this is a migration, any changes should be types-only!) const deckSetupStep: any = { ...initialDeckSetupStepForm, labwareLocationUpdate: { ...initialDeckSetupStepForm.labwareLocationUpdate, ...additionalLabware, }, pipetteLocationUpdate: { ...initialDeckSetupStepForm.pipetteLocationUpdate, ...pipetteLocations, }, } return { ...fileData, 'designer-application': { ...fileData['designer-application'], data: { ...fileData['designer-application'].data, savedStepForms: { ...savedStepForms, [INITIAL_DECK_SETUP_STEP_ID]: deckSetupStep, }, }, }, } } export const TCD_DEPRECATED_FIELD_NAMES = [ 'step-name', 'step-details', 'aspirate_changeTip', 'aspirate_disposalVol_checkbox', 'aspirate_disposalVol_volume', 'aspirate_preWetTip', 'aspirate_touchTip', 'dispense_blowout_checkbox', 'dispense_blowout_labware', 'dispense_blowout_location', 'offsetFromBottomMm', 'dispense_touchTip', 'aspirate_touchTip', 'aspirate_touchTipMmFromBottom', 'dispense_touchTipMmFromBottom', ] export const MIX_DEPRECATED_FIELD_NAMES = [ 'step-name', 'step-details', 'aspirate_changeTip', 'dispense_mmFromBottom', 'aspirate_wellOrder_first', 'aspirate_wellOrder_second', 'dispense_blowout_checkbox', 'dispense_blowout_labware', 'dispense_blowout_location', 'touchTip', 'mix_touchTipMmFromBottom', ] export function updateStepFormKeys(fileData: PDProtocolFile): PDProtocolFile { const savedStepForms = fileData['designer-application'].data.savedStepForms // NOTE: on LOAD_FILE, savedStepForms reducer will spread the form values // on top of over getDefaultsForStepType, so the defaults do not need to be // included here const migratedStepForms = mapValues(savedStepForms, formData => { if (['transfer', 'consolidate', 'distribute'].includes(formData.stepType)) { const updatedFields = { stepName: formData['step-name'], stepDetails: formData['step-details'], changeTip: formData.aspirate_changeTip, blowout_checkbox: formData.dispense_blowout_checkbox, blowout_location: formData.dispense_blowout_location || formData.dispense_blowout_labware, aspirate_touchTip_checkbox: formData.aspirate_touchTip, dispense_touchTip_checkbox: formData.dispense_touchTip, disposalVolume_checkbox: formData.aspirate_disposalVol_checkbox, disposalVolume_volume: formData.aspirate_disposalVol_volume, preWetTip: formData.aspirate_preWetTip, aspirate_touchTip_mmFromBottom: formData.aspirate_touchTipMmFromBottom, dispense_touchTip_mmFromBottom: formData.dispense_touchTipMmFromBottom, } return { ...omitBy(updatedFields, isUndefined), ...omit(formData, TCD_DEPRECATED_FIELD_NAMES), } } else if (formData.stepType === 'mix') { const updatedFields = { stepName: formData['step-name'], stepDetails: formData['step-details'], changeTip: formData.aspirate_changeTip, mix_mmFromBottom: formData.dispense_mmFromBottom, mix_wellOrder_first: formData.aspirate_wellOrder_first, mix_wellOrder_second: formData.aspirate_wellOrder_second, mix_touchTip_checkbox: formData.touchTip, blowout_checkbox: formData.dispense_blowout_checkbox, blowout_location: formData.dispense_blowout_location || formData.dispense_blowout_labware, mix_touchTip_mmFromBottom: formData.mix_touchTipMmFromBottom, } return { ...omitBy(updatedFields, isUndefined), ...omit(formData, MIX_DEPRECATED_FIELD_NAMES), } } else if (formData.stepType === 'manualIntervention') { // no step-name / step-details return formData } else { return { stepName: formData['step-name'], stepDetails: formData['step-details'], ...omit(formData, ['step-name', 'step-details']), } } }) return { ...fileData, 'designer-application': { ...fileData['designer-application'], data: { ...fileData['designer-application'].data, // @ts-expect-error migratedStepForms is missing object fields savedStepForms: migratedStepForms, }, }, } } export function replaceTCDStepsWithMoveLiquidStep( fileData: PDProtocolFile ): PDProtocolFile { const savedStepForms = fileData['designer-application'].data.savedStepForms const migratedStepForms = mapValues(savedStepForms, formData => { const { stepType } = formData if (!['transfer', 'consolidate', 'distribute'].includes(stepType)) return formData const pathMap = { transfer: 'single', consolidate: 'multiAspirate', distribute: 'multiDispense', } const proposedPatch = { // @ts-expect-error stepType not always included in pathMap path: pathMap[stepType], stepType: 'moveLiquid', aspirate_wells_grouped: false, } const pipetteEntities = mapValues( fileData.pipettes, (pipette, pipetteId) => ({ ...pipette, tiprackModel: fileData['designer-application'].data.pipetteTiprackAssignments[ pipetteId ], }) ) // update path field patch if incompatible; fallback to 'single' const resolvedPatch = _updatePatchPathField( proposedPatch, formData, // @ts-expect-error property id missing from object pipetteEntities ) return { ...formData, ...resolvedPatch } }) return { ...fileData, 'designer-application': { ...fileData['designer-application'], data: { ...fileData['designer-application'].data, savedStepForms: migratedStepForms, }, }, } } export function updateVersion(fileData: PDProtocolFile): PDProtocolFile { return { ...fileData, 'designer-application': { ...fileData['designer-application'] }, } } export const migrateFile = (fileData: PDProtocolFile): PDProtocolFile => flow([ renameOrderedSteps, addInitialDeckSetupStep, updateStepFormKeys, replaceTCDStepsWithMoveLiquidStep, ])(fileData)
the_stack
import * as fs from "fs-extra"; import * as path from "path"; import { IEyeglass } from "../IEyeglass"; import * as debug from "../util/debug"; import { AssetSourceOptions } from "../util/Options"; import { isType, SassImplementation, SassTypeError, isSassMap, isSassString } from "../util/SassImplementation"; import type * as sass from "node-sass"; import { URI } from "../util/URI"; import AssetsCollection from "./AssetsCollection"; import { isPresent } from "../util/typescriptUtils"; import errorFor from "../util/errorFor"; type EnsureSymlinkSync = (srcFile: string, destLink: string) => void; /* eslint-disable-next-line @typescript-eslint/no-var-requires */ const ensureSymlink: EnsureSymlinkSync = require("ensure-symlink"); interface Resolution { path: string; query?: string; } type ResolverCallback = (error: unknown, result?: Resolution) => unknown; type Resolver = (assetFile: string, assetUri: string, cb: ResolverCallback) => void; type WrappedResolver = (assetFile: string, assetUri: string, fallback: Resolver, cb: ResolverCallback) => void; interface Resolves { resolve: Resolver; } type InstallerCallback = (error: unknown, dest?: string) => void; type Installer = (file: string, uri: string, cb: InstallerCallback) => void; type WrappedInstaller = (file: string, uri: string, fallback: Installer, cb: InstallerCallback) => void; interface Installs { install: Installer; } export default class Assets implements Resolves, Installs { // need types for sass utils // eslint-disable-next-line @typescript-eslint/no-explicit-any eyeglass: IEyeglass; /** * Assets declared by the application. */ collection: AssetsCollection; /** * Assets declared by eyeglass modules. */ moduleCollections: Array<AssetsCollection>; sassImpl: typeof sass; constructor(eyeglass: IEyeglass, sassImpl: SassImplementation) { this.sassImpl = sassImpl; this.eyeglass = eyeglass; // create a master collection this.collection = new AssetsCollection(eyeglass.options); // and keep a list of module collections this.moduleCollections = []; } /** * @see AssetsCollection#asAssetImport */ asAssetImport(name: string | undefined): string { return this.collection.asAssetImport(name); } /** * @see AssetsCollection#addSource */ addSource(src: string, opts: Partial<AssetSourceOptions>): AssetsCollection { return this.collection.addSource(src, opts); } /** * @see AssetsCollection#cacheKey */ cacheKey(name: string): string { return this.collection.cacheKey(name); } /** * creates a new AssetsCollection and adds the given source * @see #addSource * @param {String} src - the source directory * @param {Object} opts - the options * @returns {AssetsCollection} the instance of the AssetsCollection */ export(src: string, opts: AssetSourceOptions): AssetsCollection { let assets = new AssetsCollection(this.eyeglass.options); this.moduleCollections.push(assets); return assets.addSource(src, opts); } /** * resolves an asset given a uri * @param {SassMap} $assetsMap - the map of registered Sass assets * @param {SassString} $uri - the uri of the asset * @param {Function} cb - the callback that is invoked when the asset resolves */ resolveAsset($assetsMap: sass.types.Map, $uri: sass.types.Value, cb: (error: Error | null, uri?: string, file?: string) => unknown): void { let sass = this.eyeglass.options.eyeglass.engines.sass; let options = this.eyeglass.options.eyeglass; let assets = this.eyeglass.assets; if (!isType(sass, $uri, "string")) { cb(new SassTypeError(sass, "string", $uri)) return; } // get a URI instance let originalUri = $uri.getValue(); let uri = new URI(originalUri); // normalize the uri and resolve it let $data = this.resolveAssetDefaults($assetsMap, uri.getPath()); if ($data) { let filepath: string | undefined; let assetUri: string | undefined; for (let i = 0; i < $data.getLength(); i++) { let k = ($data.getKey(i) as sass.types.String).getValue(); let v = ($data.getValue(i) as sass.types.String).getValue(); if (k === "filepath") { filepath = v; } else if (k === "uri") { assetUri = v; } } // create the URI let fullUri = URI.join( options.httpRoot, options.assets.httpPrefix, assetUri ); assets.resolve(filepath!, fullUri, function(error, assetInfo) { if (error || !isPresent(assetInfo)) { cb(errorFor(error, "Unable to resolve asset")); } else { // if relativeTo is set if (options.assets.relativeTo) { // make the URI relative to the httpRoot + relativeTo path uri.setPath(path.relative( URI.join(options.httpRoot, options.assets.relativeTo), assetInfo.path )); } else { // otherwise, just update it to the path as is uri.setPath(assetInfo.path); } // if a query param was specified, append it to the uri query if (assetInfo.query) { uri.addQuery(assetInfo.query); } assets.install(filepath!, assetInfo.path, function(error, file) { if (error) { cb(errorFor(error, "Unable to install asset")); } else { if (file) { /* istanbul ignore next - don't test debug */ debug.assets && debug.assets( "%s resolved to %s with URI %s", originalUri, path.relative(options.root, file), uri.toString() ); } cb(null, uri.toString(), file); } }); } }); } else { cb(new Error("Asset not found: " + uri.getPath())); } } /** * resolves the asset uri * @param {String} assetFile - the source file path * @param {String} assetUri - the resolved uri path * @param {Function} cb - the callback to pass the resolved uri to */ resolve(_assetFile: string, assetUri: string, cb: ResolverCallback): void { cb(null, { path: assetUri }); } /** * wraps the current resolver with a custom resolver * @param {Function} resolver - the new resolver function */ resolver(resolver: WrappedResolver): void { let oldResolver: Resolver = this.resolve.bind(this); this.resolve = function(assetFile: string, assetUri: string, cb: ResolverCallback) { resolver(assetFile, assetUri, oldResolver, cb); }; } /** * installs the given asset * @param {String} file - the source file path to install from * @param {String} uri - the resolved uri path * @param {Function} cb - the callback invoked after the installation is successful */ install(file: string, uri: string, cb: InstallerCallback): void { let options = this.eyeglass.options.eyeglass; let httpRoot = options.httpRoot; if (options.buildDir) { // normalize the uri using the system OS path separator // and make it relative to the httpRoot uri = (new URI(uri)).getPath(path.sep, httpRoot); let dest = path.join(options.buildDir, uri); this.eyeglass.once(`install:${dest}`, () => { try { if (options.installWithSymlinks) { fs.mkdirpSync(path.dirname(dest)); ensureSymlink(file, dest); debug.assets && debug.assets( "symlinked %s to %s", file, dest ); } else { // we explicitly use copySync rather than copy to avoid starving system resources fs.copySync(file, dest); debug.assets && debug.assets( "copied %s to %s", file, dest ); } cb(null, dest); } catch (error) { cb(errorFor(error, `Failed to install asset from ${file}:\n`)); } }, () => { cb(null, dest); }); } else { cb(null, file); } } /** * wraps the current installer with a custom installer * @param {Function} installer - the new installer function */ installer(installer: WrappedInstaller): void { let oldInstaller: Installer = this.install.bind(this); this.install = function(assetFile, assetUri, cb) { installer(assetFile, assetUri, oldInstaller, cb); }; } // need types for sass utils // eslint-disable-next-line @typescript-eslint/no-explicit-any private resolveAssetDefaults($registeredAssetsMap: sass.types.Map, relativePath: string): sass.types.Map | undefined { let appAssets: sass.types.Map | undefined; let moduleAssets: sass.types.Map | undefined; let moduleName: string | undefined, moduleRelativePath: string | undefined; let slashAt = relativePath.indexOf("/"); if (slashAt > 0) { moduleName = relativePath.substring(0,slashAt); moduleRelativePath = relativePath.substring(slashAt + 1) } let size = $registeredAssetsMap.getLength(); for (let i = 0; i < size; i++) { let k = $registeredAssetsMap.getKey(i); if (k === this.sassImpl.types.Null.NULL) { let v = $registeredAssetsMap.getValue(i); if (isSassMap(this.sassImpl, v)) { appAssets = v; } } else if (isSassString(this.sassImpl, k) && k.getValue() === moduleName) { let v = $registeredAssetsMap.getValue(i); if (isSassMap(this.sassImpl, v)) { moduleAssets = v; } } } if (appAssets) { let size = appAssets.getLength(); for (let i = 0; i < size; i++) { let k = appAssets.getKey(i); if (isSassString(this.sassImpl, k) && k.getValue() === relativePath) { let v = appAssets.getValue(i); if (isSassMap(this.sassImpl, v)) { return v; } } } } if (moduleAssets) { let size = moduleAssets.getLength(); for (let i = 0; i < size; i++) { let k = moduleAssets.getKey(i); if (isSassString(this.sassImpl, k) && k.getValue() === moduleRelativePath) { let v = moduleAssets.getValue(i); if (isSassMap(this.sassImpl, v)) { return v; } } } } return; } }
the_stack
import { IStorage } from "../core/interfaces/IStorage"; import type { NetworkOrSignerOrProvider, TransactionResult, TransactionResultWithId, } from "../core/types"; import { Erc721BatchMintable } from "../core/classes/erc-721-batch-mintable"; import { Erc721Enumerable } from "../core/classes/erc-721-enumerable"; import { Erc721Mintable } from "../core/classes/erc-721-mintable"; import { Erc721Supply } from "../core/classes/erc-721-supply"; import { TokenErc721ContractSchema } from "../schema/contracts/token-erc721"; import { ContractWrapper } from "../core/classes/contract-wrapper"; import { TokenERC721 } from "contracts"; import { SDKOptions } from "../schema/sdk-options"; import { ContractMetadata } from "../core/classes/contract-metadata"; import { ContractRoles } from "../core/classes/contract-roles"; import { ContractRoyalty } from "../core/classes/contract-royalty"; import { Erc721 } from "../core/classes/erc-721"; import { ContractPrimarySale } from "../core/classes/contract-sales"; import { ContractEncoder } from "../core/classes/contract-encoder"; import { Erc721SignatureMinting } from "../core/classes/erc-721-signature-minting"; import { ContractInterceptor } from "../core/classes/contract-interceptor"; import { ContractEvents } from "../core/classes/contract-events"; import { ContractPlatformFee } from "../core/classes/contract-platform-fee"; import { getRoleHash } from "../common"; import { BigNumber, BigNumberish, constants } from "ethers"; import { NFTMetadataOrUri, NFTMetadataOwner } from "../schema"; import { QueryAllParams } from "../types"; import { GasCostEstimator } from "../core/classes/gas-cost-estimator"; import { ContractAnalytics } from "../core/classes/contract-analytics"; /** * Create a collection of one-of-one NFTs. * * @example * * ```javascript * import { ThirdwebSDK } from "@thirdweb-dev/sdk"; * * const sdk = new ThirdwebSDK("rinkeby"); * const contract = sdk.getNFTCollection("{{contract_address}}"); * ``` * * @public */ export class NFTCollection extends Erc721<TokenERC721> { static contractType = "nft-collection" as const; static contractRoles = ["admin", "minter", "transfer"] as const; static contractAbi = require("../../abis/TokenERC721.json"); /** * @internal */ static schema = TokenErc721ContractSchema; public metadata: ContractMetadata<TokenERC721, typeof NFTCollection.schema>; public roles: ContractRoles< TokenERC721, typeof NFTCollection.contractRoles[number] >; public encoder: ContractEncoder<TokenERC721>; public estimator: GasCostEstimator<TokenERC721>; public events: ContractEvents<TokenERC721>; public sales: ContractPrimarySale<TokenERC721>; public platformFees: ContractPlatformFee<TokenERC721>; /** * @internal */ public analytics: ContractAnalytics<TokenERC721>; /** * Configure royalties * @remarks Set your own royalties for the entire contract or per token * @example * ```javascript * // royalties on the whole contract * contract.royalties.setDefaultRoyaltyInfo({ * seller_fee_basis_points: 100, // 1% * fee_recipient: "0x..." * }); * // override royalty for a particular token * contract.royalties.setTokenRoyaltyInfo(tokenId, { * seller_fee_basis_points: 500, // 5% * fee_recipient: "0x..." * }); * ``` */ public royalties: ContractRoyalty<TokenERC721, typeof NFTCollection.schema>; /** * Signature Minting * @remarks Generate dynamic NFTs with your own signature, and let others mint them using that signature. * @example * ```javascript * // see how to craft a payload to sign in the `contract.signature.generate()` documentation * const signedPayload = contract.signature.generate(payload); * * // now anyone can mint the NFT * const tx = contract.signature.mint(signedPayload); * const receipt = tx.receipt; // the mint transaction receipt * const mintedId = tx.id; // the id of the NFT minted * ``` */ public signature: Erc721SignatureMinting; /** * @internal */ public interceptor: ContractInterceptor<TokenERC721>; private _mint = this.mint as Erc721Mintable; private _batchMint = this._mint.batch as Erc721BatchMintable; private _query = this.query as Erc721Supply; private _owned = this._query.owned as Erc721Enumerable; constructor( network: NetworkOrSignerOrProvider, address: string, storage: IStorage, options: SDKOptions = {}, contractWrapper = new ContractWrapper<TokenERC721>( network, address, NFTCollection.contractAbi, options, ), ) { super(contractWrapper, storage, options); this.metadata = new ContractMetadata( this.contractWrapper, NFTCollection.schema, this.storage, ); this.roles = new ContractRoles( this.contractWrapper, NFTCollection.contractRoles, ); this.royalties = new ContractRoyalty(this.contractWrapper, this.metadata); this.sales = new ContractPrimarySale(this.contractWrapper); this.encoder = new ContractEncoder(this.contractWrapper); this.estimator = new GasCostEstimator(this.contractWrapper); this.signature = new Erc721SignatureMinting( this.contractWrapper, this.roles, this.storage, ); this.analytics = new ContractAnalytics(this.contractWrapper); this.events = new ContractEvents(this.contractWrapper); this.platformFees = new ContractPlatformFee(this.contractWrapper); this.interceptor = new ContractInterceptor(this.contractWrapper); } /** ****************************** * READ FUNCTIONS *******************************/ /** * Get All Minted NFTs * * @remarks Get all the data associated with every NFT in this contract. * * By default, returns the first 100 NFTs, use queryParams to fetch more. * * @example * ```javascript * const nfts = await contract.getAll(); * console.log(nfts); * ``` * @param queryParams - optional filtering to only fetch a subset of results. * @returns The NFT metadata for all NFTs queried. */ public async getAll( queryParams?: QueryAllParams, ): Promise<NFTMetadataOwner[]> { return this._query.all(queryParams); } /** * Get Owned NFTs * * @remarks Get all the data associated with the NFTs owned by a specific wallet. * * @example * ```javascript * // Address of the wallet to get the NFTs of * const address = "{{wallet_address}}"; * const nfts = await contract.getOwned(address); * console.log(nfts); * ``` * @param walletAddress - the wallet address to query, defaults to the connected wallet * @returns The NFT metadata for all NFTs in the contract. */ public async getOwned(walletAddress?: string): Promise<NFTMetadataOwner[]> { return this._owned.all(walletAddress); } /** * Get all token ids of NFTs owned by a specific wallet. * @param walletAddress - the wallet address to query, defaults to the connected wallet */ public async getOwnedTokenIds(walletAddress?: string): Promise<BigNumber[]> { return this._owned.tokenIds(walletAddress); } /** * Get the total count NFTs minted in this contract */ public async totalSupply() { return this._query.totalCirculatingSupply(); } /** * Get whether users can transfer NFTs from this contract */ public async isTransferRestricted(): Promise<boolean> { const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole( getRoleHash("transfer"), constants.AddressZero, ); return !anyoneCanTransfer; } /** ****************************** * WRITE FUNCTIONS *******************************/ /** * Mint a unique NFT * * @remarks Mint a unique NFT to a specified wallet. * * @example * ```javascript* * // Custom metadata of the NFT, note that you can fully customize this metadata with other properties. * const metadata = { * name: "Cool NFT", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }; * * const tx = await contract.mintToSelf(metadata); * const receipt = tx.receipt; // the transaction receipt * const tokenId = tx.id; // the id of the NFT minted * const nft = await tx.data(); // (optional) fetch details of minted NFT * ``` */ public async mintToSelf( metadata: NFTMetadataOrUri, ): Promise<TransactionResultWithId<NFTMetadataOwner>> { const signerAddress = await this.contractWrapper.getSignerAddress(); return this._mint.to(signerAddress, metadata); } /** * Mint a unique NFT * * @remarks Mint a unique NFT to a specified wallet. * * @example * ```javascript * // Address of the wallet you want to mint the NFT to * const walletAddress = "{{wallet_address}}"; * * // Custom metadata of the NFT, note that you can fully customize this metadata with other properties. * const metadata = { * name: "Cool NFT", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }; * * const tx = await contract.mintTo(walletAddress, metadata); * const receipt = tx.receipt; // the transaction receipt * const tokenId = tx.id; // the id of the NFT minted * const nft = await tx.data(); // (optional) fetch details of minted NFT * ``` */ public async mintTo( walletAddress: string, metadata: NFTMetadataOrUri, ): Promise<TransactionResultWithId<NFTMetadataOwner>> { return this._mint.to(walletAddress, metadata); } /** * Mint Many unique NFTs * * @remarks Mint many unique NFTs at once to the connected wallet * * @example * ```javascript* * // Custom metadata of the NFTs you want to mint. * const metadatas = [{ * name: "Cool NFT #1", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }, { * name: "Cool NFT #2", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/other/image.png"), * }]; * * const tx = await contract.mintBatch(metadatas); * const receipt = tx[0].receipt; // same transaction receipt for all minted NFTs * const firstTokenId = tx[0].id; // token id of the first minted NFT * const firstNFT = await tx[0].data(); // (optional) fetch details of the first minted NFT * ``` */ public async mintBatch( metadata: NFTMetadataOrUri[], ): Promise<TransactionResultWithId<NFTMetadataOwner>[]> { const signerAddress = await this.contractWrapper.getSignerAddress(); return this._batchMint.to(signerAddress, metadata); } /** * Mint Many unique NFTs * * @remarks Mint many unique NFTs at once to a specified wallet. * * @example * ```javascript * // Address of the wallet you want to mint the NFT to * const walletAddress = "{{wallet_address}}"; * * // Custom metadata of the NFTs you want to mint. * const metadatas = [{ * name: "Cool NFT #1", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }, { * name: "Cool NFT #2", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/other/image.png"), * }]; * * const tx = await contract.mintBatchTo(walletAddress, metadatas); * const receipt = tx[0].receipt; // same transaction receipt for all minted NFTs * const firstTokenId = tx[0].id; // token id of the first minted NFT * const firstNFT = await tx[0].data(); // (optional) fetch details of the first minted NFT * ``` */ public async mintBatchTo( walletAddress: string, metadata: NFTMetadataOrUri[], ): Promise<TransactionResultWithId<NFTMetadataOwner>[]> { return this._batchMint.to(walletAddress, metadata); } /** * Burn a single NFT * @param tokenId - the token Id to burn * * @example * ```javascript * const result = await contract.burn(tokenId); * ``` */ public async burn(tokenId: BigNumberish): Promise<TransactionResult> { return { receipt: await this.contractWrapper.sendTransaction("burn", [tokenId]), }; } }
the_stack
export interface ParsedUrlQuery { [key: string]: string | string[] | undefined; } interface ParseOptions { /** The function to use when decoding percent-encoded characters in the query string. */ decodeURIComponent?: (string: string) => string; /** Specifies the maximum number of keys to parse. */ maxKeys?: number; } export const hexTable = new Array(256); for (let i = 0; i < 256; ++i) { hexTable[i] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); } function charCodes(str: string): number[] { const ret = new Array(str.length); for (let i = 0; i < str.length; ++i) { ret[i] = str.charCodeAt(i); } return ret; } function addKeyVal( obj: ParsedUrlQuery, key: string, value: string, keyEncoded: boolean, valEncoded: boolean, decode: (encodedURIComponent: string) => string, ): void { if (key.length > 0 && keyEncoded) { key = decode(key); } if (value.length > 0 && valEncoded) { value = decode(value); } if (obj[key] === undefined) { obj[key] = value; } else { const curValue = obj[key]; // A simple Array-specific property check is enough here to // distinguish from a string value and is faster and still safe // since we are generating all of the values being assigned. if ((curValue as string[]).pop) { (curValue as string[])[curValue!.length] = value; } else { obj[key] = [curValue as string, value]; } } } // deno-fmt-ignore const isHexTable = new Int8Array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 64 - 79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80 - 95 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 96 - 111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 112 - 127 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128 ... 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ... 256 ]); /** * Parses a URL query string into a collection of key and value pairs. * @param str The URL query string to parse * @param sep The substring used to delimit key and value pairs in the query string. Default: '&'. * @param eq The substring used to delimit keys and values in the query string. Default: '='. * @param options The parse options */ export function parse( str: string, sep = "&", eq = "=", { decodeURIComponent = unescape, maxKeys = 1000 }: ParseOptions = {}, ): ParsedUrlQuery { const obj: ParsedUrlQuery = Object.create(null); if (typeof str !== "string" || str.length === 0) { return obj; } const sepCodes = (!sep ? [38] /* & */ : charCodes(String(sep))); const eqCodes = (!eq ? [61] /* = */ : charCodes(String(eq))); const sepLen = sepCodes.length; const eqLen = eqCodes.length; let pairs = 2000; if (maxKeys) { // -1 is used in place of a value like Infinity for meaning // "unlimited pairs" because of additional checks V8 (at least as of v5.4) // has to do when using variables that contain values like Infinity. Since // `pairs` is always decremented and checked explicitly for 0, -1 works // effectively the same as Infinity, while providing a significant // performance boost. pairs = maxKeys > 0 ? maxKeys : -1; } let decode = unescape; if (decodeURIComponent) { decode = decodeURIComponent; } const customDecode = (decode !== unescape); let lastPos = 0; let sepIdx = 0; let eqIdx = 0; let key = ""; let value = ""; let keyEncoded = customDecode; let valEncoded = customDecode; const plusChar = (customDecode ? "%20" : " "); let encodeCheck = 0; for (let i = 0; i < str.length; ++i) { const code = str.charCodeAt(i); // Try matching key/value pair separator (e.g. '&') if (code === sepCodes[sepIdx]) { if (++sepIdx === sepLen) { // Key/value pair separator match! const end = i - sepIdx + 1; if (eqIdx < eqLen) { // We didn't find the (entire) key/value separator if (lastPos < end) { // Treat the substring as part of the key instead of the value key += str.slice(lastPos, end); } else if (key.length === 0) { // We saw an empty substring between separators if (--pairs === 0) { return obj; } lastPos = i + 1; sepIdx = eqIdx = 0; continue; } } else if (lastPos < end) { value += str.slice(lastPos, end); } addKeyVal(obj, key, value, keyEncoded, valEncoded, decode); if (--pairs === 0) { return obj; } key = value = ""; encodeCheck = 0; lastPos = i + 1; sepIdx = eqIdx = 0; } } else { sepIdx = 0; // Try matching key/value separator (e.g. '=') if we haven't already if (eqIdx < eqLen) { if (code === eqCodes[eqIdx]) { if (++eqIdx === eqLen) { // Key/value separator match! const end = i - eqIdx + 1; if (lastPos < end) { key += str.slice(lastPos, end); } encodeCheck = 0; lastPos = i + 1; } continue; } else { eqIdx = 0; if (!keyEncoded) { // Try to match an (valid) encoded byte once to minimize unnecessary // calls to string decoding functions if (code === 37 /* % */) { encodeCheck = 1; continue; } else if (encodeCheck > 0) { if (isHexTable[code] === 1) { if (++encodeCheck === 3) { keyEncoded = true; } continue; } else { encodeCheck = 0; } } } } if (code === 43 /* + */) { if (lastPos < i) { key += str.slice(lastPos, i); } key += plusChar; lastPos = i + 1; continue; } } if (code === 43 /* + */) { if (lastPos < i) { value += str.slice(lastPos, i); } value += plusChar; lastPos = i + 1; } else if (!valEncoded) { // Try to match an (valid) encoded byte (once) to minimize unnecessary // calls to string decoding functions if (code === 37 /* % */) { encodeCheck = 1; } else if (encodeCheck > 0) { if (isHexTable[code] === 1) { if (++encodeCheck === 3) { valEncoded = true; } } else { encodeCheck = 0; } } } } } // Deal with any leftover key or value data if (lastPos < str.length) { if (eqIdx < eqLen) { key += str.slice(lastPos); } else if (sepIdx < sepLen) { value += str.slice(lastPos); } } else if (eqIdx === 0 && key.length === 0) { // We ended on an empty substring return obj; } addKeyVal(obj, key, value, keyEncoded, valEncoded, decode); return obj; } interface StringifyOptions { /** The function to use when converting URL-unsafe characters to percent-encoding in the query string. */ encodeURIComponent?: (string: string) => string; } export function encodeStr( str: string, noEscapeTable: number[], hexTable: string[], ): string { const len = str.length; if (len === 0) return ""; let out = ""; let lastPos = 0; for (let i = 0; i < len; i++) { let c = str.charCodeAt(i); // ASCII if (c < 0x80) { if (noEscapeTable[c] === 1) continue; if (lastPos < i) out += str.slice(lastPos, i); lastPos = i + 1; out += hexTable[c]; continue; } if (lastPos < i) out += str.slice(lastPos, i); // Multi-byte characters ... if (c < 0x800) { lastPos = i + 1; out += hexTable[0xc0 | (c >> 6)] + hexTable[0x80 | (c & 0x3f)]; continue; } if (c < 0xd800 || c >= 0xe000) { lastPos = i + 1; out += hexTable[0xe0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3f)] + hexTable[0x80 | (c & 0x3f)]; continue; } // Surrogate pair ++i; // This branch should never happen because all URLSearchParams entries // should already be converted to USVString. But, included for // completion's sake anyway. if (i >= len) throw new Deno.errors.InvalidData("invalid URI"); const c2 = str.charCodeAt(i) & 0x3ff; lastPos = i + 1; c = 0x10000 + (((c & 0x3ff) << 10) | c2); out += hexTable[0xf0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3f)] + hexTable[0x80 | ((c >> 6) & 0x3f)] + hexTable[0x80 | (c & 0x3f)]; } if (lastPos === 0) return str; if (lastPos < len) return out + str.slice(lastPos); return out; } /** * Produces a URL query string from a given obj by iterating through the object's "own properties". * @param obj The object to serialize into a URL query string. * @param sep The substring used to delimit key and value pairs in the query string. Default: '&'. * @param eq The substring used to delimit keys and values in the query string. Default: '='. * @param options The stringify options */ export function stringify( // deno-lint-ignore no-explicit-any obj: Record<string, any>, sep = "&", eq = "=", { encodeURIComponent = escape }: StringifyOptions = {}, ): string { const final = []; for (const entry of Object.entries(obj)) { if (Array.isArray(entry[1])) { for (const val of entry[1]) { final.push(encodeURIComponent(entry[0]) + eq + encodeURIComponent(val)); } } else if (typeof entry[1] !== "object" && entry[1] !== undefined) { final.push(entry.map(encodeURIComponent).join(eq)); } else { final.push(encodeURIComponent(entry[0]) + eq); } } return final.join(sep); } /** Alias of querystring.parse() */ export const decode = parse; /** Alias of querystring.stringify() */ export const encode = stringify; export const unescape = decodeURIComponent; export const escape = encodeURIComponent; export default { parse, encodeStr, stringify, hexTable, decode, encode, unescape, escape, };
the_stack
const VERSION = 3 const VERSION_ERROR = `DIMBIN::#0 当前程序支持版本为 ${VERSION}, 你使用的数据版本为 ` const ENDIAN_ERROR = 'DIMBIN::#1 当前版本仅支持小端数据' // types map const TYPES = [ Int8Array, // 0 Uint8Array, // 1 Uint8ClampedArray, // 2 Int16Array, // 3 Uint16Array, // 4 Int32Array, // 5 Uint32Array, // 6 Float32Array, // 7 Float64Array, // 8 ] TYPES[127] = Uint8Array // DIMBIN 嵌套 enum TYPES_MAP { Int8Array, // 0 Uint8Array, // 1 Uint8ClampedArray, // 2 Int16Array, // 3 Uint16Array, // 4 Int32Array, // 5 Uint32Array, // 6 Float32Array, // 7 Float64Array, // 8 DIMBIN = 127, } // interface export interface Meta { version: number magicNum: number segMetaBytes: number segMetaStart: number len: number bigEndian: boolean } interface DimensionalArray extends Array<number | DimensionalArray | TypedArray> {} interface MultiDimensionalArray extends Array<DimensionalArray | TypedArray> {} // ✨ /** * serialize a MultiDimensionalArray into a ArrayBuffer * @param data <MultiDimensionalArray> * @param magicNumber [0] <number> */ export function serialize(data: MultiDimensionalArray, magicNumber = 0): ArrayBuffer { // 保证第一维是数组 if (!data || !data.forEach) throw new Error('DIMBIN::#1 格式不支持, 传入数据应为2维(或更高维)数组') const meta: Meta = { version: VERSION, magicNum: magicNumber, segMetaBytes: 9, segMetaStart: 15, len: data.length, bigEndian: false, } const segments = [] let metaStart = meta.segMetaStart let dataStart = meta.segMetaStart + meta.segMetaBytes * meta.len data.forEach(seg => { // 保证第二维是数组 if (!_isArray(seg)) throw new Error('DIMBIN::#2 格式不支持, 传入数据应为2维(或更高维)数组') // segment meta let type, lendth, byteLength, data if (_isArray(seg[0])) { // 如果第三维还是数组,则需要嵌套DIMBIN data = new Uint8Array(serialize(seg as MultiDimensionalArray)) // console.log(data, parse(data.buffer)) type = TYPES_MAP['DIMBIN'] lendth = data.byteLength byteLength = data.byteLength // @NOTE 内存字节对齐 // http://t.cn/Rgac3eJ // 由于嵌套DIMBIN中可能会有各种数据结构,因此需要与8对齐(最小公倍数) const chink = dataStart % 8 if (chink > 0) { dataStart += 8 - chink } } else { // 一个分段的数据 // 如果是JS Array,则转换成 Float32Array if (!isTypedArray(seg)) { seg = new Float32Array(seg as Array<number>) } // @NOTE 内存字节对齐 // http://t.cn/Rgac3eJ const chink = dataStart % seg.BYTES_PER_ELEMENT if (chink > 0) { dataStart += seg.BYTES_PER_ELEMENT - chink } type = TYPES_MAP[seg.constructor.name] lendth = seg.length // 这里要考虑bufferview自己的范围 byteLength = seg.byteLength // seg.buffer.byteLength data = seg } segments.push({ type, metaStart, dataStart, lendth, byteLength, data, }) metaStart += 9 // 一个segment的信息位 dataStart += byteLength }) const arrayBuffer = new ArrayBuffer(dataStart + 1) const view = new DataView(arrayBuffer) // meta view.setUint8(0, meta.version) view.setUint8(1, meta.bigEndian ? 1 : 0) view.setUint8(2, meta.segMetaBytes) view.setUint32(3, meta.segMetaStart, true) // 小端 view.setFloat32(7, meta.magicNum, true) // 小端 view.setUint32(11, meta.len, true) // 小端 // segments segments.forEach(seg => { // meta view.setUint8(seg.metaStart, seg.type) view.setUint32(seg.metaStart + 1, seg.dataStart, true) view.setUint32(seg.metaStart + 5, seg.lendth, true) // data const target = new TYPES[seg.type](arrayBuffer, seg.dataStart, seg.lendth) target.set(seg.data) }) return arrayBuffer } /** * parse parse a DIMBIN buffer into a multiDimensionalArray * @param buffer <ArrayBuffer|Buffer|DataView> */ export function parse(buffer: ArrayBuffer | Buffer | DataView): MultiDimensionalArray { const view = buffer instanceof DataView ? buffer : new DataView(buffer) buffer = view.buffer const meta = getMeta(view) if (meta.version !== 3) throw new Error(VERSION_ERROR + meta.version) if (meta.bigEndian) throw new Error(ENDIAN_ERROR) const result = [] let metaStart = meta.segMetaStart for (let i = 0; i < meta.len; i++) { const type = view.getUint8(metaStart) const dataStart = view.getUint32(metaStart + 1, true) const lendth = view.getUint32(metaStart + 5, true) if (type === 127) { result.push(parse(new DataView(buffer, dataStart + view.byteOffset, lendth))) } else { result.push(new TYPES[type](buffer, dataStart + view.byteOffset, lendth)) } metaStart += meta.segMetaBytes } return result } /** * read meta data from a DIMBIN buffer * @param buffer <ArrayBuffer|Buffer|DataView> */ export function getMeta(buffer: ArrayBuffer | Buffer | DataView): Meta { const view = buffer instanceof DataView ? buffer : new DataView(buffer) const version = view.getUint8(0) const bigEndian = !!view.getUint8(1) if (version !== 3) console.error(VERSION_ERROR + version) if (bigEndian) console.error(ENDIAN_ERROR) return { version, bigEndian, segMetaBytes: view.getUint8(2), segMetaStart: view.getUint32(3, true), // 小端 magicNum: view.getFloat32(7, true), // 小端 len: view.getUint32(11, true), // 小端 } } // // polyfill export type TypedArray = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array // TS 类型保护 function isTypedArray(sth: any): sth is TypedArray { return !!sth.BYTES_PER_ELEMENT } // test array-like obj function _isArray(d: any): boolean { if (!d) return false if (!Array.isArray(d) && !d.BYTES_PER_ELEMENT) return false return true } // // non-numberical value support // - string /** * serialize an array of strings into Uint8Array, which you can use in DIMBIN.parse * @param strs <string[]> */ export function stringsSerialize(strs: string[]): Uint8Array { 'use strict' let i = 0 const length = strs.length // 2ms let sum = 0 while (i < length) { sum += strs[i].length i++ } // version 4 | length 4 | segments 4 * len | utf8 const buffer = new ArrayBuffer(4 + 4 + length * 4 + sum * 4) // 按32位分配,这里不见得用得到32位,输出前裁掉 const view = new DataView(buffer) view.setUint32(0, 0, true) view.setUint32(4, length, true) // 5ms const utf8 = new Uint8Array(buffer, 4 + 4 + length * 4, sum * 4) // 用不完 i = 0 let pointer = 0 while (i < length) { const str = strs[i] // view.setUint32(8 + 4 * i, str.length) const start = pointer let j = 0 while (j < str.length) { // buffer[pointer] = str.charCodeAt(j) // 7ms const code = str.charCodeAt(j++) // ~0ms // utf16 -> unicode let codePoint if (code < 0xd800 || code >= 0xdc00) { codePoint = code } else { const b = str.charCodeAt(j++) codePoint = (code << 10) + b + (0x10000 - (0xd800 << 10) - 0xdc00) } // unicode -> utf8 // const utf8 = [] if (codePoint < 0x80) { // 7ms utf8[pointer++] = codePoint // utf8.push(codePoint) } else { if (codePoint < 0x800) { utf8[pointer++] = ((codePoint >> 6) & 0x1f) | 0xc0 } else { if (codePoint < 0x10000) { utf8[pointer++] = ((codePoint >> 12) & 0x0f) | 0xe0 } else { utf8[pointer++] = ((codePoint >> 18) & 0x07) | 0xf0 utf8[pointer++] = ((codePoint >> 12) & 0x3f) | 0x80 } utf8[pointer++] = ((codePoint >> 6) & 0x3f) | 0x80 } utf8[pointer++] = (codePoint & 0x3f) | 0x80 } // 17ms // const codePoint = str.codePointAt(j++) // 26ms // buffer[pointer++] = str.charCodeAt(j) // 90ms // codes.push(code) } const end = pointer view.setUint32(8 + 4 * i, end - start, true) i++ } return new Uint8Array(buffer, 0, 4 + 4 + length * 4 + pointer) } /** * parse the Uint8Array generated by stringsSerialize back into array of strings * @param uint8array <Uint8Array> */ export function stringsParse(uint8array: Uint8Array): string[] { 'use strict' // version (4 bytes) | length (4 bytes) | segments (4 * len bytes) | utf8 const view = new DataView(uint8array.buffer, uint8array.byteOffset, uint8array.byteLength) const version = view.getUint32(0, true) const length = view.getUint32(4, true) const utf8 = new Uint8Array(uint8array.buffer, uint8array.byteOffset + 4 + 4 + length * 4) const strs = [] let i = 0 let pointer = 0 let end = 0 while (i < length) { const len = view.getUint32(8 + 4 * i++, true) const isLongString = len > 20 const codePoints = [] let result = '' end += len while (pointer < end) { let codePoint = 0 // UTF-8 -> unicode const a = utf8[pointer++] if (a < 0xc0) { codePoint = a } else { const b = utf8[pointer++] if (a < 0xe0) { codePoint = ((a & 0x1f) << 6) | (b & 0x3f) } else { const c = utf8[pointer++] if (a < 0xf0) { codePoint = ((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f) } else { const d = utf8[pointer++] codePoint = ((a & 0x07) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f) } } } // unicode -> UTF-16 if (isLongString) { codePoints.push(codePoint) } else { // 该方案在处理短字符串时性能更好 if (codePoint < 0x10000) { result += String.fromCharCode(codePoint) } else { codePoint -= 0x10000 result += String.fromCharCode( (codePoint >> 10) + 0xd800, (codePoint & ((1 << 10) - 1)) + 0xdc00 ) } } } if (isLongString) { // 该方案在处理长字符串时性能更好 strs.push(String.fromCodePoint.apply(null, codePoints)) } else { strs.push(result) } } return strs } // - boolean function packBooleans(b0, b1, b2, b3, b4, b5, b6, b7): number { 'use strict' return ( (b0 || 0) + (b1 || 0) * 2 + (b2 || 0) * 4 + (b3 || 0) * 8 + (b4 || 0) * 16 + (b5 || 0) * 32 + (b6 || 0) * 64 + (b7 || 0) * 128 ) } /** * serialize an array of booleans into Uint8Array, which you can use in DIMBIN.parse * @param booleans */ export function booleansSerialize(booleans: boolean[]): Uint8Array { 'use strict' const length = booleans.length // version 4 | length 4 | bits const buffer = new ArrayBuffer(4 + 4 + Math.ceil(length / 8)) const view = new DataView(buffer) view.setUint32(0, 0, true) view.setUint32(4, length, true) const masks = new Uint8Array(buffer, 8) for (let i = 0; i < length; i += 8) { masks[i / 8] = packBooleans( booleans[i + 0], booleans[i + 1], booleans[i + 2], booleans[i + 3], booleans[i + 4], booleans[i + 5], booleans[i + 6], booleans[i + 7] ) } return new Uint8Array(buffer) } /** * parse the Uint8Array generated by booleansSerialize back into array of booleans * @param uint8array <Uint8Array> */ export function booleansParse(uint8array: Uint8Array): boolean[] { 'use strict' // version 4 | length 4 | bits const view = new DataView(uint8array.buffer, uint8array.byteOffset, uint8array.byteLength) const version = view.getUint32(0, true) const length = view.getUint32(4, true) const masks = new Uint8Array(uint8array.buffer, uint8array.byteOffset + 4 + 4) const booleans = [] const maskLen = Math.ceil(length / 8) for (let i = 0; i < maskLen; i++) { let mask = masks[i] for (let j = 0; j < 8; booleans.push(!!(mask & 1)), mask >>>= 1, j++); } const paddingLen = booleans.length - length for (let i = 0; i < paddingLen; i++) { booleans.pop() } return booleans } // export const DIMBIN = { version: VERSION, // parse, serialize, getMeta, // stringsSerialize, stringsParse, booleansSerialize, booleansParse, } export default DIMBIN
the_stack
import { Observable } from "rxjs"; import { map } from "rxjs/operators"; import { ImageCache } from "./ImageCache"; import { NavigationEdge } from "./edge/interfaces/NavigationEdge"; import { NavigationEdgeStatus } from "./interfaces/NavigationEdgeStatus"; import { CoreImageEnt } from "../api/ents/CoreImageEnt"; import { SpatialImageEnt } from "../api/ents/SpatialImageEnt"; import { LngLat } from "../api/interfaces/LngLat"; import { MeshContract } from "../api/contracts/MeshContract"; /** * @class Image * * @classdesc Represents a image in the navigation graph. * * Explanation of position and bearing properties: * * When images are uploaded they will have GPS information in the EXIF, this is what * is called `originalLngLat` {@link Image.originalLngLat}. * * When Structure from Motions has been run for a image a `computedLngLat` that * differs from the `originalLngLat` will be created. It is different because * GPS positions are not very exact and SfM aligns the camera positions according * to the 3D reconstruction {@link Image.computedLngLat}. * * At last there exist a `lngLat` property which evaluates to * the `computedLngLat` from SfM if it exists but falls back * to the `originalLngLat` from the EXIF GPS otherwise {@link Image.lngLat}. * * Everything that is done in in the Viewer is based on the SfM positions, * i.e. `computedLngLat`. That is why the smooth transitions go in the right * direction (nd not in strange directions because of bad GPS). * * E.g. when placing a marker in the Viewer it is relative to the SfM * position i.e. the `computedLngLat`. * * The same concept as above also applies to the compass angle (or bearing) properties * `originalCa`, `computedCa` and `ca`. */ export class Image { private _cache: ImageCache; private _core: CoreImageEnt; private _spatial: SpatialImageEnt; /** * Create a new image instance. * * @description Images are always created internally by the library. * Images can not be added to the library through any API method. * * @param {CoreImageEnt} core- Raw core image data. * @ignore */ constructor(core: CoreImageEnt) { if (!core) { throw new Error(`Incorrect core image data ${core}`); } this._cache = null; this._core = core; this._spatial = null; } /** * Get assets cached. * * @description The assets that need to be cached for this property * to report true are the following: fill properties, image and mesh. * The library ensures that the current image will always have the * assets cached. * * @returns {boolean} Value indicating whether all assets have been * cached. * * @ignore */ public get assetsCached(): boolean { return this._core != null && this._spatial != null && this._cache != null && this._cache.image != null && this._cache.mesh != null; } /** * Get cameraParameters. * * @description Will be undefined if SfM has * not been run. * * Camera type dependent parameters. * * For perspective and fisheye camera types, * the camera parameters array should be * constructed according to * * `[focal, k1, k2]` * * where focal is the camera focal length, * and k1, k2 are radial distortion parameters. * * For spherical camera type the camera * parameters are unset or emtpy array. * * @returns {Array<number>} The parameters * related to the camera type. */ public get cameraParameters(): number[] { return this._spatial.camera_parameters; } /** * Get cameraType. * * @description Will be undefined if SfM has not been run. * * @returns {string} The camera type that captured the image. */ public get cameraType(): string { return this._spatial.camera_type; } /** * Get capturedAt. * * @description Timestamp of the image capture date * and time represented as a Unix epoch timestamp in milliseconds. * * @returns {number} Timestamp when the image was captured. */ public get capturedAt(): number { return this._spatial.captured_at; } /** * Get clusterId. * * @returns {string} Globally unique id of the SfM cluster to which * the image belongs. */ public get clusterId(): string { return !!this._spatial.cluster ? this._spatial.cluster.id : null; } /** * Get clusterUrl. * * @returns {string} Url to the cluster reconstruction file. * * @ignore */ public get clusterUrl(): string { return !!this._spatial.cluster ? this._spatial.cluster.url : null; } /** * Get compassAngle. * * @description If the SfM computed compass angle exists it will * be returned, otherwise the original EXIF compass angle. * * @returns {number} Compass angle, measured in degrees * clockwise with respect to north. */ public get compassAngle(): number { return this._spatial.computed_compass_angle != null ? this._spatial.computed_compass_angle : this._spatial.compass_angle; } /** * Get complete. * * @description The library ensures that the current image will * always be full. * * @returns {boolean} Value indicating whether the image has all * properties filled. * * @ignore */ public get complete(): boolean { return this._spatial != null; } /** * Get computedAltitude. * * @description If SfM has not been run the computed altitude is * set to a default value of two meters. * * @returns {number} Altitude, in meters. */ public get computedAltitude(): number { return this._spatial.computed_altitude; } /** * Get computedCompassAngle. * * @description Will not be set if SfM has not been run. * * @returns {number} SfM computed compass angle, measured * in degrees clockwise with respect to north. */ public get computedCompassAngle(): number { return this._spatial.computed_compass_angle; } /** * Get computedLngLat. * * @description Will not be set if SfM has not been run. * * @returns {LngLat} SfM computed longitude, latitude in WGS84 datum, * measured in degrees. */ public get computedLngLat(): LngLat { return this._core.computed_geometry; } /** * Get creatorId. * * @description Note that the creator ID will not be set when using * the Mapillary API. * * @returns {string} Globally unique id of the user who uploaded * the image. */ public get creatorId(): string { return this._spatial.creator.id; } /** * Get creatorUsername. * * @description Note that the creator username will not be set when * using the Mapillary API. * * @returns {string} Username of the creator who uploaded * the image. */ public get creatorUsername(): string { return this._spatial.creator.username; } /** * Get exifOrientation. * * @returns {number} EXIF orientation of original image. */ public get exifOrientation(): number { return this._spatial.exif_orientation; } /** * Get height. * * @returns {number} Height of original image, not adjusted * for orientation. */ public get height(): number { return this._spatial.height; } /** * Get image. * * @description The image will always be set on the current image. * * @returns {HTMLImageElement} Cached image element of the image. */ public get image(): HTMLImageElement { return this._cache.image; } /** * Get image$. * * @returns {Observable<HTMLImageElement>} Observable emitting * the cached image when it is updated. * * @ignore */ public get image$(): Observable<HTMLImageElement> { return this._cache.image$; } /** * Get id. * * @returns {string} Globally unique id of the image. */ public get id(): string { return this._core.id; } /** * Get lngLat. * * @description If the SfM computed longitude, latitude exist * it will be returned, otherwise the original EXIF latitude * longitude. * * @returns {LngLat} Longitude, latitude in WGS84 datum, * measured in degrees. */ public get lngLat(): LngLat { return this._core.computed_geometry != null ? this._core.computed_geometry : this._core.geometry; } /** * Get merged. * * @returns {boolean} Value indicating whether SfM has been * run on the image and the image has been merged into a * connected component. */ public get merged(): boolean { return this._spatial != null && this._spatial.merge_id != null; } /** * Get mergeId. * * @description Will not be set if SfM has not yet been run on * image. * * @returns {stirng} Id of connected component to which image * belongs after the aligning merge. */ public get mergeId(): string { return this._spatial.merge_id; } /** * Get mesh. * * @description The mesh will always be set on the current image. * * @returns {MeshContract} SfM triangulated mesh of reconstructed * atomic 3D points. */ public get mesh(): MeshContract { return this._cache.mesh; } /** * Get originalAltitude. * * @returns {number} EXIF altitude, in meters, if available. */ public get originalAltitude(): number { return this._spatial.altitude; } /** * Get originalCompassAngle. * * @returns {number} Original EXIF compass angle, measured in * degrees. */ public get originalCompassAngle(): number { return this._spatial.compass_angle; } /** * Get originalLngLat. * * @returns {LngLat} Original EXIF longitude, latitude in * WGS84 datum, measured in degrees. */ public get originalLngLat(): LngLat { return this._core.geometry; } /** * Get ownerId. * * @returns {string} Globally unique id of the owner to which * the image belongs. If the image does not belong to an * owner the owner id will be undefined. */ public get ownerId(): string { return !!this._spatial.owner ? this._spatial.owner.id : null; } /** * Get private. * * @returns {boolean} Value specifying if image is accessible to * organization members only or to everyone. */ public get private(): boolean { return this._spatial.private; } /** * Get qualityScore. * * @returns {number} A number between zero and one * determining the quality of the image. Blurriness * (motion blur / out-of-focus), occlusion (camera * mount, ego vehicle, water-drops), windshield * reflections, bad illumination (exposure, glare), * and bad weather condition (fog, rain, snow) * affect the quality score. * * @description Value should be on the interval [0, 1]. */ public get qualityScore(): number { return this._spatial.quality_score; } /** * Get rotation. * * @description Will not be set if SfM has not been run. * * @returns {Array<number>} Rotation vector in angle axis representation. */ public get rotation(): number[] { return this._spatial.computed_rotation; } /** * Get scale. * * @description Will not be set if SfM has not been run. * * @returns {number} Scale of reconstruction the image * belongs to. */ public get scale(): number { return this._spatial.atomic_scale; } /** * Get sequenceId. * * @returns {string} Globally unique id of the sequence * to which the image belongs. */ public get sequenceId(): string { return !!this._core.sequence ? this._core.sequence.id : null; } /** * Get sequenceEdges. * * @returns {NavigationEdgeStatus} Value describing the status of the * sequence edges. * * @ignore */ public get sequenceEdges(): NavigationEdgeStatus { return this._cache.sequenceEdges; } /** * Get sequenceEdges$. * * @description Internal observable, should not be used as an API. * * @returns {Observable<NavigationEdgeStatus>} Observable emitting * values describing the status of the sequence edges. * * @ignore */ public get sequenceEdges$(): Observable<NavigationEdgeStatus> { return this._cache.sequenceEdges$; } /** * Get spatialEdges. * * @returns {NavigationEdgeStatus} Value describing the status of the * spatial edges. * * @ignore */ public get spatialEdges(): NavigationEdgeStatus { return this._cache.spatialEdges; } /** * Get spatialEdges$. * * @description Internal observable, should not be used as an API. * * @returns {Observable<NavigationEdgeStatus>} Observable emitting * values describing the status of the spatial edges. * * @ignore */ public get spatialEdges$(): Observable<NavigationEdgeStatus> { return this._cache.spatialEdges$; } /** * Get width. * * @returns {number} Width of original image, not * adjusted for orientation. */ public get width(): number { return this._spatial.width; } /** * Cache the image and mesh assets. * * @description The assets are always cached internally by the * library prior to setting a image as the current image. * * @returns {Observable<Image>} Observable emitting this image whenever the * load status has changed and when the mesh or image has been fully loaded. * * @ignore */ public cacheAssets$(): Observable<Image> { return this._cache .cacheAssets$(this._spatial, this.merged) .pipe( map((): Image => { return this; })); } /** * Cache the image asset. * * @description Use for caching a differently sized image than * the one currently held by the image. * * @returns {Observable<Image>} Observable emitting this image whenever the * load status has changed and when the mesh or image has been fully loaded. * * @ignore */ public cacheImage$(): Observable<Image> { return this._cache .cacheImage$(this._spatial) .pipe( map((): Image => { return this; })); } /** * Cache the sequence edges. * * @description The sequence edges are cached asynchronously * internally by the library. * * @param {Array<NavigationEdge>} edges - Sequence edges to cache. * @ignore */ public cacheSequenceEdges(edges: NavigationEdge[]): void { this._cache.cacheSequenceEdges(edges); } /** * Cache the spatial edges. * * @description The spatial edges are cached asynchronously * internally by the library. * * @param {Array<NavigationEdge>} edges - Spatial edges to cache. * @ignore */ public cacheSpatialEdges(edges: NavigationEdge[]): void { this._cache.cacheSpatialEdges(edges); } /** * Dispose the image. * * @description Disposes all cached assets. * @ignore */ public dispose(): void { if (this._cache != null) { this._cache.dispose(); this._cache = null; } this._core = null; this._spatial = null; } /** * Initialize the image cache. * * @description The image cache is initialized internally by * the library. * * @param {ImageCache} cache - The image cache to set as cache. * @ignore */ public initializeCache(cache: ImageCache): void { if (this._cache != null) { throw new Error(`Image cache already initialized (${this.id}).`); } this._cache = cache; } /** * Complete an image with spatial properties. * * @description The image is completed internally by * the library. * * @param {SpatialImageEnt} fill - The spatial image struct. * @ignore */ public makeComplete(fill: SpatialImageEnt): void { if (fill == null) { throw new Error("Fill can not be null."); } this._spatial = fill; } /** * Reset the sequence edges. * * @ignore */ public resetSequenceEdges(): void { this._cache.resetSequenceEdges(); } /** * Reset the spatial edges. * * @ignore */ public resetSpatialEdges(): void { this._cache.resetSpatialEdges(); } /** * Clears the image and mesh assets, aborts * any outstanding requests and resets edges. * * @ignore */ public uncache(): void { if (this._cache == null) { return; } this._cache.dispose(); this._cache = null; } }
the_stack
import DEMData from './dem_data'; import {RGBAImage} from '../util/image'; import {serialize, deserialize} from '../util/web_worker_transfer'; function createMockImage(height, width) { // RGBAImage passed to constructor has uniform 1px padding on all sides. height += 2; width += 2; const pixels = new Uint8Array(height * width * 4); for (let i = 0; i < pixels.length; i++) { pixels[i] = (i + 1) % 4 === 0 ? 1 : Math.floor(Math.random() * 256); } return new RGBAImage({height, width}, pixels); } function createMockClampImage(height, width) { const pixels = new Uint8ClampedArray(height * width * 4); for (let i = 0; i < pixels.length; i++) { pixels[i] = (i + 1) % 4 === 0 ? 1 : Math.floor(Math.random() * 256); } return new RGBAImage({height, width}, pixels); } describe('DEMData', () => { describe('constructor', () => { test('Uint8Array', () => { const imageData0 = createMockImage(4, 4); const dem = new DEMData('0', imageData0, 'mapbox'); expect(dem.uid).toBe('0'); expect(dem.dim).toBe(4); expect(dem.stride).toBe(6); }); test('Uint8ClampedArray', () => { const imageData0 = createMockClampImage(4, 4); const dem = new DEMData('0', imageData0, 'mapbox'); expect(dem).not.toBeNull(); expect(dem['uid']).toBe('0'); expect(dem['dim']).toBe(2); expect(dem['stride']).toBe(4); }); test('otherEncoding', () => { const spyOnWarnConsole = jest.spyOn(console, 'warn').mockImplementation(); const imageData0 = createMockImage(4, 4); new DEMData('0', imageData0, 'otherEncoding' as any); expect(spyOnWarnConsole).toHaveBeenCalledTimes(1); expect(spyOnWarnConsole.mock.calls).toEqual([['\"otherEncoding\" is not a valid encoding type. Valid types include \"mapbox\" and \"terrarium\".']]); }); }); }); describe('DEMData#backfillBorder with encoding', () => { describe('mabox encoding', () => { const dem0 = new DEMData('0', createMockImage(4, 4), 'mapbox'); const dem1 = new DEMData('1', createMockImage(4, 4), 'mapbox'); test('border region is initially populated with neighboring data', () => { let nonempty = true; for (let x = -1; x < 5; x++) { for (let y = -1; y < 5; y++) { if (dem0.get(x, y) === -65536) { nonempty = false; break; } } } expect(nonempty).toBeTruthy(); let verticalBorderMatch = true; for (const x of [-1, 4]) { for (let y = 0; y < 4; y++) { if (dem0.get(x, y) !== dem0.get(x < 0 ? x + 1 : x - 1, y)) { verticalBorderMatch = false; break; } } } expect(verticalBorderMatch).toBeTruthy(); // horizontal borders empty let horizontalBorderMatch = true; for (const y of [-1, 4]) { for (let x = 0; x < 4; x++) { if (dem0.get(x, y) !== dem0.get(x, y < 0 ? y + 1 : y - 1)) { horizontalBorderMatch = false; break; } } } expect(horizontalBorderMatch).toBeTruthy(); expect(dem0.get(-1, 4) === dem0.get(0, 3)).toBeTruthy(); expect(dem0.get(4, 4) === dem0.get(3, 3)).toBeTruthy(); expect(dem0.get(-1, -1) === dem0.get(0, 0)).toBeTruthy(); expect(dem0.get(4, -1) === dem0.get(3, 0)).toBeTruthy(); }); test('backfillBorder correctly populates borders with neighboring data', () => { dem0.backfillBorder(dem1, -1, 0); for (let y = 0; y < 4; y++) { // dx = -1, dy = 0, so the left edge of dem1 should equal the right edge of dem0 expect(dem0.get(-1, y) === dem1.get(3, y)).toBeTruthy(); } dem0.backfillBorder(dem1, 0, -1); for (let x = 0; x < 4; x++) { expect(dem0.get(x, -1) === dem1.get(x, 3)).toBeTruthy(); } dem0.backfillBorder(dem1, 1, 0); for (let y = 0; y < 4; y++) { expect(dem0.get(4, y) === dem1.get(0, y)).toBeTruthy(); } dem0.backfillBorder(dem1, 0, 1); for (let x = 0; x < 4; x++) { expect(dem0.get(x, 4) === dem1.get(x, 0)).toBeTruthy(); } dem0.backfillBorder(dem1, -1, 1); expect(dem0.get(-1, 4) === dem1.get(3, 0)).toBeTruthy(); dem0.backfillBorder(dem1, 1, 1); expect(dem0.get(4, 4) === dem1.get(0, 0)).toBeTruthy(); dem0.backfillBorder(dem1, -1, -1); expect(dem0.get(-1, -1) === dem1.get(3, 3)).toBeTruthy(); dem0.backfillBorder(dem1, 1, -1); expect(dem0.get(4, -1) === dem1.get(0, 3)).toBeTruthy(); }); }); describe('terrarium encoding', () => { const dem0 = new DEMData('0', createMockImage(4, 4), 'terrarium'); const dem1 = new DEMData('1', createMockImage(4, 4), 'terrarium'); test('border region is initially populated with neighboring data', () => { let nonempty = true; for (let x = -1; x < 5; x++) { for (let y = -1; y < 5; y++) { if (dem0.get(x, y) === -65536) { nonempty = false; break; } } } expect(nonempty).toBeTruthy(); let verticalBorderMatch = true; for (const x of [-1, 4]) { for (let y = 0; y < 4; y++) { if (dem0.get(x, y) !== dem0.get(x < 0 ? x + 1 : x - 1, y)) { verticalBorderMatch = false; break; } } } expect(verticalBorderMatch).toBeTruthy(); // horizontal borders empty let horizontalBorderMatch = true; for (const y of [-1, 4]) { for (let x = 0; x < 4; x++) { if (dem0.get(x, y) !== dem0.get(x, y < 0 ? y + 1 : y - 1)) { horizontalBorderMatch = false; break; } } } expect(horizontalBorderMatch).toBeTruthy(); expect(dem0.get(-1, 4) === dem0.get(0, 3)).toBeTruthy(); expect(dem0.get(4, 4) === dem0.get(3, 3)).toBeTruthy(); expect(dem0.get(-1, -1) === dem0.get(0, 0)).toBeTruthy(); expect(dem0.get(4, -1) === dem0.get(3, 0)).toBeTruthy(); }); test('backfillBorder correctly populates borders with neighboring data', () => { dem0.backfillBorder(dem1, -1, 0); for (let y = 0; y < 4; y++) { // dx = -1, dy = 0, so the left edge of dem1 should equal the right edge of dem0 expect(dem0.get(-1, y) === dem1.get(3, y)).toBeTruthy(); } dem0.backfillBorder(dem1, 0, -1); for (let x = 0; x < 4; x++) { expect(dem0.get(x, -1) === dem1.get(x, 3)).toBeTruthy(); } dem0.backfillBorder(dem1, 1, 0); for (let y = 0; y < 4; y++) { expect(dem0.get(4, y) === dem1.get(0, y)).toBeTruthy(); } dem0.backfillBorder(dem1, 0, 1); for (let x = 0; x < 4; x++) { expect(dem0.get(x, 4) === dem1.get(x, 0)).toBeTruthy(); } dem0.backfillBorder(dem1, -1, 1); expect(dem0.get(-1, 4) === dem1.get(3, 0)).toBeTruthy(); dem0.backfillBorder(dem1, 1, 1); expect(dem0.get(4, 4) === dem1.get(0, 0)).toBeTruthy(); dem0.backfillBorder(dem1, -1, -1); expect(dem0.get(-1, -1) === dem1.get(3, 3)).toBeTruthy(); dem0.backfillBorder(dem1, 1, -1); expect(dem0.get(4, -1) === dem1.get(0, 3)).toBeTruthy(); }); }); }); describe('DEMData is correctly serialized and deserialized', () => { test('serialized', () => { const imageData0 = createMockImage(4, 4); const dem0 = new DEMData('0', imageData0, 'mapbox'); const serialized = serialize(dem0); // calculate min/max values let min = Number.MAX_SAFE_INTEGER; let max = Number.MIN_SAFE_INTEGER; for (let x = 0; x < 4; x++) { for (let y = 0; y < 4; y++) { const ele = dem0.get(x, y); if (ele > max) max = ele; if (ele < min) min = ele; } } expect(serialized).toEqual({ $name: 'DEMData', uid: '0', dim: 4, stride: 6, data: dem0.data, encoding: 'mapbox', max, min, }); const transferrables = []; serialize(dem0, transferrables); expect(new Uint32Array(transferrables[0])).toEqual(dem0.data); }); test('deserialized', () => { const imageData0 = createMockImage(4, 4); const dem0 = new DEMData('0', imageData0, 'terrarium'); const serialized = serialize(dem0); const deserialized = deserialize(serialized); expect(deserialized).toEqual(dem0); }); }); describe('UnpackVector is correctly returned', () => { test('terrarium and mapbox', () => { const imageData1 = createMockImage(4, 4); const dem1 = new DEMData('0', imageData1, 'terrarium'); const imageData2 = createMockImage(4, 4); const dem2 = new DEMData('0', imageData2, 'mapbox'); expect(dem1.getUnpackVector()).toEqual([256.0, 1.0, 1.0 / 256.0, 32768.0]); expect(dem2.getUnpackVector()).toEqual([6553.6, 25.6, 0.1, 10000.0]); }); }); describe('DEMData#getImage', () => { test('Image is correctly returned', () => { const imageData = createMockImage(4, 4); const dem = new DEMData('0', imageData, 'terrarium'); expect(dem.getPixels()).toEqual(imageData); }); });
the_stack
import {ipcRenderer as ipc} from 'electron' import React from "react" import { withStyles, WithStyles } from '@material-ui/core/styles' import { Table, TableBody, TableRow, TableCell, CircularProgress, FormControlLabel, Typography, Switch, LinearProgress } from "@material-ui/core"; import StyledActions, {Actions} from '../actions/actions' import ActionChoiceDialog from '../actions/actionChoiceDialog' import ActionInfoDialog from '../actions/actionInfoDialog' import ContextPanel from '../context/contextPanel' import ContextSelector from '../context/contextSelector' import Context from "../context/contextStore"; import BlackBox from '../output/blackbox' import TableOutput, {TableBox} from '../output/tableBox' import {ActionOutput, ActionOutputStyle, ActionOutputCollector, ActionStreamOutputCollector, ActionChoiceMaker, Choice, BoundActionAct, BoundAction} from '../actions/actionSpec' import {ActionLoader} from '../actions/actionLoader' import ChoiceManager from "../actions/choiceManager" import OutputManager from '../output/outputManager' import styles from './workspace.styles' import { Cluster, Namespace } from '../k8s/k8sObjectTypes' interface IState { output: ActionOutput outputStyle: ActionOutputStyle loading: boolean loadingMessage: string showActionInitChoices: boolean showActionChoices: boolean minChoices: number maxChoices: number choiceTitle: string choices: Choice[] showChoiceSubItems: boolean previousSelections: Choice[] showInfo: boolean infoTitle: string, info: any[] columnWidths: any[] scrollMode: boolean outputRowLimit: number deferredAction?: BoundActionAct } interface IProps extends WithStyles<typeof styles> { onChangeTheme: (boolean) => void } interface IRefs { [k: string]: any contextSelector: ContextSelector|undefined } export class Workspace extends React.Component<IProps, IState, IRefs> { refs: IRefs = { terminal: undefined, contextSelector: undefined, } state: IState = { output: [], outputStyle: ActionOutputStyle.None, loading: false, loadingMessage: '', showActionInitChoices: false, showActionChoices: false, minChoices: 0, maxChoices: 0, choiceTitle: '', choices: [], showChoiceSubItems: true, previousSelections: [], showInfo: false, infoTitle: '', info: [], columnWidths: [], scrollMode: false, outputRowLimit: 0, } currentAction?: BoundAction commandHandler?: ((string) => void) = undefined tableBox?: TableBox actions?: Actions componentDidMount() { this.componentWillReceiveProps(this.props) const workspace = this ipc.on('updateContext', async (event: Electron.Event, context: {clusters: any[], namespaces: any[]}) => { if(Context.clusters.length === 0 && context && context.clusters && context.clusters.length > 0) { for(const c of context.clusters) { await Context.addCluster(new Cluster(c.name, c.context)) } if(context.namespaces && context.namespaces.length > 0) { context.namespaces.forEach(ns => { Context.addNamespace(new Namespace(ns.namespace, Context.cluster(ns.cluster))) }) } workspace.forceUpdate() } }) } componentWillReceiveProps(props: IProps) { } onAction = (action: BoundAction) => { this.currentAction = action this.tableBox && this.tableBox.clearContent() this.tableBox && this.tableBox.clearFilter() this.tableBox && this.tableBox.clearActionInput() OutputManager.clearContent() OutputManager.clearFilter() this.setState({ scrollMode: false, outputRowLimit: action.outputRowLimit || 0, output: [], columnWidths: [], }) } showOutputLoading = (loading: boolean) => { this.tableBox && this.tableBox.showLoading(loading) } showOutput : ActionOutputCollector = (output, outputStyle) => { this.tableBox && this.tableBox.clearContent() OutputManager.clearContent() this.setState({ output, outputStyle: outputStyle || ActionOutputStyle.Text, loading: false, }) } showStreamOutput : ActionStreamOutputCollector = (output) => { this.tableBox && this.tableBox.appendOutput(output as ActionOutput) } setColumnWidths = (...columnWidths) => { this.setState({columnWidths}) } setScrollMode = (scrollMode: boolean) => { this.setState({scrollMode}) } onActionInitChoices : ActionChoiceMaker = (act, title, choices, minChoices, maxChoices, showChoiceSubItems, previousSelections) => { this.tableBox && this.tableBox.clearContent() this.setState({ choices, minChoices, maxChoices, choiceTitle: title, showActionInitChoices: true, showChoiceSubItems, previousSelections, deferredAction: act, output: [], loading: false, }) } onActionChoices : ActionChoiceMaker = (react, title, choices, minChoices, maxChoices, showChoiceSubItems, previousSelections) => { this.setState({ choices, minChoices, maxChoices, choiceTitle: title, showActionChoices: true, showChoiceSubItems, previousSelections, deferredAction: react, loading: false, }) } onRefreshActionChoices = () => { ChoiceManager.clear() ChoiceManager.clearPreCache() Context.selections = [] this.currentAction && this.currentAction.chooseAndAct() } onSelectActionChoice = (selections: Choice[]) => { const {deferredAction} = this.state Context.selections = selections ChoiceManager.onActionChoiceCompleted() this.setState({showActionInitChoices: false, showActionChoices: false, loading: false}) deferredAction && deferredAction() } onCancelActionChoice = () => { this.setState({showActionInitChoices: false, showActionChoices: false, loading: false}) } showInfo = (infoTitle: string, info: any[]) => { this.setState({ info, infoTitle, showInfo: true, loading: false, }) } onInfoOK = () => { this.setState({showInfo: false}) } onInfoCancel = () => { this.setState({showInfo: false}) } onActionInput = (text: string) => { if(this.currentAction && this.currentAction.react) { ActionLoader.actionContext.inputText = text this.currentAction.react() } } showLoading = (loadingMessage: string) => { this.setState({loading: true, loadingMessage, outputStyle: ActionOutputStyle.None}) } stopLoading = () => { this.setState({loading: false, loadingMessage: ''}) } showContextDialog = () => { Context.incrementOperation() this.currentAction && this.currentAction.stop && this.currentAction.stop() this.refs.contextSelector && this.refs.contextSelector.showContextDialog() } onUpdateContext = () => { this.tableBox && this.tableBox.clearContent() ChoiceManager.clear() ChoiceManager.startAsyncCacheLoader() Context.selections = [] this.setState({output: []}) ipc.send('context', { clusters: Context.clusters.map(c => {return {name: c.name, context: c.context}}), namespaces: Context.namespaces.map(ns => { return {cluster: ns.cluster.name, namespace: ns.name} }) }) } runAction = (name, ...params) => { this.actions && this.actions.runAction(name, ...params) } render() { const { classes } = this.props; const { output, outputStyle, loading, loadingMessage, scrollMode, columnWidths, showActionInitChoices, showActionChoices, minChoices, maxChoices, choiceTitle, choices, showChoiceSubItems, previousSelections, showInfo, infoTitle, info, outputRowLimit } = this.state; const showBlackBox = outputStyle === ActionOutputStyle.Text const log = outputStyle === ActionOutputStyle.Log const mono = outputStyle === ActionOutputStyle.Mono || outputStyle === ActionOutputStyle.LogWithHealth const health = outputStyle === ActionOutputStyle.TableWithHealth || outputStyle === ActionOutputStyle.LogWithHealth const compare = outputStyle === ActionOutputStyle.Compare const acceptInput = this.currentAction && this.currentAction.react ? true : false const allowRefresh = this.currentAction && this.currentAction.refresh ? true : false return ( <div className={classes.root} tabIndex={0}> <Table className={classes.table}> <TableBody> <TableRow className={classes.upperRow}> <TableCell colSpan={2} className={classes.contextCell}> <ContextPanel onUpdateContext={this.onUpdateContext} onSelectContext={this.showContextDialog} runAction={this.runAction} /> </TableCell> </TableRow> <TableRow className={classes.lowerRow}> <TableCell className={classes.actionCell}> <StyledActions innerRef={ref => this.actions=ref} showLoading={this.showLoading} onOutput={this.showOutput} onStreamOutput={this.showStreamOutput} onActionInitChoices={this.onActionInitChoices} onActionChoices={this.onActionChoices} onCancelActionChoice={this.onCancelActionChoice} onShowInfo={this.showInfo} onSetColumnWidths={this.setColumnWidths} onSetScrollMode={this.setScrollMode} onAction={this.onAction} onOutputLoading={this.showOutputLoading} /> </TableCell> <TableCell className={classes.outputCell}> {loading && loadingMessage && <div> <Typography variant="h5" gutterBottom className={classes.loadingMessage}> {loadingMessage} </Typography> <LinearProgress className={classes.loadingLinear} /> </div> } {loading && !loadingMessage && <CircularProgress className={classes.loadingCircular} /> } {showBlackBox && <BlackBox output={output} />} {!showBlackBox && <TableOutput innerRef={ref => this.tableBox=ref} output={output} compare={compare} log={log} mono={mono} health={health} rowLimit={outputRowLimit} acceptInput={acceptInput} allowRefresh={allowRefresh} columnWidths={columnWidths} scrollMode={scrollMode} onActionInput={this.onActionInput} /> } </TableCell> </TableRow> <TableRow className={classes.bottomRow}> <TableCell className={classes.bottomRow}> <FormControlLabel control={ <Switch checked={global['useDarkTheme']} onChange={this.props.onChangeTheme} value="Dark" /> } label="Dark Theme" /> <div className={classes.statusMessage}> {Context.errorMessage} </div> </TableCell> </TableRow> </TableBody> </Table> <ContextSelector ref='contextSelector' onUpdateContext={this.onUpdateContext.bind(this)} /> { (showActionInitChoices || showActionChoices) && <ActionChoiceDialog open={showActionInitChoices || showActionChoices} title={choiceTitle} choices={choices} minChoices={minChoices} maxChoices={maxChoices} showChoiceSubItems={showChoiceSubItems} previousSelections={previousSelections} onSelection={this.onSelectActionChoice} onRefresh={this.onRefreshActionChoices} onCancel={this.onCancelActionChoice} /> } { showInfo && <ActionInfoDialog open={showInfo} title={infoTitle} items={info} onOK={this.onInfoOK} onCancel={this.onInfoCancel} /> } </div> ); } } export default withStyles(styles)(Workspace)
the_stack
export interface DescribeClusterPersonArrivedMallResponse { /** * 卖场系统编码 */ MallId?: string; /** * 卖场客户编码 */ MallCode?: string; /** * 客户编码 */ PersonId?: string; /** * 到场信息 */ ArrivedMallSet?: Array<ArrivedMallInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeShopTrafficInfo请求参数结构体 */ export interface DescribeShopTrafficInfoRequest { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 介绍日期,格式yyyy-MM-dd */ EndDate: string; /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; } /** * 性别年龄分组下的客流信息 */ export interface GenderAgeTrafficDetail { /** * 性别: 0男1女 */ Gender: number; /** * 年龄区间,枚举值:0-17、18-23、24-30、31-40、41-50、51-60、>60 */ AgeGap: string; /** * 客流量 */ TrafficCount: number; } /** * DescribeZoneFlowAndStayTime返回参数结构体 */ export interface DescribeZoneFlowAndStayTimeResponse { /** * 集团id */ CompanyId?: string; /** * 店铺id */ ShopId?: number; /** * 各区域人流数目和停留时长 */ Data?: Array<ZoneFlowAndAvrStayTime>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribePersonArrivedMall返回参数结构体 */ export interface DescribePersonArrivedMallResponse { /** * 卖场系统编码 */ MallId?: string; /** * 卖场用户编码 */ MallCode?: string; /** * 客户编码 */ PersonId?: string; /** * 到场轨迹 */ ArrivedMallSet?: Array<ArrivedMallInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyPersonType返回参数结构体 */ export interface ModifyPersonTypeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 分时客流量详细信息 */ export interface HourTrafficInfoDetail { /** * 小时 取值为:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 */ Hour: number; /** * 分时客流量 */ HourTrafficTotalCount: number; } /** * DescribeZoneFlowDailyByZoneId返回参数结构体 */ export interface DescribeZoneFlowDailyByZoneIdResponse { /** * 集团id */ CompanyId?: string; /** * 店铺id */ ShopId?: number; /** * 区域ID */ ZoneId?: number; /** * 区域名称 */ ZoneName?: string; /** * 每日人流量 */ Data?: Array<ZoneDayFlow>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeZoneFlowAgeInfoByZoneId返回参数结构体 */ export interface DescribeZoneFlowAgeInfoByZoneIdResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID */ ShopId?: number; /** * 区域ID */ ZoneId?: number; /** * 区域名称 */ ZoneName?: string; /** * 当前年龄段占比 */ Data?: Array<number>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeClusterPersonTrace返回参数结构体 */ export interface DescribeClusterPersonTraceResponse { /** * 卖场系统编码 */ MallId?: string; /** * 卖场用户编码 */ MallCode?: string; /** * 客户编码 */ PersonId?: string; /** * 轨迹序列 */ TracePointSet?: Array<DailyTracePoint>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribePersonInfo请求参数结构体 */ export interface DescribePersonInfoRequest { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 起始ID,第一次拉取时StartPersonId传0,后续送入的值为上一页最后一条数据项的PersonId */ StartPersonId: number; /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; /** * 图片url过期时间:在当前时间+PictureExpires秒后,图片url无法继续正常访问;单位s;默认值1*24*60*60(1天) */ PictureExpires?: number; /** * 身份类型(0表示普通顾客,1 白名单,2 表示黑名单) */ PersonType?: number; } /** * DescribePersonInfoByFacePicture返回参数结构体 */ export interface DescribePersonInfoByFacePictureResponse { /** * 集团id */ CompanyId?: string; /** * 店铺id */ ShopId?: number; /** * 顾客face id */ PersonId?: number; /** * 顾客底图url */ PictureUrl?: string; /** * 顾客类型(0表示普通顾客,1 白名单,2 表示黑名单,101表示集团白名单,102表示集团黑名单) */ PersonType?: number; /** * 顾客首次进店时间 */ FirstVisitTime?: string; /** * 顾客历史到访次数 */ VisitTimes?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribePersonTraceDetail请求参数结构体 */ export interface DescribePersonTraceDetailRequest { /** * 卖场编码 */ MallId: string; /** * 客户编码 */ PersonId: string; /** * 轨迹编码 */ TraceId: string; } /** * CreateAccount请求参数结构体 */ export interface CreateAccountRequest { /** * 集团ID */ CompanyId: string; /** * 账号名;需要是手机号 */ Name: string; /** * 密码;需要是(`~!@#$%^&*()_+=-)中的至少两种且八位以上 */ Password: string; /** * 客户门店编码 */ ShopCode: string; /** * 备注说明; 30个字符以内 */ Remark?: string; } /** * 获取当前门店最新网络状态数据返回结构 */ export interface NetworkLastInfo { /** * 总数 */ Count: number; /** * 网络状态 */ Infos: Array<NetworkAndShopInfo>; } /** * DescribeZoneFlowGenderAvrStayTimeByZoneId返回参数结构体 */ export interface DescribeZoneFlowGenderAvrStayTimeByZoneIdResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID */ ShopId?: number; /** * 区域ID */ ZoneId?: number; /** * 区域名称 */ ZoneName?: string; /** * 不同年龄段男女停留时间(返回格式为数组,从第 1 个到最后一个数据,年龄段分别为 0-17,18 - 23, 24 - 30, 31 - 40, 41 - 50, 51 - 60, 61 - 100) */ Data?: Array<ZoneAgeGroupAvrStayTime>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeletePersonFeature返回参数结构体 */ export interface DeletePersonFeatureResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCameraPerson返回参数结构体 */ export interface DescribeCameraPersonResponse { /** * 集团id */ CompanyId?: string; /** * 店铺id */ ShopId?: number; /** * 摄像机id */ CameraId?: number; /** * pos机id */ PosId?: string; /** * 抓取的顾客信息 */ Infos?: Array<CameraPersonInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyPersonTagInfo返回参数结构体 */ export interface ModifyPersonTagInfoResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeShopHourTrafficInfo返回参数结构体 */ export interface DescribeShopHourTrafficInfoResponse { /** * 公司ID */ CompanyId?: string; /** * 门店ID */ ShopId?: number; /** * 查询结果总数 */ TotalCount?: number; /** * 分时客流信息 */ ShopHourTrafficInfoSet?: Array<ShopHourTrafficInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * RegisterCallback返回参数结构体 */ export interface RegisterCallbackResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 没有店铺信息的网络状态 */ export interface NetworkInfo { /** * 上传带宽,单位Mb/s,-1:未知 */ Upload: number; /** * 下载带宽,单位Mb/s,-1:未知 */ Download: number; /** * 最小延迟,单位ms,-1:未知 */ MinRtt: number; /** * 平均延迟,单位ms,-1:未知 */ AvgRtt: number; /** * 最大延迟,单位ms,-1:未知 */ MaxRtt: number; /** * 平均偏差延迟,单位ms,-1:未知 */ MdevRtt: number; /** * 丢包率百分比,-1:未知 */ Loss: number; /** * 更新时间戳 */ UpdateTime: number; /** * 上报网络状态设备 */ Mac: string; } /** * DescribeClusterPersonArrivedMall请求参数结构体 */ export interface DescribeClusterPersonArrivedMallRequest { /** * 卖场编码 */ MallId: string; /** * 客户编码 */ PersonId: string; /** * 查询开始时间 */ StartTime: string; /** * 查询结束时间 */ EndTime: string; } /** * DescribeZoneFlowGenderInfoByZoneId返回参数结构体 */ export interface DescribeZoneFlowGenderInfoByZoneIdResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID */ ShopId?: number; /** * 区域ID */ ZoneId?: number; /** * 区域名称 */ ZoneName?: string; /** * 男性占比 */ MalePercent?: number; /** * 女性占比 */ FemalePercent?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeHistoryNetworkInfo请求参数结构体 */ export interface DescribeHistoryNetworkInfoRequest { /** * 请求时间戳 */ Time: number; /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取,为0则拉取集团全部店铺当前 */ ShopId: number; /** * 拉取开始日期,格式:2018-09-05 */ StartDay: string; /** * 拉取结束日期,格式L:2018-09-05,超过StartDay 90天,按StartDay+90天算 */ EndDay: string; /** * 拉取条数,默认10 */ Limit?: number; /** * 拉取偏移,返回offset之后的数据 */ Offset?: number; } /** * DescribePersonTraceDetail返回参数结构体 */ export interface DescribePersonTraceDetailResponse { /** * 卖场编码 */ MallId?: string; /** * 客户编码 */ PersonId?: string; /** * 轨迹编码 */ TraceId?: string; /** * 轨迹点坐标序列 */ CoordinateSet?: Array<PersonCoordinate>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribePersonInfoByFacePicture请求参数结构体 */ export interface DescribePersonInfoByFacePictureRequest { /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取 */ ShopId: number; /** * 人脸图片BASE编码 */ Picture: string; } /** * DescribePersonVisitInfo请求参数结构体 */ export interface DescribePersonVisitInfoRequest { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; /** * 开始日期,格式yyyy-MM-dd,已废弃,请使用StartDateTime */ StartDate?: string; /** * 结束日期,格式yyyy-MM-dd,已废弃,请使用EndDateTime */ EndDate?: string; /** * 图片url过期时间:在当前时间+PictureExpires秒后,图片url无法继续正常访问;单位s;默认值1*24*60*60(1天) */ PictureExpires?: number; /** * 开始时间,格式yyyy-MM-dd HH:mm:ss */ StartDateTime?: string; /** * 结束时间,格式yyyy-MM-dd HH:mm:ss */ EndDateTime?: string; } /** * DescribeZoneTrafficInfo返回参数结构体 */ export interface DescribeZoneTrafficInfoResponse { /** * 公司ID */ CompanyId?: string; /** * 门店ID */ ShopId?: number; /** * 查询结果总数 */ TotalCount?: number; /** * 区域客流信息列表 */ ZoneTrafficInfoSet?: Array<ZoneTrafficInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeletePersonFeature请求参数结构体 */ export interface DeletePersonFeatureRequest { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 顾客ID */ PersonId: number; } /** * DescribeFaceIdByTempId请求参数结构体 */ export interface DescribeFaceIdByTempIdRequest { /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取 */ ShopId: number; /** * 临时id */ TempId: string; /** * 摄像头id */ CameraId: number; /** * pos机id */ PosId?: string; /** * 图片url过期时间:在当前时间+PictureExpires秒后,图片url无法继续正常访问;单位s;默认值1*24*60*60(1天) */ PictureExpires?: number; } /** * 来访客人基本资料 */ export interface PersonProfile { /** * 客人编码 */ PersonId: string; /** * 性别 */ Gender: number; /** * 年龄 */ Age: number; /** * 首次到场时间 */ FirstArrivedTime: string; /** * 来访次数 */ ArrivedCount: number; /** * 客户图片 */ PicUrl: string; /** * 置信度 */ Similarity: number; } /** * DescribePerson返回参数结构体 */ export interface DescribePersonResponse { /** * 总计客户数量 */ TotalCount?: number; /** * 客户信息 */ PersonSet?: Array<PersonProfile>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeTrajectoryData请求参数结构体 */ export interface DescribeTrajectoryDataRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; /** * 限制返回数据的最大条数,最大 400(负数代为 400) */ Limit: number; /** * 顾客性别顾虑,0是男,1是女,其它代表不分性别 */ Gender: number; } /** * DescribeZoneTrafficInfo请求参数结构体 */ export interface DescribeZoneTrafficInfoRequest { /** * 公司ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; } /** * ModifyPersonFeatureInfo返回参数结构体 */ export interface ModifyPersonFeatureInfoResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID,如果不填表示操作集团身份库 */ ShopId?: number; /** * 请求的顾客id */ PersonId?: number; /** * 图片实际绑定person_id,可能与请求的person_id不同,以此id为准 */ PersonIdBind?: number; /** * 请求的顾客类型 */ PersonType?: number; /** * 与请求的person_id类型相同、与请求图片特征相似的一个或多个person_id,需要额外确认这些id是否是同一个人 */ SimilarPersonIds?: Array<number>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 门店区域客流详细信息 */ export interface ZoneTrafficInfoDetail { /** * 区域ID */ ZoneId: number; /** * 区域名称 */ ZoneName: string; /** * 客流量 */ TrafficTotalCount: number; /** * 平均停留时间 */ AvgStayTime: number; } /** * DescribeZoneFlowGenderAvrStayTimeByZoneId请求参数结构体 */ export interface DescribeZoneFlowGenderAvrStayTimeByZoneIdRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 区域ID */ ZoneId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * 客流停留统计子结构 */ export interface ZoneFlowAndAvrStayTime { /** * 区域id */ ZoneId: number; /** * 区域名称 */ ZoneName: string; /** * 人流量 */ FlowCount: number; /** * 平均停留时长 */ AvrStayTime: number; } /** * 场景图信息 */ export interface SceneInfo { /** * 场景图 */ ScenePictureURL: string; /** * 抓拍头像左上角X坐标在场景图中的像素点位置 */ HeadX: number; /** * 抓拍头像左上角Y坐标在场景图中的像素点位置 */ HeadY: number; /** * 抓拍头像在场景图中占有的像素宽度 */ HeadWidth: number; /** * 抓拍头像在场景图中占有的像素高度 */ HeadHeight: number; } /** * 摄像头抓图人物属性 */ export interface CameraPersonInfo { /** * 临时id,还未生成face id时返回 */ TempId: string; /** * 人脸face id */ FaceId: number; /** * 确定当次返回的哪个id有效,1-FaceId,2-TempId */ IdType: number; /** * 当次抓拍到的人脸图片base编码 */ FacePic: string; /** * 当次抓拍时间戳 */ Time: number; /** * 当前的person基本信息,图片以FacePic为准,结构体内未填 */ PersonInfo: PersonInfo; } /** * DescribePersonVisitInfo返回参数结构体 */ export interface DescribePersonVisitInfoResponse { /** * 公司ID */ CompanyId?: string; /** * 门店ID */ ShopId?: number; /** * 总数 */ TotalCount?: number; /** * 用户到访明细 */ PersonVisitInfoSet?: Array<PersonVisitInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeNetworkInfo请求参数结构体 */ export interface DescribeNetworkInfoRequest { /** * 请求时间戳 */ Time: number; /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取,不填则拉取集团全部店铺当前 */ ShopId?: number; } /** * DescribeZoneFlowAndStayTime请求参数结构体 */ export interface DescribeZoneFlowAndStayTimeRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * DescribeZoneFlowHourlyByZoneId请求参数结构体 */ export interface DescribeZoneFlowHourlyByZoneIdRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 区域ID */ ZoneId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * DescribeFaceIdByTempId返回参数结构体 */ export interface DescribeFaceIdByTempIdResponse { /** * 集团id */ CompanyId?: string; /** * 店铺id */ ShopId?: number; /** * 摄像机id */ CameraId?: number; /** * pos机id */ PosId?: string; /** * 请求的临时id */ TempId?: string; /** * 临时id对应的face id */ FaceId?: number; /** * 顾客属性信息 */ PersonInfo?: PersonInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 轨迹动线信息子结构 */ export interface TrajectorySunData { /** * 区域动线,形如 x-x-x-x-x,其中 x 为区域 ID */ Zones: string; /** * 该动线出现次数 */ Count: number; /** * 该动线平均停留时间(秒) */ AvgStayTime: number; } /** * ModifyPersonTagInfo请求参数结构体 */ export interface ModifyPersonTagInfoRequest { /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取,为0则拉取集团全部店铺当前 */ ShopId: number; /** * 需要设置的顾客信息,批量设置最大为10个 */ Tags: Array<PersonTagInfo>; } /** * 门店客流量列表信息 */ export interface ShopDayTrafficInfo { /** * 日期 */ Date: string; /** * 客流量 */ DayTrafficTotalCount: number; /** * 性别年龄分组下的客流信息 */ GenderAgeTrafficDetailSet: Array<GenderAgeTrafficDetail>; } /** * DescribePerson请求参数结构体 */ export interface DescribePersonRequest { /** * 卖场编码 */ MallId: string; /** * 查询偏移 */ Offset?: number; /** * 查询数量,默认20,最大查询数量100 */ Limit?: number; } /** * DescribePersonTrace返回参数结构体 */ export interface DescribePersonTraceResponse { /** * 卖场系统编码 */ MallId?: string; /** * 卖场用户编码 */ MallCode?: string; /** * 客户编码 */ PersonId?: string; /** * 轨迹列表 */ TraceRouteSet?: Array<PersonTraceRoute>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 客户轨迹序列 */ export interface PersonTraceRoute { /** * 轨迹编码 */ TraceId: string; /** * 轨迹点序列 */ TracePointSet: Array<PersonTracePoint>; } /** * 客户轨迹点 */ export interface PersonTracePoint { /** * 卖场区域编码 */ MallAreaId: number; /** * 门店编码 */ ShopId: number; /** * 卖场区域类型 */ MallAreaType: number; /** * 轨迹事件 */ TraceEventType: number; /** * 轨迹事件发生时间点 */ TraceEventTime: string; /** * 抓拍图片 */ CapPic: string; /** * 购物袋类型 */ ShoppingBagType: number; /** * 购物袋数量 */ ShoppingBagCount: number; } /** * 门店区域客流信息 */ export interface ZoneTrafficInfo { /** * 日期 */ Date: string; /** * 门店区域客流详细信息 */ ZoneTrafficInfoDetailSet: Array<ZoneTrafficInfoDetail>; } /** * DescribeNetworkInfo返回参数结构体 */ export interface DescribeNetworkInfoResponse { /** * 网络状态详情 */ InstanceSet?: NetworkLastInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 网络状态 */ export interface NetworkAndShopInfo { /** * 集团id */ CompanyId: string; /** * 店铺id */ ShopId: number; /** * 店铺省份 */ Province: string; /** * 店铺城市 */ City: string; /** * 店铺名 */ ShopName: string; /** * 上传带宽,单位Mb/s,-1:未知 */ Upload: number; /** * 下载带宽,单位Mb/s,-1:未知 */ Download: number; /** * 最小延迟,单位ms,-1:未知 */ MinRtt: number; /** * 平均延迟,单位ms,-1:未知 */ AvgRtt: number; /** * 最大延迟,单位ms,-1:未知 */ MaxRtt: number; /** * 平均偏差延迟,单位ms,-1:未知 */ MdevRtt: number; /** * 丢包率百分比,-1:未知 */ Loss: number; /** * 更新时间戳 */ UpdateTime: number; /** * 上报网络状态设备 */ Mac: string; } /** * DescribeZoneFlowGenderInfoByZoneId请求参数结构体 */ export interface DescribeZoneFlowGenderInfoByZoneIdRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 区域ID */ ZoneId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * DescribeShopHourTrafficInfo请求参数结构体 */ export interface DescribeShopHourTrafficInfoRequest { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 开始日期,格式:yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式:yyyy-MM-dd */ EndDate: string; /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; } /** * RegisterCallback请求参数结构体 */ export interface RegisterCallbackRequest { /** * 集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 通知回调地址,完整url,示例(http://youmall.tencentcloudapi.com/) */ BackUrl: string; /** * 请求时间戳 */ Time: number; /** * 是否需要顾客图片,1-需要图片,其它-不需要图片 */ NeedFacePic?: number; } /** * DescribeShopInfo请求参数结构体 */ export interface DescribeShopInfoRequest { /** * 偏移量:分页控制参数,第一页传0,第n页Offset=(n-1)*Limit */ Offset: number; /** * Limit:每页的数据项,最大100,超过100会被强制指定为100 */ Limit: number; } /** * 查询网络状态历史数据输出 */ export interface NetworkHistoryInfo { /** * 总数 */ Count: number; /** * 集团id */ CompanyId: string; /** * 店铺id */ ShopId: number; /** * 店铺省份 */ Province: string; /** * 店铺城市 */ City: string; /** * 店铺名称 */ ShopName: string; /** * 网络信息 */ Infos: Array<NetworkInfo>; } /** * 用户信息 */ export interface PersonInfo { /** * 用户ID */ PersonId: number; /** * 人脸图片Base64内容,已弃用,返回默认空值 */ PersonPicture: string; /** * 性别:0男1女 */ Gender: number; /** * 年龄 */ Age: number; /** * 身份类型(0表示普通顾客,1 白名单,2 表示黑名单) */ PersonType: number; /** * 人脸图片Url,在有效期内可以访问下载 */ PersonPictureUrl: string; /** * 身份子类型: PersonType=0时(普通顾客),0普通顾客 PersonType=1时(白名单),0店员,1商场人员,2其他类型人员,3区域经理,4注册用户,5VIP用户 PersonType=2时(黑名单),0普通黑名单,1小偷) */ PersonSubType: number; /** * 到访次数,-1表示未知 */ VisitTimes: number; /** * 到访天数,-1表示未知 */ VisitDays: number; } /** * 修改顾客属性参数 */ export interface PersonTagInfo { /** * 顾客原类型 */ OldType: number; /** * 顾客新类型 */ NewType: number; /** * 顾客face id */ PersonId: number; } /** * 客流统计分时数据子结构 */ export interface ZoneHourFlow { /** * 分时 0~23 */ Hour: number; /** * 客流量 */ FlowCount: number; } /** * 分时客流量信息 */ export interface ShopHourTrafficInfo { /** * 日期,格式yyyy-MM-dd */ Date: string; /** * 分时客流详细信息 */ HourTrafficInfoDetailSet: Array<HourTrafficInfoDetail>; } /** * DescribeClusterPersonTrace请求参数结构体 */ export interface DescribeClusterPersonTraceRequest { /** * 卖场编码 */ MallId: string; /** * 客户编码 */ PersonId: string; /** * 查询开始时间 */ StartTime: string; /** * 查询结束时间 */ EndTime: string; } /** * 轨迹点坐标 */ export interface PersonCoordinate { /** * CAD图X坐标 */ CADX: number; /** * CAD图Y坐标 */ CADY: number; /** * 抓拍时间点 */ CapTime: string; /** * 抓拍图片 */ CapPic: string; /** * 卖场区域类型 */ MallAreaType: number; /** * 坐标编号 */ PosId: number; /** * 门店编号 */ ShopId: number; /** * 事件 */ Event: string; } /** * ModifyPersonFeatureInfo请求参数结构体 */ export interface ModifyPersonFeatureInfoRequest { /** * 集团ID */ CompanyId: string; /** * 需要修改的顾客id */ PersonId: number; /** * 图片BASE编码 */ Picture: string; /** * 图片名称(尽量不要重复) */ PictureName: string; /** * 人物类型,仅能操作黑白名单顾客(1 白名单,2 表示黑名单,101表示集团白名单,102表示集团黑名单) */ PersonType: number; /** * 店铺ID,如果不填表示操作集团身份库 */ ShopId?: number; } /** * 每日客流统计子结构 */ export interface ZoneDayFlow { /** * 日期,如 2018-08-6 */ Day: string; /** * 客流量 */ FlowCount: number; } /** * DescribePersonTrace请求参数结构体 */ export interface DescribePersonTraceRequest { /** * 卖场编码 */ MallId: string; /** * 客户编码 */ PersonId: string; /** * 查询开始时间 */ StartTime: string; /** * 查询结束时间 */ EndTime: string; } /** * DescribeZoneFlowHourlyByZoneId返回参数结构体 */ export interface DescribeZoneFlowHourlyByZoneIdResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID */ ShopId?: number; /** * 区域ID */ ZoneId?: number; /** * 区域名称 */ ZoneName?: string; /** * 各个分时人流量 */ Data?: Array<ZoneHourFlow>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeZoneFlowDailyByZoneId请求参数结构体 */ export interface DescribeZoneFlowDailyByZoneIdRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 区域ID */ ZoneId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * DescribePersonInfo返回参数结构体 */ export interface DescribePersonInfoResponse { /** * 公司ID */ CompanyId?: string; /** * 门店ID */ ShopId?: number; /** * 总数 */ TotalCount?: number; /** * 用户信息 */ PersonInfoSet?: Array<PersonInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 客户天轨迹 */ export interface DailyTracePoint { /** * 轨迹日期 */ TraceDate: string; /** * 轨迹点序列 */ TracePointSet: Array<PersonTracePoint>; } /** * CreateAccount返回参数结构体 */ export interface CreateAccountResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeHistoryNetworkInfo返回参数结构体 */ export interface DescribeHistoryNetworkInfoResponse { /** * 网络状态数据 */ InstanceSet?: NetworkHistoryInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateFacePicture返回参数结构体 */ export interface CreateFacePictureResponse { /** * 人物ID */ PersonId?: number; /** * 0.正常建档 1.重复身份 2.未检测到人脸 3.检测到多个人脸 4.人脸大小过小 5.人脸质量不达标 6.其他错误 */ Status?: number; /** * 图片url */ PictureUrl?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeShopInfo返回参数结构体 */ export interface DescribeShopInfoResponse { /** * 门店总数 */ TotalCount?: number; /** * 门店列表信息 */ ShopInfoSet?: Array<ShopInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 用户到访明细 */ export interface PersonVisitInfo { /** * 用户ID */ PersonId: number; /** * 用户到访ID */ VisitId: number; /** * 到访时间:Unix时间戳 */ InTime: number; /** * 抓拍到的头像Base64内容,已弃用,返回默认空值 */ CapturedPicture: string; /** * 口罩类型:0不戴口罩,1戴口罩 */ MaskType: number; /** * 眼镜类型:0不戴眼镜,1普通眼镜 , 2墨镜 */ GlassType: number; /** * 发型:0 短发, 1长发 */ HairType: number; /** * 抓拍到的头像Url,在有效期内可以访问下载 */ CapturedPictureUrl: string; /** * 抓拍头像的场景图信息 */ SceneInfo: SceneInfo; } /** * CreateFacePicture请求参数结构体 */ export interface CreateFacePictureRequest { /** * 集团ID */ CompanyId: string; /** * 人物类型(0表示普通顾客,1 白名单,2 表示黑名单,101表示集团白名单,102表示集团黑名单) */ PersonType: number; /** * 图片BASE编码 */ Picture: string; /** * 图片名称 */ PictureName: string; /** * 店铺ID,如果不填表示操作集团身份库 */ ShopId?: number; /** * 是否强制更新:为ture时会为用户创建一个新的指定PersonType的身份;目前这个参数已废弃,可不传 */ IsForceUpload?: boolean; } /** * DescribeZoneFlowAgeInfoByZoneId请求参数结构体 */ export interface DescribeZoneFlowAgeInfoByZoneIdRequest { /** * 集团ID */ CompanyId: string; /** * 店铺ID */ ShopId: number; /** * 区域ID */ ZoneId: number; /** * 开始日期,格式yyyy-MM-dd */ StartDate: string; /** * 结束日期,格式yyyy-MM-dd */ EndDate: string; } /** * 客户所属的门店信息 */ export interface ShopInfo { /** * 公司ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 门店名称 */ ShopName: string; /** * 客户门店编码 */ ShopCode: string; /** * 省 */ Province: string; /** * 市 */ City: string; /** * 公司名称 */ CompanyName: string; } /** * ModifyPersonType请求参数结构体 */ export interface ModifyPersonTypeRequest { /** * 集团ID */ CompanyId: string; /** * 门店ID */ ShopId: number; /** * 顾客ID */ PersonId: number; /** * 身份类型(0表示普通顾客,1 白名单,2 表示黑名单) */ PersonType: number; /** * 身份子类型: PersonType=0时(普通顾客),0普通顾客 PersonType=1时(白名单),0店员,1商场人员,2其他类型人员,3区域经理,4注册会员,5VIP用户 PersonType=2时(黑名单),0普通黑名单,1小偷) */ PersonSubType: number; } /** * 客户到场信息 */ export interface ArrivedMallInfo { /** * 到场时间 */ ArrivedTime: string; /** * 出场时间 */ LeaveTime: string; /** * 停留时间,秒 */ StaySecond: number; /** * 到场抓拍图片 */ InCapPic: string; /** * 出场抓拍图片 */ OutCapPic: string; /** * 轨迹编码 */ TraceId: string; } /** * 区域性别平均停留时间子结构 */ export interface ZoneAgeGroupAvrStayTime { /** * 男性平均停留时间 */ MaleAvrStayTime: number; /** * 女性平均停留时间 */ FemaleAvrStayTime: number; } /** * DescribePersonArrivedMall请求参数结构体 */ export interface DescribePersonArrivedMallRequest { /** * 卖场编码 */ MallId: string; /** * 客户编码 */ PersonId: string; /** * 查询开始时间 */ StartTime: string; /** * 查询结束时间 */ EndTime: string; } /** * DescribeCameraPerson请求参数结构体 */ export interface DescribeCameraPersonRequest { /** * 优mall集团id,通过"指定身份标识获取客户门店列表"接口获取 */ CompanyId: string; /** * 优mall店铺id,通过"指定身份标识获取客户门店列表"接口获取 */ ShopId: number; /** * 摄像头id */ CameraId: number; /** * 拉取开始时间戳,单位秒 */ StartTime: number; /** * 拉取结束时间戳,单位秒,不超过StartTime+10秒,超过默认为StartTime+10 */ EndTime: number; /** * pos机id */ PosId?: string; /** * 拉取图片数,默认为1,最大为3 */ Num?: number; /** * 是否需要base64的图片,0-不需要,1-需要,默认0 */ IsNeedPic?: number; } /** * DescribeShopTrafficInfo返回参数结构体 */ export interface DescribeShopTrafficInfoResponse { /** * 公司ID */ CompanyId?: string; /** * 门店ID */ ShopId?: number; /** * 查询结果总数 */ TotalCount?: number; /** * 客流信息列表 */ ShopDayTrafficInfoSet?: Array<ShopDayTrafficInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeTrajectoryData返回参数结构体 */ export interface DescribeTrajectoryDataResponse { /** * 集团ID */ CompanyId?: string; /** * 店铺ID */ ShopId?: number; /** * 总人数 */ TotalPerson?: number; /** * 总动迹数目 */ TotalTrajectory?: number; /** * 返回动迹中的总人数 */ Person?: number; /** * 返回动迹的数目 */ Trajectory?: number; /** * 返回动迹的具体信息 */ Data?: Array<TrajectorySunData>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; }
the_stack
import axios from 'axios' import os from 'os' import help from '@oclif/plugin-help' import * as Config from '@oclif/config' import { HookKeyOrOptions } from '@oclif/config/lib/hooks' import { error } from '@oclif/errors' import { FeatureFlag } from '../../api/modules/featureFlag' import { envCookies } from '../../api/env' import { CLIPreTasks } from '../../CLIPreTasks/CLIPreTasks' import { TelemetryCollector } from '../../lib/telemetry/TelemetryCollector' import { hrTimeToMs } from '../../lib/utils/hrTimeToMs' import { updateNotify } from '../../update' import log from '../../api/logger' import * as pkg from '../../../package.json' import * as conf from '../../api/conf' import { checkAndOpenNPSLink } from '../../nps' import { Metric } from '../../api/metrics/MetricReport' import authLogin from '../../modules/auth/login' import { MetricNames } from '../../api/metrics/MetricNames' import { SessionManager } from '../../api/session/SessionManager' import { SSEConnectionError } from '../../api/error/errors' import { ErrorReport } from '../../api/error/ErrorReport' import * as fse from 'fs-extra' import path from 'path' import { sortBy, uniqBy } from 'ramda' import { getHelpSubject, CommandI, renderCommands } from './utils' // eslint-disable-next-line @typescript-eslint/no-var-requires const { initTimeStartTime } = require('../../../bin/run') let loginPending = false const logToolbeltVersion = () => { log.debug(`Toolbelt version: ${pkg.version}`) } const checkLogin = async (command: string) => { /** * Commands for which previous login is not necessary. There's some exceptions: * - link: It's necessary to be logged in, but there's some login logic there before running the link per se */ const allowedList = [ undefined, 'config', 'login', 'logout', 'switch', 'whoami', 'init', '-v', '--version', 'release', 'link', ] if (!SessionManager.getSingleton().checkValidCredentials() && allowedList.indexOf(command) === -1) { log.debug('Requesting login before command:', command) await authLogin({}) } } const createSymlink = async options => { try { await fse.symlink(options.config.root, path.join(options.config.root, 'node_modules', 'vtex')) } catch (symLinkErr) { if (symLinkErr.code === 'EEXIST') { log.error(`Symbolic link already exist, there is another error that couldn't be solved`) } else { log.error('Failed to create symbolic link. Please run this command on Administrator mode') } process.exit(1) } } const checkAndFixSymlink = async options => { try { require('vtex') } catch (requireErr) { if (requireErr.code === 'MODULE_NOT_FOUND') { log.error('Import VTEX error, trying to autofix...') await createSymlink(options) log.info('Problem solved. Please, run the command again') } else { log.error('Unexpected behaviour with vtex package') } process.exit(1) } log.debug('Import VTEX OK') } const main = async (options?: HookKeyOrOptions<'init'>, calculateInitTime?: boolean) => { const cliPreTasksStart = process.hrtime() CLIPreTasks.getCLIPreTasks(pkg).runTasks(options.id) TelemetryCollector.getCollector().registerMetric({ command: 'not-applicable', [MetricNames.CLI_PRE_TASKS_LATENCY]: hrTimeToMs(process.hrtime(cliPreTasksStart)), }) // Show update notification if newer version is available updateNotify() const args = process.argv.slice(2) conf.saveEnvironment(conf.Environment.Production) // Just to be backwards compatible with who used staging previously logToolbeltVersion() log.debug('node %s - %s %s', process.version, os.platform(), os.release()) log.debug(args) await checkLogin(options.id) await checkAndFixSymlink(options) await checkAndOpenNPSLink() if (calculateInitTime) { const initTime = process.hrtime(initTimeStartTime) const initTimeMetric: Metric = { command: options.id, [MetricNames.START_TIME]: hrTimeToMs(initTime), } TelemetryCollector.getCollector().registerMetric(initTimeMetric) } } export const onError = async (e: any) => { const status = e?.response?.status const statusText = e?.response?.statusText const headers = e?.response?.headers const data = e?.response?.data const code = e?.code || null if (headers) { log.debug('Failed request headers:', headers) } if (status === 401) { if (!loginPending) { log.error('There was an authentication error. Please login again') // Try to login and re-issue the command. loginPending = true authLogin({}).then(() => { main() }) // TODO: catch with different handler for second error } return // Prevent multiple login attempts } if (status) { if (status >= 400) { const message = data ? data.message : null const source = e.config.url log.error('API:', status, statusText) log.error('Source:', source) if (e.config?.method) { log.error('Method:', e.config.method) } if (message) { log.error('Message:', message) log.debug('Raw error:', data) } else { log.error('Raw error:', { data, source, }) } } else { log.error('Oops! There was an unexpected error:') log.error(e.read ? e.read().toString('utf8') : data) } } else if (code) { switch (code) { case 'ENOTFOUND': log.error('Connection failure :(') log.error('Please check your internet') break case 'EAI_AGAIN': log.error('A temporary failure in name resolution occurred :(') break default: log.error('Unhandled exception') log.error('Please report the issue in https://github.com/vtex/toolbelt/issues') if (e.config?.url && e.config?.method) { log.error(`${e.config.method} ${e.config.url}`) } log.debug(e) } } else if (ErrorReport.isFlowIssue(e)) { if (e.message && e.message !== '') { log.error(e.message) } } else if (e instanceof SSEConnectionError) { log.error(e.message) } else { log.error('Unhandled exception') log.error('Please report the issue in https://github.com/vtex/toolbelt/issues') log.error('Raw error: ', e) } process.removeListener('unhandledRejection', onError) const errorReport = TelemetryCollector.getCollector().registerError(e) if (!ErrorReport.isFlowIssue(e)) { log.error(`ErrorID: ${errorReport.metadata.errorId}`) } process.exit(1) } export default async function(options: HookKeyOrOptions<'init'>) { // overwrite Help#showCommandHelp to customize help formating help.prototype.showHelp = function showHelp(_argv: string[]) { const sortedTopics = () => { let { topics } = this.config topics = topics.filter(t => this.opts.all || !t.hidden) topics = sortBy((t: any) => t.name, topics) topics = uniqBy((t: any) => t.name, topics) return topics } const showTopicHelp = (topic: Config.Topic) => { const { name } = topic const depth = name.split(':').length const subTopics = sortedTopics().filter( t => t.name.startsWith(name + ':') && t.name.split(':').length === depth + 1 ) console.log(this.topic(topic)) if (subTopics.length > 0) { console.log(this.topics(subTopics)) console.log('') } } const showCommandHelp = (command: Config.Command) => { const name = command.id const depth = name.split(':').length const subTopics = sortedTopics().filter( t => t.name.startsWith(name + ':') && t.name.split(':').length === depth + 1 ) const title = command.description && this.render(command.description).split('\n')[0] if (title) console.log(`${title}\n`) console.log(this.command(command)) console.log('') if (subTopics.length > 0) { console.log(this.topics(subTopics)) console.log('') } } const subject = getHelpSubject(_argv) if (subject) { const command = this.config.findCommand(subject) if (command) { showCommandHelp(command) return } const topic = this.config.findTopic(subject) if (topic) { showTopicHelp(topic) return } error(`command ${subject} not found`) } const commandsGroup: Record<string, number> = FeatureFlag.getSingleton().getFeatureFlagInfo<Record<string, number>>( 'COMMANDS_GROUP' ) const commandsId: Record<number, string> = FeatureFlag.getSingleton().getFeatureFlagInfo<Record<number, string>>( 'COMMANDS_GROUP_ID' ) const commandsGroupLength: number = Object.keys(commandsId).length const commands = this.config.commands .filter(c => !c.id.includes(':')) .map(c => { return { name: c.id, description: c.description } }) const topics = this.config.topics .filter(t => !t.name.includes(':')) .map(c => { return { name: c.name, description: c.description } }) const allCommands = commands.concat(topics) const groups: CommandI[][] = Object.keys(commandsId).map(_ => []) const cachedObject: Map<string, boolean> = new Map<string, boolean>() allCommands.forEach((command: CommandI) => { if (cachedObject.has(command.name)) return cachedObject.set(command.name, true) const commandGroupId = commandsGroup[command.name] if (commandGroupId) { groups[commandGroupId].push(command) } else { groups[commandsGroupLength - 1].push(command) } }) const renderedCommands = renderCommands(commandsId, groups, { render: this.render, opts: this.opts, config: this.config, }) console.log(renderedCommands) } axios.interceptors.request.use(config => { if (envCookies()) { config.headers.Cookie = `${envCookies()}; ${config.headers.Cookie || ''}` } return config }) process.on('unhandledRejection', onError) process.on('exit', () => { TelemetryCollector.getCollector().flush() }) await main(options, true) }
the_stack
import { Client, defaultSub, FlushCallback, NatsConnectionOptions, Payload, Req, ServerInfo, Sub, SubEvent, Subscription, VERSION } from './nats'; import {MuxSubscriptions} from './muxsubscriptions'; import {Callback, Transport, TransportHandlers} from './transport'; import {CONN_ERR_PREFIX, ErrorCode, NatsError} from './error'; import {EventEmitter} from 'events'; import {CR_LF, DEFAULT_PING_INTERVAL, EMPTY} from './const'; import {Server, Servers} from './servers'; import {TCPTransport} from './tcptransport'; import {Subscriptions} from './subscriptions'; import {DataBuffer} from './databuffer'; import {MsgBuffer} from './messagebuffer'; import {delay, settle} from './util'; import * as fs from 'fs'; import * as url from 'url'; import * as nkeys from 'ts-nkeys'; import Timeout = NodeJS.Timeout; // Protocol const MSG = /^MSG\s+([^\s\r\n]+)\s+([^\s\r\n]+)\s+(([^\s\r\n]+)[^\S\r\n]+)?(\d+)\r\n/i, OK = /^\+OK\s*\r\n/i, ERR = /^-ERR\s+('.+')?\r\n/i, PING = /^PING\r\n/i, PONG = /^PONG\r\n/i, INFO = /^INFO\s+([^\r\n]+)\r\n/i, SUBRE = /^SUB\s+([^\r\n]+)\r\n/i, CREDS = /\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/i, // Protocol SUB = 'SUB', UNSUB = 'UNSUB', CONNECT = 'CONNECT', FLUSH_THRESHOLD = 65536; const CRLF_BUF = Buffer.from('\r\n'); // Parser state enum ParserState { CLOSED = -1, AWAITING_CONTROL = 0, AWAITING_MSG_PAYLOAD = 1 } enum TlsRequirement { OFF = -1, ANY = 0, ON = 1 } /** * @hidden */ export class ProtocolHandler extends EventEmitter { options: NatsConnectionOptions; subscriptions: Subscriptions; muxSubscriptions = new MuxSubscriptions(); private client: Client; private closed: boolean = false; private connected: boolean = false; private currentServer!: Server; private encoding: BufferEncoding; private inbound = new DataBuffer(); private info: ServerInfo = {} as ServerInfo; private infoReceived: boolean = false; private msgBuffer?: MsgBuffer | null; private outbound = new DataBuffer(); private payload: Payload; private pingTimer?: Timeout; private pongs: any[] = []; private pout: number = 0; private reconnecting: boolean = false; private servers: Servers; private state: ParserState = ParserState.AWAITING_CONTROL; private transport: Transport; private url!: url.UrlObject; private wasConnected: boolean = false; private draining: boolean = false; private noMorePublishing: boolean = false; private connectionTimer?: NodeJS.Timeout | undefined; constructor(client: Client, options: NatsConnectionOptions) { super(); EventEmitter.call(this); this.client = client; this.options = options; this.encoding = options.encoding || 'utf8'; this.payload = options.payload || Payload.STRING; this.subscriptions = new Subscriptions(); this.subscriptions.on('subscribe', (sub) => { this.client.emit('subscribe', sub); }); this.subscriptions.on('unsubscribe', (unsub) => { this.client.emit('unsubscribe', unsub); }); this.servers = new Servers(!this.options.noRandomize, this.options.servers || [], this.options.url); this.transport = new TCPTransport(this.getTransportHandlers()); } static connect(client: Client, opts: NatsConnectionOptions): Promise<ProtocolHandler> { let lastError: Error|undefined; // loop through all the servers and bail or loop until connect if waitOnFirstConnect return new Promise<ProtocolHandler>(async(resolve, reject) => { let ph = new ProtocolHandler(client, opts); while(true) { // @ts-ignore let wait = ph.options.reconnectDelayHandler(); let maxWait = wait; for (let i=0; i < ph.servers.length(); i++) { const srv = ph.selectServer(); if (srv) { const now = Date.now(); if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) { try { await ph.connect(); resolve(ph); ph.startHandshakeTimeout(); return; } catch (err) { lastError = err; // if waitOnFirstConnect and fail, remove the server if (!ph.options.waitOnFirstConnect) { ph.servers.removeCurrentServer(); } } } else { maxWait = Math.min(maxWait, srv.lastConnect + wait - now); } } } // we could have removed all the known servers if (ph.servers.length() === 0) { const err = lastError || NatsError.errorForCode(ErrorCode.UNABLE_TO_CONNECT); reject(err); return; } // soonest to retry is maxWait await delay(maxWait); } }); } startHandshakeTimeout(): void { if(this.options.timeout) { this.connectionTimer = setTimeout(() => { this.processErr('conn_timeout'); }, this.options.timeout - this.transport.dialDuration()); } } flush(cb: FlushCallback): void { if (this.closed) { if (typeof cb === 'function') { cb(NatsError.errorForCode(ErrorCode.CONN_CLOSED)); return; } else { throw NatsError.errorForCode(ErrorCode.CONN_CLOSED); } } this.pongs.push(cb); this.sendCommand(ProtocolHandler.buildProtocolMessage('PING')); } closeAndEmit() { this.close(); this.client.emit('close'); } close(): void { this.cancelHeartbeat(); this.closed = true; this.removeAllListeners(); this.closeStream(); this.subscriptions.close(); this.muxSubscriptions.close(); this.state = ParserState.CLOSED; this.pongs = []; this.outbound.reset(); }; drain(): Promise<any> { if (this.closed) { return Promise.reject(NatsError.errorForCode(ErrorCode.CONN_CLOSED)); } if (this.draining) { return Promise.reject(NatsError.errorForCode(ErrorCode.CONN_DRAINING)); } this.draining = true; let subs = this.subscriptions.all(); let promises: Promise<SubEvent>[] = []; subs.forEach((sub) => { let p = this.drainSubscription(sub.sid); promises.push(p); }); return new Promise((resolve) => { settle(promises) .then((a) => { this.noMorePublishing = true; process.nextTick(() => { // send pending buffer this.flush(() => { this.close(); resolve(a); }); }); }) .catch(() => { // cannot happen }); }); } publish(subject: string, data: any, reply: string = ''): void { if (this.closed) { throw NatsError.errorForCode(ErrorCode.CONN_CLOSED); } if (this.noMorePublishing) { throw NatsError.errorForCode(ErrorCode.CONN_DRAINING); } data = this.toBuffer(data); let len = data.length; let proto: string; if (reply) { proto = `PUB ${subject} ${reply} ${len}`; } else { proto = `PUB ${subject} ${len}`; } this.sendCommand(ProtocolHandler.buildProtocolMessage(proto, data)) } subscribe(s: Sub): Subscription { if (this.isClosed()) { throw NatsError.errorForCode(ErrorCode.CONN_CLOSED); } if (this.draining) { throw NatsError.errorForCode(ErrorCode.CONN_DRAINING); } let sub = this.subscriptions.add(s) as Sub; if (sub.queue) { this.sendCommand(ProtocolHandler.buildProtocolMessage(`SUB ${sub.subject} ${sub.queue} ${sub.sid}`)); } else { this.sendCommand(ProtocolHandler.buildProtocolMessage(`SUB ${sub.subject} ${sub.sid}`)); } if (s.max) { this.unsubscribe(sub.sid, s.max); } return new Subscription(sub, this); } drainSubscription(sid: number): Promise<SubEvent> { if (this.closed) { return Promise.reject(NatsError.errorForCode(ErrorCode.CONN_CLOSED)); } if (!sid) { return Promise.reject(NatsError.errorForCode(ErrorCode.SUB_CLOSED)); } let s = this.subscriptions.get(sid); if (!s) { return Promise.reject(NatsError.errorForCode(ErrorCode.SUB_CLOSED)); } if (s.draining) { return Promise.reject(NatsError.errorForCode(ErrorCode.SUB_DRAINING)); } let sub = s; return new Promise((resolve) => { sub.draining = true; this.sendCommand(ProtocolHandler.buildProtocolMessage(`UNSUB ${sid}`)); this.flush(() => { this.subscriptions.cancel(sub); resolve({sid: sub.sid, subject: sub.subject, queue: sub.queue} as SubEvent); }); }) } unsubscribe(sid: number, max?: number) { if (!sid || this.closed) { return; } let s = this.subscriptions.get(sid); if (s) { if (max) { this.sendCommand(ProtocolHandler.buildProtocolMessage(`${UNSUB} ${sid} ${max}`)); } else { this.sendCommand(ProtocolHandler.buildProtocolMessage(`${UNSUB} ${sid}`)); } s.max = max; if (s.max === undefined || s.received >= s.max) { this.subscriptions.cancel(s); } } } request(r: Req): Request { if (this.closed) { throw NatsError.errorForCode(ErrorCode.CONN_CLOSED); } if (this.draining) { throw NatsError.errorForCode(ErrorCode.CONN_DRAINING); } this.initMux(); this.muxSubscriptions.add(r); return new Request(r, this); } numSubscriptions(): number { return this.subscriptions.length; } isClosed(): boolean { return this.closed; } cancelRequest(token: string, max?: number): void { if (!token || this.isClosed()) { return; } let r = this.muxSubscriptions.get(token); if (r) { r.max = max; if (r.max === undefined || r.received >= r.max) { this.muxSubscriptions.cancel(r); } } } private connect(): Promise<Transport> { this.currentServer.lastConnect = Date.now(); this.prepareConnection(); if (this.reconnecting) { this.currentServer.reconnects += 1; this.client.emit('reconnecting', this.url.href); } return this.transport.connect(this.url, this.options.timeout); } private flushPending(): void { if (!this.infoReceived) { return; } if (this.outbound.size()) { let d = this.outbound.drain(); this.transport.write(d); } } private static buildProtocolMessage(protocol: string, payload?: Buffer): Buffer { let protoLen = Buffer.byteLength(protocol); let cmd = protoLen + 2; let len = cmd; if (payload) { len += payload.byteLength + 2; } let buf = Buffer.allocUnsafe(len); buf.write(protocol); CRLF_BUF.copy(buf, protoLen); if (payload) { payload.copy(buf, cmd); CRLF_BUF.copy(buf, buf.byteLength - 2); } return buf; } private sendCommand(cmd: string | Buffer): void { // Buffer to cut down on system calls, increase throughput. // When receive gets faster, should make this Buffer based.. if (this.closed) { return; } let buf: Buffer; if (typeof cmd === 'string') { let len = Buffer.byteLength(cmd); buf = Buffer.allocUnsafe(len); buf.write(cmd, 0, len, 'utf8'); } else { buf = cmd as Buffer; } if (buf.byteLength === 0) { return; } this.outbound.fill(buf); if (this.outbound.length() === 1) { setImmediate(() => { this.flushPending(); }); } else if (this.outbound.size() > FLUSH_THRESHOLD) { this.flushPending(); } } private getTransportHandlers(): TransportHandlers { let handlers = {} as TransportHandlers; handlers.connect = () => { this.connected = true; }; handlers.close = () => { this.cancelHeartbeat(); let wasConnected = this.connected; this.closeStream(); if (wasConnected) { this.client.emit('disconnect', this.currentServer.url.href); } if (this.closed) { this.closeAndEmit(); } else { this.scheduleReconnect(); } }; handlers.error = (exception: Error) => { // If we were connected just return, close event will process if (this.wasConnected && this.currentServer.didConnect) { return; } // if the current server did not connect at all, and we in // general have not connected to any server, remove it from // this list. Unless overridden if (!this.wasConnected && !this.currentServer.didConnect) { // We can override this behavior with waitOnFirstConnect, which will // treat it like a reconnect scenario. if (this.options.waitOnFirstConnect) { // Pretend to move us into a reconnect state. this.currentServer.didConnect = true; } else { this.servers.removeCurrentServer(); } } // Only bubble up error if we never had connected // to the server and we only have one. if (!this.wasConnected && this.servers.length() === 0) { this.client.emit('error', new NatsError(CONN_ERR_PREFIX + exception, ErrorCode.CONN_ERR, exception)); } this.closeStream(); }; handlers.data = (data: Buffer) => { // If inbound exists, concat them together. We try to avoid this for split // messages, so this should only really happen for a split control line. // Long term answer is hand rolled parser and not regexp. this.inbound.fill(data); // Process the inbound queue. this.processInbound(); }; return handlers; } private prepareConnection(): void { // Commands may have been queued during reconnect. Discard everything except: // 1) ping requests with a pong callback // 2) publish requests // // Rationale: CONNECT and SUBs are written directly upon connecting, any PONG // response is no longer relevant, and any UNSUB will be accounted for when we // sync our SUBs. Without this, users of the client may miss state transitions // via callbacks, would have to track the client's internal connection state, // and may have to double buffer messages (which we are already doing) if they // wanted to ensure their messages reach the server. // copy outbound and reset it let buffers = this.outbound.reset(); let pongs = [] as Callback[]; if (buffers.length) { let pongIndex = 0; // find all the pings with associated callback, and pubs buffers.forEach((buf) => { let cmd = buf.toString('binary'); if (PING.test(cmd) && this.pongs !== null && pongIndex < this.pongs.length) { let f = this.pongs[pongIndex++]; if (f) { this.outbound.fill(buf); pongs.push(f); } } else if (cmd.length > 3 && cmd[0] === 'P' && cmd[1] === 'U' && cmd[2] === 'B') { this.outbound.fill(buf); } }); } this.pongs = pongs; this.state = ParserState.AWAITING_CONTROL; // Clear info processing. this.info = {} as ServerInfo; this.infoReceived = false; }; getInfo(): ServerInfo | null { if (this.infoReceived) { return this.info; } return null; } /** * Strips all SUBS commands from pending during initial connection completed since * we send the subscriptions as a separate operation. * * @api private */ private stripPendingSubs(): void { if (this.outbound.size() === 0) { return; } // FIXME: outbound doesn't peek so there's no packing let buffers = this.outbound.reset(); for (let i = 0; i < buffers.length; i++) { let s = buffers[i].toString('binary'); if (!SUBRE.test(s)) { // requeue the command this.sendCommand(buffers[i]); } } } /** * Sends existing subscriptions to new server after reconnect. * * @api private */ private sendSubscriptions(): void { if (this.subscriptions.length === 0 || !this.transport.isConnected()) { return; } let cmds: string[] = []; this.subscriptions.all().forEach((s) => { if (s.queue) { cmds.push(`${SUB} ${s.subject} ${s.queue} ${s.sid}${CR_LF}`); } else { cmds.push(`${SUB} ${s.subject} ${s.sid}${CR_LF}`); } if (s.max) { const max = s.max - s.received; if (max > 0) { cmds.push(`${UNSUB} ${s.sid} ${max}${CR_LF}`); } else { cmds.push(`${UNSUB} ${s.sid}${CR_LF}`); } } }); if (cmds.length) { this.transport.write(cmds.join('')); } } /** * Process the inbound data queue. * * @api private */ private processInbound(): void { // Hold any regex matches. let m; // For optional yield let start; if (!this.transport) { // if we are here, the stream was reaped and errors raised // if we continue. return; } // unpause if needed. this.transport.resume(); if (this.options.yieldTime !== undefined) { start = Date.now(); } while (!this.closed && this.inbound.size()) { switch (this.state) { case ParserState.AWAITING_CONTROL: // Regex only works on strings, so convert once to be more efficient. // Long term answer is a hand rolled parser, not regex. let len = this.inbound.protoLen(); if (len === -1) { return; } let bb = this.inbound.drain(len); if (bb.byteLength === 0) { return; } // specifying an encoding here like 'ascii' slows it down let buf = bb.toString(); if ((m = MSG.exec(buf)) !== null) { this.msgBuffer = new MsgBuffer(m, this.payload, this.encoding); this.state = ParserState.AWAITING_MSG_PAYLOAD; } else if ((m = OK.exec(buf)) !== null) { // Ignore for now.. } else if ((m = ERR.exec(buf)) !== null) { if (this.processErr(m[1])) { return; } } else if ((m = PONG.exec(buf)) !== null) { this.pout = 0; let cb = this.pongs && this.pongs.shift(); if (cb) { try { cb(); } catch (err) { console.error('error while processing pong', err); } } // FIXME: Should we check for exceptions? } else if ((m = PING.exec(buf)) !== null) { this.sendCommand(ProtocolHandler.buildProtocolMessage('PONG')); } else if ((m = INFO.exec(buf)) !== null) { this.info = JSON.parse(m[1]); // Check on TLS mismatch. if (this.checkTLSMismatch()) { return; } if (this.checkNoEchoMismatch()) { return; } if (this.checkNonceSigner()) { return; } // Always try to read the connect_urls from info let change = this.servers.processServerUpdate(this.info); if (change.deleted.length > 0 || change.added.length > 0) { this.client.emit('serversChanged', change); } // Process first INFO if (!this.infoReceived) { // Switch over to TLS as needed. // are we a tls socket? let encrypted = this.transport.isEncrypted(); if (this.info.tls_required === true && !encrypted) { this.transport.upgrade(this.options.tls, () => { this.flushPending(); }); } // Send the connect message and subscriptions immediately let cs = JSON.stringify(new Connect(this.currentServer, this.options, this.info)); this.transport.write(`${CONNECT} ${cs}${CR_LF}`); this.pongs.unshift(() => { if(this.connectionTimer) { clearTimeout(this.connectionTimer); this.connectionTimer = undefined; } this.sendSubscriptions(); this.stripPendingSubs(); this.scheduleHeartbeat(); this.connectCB(); }); this.transport.write(ProtocolHandler.buildProtocolMessage('PING')); // Mark as received this.flushPending(); this.infoReceived = true; } } else { // FIXME, check line length for something weird. // Nothing here yet, return return; } break; case ParserState.AWAITING_MSG_PAYLOAD: if (!this.msgBuffer) { break; } // wait for more data to arrive if (this.inbound.size() < this.msgBuffer.length) { return; } // drain the number of bytes we need let dd = this.inbound.drain(this.msgBuffer.length); this.msgBuffer.fill(dd); this.processMsg(); this.state = ParserState.AWAITING_CONTROL; this.msgBuffer = null; // Check to see if we have an option to yield for other events after yieldTime. if (start !== undefined && this.options && this.options.yieldTime) { if ((Date.now() - start) > this.options.yieldTime) { this.transport.pause(); this.client.emit('yield'); setImmediate(() => { this.processInbound(); }); return; } } break; } } } private clientTLSRequirement(): TlsRequirement { if (this.options.tls === undefined) { return TlsRequirement.ANY; } if (this.options.tls === false) { return TlsRequirement.OFF; } return TlsRequirement.ON; } /** * Check for TLS configuration mismatch. * * @api private */ private checkTLSMismatch(): boolean { switch (this.clientTLSRequirement()) { case TlsRequirement.OFF: if (this.info.tls_required) { this.client.emit('error', NatsError.errorForCode(ErrorCode.SECURE_CONN_REQ)); this.closeStream(); return true; } break; case TlsRequirement.ON: if (!this.info.tls_required) { this.client.emit('error', NatsError.errorForCode(ErrorCode.NON_SECURE_CONN_REQ)); this.closeStream(); return true; } break; case TlsRequirement.ANY: // tls auto-upgrade break; } let cert = false; if (this.options.tls && typeof this.options.tls === 'object') { cert = this.options.tls.cert != null; } if (this.info.tls_verify && !cert) { this.client.emit('error', NatsError.errorForCode(ErrorCode.CLIENT_CERT_REQ)); this.closeStream(); return true; } return false; } /** * Check no echo * @api private */ private checkNoEchoMismatch(): boolean { if ((this.info.proto === undefined || this.info.proto < 1) && this.options.noEcho) { this.client.emit('error', NatsError.errorForCode(ErrorCode.NO_ECHO_NOT_SUPPORTED)); this.closeStream(); return true; } return false; } private checkNonceSigner(): boolean { if (this.info.nonce === undefined) { return false; } if (this.options.nkeyCreds) { try { let seed = nkeys.fromSeed(this.getNkeyCreds()); this.options.nkey = seed.getPublicKey().toString(); this.options.nonceSigner = (nonce: string): any => { return this.nkeyNonceSigner(Buffer.from(nonce)); } } catch (err) { this.client.emit('error', err); this.closeStream(); return true; } } if (this.options.userCreds) { try { // simple test that we got a creds file - exception is thrown // if the file is not a valid creds file this.getUserCreds(true); this.options.nonceSigner = (nonce: string): any => { return this.credsNonceSigner(Buffer.from(nonce)); }; this.options.userJWT = () => { return this.loadJwt(); } } catch (err) { this.client.emit('error', err); this.closeStream(); return true; } } if (this.options.nonceSigner === undefined) { this.client.emit('error', NatsError.errorForCode(ErrorCode.SIGNATURE_REQUIRED)); this.closeStream(); return true; } if (this.options.nkey === undefined && this.options.userJWT === undefined) { this.client.emit('error', NatsError.errorForCode(ErrorCode.NKEY_OR_JWT_REQ)); this.closeStream(); return true; } return false; } private getNkeyCreds(): Buffer { if (this.options.nkeyCreds) { return fs.readFileSync(this.options.nkeyCreds); } throw NatsError.errorForCode(ErrorCode.BAD_NKEY_SEED); } // returns a regex array - first match is the jwt, second match is the nkey private getUserCreds(jwt = false): RegExpExecArray { if (this.options.userCreds) { let buf = fs.readFileSync(this.options.userCreds); if (buf) { let re = jwt ? CREDS : new RegExp(CREDS, 'g'); let contents = buf.toString(); // first match jwt let m = re.exec(contents); if (m === null) { throw NatsError.errorForCode(ErrorCode.BAD_CREDS); } if (jwt) { return m; } // second match the seed m = re.exec(contents); if (m === null) { throw NatsError.errorForCode(ErrorCode.BAD_CREDS); } return m; } } throw NatsError.errorForCode(ErrorCode.BAD_CREDS); } // built-in handler for signing nonces based on a nkey seed file private nkeyNonceSigner(nonce: Buffer): any { try { let m = this.getNkeyCreds(); let sk = nkeys.fromSeed(m); return sk.sign(nonce) } catch (ex) { this.closeStream(); this.client.emit('error', ex) } } // built-in handler for signing nonces based on user creds file private credsNonceSigner(nonce: Buffer): any { try { let m = this.getUserCreds(); let sk = nkeys.fromSeed(Buffer.from(m[1])); return sk.sign(nonce) } catch (ex) { this.closeStream(); this.client.emit('error', ex) } } // built-in handler for loading user jwt based on user creds file private loadJwt(): any { try { let m = this.getUserCreds(true); return m[1]; } catch (ex) { this.closeStream(); this.client.emit('error', ex) } } /** * Process a delivered message and deliver to appropriate subscriber. * * @api private */ private processMsg(): void { if (this.subscriptions.length === 0 || !this.msgBuffer) { return; } let sub = this.subscriptions.get(this.msgBuffer.msg.sid); if (!sub) { return; } sub.received += 1; // cancel the timeout if we got the expected number of messages if (sub.timeout && (sub.max === undefined || sub.received >= sub.max)) { Subscription.cancelTimeout(sub); } // if we got max number of messages, unsubscribe if (sub.max !== undefined && sub.received >= sub.max) { this.unsubscribe(sub.sid); } if (sub.callback) { try { if (this.msgBuffer.error) { sub.callback(this.msgBuffer.error, this.msgBuffer.msg); } else { sub.callback(null, this.msgBuffer.msg); } } catch (error) { // client could have died this.client.emit('error', error); } } }; static toError(s: string) { let t = s ? s.toLowerCase() : ''; if (t.indexOf('permissions violation') !== -1) { return new NatsError(s, ErrorCode.PERMISSIONS_VIOLATION); } else if (t.indexOf('authorization violation') !== -1) { return new NatsError(s, ErrorCode.AUTHORIZATION_VIOLATION); } else if (t.indexOf('conn_timeout') !== -1) { return NatsError.errorForCode(ErrorCode.CONN_TIMEOUT); } else { return new NatsError(s, ErrorCode.NATS_PROTOCOL_ERR); } } /** * ProcessErr processes any error messages from the server * Return true if the error closed the connection * @api private */ private processErr(s: string): boolean { // current NATS clients, will raise an error and close on any errors // except stale connection and permission errors let err = ProtocolHandler.toError(s); switch(err.code) { case ErrorCode.AUTHORIZATION_VIOLATION: this.client.emit('error', err); // closeStream() triggers a reconnect if allowed this.closeStream(); return true; case ErrorCode.PERMISSIONS_VIOLATION: // just emit this.client.emit('permissionError', err); return false; case ErrorCode.CONN_TIMEOUT: this.client.emit('error', NatsError.errorForCode(ErrorCode.CONN_TIMEOUT)); this.closeStream(); return true; default: this.client.emit('error', err); // closeStream() triggers a reconnect if allowed this.closeStream(); return true; } }; /** * Close down the stream and clear state. * * @api private */ private closeStream(): void { this.transport.destroy(); if (this.connected || this.closed) { this.pongs = []; this.pout = 0; this.connected = false; this.inbound.reset(); } }; /** * Setup a timer event to attempt reconnect. * * @api private */ private scheduleReconnect(): void { if (this.closed) { return; } // Just return if no more servers or if no reconnect is desired if (this.servers.length() === 0 || this.options.reconnect === false) { this.closeAndEmit(); return; } // Don't set reconnecting state if we are just trying for the first time. if (this.wasConnected) { this.reconnecting = true; } //@ts-ignore let wait = this.options.reconnectDelayHandler(); let maxWait = wait; const now = Date.now(); for (let i=0; i < this.servers.length(); i++) { const srv = this.selectServer(); if (srv) { const mra = this.options.maxReconnectAttempts || 0; if (mra !== -1 && srv.reconnects >= mra) { this.servers.removeCurrentServer(); continue; } // if never connected or last connect is past the wait, try right away if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) { this.reconnect(); return; } // start collecting min retry maxWait = Math.min(maxWait, srv.lastConnect + wait - now); } } // we could have removed all the known servers if (this.servers.length() === 0) { this.closeAndEmit(); return; } // soonest to retry is maxWait setTimeout(() => { this.scheduleReconnect() }, maxWait); } private scheduleHeartbeat(): void { this.pingTimer = setTimeout(() => { this.client.emit('pingtimer'); if (this.closed) { return; } // we could be waiting on the socket to connect if (this.transport.isConnected()) { this.client.emit('pingcount', this.pout); this.pout++; // @ts-ignore if (this.pout > this.options.maxPingOut) { // processErr will scheduleReconnect this.processErr(ErrorCode.STALE_CONNECTION_ERR); // don't reschedule, new connection initiated return; } else { // send the ping this.sendCommand(ProtocolHandler.buildProtocolMessage('PING')); if (this.pongs) { // no callback this.pongs.push(undefined); } } } // reschedule this.scheduleHeartbeat(); }, this.options.pingInterval || DEFAULT_PING_INTERVAL, this); } private cancelHeartbeat(): void { if (this.pingTimer) { clearTimeout(this.pingTimer); delete this.pingTimer; } } /** * Reconnect to the server. * * @api private */ private reconnect(): void { if (this.closed) { return; } const ph = this; this.connect().then(() => { ph.startHandshakeTimeout(); // all good the pong handler deals with it }).catch(() => { // the stream handler deals with it }); } /** * Properly select the next server. * We rotate the server list as we go, * we also pull auth from urls as needed, or * if they were set in options use that as override. * * @api private */ private selectServer(): Server | undefined { let server = this.servers.selectServer(); if (server === undefined) { return undefined } // Place in client context. this.currentServer = server; this.url = server.url; return this.currentServer; } private toBuffer(data: any = undefined): Buffer { if (this.options.payload === Payload.JSON) { // undefined is not a valid JSON-serializable value, but null is data = data === undefined ? null : data; try { data = JSON.stringify(data); } catch (e) { throw NatsError.errorForCode(ErrorCode.BAD_JSON); } } else { data = data || EMPTY; } // if not a buffer, it is already serialized json or a string if (!Buffer.isBuffer(data)) { // must be utf8 - omitting encoding to prevent clever change data = Buffer.from(data); } return data; } private initMux(): void { let mux = this.subscriptions.getMux(); if (!mux) { let inbox = this.muxSubscriptions.init(); let sub = defaultSub(); // dot is already part of mux sub.subject = `${inbox}*`; sub.callback = this.muxSubscriptions.dispatcher(); this.subscriptions.setMux(sub); this.subscribe(sub); } } /** * Callback for first flush/connect. * * @api private */ private connectCB(): void { let event = this.reconnecting ? 'reconnect' : 'connect'; this.reconnecting = false; this.wasConnected = true; if (this.currentServer) { this.currentServer.didConnect = true; this.currentServer.reconnects = 0; } // copy the info let info: ServerInfo = {} as ServerInfo; try { info = JSON.parse(JSON.stringify(this.info)); } catch (err) { // ignore } this.client.emit(event, this.client, this.currentServer.url.href, info); this.flushPending(); } } export class Request { token: string; private protocol: ProtocolHandler; constructor(req: Req, protocol: ProtocolHandler) { this.token = req.token; this.protocol = protocol; } cancel(): void { this.protocol.cancelRequest(this.token, 0); } } export class Connect { lang: string = 'typescript'; version: string = VERSION; verbose: boolean = false; pedantic: boolean = false; protocol: number = 1; user?: string; pass?: string; auth_token?: string; name?: string; echo?: boolean; sig?: string; jwt?: string; nkey?: string; constructor(server: Server, opts: NatsConnectionOptions, info: ServerInfo) { opts = opts || {} as NatsConnectionOptions; if (opts.user) { this.user = opts.user; this.pass = opts.pass; } if (opts.token) { this.auth_token = opts.token; } let auth = server.getCredentials(); if (auth) { if (auth.length !== 1) { if (this.user === undefined) { this.user = auth[0]; } if (this.pass === undefined) { this.pass = auth[1]; } } else if (this.auth_token === undefined) { this.auth_token = auth[0]; } } if (opts.name) { this.name = opts.name; } if (opts.verbose !== undefined) { this.verbose = opts.verbose; } if (opts.pedantic !== undefined) { this.pedantic = opts.pedantic; } if (opts.noEcho) { this.echo = false; } if (info.nonce && opts.nonceSigner) { let sig = opts.nonceSigner(info.nonce); this.sig = sig.toString('base64'); } if (opts.userJWT) { if (typeof opts.userJWT === 'function') { this.jwt = opts.userJWT(); } else { this.jwt = opts.userJWT; } } if (opts.nkey) { this.nkey = opts.nkey; } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_forecastinstance_Information { interface tab_tab_Sections { section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_tab extends DevKit.Controls.ITab { Section: tab_tab_Sections; } interface Tabs { tab: tab_tab; } interface Body { Tab: Tabs; /** Shows the actual value (money) achieved toward the target as of the last rollup date. */ msdyn_actualamount: DevKit.Controls.Money; /** Unique identifier for the forecast definition that is associated with the forecast. */ msdyn_forecastdefinitionid: DevKit.Controls.Lookup; /** Unique identifier for the forecast recurrence associated with the forecast. */ msdyn_forecastrecurrenceid: DevKit.Controls.Lookup; /** Shows the changed value of the best case rollup (Money type) as of the last rolled-up date. */ msdyn_manualbestcaseamount: DevKit.Controls.Money; /** Shows the changed value of the committed rollup (Money type) as of the last rolled-up date. */ msdyn_manualcommittedamount: DevKit.Controls.Money; /** Shows the changed value of the pipeline rollup (Money type) as of the last rolled-up date. */ msdyn_manualpipelineamount: DevKit.Controls.Money; /** Shows the percentage achieved against the target. */ msdyn_percentageachieved: DevKit.Controls.Decimal; /** Select a target (Money type) to track a monetary amount, such as estimated revenue from an opportunity. */ msdyn_targetamount: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } } class Formmsdyn_forecastinstance_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_forecastinstance_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_forecastinstance_Information */ Body: DevKit.Formmsdyn_forecastinstance_Information.Body; } class msdyn_forecastinstanceApi { /** * DynamicsCrm.DevKit msdyn_forecastinstanceApi * @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; /** Shows the actual value (money) achieved toward the target as of the last rollup date. */ msdyn_actualamount: DevKit.WebApi.MoneyValue; /** Value of the Actual (Money) in base currency. */ msdyn_actualamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the rollup value (money) for the best case category as of the last rollup date. */ msdyn_bestcaseamount: DevKit.WebApi.MoneyValue; /** Value of the BestCase in base currency. */ msdyn_bestcaseamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the committed rollup value (money) as of the last rollup date. */ msdyn_committedamount: DevKit.WebApi.MoneyValue; /** Value of the Committed in base currency. */ msdyn_committedamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier for the forecast definition that is associated with the forecast. */ msdyn_forecastdefinitionid: DevKit.WebApi.LookupValue; /** Unique identifier for the forecast. */ msdyn_forecastinstanceId: DevKit.WebApi.GuidValue; /** For internal use only. */ msdyn_forecastinstancetype: DevKit.WebApi.IntegerValue; /** Name of the forecast. */ msdyn_forecastname: DevKit.WebApi.StringValue; /** Unique identifier for the parent forecast that is associated with the forecast. */ msdyn_forecastparentid: DevKit.WebApi.LookupValue; /** Unique identifier for the forecast recurrence associated with the forecast. */ msdyn_forecastrecurrenceid: DevKit.WebApi.LookupValue; /** Select whether the bestcase rollup has been manually updated. */ msdyn_ismanualbestcase: DevKit.WebApi.IntegerValue; /** Select whether the committed rollup has been manually updated. */ msdyn_ismanualcommitted: DevKit.WebApi.IntegerValue; /** Select whether the pipeline rollup has been manually updated. */ msdyn_ismanualpipeline: DevKit.WebApi.IntegerValue; /** Is quota source manual */ msdyn_isquotasourcemanual: DevKit.WebApi.BooleanValue; /** For internal use only. */ msdyn_level: DevKit.WebApi.IntegerValue; /** Shows the changed value of the best case rollup (Money type) as of the last rolled-up date. */ msdyn_manualbestcaseamount: DevKit.WebApi.MoneyValue; /** Value of the Manual BestCase in base currency. */ msdyn_manualbestcaseamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the changed value of the committed rollup (Money type) as of the last rolled-up date. */ msdyn_manualcommittedamount: DevKit.WebApi.MoneyValue; /** Value of the Manual Committed in base currency. */ msdyn_manualcommittedamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the changed value of the pipeline rollup (Money type) as of the last rolled-up date. */ msdyn_manualpipelineamount: DevKit.WebApi.MoneyValue; /** Value of the Manual Pipeline in base currency. */ msdyn_manualpipelineamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier for the matching goal associated with the forecast. */ msdyn_matchinggoalid: DevKit.WebApi.LookupValue; /** Shows the percentage achieved against the target. */ msdyn_percentageachieved: DevKit.WebApi.DecimalValueReadonly; /** Shows the pipeline rollup value (money) as of the last rollup date. */ msdyn_pipelineamount: DevKit.WebApi.MoneyValue; /** Value of the Pipeline in base currency. */ msdyn_pipelineamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the recurrence index of the forecast created from the forecast definition. */ msdyn_recurrenceindex: DevKit.WebApi.IntegerValue; /** Select a target (Money type) to track a monetary amount, such as estimated revenue from an opportunity. */ msdyn_targetamount: DevKit.WebApi.MoneyValue; /** Value of the Target (Money) in base currency. */ msdyn_targetamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Forecast */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Forecast */ 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; /** 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_forecastinstance { 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 * as d3 from "d3"; import { assert } from "chai"; import * as Plottable from "../../src"; import { TierLabelPosition } from "../../src/axes/timeAxis"; import * as TestMethods from "../testMethods"; describe("TimeAxis", () => { const orientations: ["top", "bottom"] = ["top", "bottom"]; describe("setting the orientation", () => { it("throws an error when setting a vertical orientation", () => { const scale = new Plottable.Scales.Time(); assert.throws(() => new Plottable.Axes.Time(scale, "left" as any), "horizontal"); assert.throws(() => new Plottable.Axes.Time(scale, "right" as any), "horizontal"); }); it("cannot change to a vertical orientation", () => { const scale = new Plottable.Scales.Time(); const originalOrientation: "bottom" = "bottom"; const axis = new Plottable.Axes.Time(scale, originalOrientation); assert.throws(() => axis.orientation("left" as any), "horizontal"); assert.throws(() => axis.orientation("right" as any), "horizontal"); assert.strictEqual(axis.orientation(), originalOrientation, "orientation unchanged"); axis.destroy(); }); }); describe("rendering in edge case scenarios", () => { it("does not error when setting the domain to a large span", () => { const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, "bottom"); const div = TestMethods.generateDiv(); axis.renderTo(div); // very large time span assert.doesNotThrow(() => scale.domain([new Date(0, 0, 1, 0, 0, 0, 0), new Date(5000, 0, 1, 0, 0, 0, 0)])); axis.destroy(); div.remove(); }); it("does not error when setting the domain to a small span", () => { const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, "bottom"); const div = TestMethods.generateDiv(); axis.renderTo(div); // very small time span assert.doesNotThrow(() => scale.domain([new Date(0, 0, 1, 0, 0, 0, 0), new Date(0, 0, 1, 0, 0, 0, 100)])); axis.destroy(); div.remove(); }); }); function assertVisibleLabelsDoNotOverlap(axis: Plottable.Axes.Time) { axis.content().selectAll<Element, any>(`.${Plottable.Axis.TICK_LABEL_CLASS}-container`).each(function(d, i) { const container = d3.select(this); const visibleTickLabels = container .selectAll<Element, any>(`.${Plottable.Axis.TICK_LABEL_CLASS}`) .filter(function() { return d3.select(this).style("visibility") === "visible"; }); visibleTickLabels.each(function(d2, j) { const clientRect1 = this.getBoundingClientRect(); visibleTickLabels.filter((d3, k) => k > j).each(function(d3, k) { const clientRect2 = this.getBoundingClientRect(); assert.isFalse(Plottable.Utils.DOM.clientRectsOverlap(clientRect1, clientRect2), "tick labels don't overlap"); }); }); }); } orientations.forEach((orientation) => { const domains = [ // 100 year span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2100, 0, 1, 0, 0, 0, 0)], // 1 year span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 11, 31, 0, 0, 0, 0)], // 1 month span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 1, 1, 0, 0, 0, 0)], // 1 day span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 0, 1, 23, 0, 0, 0)], // 1 hour span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 0, 1, 1, 0, 0, 0)], // 1 minute span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 0, 1, 0, 1, 0, 0)], // 1 second span [new Date(2000, 0, 1, 0, 0, 0, 0), new Date(2000, 0, 1, 0, 0, 1, 0)], ]; it(`does not overlap visible tick labels with orientation ${orientation}`, () => { const div = TestMethods.generateDiv(); const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, orientation); axis.renderTo(div); domains.forEach((domain) => { scale.domain(domain); assertVisibleLabelsDoNotOverlap(axis); }); axis.destroy(); div.remove(); }); }); function assertTickMarksAndLabelsDoNotOverlap(axis: Plottable.Axes.Time) { const tickMarks = axis.content().selectAll<Element, any>(`.${Plottable.Axis.TICK_MARK_CLASS}:not(.${Plottable.Axis.END_TICK_MARK_CLASS})`); assert.operator(tickMarks.size(), ">=", 1, "There is at least one tick mark in the test"); const tickLabels = axis.content().selectAll<Element, any>(`.${Plottable.Axis.TICK_LABEL_CLASS}`).filter(function(d, i) { return d3.select(this).style("visibility") !== "hidden"; }); assert.operator(tickLabels.size(), ">=", 1, "There is at least one tick label in the test"); tickMarks.each(function(tickMark, i) { const tickMarkRect = this.getBoundingClientRect(); tickLabels.each(function(tickLabel, j) { const tickLabelRect = this.getBoundingClientRect(); const isOverlap = Plottable.Utils.DOM.clientRectsOverlap(tickMarkRect, tickLabelRect); assert.isFalse(isOverlap, `Tick mark ${i} should not overlap with tick label ${j}`); }); }); } const tierLabelPositions: TierLabelPosition[] = ["center", "between"]; orientations.forEach((orientation) => { tierLabelPositions.forEach((tierLabelPosition) => { it(`does not overlap labels with tick marks when label position is ${tierLabelPosition} and orientation ${orientation}`, () => { const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, orientation); const div = TestMethods.generateDiv(); axis.tierLabelPositions([tierLabelPosition, tierLabelPosition]); axis.renderTo(div); assertTickMarksAndLabelsDoNotOverlap(axis); div.remove(); }); }); }); describe("drawing tick marks", () => { let axis: Plottable.Axes.Time; let div: d3.Selection<HTMLDivElement, any, any, any>; beforeEach(() => { const scale = new Plottable.Scales.Time(); axis = new Plottable.Axes.Time(scale, "bottom"); div = TestMethods.generateDiv(); }); afterEach(() => { axis.destroy(); }); it("renders end ticks at the two edges", () => { axis.renderTo(div); const firstTick = axis.content().select(`.${Plottable.Axis.TICK_MARK_CLASS}`); assert.strictEqual(firstTick.attr("x1"), "0", "first tick mark at beginning of axis"); assert.strictEqual(firstTick.attr("x2"), "0", "first tick mark at beginning of axis"); const lastTick = axis.content().select(`.${Plottable.Axis.TICK_MARK_CLASS}:last-child`); assert.strictEqual(lastTick.attr("x1")+"px", div.style("width"), "last end tick mark at end of axis"); assert.strictEqual(lastTick.attr("x2")+"px", div.style("width"), "last end tick mark at end of axis"); div.remove(); }); it("adds the end-tick class to the first and last ticks", () => { axis.renderTo(div); const firstTick = axis.content().select(`.${Plottable.Axis.TICK_MARK_CLASS}`); assert.isTrue(firstTick.classed(Plottable.Axis.END_TICK_MARK_CLASS), "first end tick has end-tick-mark class"); const lastTick = axis.content().select(`.${Plottable.Axis.TICK_MARK_CLASS}:last-child`); assert.isTrue(lastTick.classed(Plottable.Axis.END_TICK_MARK_CLASS), "last end tick has end-tick-mark class"); div.remove(); }); it("sets the length of the end ticks to the specified value when tierLabelPosition is set to center", () => { axis.tierLabelPositions(["center", "center"]); axis.renderTo(div); const endTicks = axis.content().selectAll<Element, any>(`.${Plottable.Axis.END_TICK_MARK_CLASS}`); assert.operator(endTicks.size(), ">=", 1, "At least one end tick mark is selected in the test"); endTicks.each(function(d, i){ const endTick = d3.select(this); const tickLength = Math.abs(TestMethods.numAttr(endTick, "y1") - TestMethods.numAttr(endTick, "y2")); assert.closeTo(tickLength, axis.endTickLength(), window.Pixel_CloseTo_Requirement, `end tick mark ${i} length should equal the specified amount`); }); div.remove(); }); }); describe("formatting annotation ticks", () => { it("formats the dates to '{{abbreviated weekday}} {{abbreviated month}} {{day of month}}, {{year}}' by default", () => { const div = TestMethods.generateDiv(); const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, "bottom"); axis.annotationsEnabled(true); const testDate = new Date((scale.domain()[0].valueOf() + scale.domain()[1].valueOf()) / 2); axis.annotatedTicks([testDate]); const defaultFormatter = Plottable.Formatters.time("%a %b %d, %Y"); const annotationFormatter = axis.annotationFormatter(); assert.strictEqual(annotationFormatter(testDate), defaultFormatter(testDate), "formats to a default customized time formatter"); axis.renderTo(div); const annotationLabels = axis.content().selectAll<Element, any>(".annotation-label"); annotationLabels.each(function(d, i) { const annotationLabel = d3.select(this); assert.strictEqual(annotationLabel.text(), defaultFormatter(d), "formats to a default customized time formatter"); }); div.remove(); }); }); describe("calculating space", () => { let axis: Plottable.Axes.Time; let div: d3.Selection<HTMLDivElement, any, any, any>; beforeEach(() => { const scale = new Plottable.Scales.Time(); axis = new Plottable.Axes.Time(scale, "bottom"); div = TestMethods.generateDiv(); }); afterEach(() => { axis.destroy(); }); it("grows in height for each added tier", () => { axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, ], ]); axis.renderTo(div); const oneTierHeight = axis.height(); axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, ], ]); const twoTierHeight = axis.height(); assert.operator(twoTierHeight, ">", oneTierHeight, "two-tiered a taller than one-tiered"); axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, ], ]); const threeTierHeight = axis.height(); assert.operator(threeTierHeight, ">", twoTierHeight, "three-tiered is taller than the two-tiered"); div.remove(); }); it("shrinks in height if a newly set configuration provides less tiers", () => { axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, ], ]); axis.renderTo(div); const twoTierHeight = axis.height(); axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e")}, ], ]); const newHeight = axis.height(); assert.operator(newHeight, "<", twoTierHeight, "two-tier time axis shrinks when changed to 1 tier"); div.remove(); }); it("includes the margin, label padding, and tick length in the height", () => { axis.margin(100); axis.anchor(div); axis.computeLayout({ x: 0, y: 0 }, 400, 400); const minimumHeight = axis.tickLabelPadding() + axis.margin() + axis.innerTickLength(); assert.operator(axis.height(), ">=", minimumHeight, "height includes all relevant pieces"); div.remove(); }); it("includes the annotation space in the height", () => { axis.annotationsEnabled(true); axis.annotationTierCount(2); axis.anchor(div); axis.computeLayout({ x: 0, y: 0}, Plottable.Utils.DOM.elementWidth(div), Plottable.Utils.DOM.elementHeight(div)); const twoAnnotationTierHeight = axis.height(); axis.annotationTierCount(3); axis.computeLayout({ x: 0, y: 0}, Plottable.Utils.DOM.elementWidth(div), Plottable.Utils.DOM.elementHeight(div)); assert.operator(axis.height(), ">", twoAnnotationTierHeight, "height includes all relevant pieces"); axis.destroy(); div.remove(); }); }); describe("drawing tiers", () => { it("draws all of tiers within the component space", () => { const div = TestMethods.generateDiv(); const constrainedHeight = 50; div.style("height", constrainedHeight+"px"); const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, "bottom"); const tiersToCreate = 15; const configuration = Array.apply(null, Array(tiersToCreate)).map(() => { return {interval: Plottable.TimeInterval.day, step: 2, formatter: Plottable.Formatters.time("%a %e") }; }); axis.axisConfigurations([configuration]); axis.renderTo(div); const axisBoundingRect = axis.element().node().getBoundingClientRect(); const isInsideAxisBoundingRect = function(innerRect: ClientRect) { return Math.floor(innerRect.bottom) <= Math.ceil(axisBoundingRect.bottom) + window.Pixel_CloseTo_Requirement && Math.floor(axisBoundingRect.top) <= Math.ceil(innerRect.top) + window.Pixel_CloseTo_Requirement; }; axis.content() .selectAll<Element, any>(`.${Plottable.Axes.Time.TIME_AXIS_TIER_CLASS}`) .each(function(d, i) { const tier = d3.select(this); let visibility = tier.style("visibility"); // HACKHACK window.getComputedStyle().visibility returns "inherit" in IE instead of an actual value if (visibility === "inherit") { visibility = getInheritedVisibilityProperty(tier.node()); } if (isInsideAxisBoundingRect(tier.node().getBoundingClientRect())) { assert.strictEqual(visibility, "visible", `tier ${i} inside axis should be visible`); } else { assert.strictEqual(visibility, "hidden", `tier ${i} outside axis should not be visible`); } }); div.remove(); axis.destroy(); function getInheritedVisibilityProperty(element: Element) { while (element) { const visibility = window.getComputedStyle(element).visibility; if (visibility !== "inherit") { return visibility; } element = <Element> element.parentNode; } return "visible"; } }); }); describe("configuring the label presentation", () => { it("allows usage of a custom configuration list", () => { const div = TestMethods.generateDiv(); const scale = new Plottable.Scales.Time(); const axis = new Plottable.Axes.Time(scale, "bottom"); const formatter = Plottable.Formatters.time("%a %e"); axis.axisConfigurations([ [ {interval: Plottable.TimeInterval.day, step: 2, formatter: formatter}, ], ]); axis.renderTo(div); const tickLabels = axis.content().selectAll<Element, any>(".tick-label"); tickLabels.each(function(d, i) { const tickLabel = d3.select(this); assert.strictEqual(tickLabel.text(), formatter(d), "formats to a customized time formatter"); }); axis.destroy(); div.remove(); }); }); describe("limiting timeinterval precision", () => { it("uses default axis config when maxTimeIntervalPrecision not set", () => { const div = TestMethods.generateDiv(); const axis = new Plottable.Axes.Time(new Plottable.Scales.Time(), "bottom"); axis.renderTo(div); const config = axis.currentAxisConfiguration(); assert.strictEqual(config.length, 2, "2 tiers"); assert.strictEqual(config[0].interval, "hour"); assert.strictEqual(config[1].interval, "day"); axis.destroy(); div.remove(); }); it("still works when maxTimeIntervalPrecision is set high", () => { const div = TestMethods.generateDiv(); const axis = new Plottable.Axes.Time(new Plottable.Scales.Time(), "bottom"); axis.maxTimeIntervalPrecision("minute"); axis.renderTo(div); const config = axis.currentAxisConfiguration(); assert.strictEqual(config.length, 2, "2 tiers"); assert.strictEqual(config[0].interval, "hour"); assert.strictEqual(config[1].interval, "day"); axis.destroy(); div.remove(); }); it("limits axis config when maxTimeIntervalPrecision is set", () => { const div = TestMethods.generateDiv(); const axis = new Plottable.Axes.Time(new Plottable.Scales.Time(), "bottom"); axis.maxTimeIntervalPrecision("day"); axis.renderTo(div); const config = axis.currentAxisConfiguration(); // day/month is most precise valid config after hour/day assert.strictEqual(config.length, 2, "2 tiers"); assert.strictEqual(config[0].interval, "day"); assert.strictEqual(config[1].interval, "month"); axis.destroy(); div.remove(); }); }); });
the_stack
import { Typography } from 'antd'; import React, { useState } from 'react'; import { Fa500Px, FaAdobe, FaAdversal, FaAirbnb, FaAlipay, FaAmazon, FaAmazonPay, FaApple, FaAppStoreIos, FaBehanceSquare, FaGoogle, FaInstagramSquare, FaLaugh, FaMagento, FaOpera, FaYinYang } from 'react-icons/fa'; import { Helmet } from 'umi'; import packageInfo from '../config'; import { Api, Code, Code0, Code1, Code2, Code3, Code4, Footer } from './components'; import './index.less'; import Intro from './intro'; // import Background from 'smart-background'; import Background from './package'; const { Title, Paragraph, Text, Link } = Typography; const images = [ 'https://cdn.dribbble.com/users/3550736/screenshots/16244010/media/cead570591b124ed91c34dc9958f315c.jpg?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/3550736/screenshots/16244010/media/f03f7960c2d88f6fec3b43b9e1b5935b.jpg?compress=1&resize=1600x1200', 'https://cdn.dribbble.com/users/4666085/screenshots/16244479/media/d3d5b6d3e546fa17170b5daa46de375e.png?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/4588540/screenshots/16243929/media/430745b49a20f462bbfbdabc77b542f9.png?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/4835348/screenshots/16229715/media/5c68b55f75b04e96ff6f110ab2617996.png?compress=1&resize=800x600', 'https://cdn.dribbble.com/users/323673/screenshots/16223702/media/60b90d6e0f673e0ccee30056b8ae83d2.png?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/427857/screenshots/16157651/media/d8739d9147bb28ae6376e2206f67ba60.png?compress=1&resize=1600x1200', 'https://cdn.dribbble.com/users/427857/screenshots/16157651/media/18fcbf0c65cb47c14f633b162042cc65.png?compress=1&resize=1600x1200', 'https://cdn.dribbble.com/users/427857/screenshots/16157651/media/ecd0b4a299aabb66c8358b1051a139cd.png?compress=1&resize=1600x1200', 'https://cdn.dribbble.com/users/6532302/screenshots/16244413/media/c554d3e5bcf8c680ae56852b1b290fa7.jpg?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/2192147/screenshots/16242676/media/20f56e6b73bfc7ee4b9d9143f6449ad3.jpg?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/730703/screenshots/16207835/media/a9ad81cbcc73c87629471f4546828f2c.gif', 'https://cdn.dribbble.com/users/86429/screenshots/16241756/media/2d6331f16965e1ee4453b197e4d7f442.jpg?compress=1&resize=800x600', 'https://cdn.dribbble.com/users/5462867/screenshots/16165195/media/2a7203b0e3d1bbca91be7565d25d3f39.jpg?compress=1&resize=1200x900', 'https://cdn.dribbble.com/users/500242/screenshots/15428350/media/7b8a007e88d9050fe3d52c3625d2ff24.gif', ]; const icons = [ <Fa500Px />, <FaApple />, <FaAdobe />, <FaAdversal />, <FaAirbnb />, <FaAlipay />, <FaAmazonPay />, <FaAmazon />, <FaAppStoreIos />, <FaBehanceSquare />, <FaMagento />, <FaGoogle />, <FaInstagramSquare />, <FaOpera />, ]; const icons1 = [ <Fa500Px />, <FaApple />, <FaAdobe />, <FaAdversal />, <FaAirbnb />, ]; const dots = [ { x: '-10%', y: '-20%', size: 200, background: 'linear-gradient(to top, #0ba360 0%, #3cba92 100%)', borderRadius: '50%', }, { x: '60%', y: '40%', size: 500, background: 'linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%)', borderRadius: '50%', }, { x: '-30%', y: '50%', size: 450, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', borderRadius: '50%', }, ]; interface IProps {} const Index: React.FunctionComponent<IProps> = () => { const [collapsed, setCollapsed] = useState(false); const onCtrlB = () => { setCollapsed(!collapsed); }; console.log('packageInfo',packageInfo) return ( <> <Helmet> <meta charSet="utf-8" /> <title> Smart Background —— An React Component Automatically generate the background </title> <link rel="canonical" href={packageInfo.homePageUrl} /> <link rel="shortcut icon" type="image/x-icon" href="/assets/logo.png" /> </Helmet> <div className="App"> <a className="github" href={packageInfo.homePageUrl} target="_blank" ></a> <Background style={{ width: '100%', height: '500px' }} underlayColor="#0252D9" symbolsStyle={{ color: '#000', opacity: '0.3', }} animation={{ type: 'top', speed: 5 }} gap={20} symbols={icons} > <a className="github" href={packageInfo.homePageUrl} style={{ backgroundImage: `url(https://img.shields.io/github/stars/yuanguandong/${packageInfo.packageName}?style=social)`, }} target="_blank" ></a> </Background> <div className="wrap"> <div className="alignCenter"> <div className=""> {/* <img className="logoImage" src={Logo} alt="react-keyevent" /> */} <div className="logo" style={{ color: '#fff' }}> {packageInfo.symbol} </div> <span className="name" style={{ color: '#fff' }}> Smart Background </span> </div> </div> <Intro /> <div className="container"> <Background underlayColor="#f00" animation={{ type: 'bottom', speed: 5 }} > <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', }} > <FaLaugh style={{ color: '#fff', fontSize: 120 }} /> <h1 style={{ color: '#fff', fontSize: 36, fontWeight: 'bold' }}> JUST DO IT </h1> </div> </Background> </div> {/* <Title level={2}>Easy To Use 容易使用</Title> */} <Paragraph>默认以圆点作为符号</Paragraph> <Code content={Code0} /> <Title level={2}>Animation 动画</Title> <Paragraph>支持四个方向的滚动循环动画,可以控制速度</Paragraph> <Paragraph>GPU rendering, Does not occupy the js process</Paragraph> <Paragraph>GPU 渲染, 动画不占用javascript线程</Paragraph> <div className="container"> <Background underlayImage="linear-gradient(to right, #434343 0%, black 100%)" symbolsStyle={{ color: 'rgba(255,255,255,0.8)' }} symbolSize={20} gap={20} animation={{ type: 'right', speed: 5 }} rotate={45} symbols={[ '乾', '坤', '震', '巽', '坎', '离', '艮', '兑', '天', '地', '雷', '风', '水', '火', '山', '泽', ]} > <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', fontWeight: 'bold', }} > <FaYinYang style={{ color: '#fff', fontSize: 120 }} /> <h1 style={{ color: '#fff', fontSize: 36 }}>乾坤</h1> </div> </Background> </div> <Code content={Code1} /> <Title level={2}>Curtain 幕布</Title> <Paragraph>使用适当的实现可以很方便的实现一个图片幕布墙</Paragraph> <div className="container"> <Background symbolsStyle={{ opacity: 1 }} symbolSize={100} gap={0} symbols={[ ...images.map((img) => ( <div style={{ width: '100%', height: '100%', backgroundSize: 'cover', backgroundImage: `url(${img})`, transform: 'scale(1.2)', }} /> )), ]} animation={{ type: 'top', speed: 5 }} > <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', background: 'rgba(0,0,0,0.5)', fontSize: 120, }} > 😋 <h1 style={{ color: '#fff', fontSize: 36, fontWeight: 'bold' }}> Nice Image </h1> </div> </Background> </div> <Code content={Code2} /> <Title level={2}>Exact 精确模式</Title> <Paragraph>使用精确模式,可以让元素固定在某一位置</Paragraph> <div className="container"> <Background symbolsStyle={{ opacity: 1 }} exact={true} symbols={[ ...dots.map((dot) => ( <div style={{ position: 'absolute', width: dot.size, height: dot.size, borderRadius: dot.borderRadius, background: dot.background, top: dot.y, left: dot.x, }} /> )), ]} > <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', fontSize: 120, }} > <FaApple /> <h1 style={{ color: '#000', fontSize: 36, fontWeight: 'bold' }}> Apple </h1> </div> </Background> </div> <Code content={Code3} /> <Title level={2}>Random 随机模式</Title> <Paragraph>使用随机模式,可以让元素位置随机显示</Paragraph> <div className="container"> <Background symbols={icons1} random={{ fontSizeRange: [60, 90] }} rotate={45} underlayImage="linear-gradient(to right, #ff0844 0%, #ffb199 100%)" > <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', fontSize: 120, }} > <FaApple style={{ color: '#fff' }} /> <h1 style={{ color: '#fff', fontSize: 36, fontWeight: 'bold' }}> Apple </h1> </div> </Background> </div> <Code content={Code4} /> <Title level={2}>Why 为什么?</Title> 在开发过程中,我们经常会遇到使用背景的地方,比如登录页面,用户信息页面,封面图…… 寻找契合业务主题的背景十分耗费精力,总觉得做的背景不合适,如果直接用图片呢,逻辑是比较简单,但寻找到一张契合业务主题的图片也不是那么容易,所以想到用符号生成幕布一样的背景,从这个出发点做了这个组件,滚动的图片墙可能这个需求比较常见,用SmartBackground可以很快速的实现,希望可以帮到您,别忘了star哟 <Title level={2}>Props</Title> <Api /> <Title level={2}>Tip 注意</Title> Background的高度默认继承父级元素 如果Background有children,需要给Background的父级元素添加position:relative属性 <Footer /> </div> </div> </> ); }; export default Index;
the_stack
import Component, { types } from "@ff/graph/Component"; import CRenderer from "@ff/scene/components/CRenderer"; import CTransform from "@ff/scene/components/CTransform"; import CScene from "@ff/scene/components/CScene"; import RenderView from "@ff/scene/RenderView"; import UniversalCamera from "@ff/three/UniversalCamera"; import CPulse from "@ff/graph/components/CPulse"; import {Matrix4, Vector3, Ray, Raycaster, Mesh, Object3D, PlaneBufferGeometry, MeshBasicMaterial, ArrayCamera, Material, PerspectiveCamera, Shape, ShapeBufferGeometry, DoubleSide, WebGLRenderer, Box3, Quaternion} from 'three'; //import * as WebXR from "../types/WebXR"; import {IS_ANDROID, IS_AR_QUICKLOOK_CANDIDATE, IS_IOS, /*IS_IOS_CHROME, IS_IOS_SAFARI,*/ IS_WEBXR_AR_CANDIDATE, IS_MOBILE} from '../constants'; import CVScene from "./CVScene"; import CVSetup from "./CVSetup"; import { EUnitType } from "client/schema/common"; import { EDerivativeUsage, EDerivativeQuality, EAssetType } from "client/models/Derivative"; import CVModel2 from "./CVModel2"; import CVAssetManager from "./CVAssetManager"; import CVAnnotationView from "./CVAnnotationView"; import { Shadow } from "../xr/XRShadow" import CVDirectionalLight from "./CVDirectionalLight"; import { EShaderMode } from "client/schema/setup"; import CVAnalytics from "./CVAnalytics"; //////////////////////////////////////////////////////////////////////////////// const _matrix4 = new Matrix4(); const _vector3 = new Vector3(); //const _vector3b = new Vector3(); const _hitPosition = new Vector3(); const _boundingBox = new Box3(); const _quat = new Quaternion(); const ROTATION_RATE = 1.5; const ANNOTATION_SCALE = 2.0; export default class CVARManager extends Component { static readonly typeName: string = "CVARManager"; static readonly text: string = "ARManager"; static readonly icon: string = ""; static readonly isSystemSingleton = true; private _shadowRoot = null; protected static readonly ins = { enabled: types.Boolean("State.Enabled") }; protected static readonly outs = { enabled: types.Boolean("State.Enabled"), available: types.Boolean("State.Available", IS_MOBILE), isPlaced: types.Boolean("AR.Placed", false), isPresenting: types.Boolean("AR.Presenting", false) }; ins = this.addInputs(CVARManager.ins); outs = this.addOutputs(CVARManager.outs); protected get renderer() { return this.getMainComponent(CRenderer); } protected get pulse() { return this.getMainComponent(CPulse); } protected get sceneNode() { return this.getSystemComponent(CVScene); } protected get analytics() { return this.system.getMainComponent(CVAnalytics); } protected get assetManager() { return this.getMainComponent(CVAssetManager); } get shadowRoot() { return this._shadowRoot; } set shadowRoot(root: ShadowRoot) { this._shadowRoot = root; } protected arLink = document.createElement('a'); protected raycaster: Raycaster = new Raycaster(); protected initialHitTestSource: XRHitTestSource = null; protected inputSource: XRInputSource = null; protected transientHitTestSource: XRTransientInputHitTestSource = null; protected refSpace: XRReferenceSpace = null; protected frame: XRFrame = null; protected vScene: CScene = null; protected camera: UniversalCamera = null; protected cameraParent: Object3D = null; protected cachedView: RenderView = null; protected cachedQuality: EDerivativeQuality = null; protected cachedNearPlane: number = 0.0; protected xrCamera: PerspectiveCamera = null; protected hitPlane: Mesh = null; protected selectionRing: Mesh = null; protected session: XRSession = null; protected setup: CVSetup = null; protected originalUnits: EUnitType = null; protected isTranslating: boolean = false; protected isRotating: boolean = false; protected isScaling: boolean = false; protected lastDragValueX: number = 0.0; protected lastDragValueY: number = 0.0; protected totalDrag: number = 0; protected lastScale: number = 0.0; protected lastHitPosition: Vector3 = new Vector3(); protected lastFrameTime: number = 0; protected targetOpacity: number = 0.0; protected modelFloorOffset: number = 0.0; protected optimalCameraDistance: number = 0.0; protected shadow: Shadow = null; protected lightTransform: CTransform = null; protected lightsToReset: CVDirectionalLight[] = []; protected featuresToReset: number[] = []; // in order: floor/grid/tape/slicer/material update() { const { ins, outs } = this; if (ins.enabled.changed) { let isEnabled = ins.enabled.value; if (isEnabled) { if(IS_WEBXR_AR_CANDIDATE) { this.launchWebXR(); this.analytics.sendProperty("AR.Enabled", "WebXR"); } else if(IS_ANDROID) { this.launchSceneViewer(); this.analytics.sendProperty("AR.Enabled", "SceneViewer"); } else if(IS_IOS && IS_AR_QUICKLOOK_CANDIDATE) { this.launchQuickLook(); this.analytics.sendProperty("AR.Enabled", "QuickLook"); } else { isEnabled = false; this.analytics.sendProperty("AR.Enabled", "Unavailable"); } } outs.enabled.setValue(isEnabled); } return true; } protected launchWebXR() { const renderer = this.renderer?.views[0].renderer; const sceneComponent = this.vScene = this.renderer?.activeSceneComponent; const camera = this.camera = sceneComponent?.activeCamera; this.cameraParent = camera.parent; const setup = this.setup = this.getSystemComponent(CVSetup); //this.documentProvider.outs.activeDocument.value.setup; if(!setup) { return false; } const models = this.sceneNode?.getGraphComponents(CVModel2); const derivative = models[0] ? models[0].derivatives.get(EDerivativeUsage.Web3D, EDerivativeQuality.AR) : null; if(derivative) { this.setup.navigation.setChanged(true); // set changed var to disable autoZoom for bounds changes this.cachedQuality = models[0].ins.quality.value; models.forEach(model => { model.ins.quality.setValue(EDerivativeQuality.AR); }); renderer.setAnimationLoop( (time, frame) => this.render(time, frame) ); navigator.xr.requestSession( 'immersive-ar', { requiredFeatures: ['hit-test'], optionalFeatures: ['dom-overlay'], domOverlay: {root: this.shadowRoot.querySelector('ff-viewport-overlay')} } ).then( session => this.onSessionStarted(renderer, session) ); //.catch(reason => { console.log("Error starting session: " + reason); }); **TODO } } protected async onSessionStarted( renderer: WebGLRenderer, session: XRSession ) { const gl = this.renderer.views[0].renderer.getContext(); await gl.makeXRCompatible(); session.updateRenderState( {baseLayer: new XRWebGLLayer(session, gl, {alpha: true})} ); this.setupScene(); renderer.shadowMap.autoUpdate = false; renderer.xr.enabled = true; renderer.xr.setReferenceSpaceType( 'local' ); renderer.xr.setSession( session as unknown as THREE.XRSession ); session.addEventListener( 'end', this.onSessionEnded ); this.refSpace = await session.requestReferenceSpace('local'); const viewerRefSpace = await session.requestReferenceSpace('viewer'); // Do an initial hit test (model-viewer suggested 20 deg down) const radians = 20 * Math.PI / 180; const ray = new XRRay( new DOMPoint(0, 0, 0), {x: 0, y: -Math.sin(radians), z: -Math.cos(radians)}); session.requestHitTestSource({space: viewerRefSpace!, offsetRay: ray}) .then(hitTestSource => { this.initialHitTestSource = hitTestSource; }); this.outs.isPresenting.setValue(true); this.session = session; this.lastFrameTime = performance.now(); this.setup.reader.ins.enabled.on("value", this.endSession, this); } protected endSession() { if(this.session) { this.session.end(); } } protected onSessionEnded = () => { this.outs.isPresenting.setValue(false); const renderer = this.renderer.views[0].renderer; this.resetScene(); renderer.shadowMap.autoUpdate = true; // Clean up const hitSourceInitial = this.initialHitTestSource; if (hitSourceInitial != null) { hitSourceInitial.cancel(); this.initialHitTestSource = null; } const hitSource = this.transientHitTestSource; if (hitSource != null) { hitSource.cancel(); this.transientHitTestSource = null; } this.refSpace = null; this.frame = null; this.inputSource = null; this.xrCamera = null; this.cachedView = null; this.vScene = null; this.cachedView = null; this.camera = null; const session = this.session; if(session) { session.removeEventListener( 'end', this.onSessionEnded ); session.removeEventListener('selectstart', this.onSelectStart); session.removeEventListener('selectend', this.onSelectEnd); this.session = null; } this.setup.reader.ins.enabled.off("value", this.endSession, this); renderer.setAnimationLoop(null); renderer.xr.enabled = false; this.outs.isPlaced.setValue(false); this.setup.navigation.ins.enabled.setValue(true); //this.pulse.start(); this.renderer.views[0].render(); } protected setupScene() { const { cameraParent, setup, featuresToReset } = this; const scene = this.sceneNode; if(cameraParent) { cameraParent.remove(this.camera); } this.setup.background.hide(); // Disable navigation so we don't get duplicate events with dom overlay //this.pulse.stop(); this.setup.navigation.ins.enabled.setValue(false); // Reset lights moved by navigation const lightNode = scene.graph.findNodeByName("Lights"); const lightTransform = this.lightTransform = lightNode.getComponent(CTransform, true); lightTransform.ins.rotation.reset(); // Cache extended feature values featuresToReset.push(setup.floor.ins.visible.value ? 1 : 0); featuresToReset.push(setup.grid.ins.visible.value ? 1 : 0); featuresToReset.push(setup.tape.ins.visible.value ? 1 : 0); featuresToReset.push(setup.slicer.ins.enabled.value ? 1 : 0); featuresToReset.push(setup.viewer.ins.shader.value); // Disable extended features (TODO: support some/all of these features) setup.floor.ins.visible.setValue(false); setup.grid.ins.visible.setValue(false); setup.tape.ins.visible.setValue(false); setup.slicer.ins.enabled.setValue(false); if(setup.viewer.ins.shader.value !== EShaderMode.Default) { setup.viewer.ins.shader.setValue(EShaderMode.Default); } // Set scale to m const originalUnits = this.originalUnits = scene.ins.units.getValidatedValue(); if(originalUnits != EUnitType.m) { this.sceneNode.ins.units.setValue(EUnitType.m); } // Temporary until annotation scale implementation is resolved const views = scene.getGraphComponents(CVAnnotationView); views.forEach(component => { component.setXRScale(ANNOTATION_SCALE); }); // Disable any shadow casting lights const lights = scene.getGraphComponents(CVDirectionalLight); lights.forEach(light => { if(light.ins.shadowEnabled.value) { light.ins.shadowEnabled.setValue(false); this.lightsToReset.push(light); } }); // Setup shadow this.pulse.pulse(Date.now()); scene.update(null); // force bounding box update so shadow is correct size const shadow = this.shadow = new Shadow(this.sceneNode, this.vScene.scene, 0.5); shadow.setIntensity(0.3); // Cache bounding box for placement _boundingBox.copy(this.sceneNode.outs.boundingBox.value); // Compute optimal camera distance for initial placement _boundingBox.getSize(_vector3); /*_boundingBox.getCenter(_vector3b); const size = Math.max(_vector3.x / this.camera.aspect, _vector3.y); const fovFactor = 1 / (2 * Math.tan(this.camera.fov * (180/Math.PI) * 0.5)); this.optimalCameraDistance = (_vector3b.z + size * fovFactor + _vector3.z * 0.75);*/ this.cachedNearPlane = this.camera.near; if(Math.max(_vector3.x, _vector3.y, _vector3.z) < 0.5) { this.camera.near = 0.01; } } protected resetScene() { const {camera, cameraParent, setup, featuresToReset} = this; const scene = this.vScene.scene; // Reset component camera view if(cameraParent) { cameraParent.add(camera); } camera.position.set(0, 0, 0); camera.rotation.set(0, 0, 0); camera.near = this.cachedNearPlane; camera.updateMatrix(); // reset lights this.lightTransform.object3D.rotation.set(0,0,0); this.lightTransform.object3D.updateMatrix(); // Reset scene and update graph this.sceneNode.ins.units.setValue(this.originalUnits); scene.position.setScalar(0); scene.rotation.y = 0; scene.scale.setScalar(1); scene.updateMatrix(); scene.updateMatrixWorld(true); // Reset cached extended feature values featuresToReset.reverse(); setup.floor.ins.visible.setValue(!!featuresToReset.pop()); setup.grid.ins.visible.setValue(!!featuresToReset.pop()); setup.tape.ins.visible.setValue(!!featuresToReset.pop()); setup.slicer.ins.enabled.setValue(!!featuresToReset.pop()); const cachedShader = featuresToReset.pop(); if(cachedShader !== EShaderMode.Default) { setup.viewer.ins.shader.setValue(cachedShader); } // Temporary until annotation scale implementation is resolved const views = this.sceneNode.getGraphComponents(CVAnnotationView); views.forEach(component => { component.setXRScale(1.0); }); // Reset shadowing lights this.lightsToReset.forEach(light => { light.ins.shadowEnabled.setValue(true); }); this.lightsToReset.length = 0; setup.background.show(); // Reset quality const models = this.sceneNode.getGraphComponents(CVModel2); models.forEach(model => { model.ins.quality.setValue(this.cachedQuality); }); // Clean up const hitPlane = this.hitPlane; if (hitPlane != null) { scene.remove(hitPlane); hitPlane!.geometry.dispose(); (hitPlane!.material as Material).dispose(); this.hitPlane = null; } const selectionRing = this.selectionRing; if (selectionRing != null) { scene.remove(selectionRing); selectionRing!.geometry.dispose(); (selectionRing!.material as Material).dispose(); this.selectionRing = null; } const shadow = this.shadow; if (shadow != null) { scene.remove(shadow); shadow.dispose(); this.shadow = null; } camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); } protected render = (timestamp, frame) => { this.frame = frame; const renderer = this.renderer.views[0].renderer; const {camera, xrCamera, refSpace, initialHitTestSource, vScene, sceneNode, shadow, lastFrameTime} = this; if(!frame || !frame.getViewerPose(refSpace!)) { return; } // Get xr camera from Three.js to set local camera properties. TODO: More efficient use of xrcamera if(!xrCamera && this.session) { const xrCameraArray : ArrayCamera = renderer.xr.getCamera(camera) as ArrayCamera; this.xrCamera = xrCameraArray.cameras[0]; return; } else if(xrCamera) { camera.position.setFromMatrixPosition(xrCamera.matrixWorld); xrCamera.projectionMatrixInverse.copy(xrCamera.projectionMatrix).invert(); camera.projectionMatrix.fromArray(xrCamera.projectionMatrix.elements); camera.projectionMatrixInverse.copy(xrCamera.projectionMatrix).invert(); } // center model in front of camera while trying for initial placement if (initialHitTestSource != null && xrCamera) { const scene = vScene.scene; const {position} = scene; const radius = sceneNode.outs.boundingRadius.value * 2.0 + xrCamera.near; // Math.abs(this.optimalCameraDistance); const e = xrCamera.matrixWorld.elements; position.set(-e[ 8 ], -e[ 9 ], -e[ 10 ]).normalize(); position.multiplyScalar(radius); position.add(camera.position); _boundingBox.getCenter(_vector3); position.add(_vector3.negate()); scene.updateMatrix(); scene.updateMatrixWorld(); //this.updateBoundingBox(); } this.setInitialPosition(frame); this.handleInput(frame); if(this.outs.isPlaced.value) { // update selection ring opacity const deltaT = timestamp - lastFrameTime; this.updateOpacity(deltaT, this.targetOpacity); this.lastFrameTime = timestamp; } // TODO: Temporary fix for Chrome depth bug // https://bugs.chromium.org/p/chromium/issues/detail?id=1184085 const gl = renderer.getContext(); gl.depthMask(false); gl.clear(gl.DEPTH_BUFFER_BIT); gl.depthMask(true); if(shadow.needsUpdate) { renderer.shadowMap.needsUpdate = true; shadow.needsUpdate = false; } renderer.render( vScene.scene, camera ); } // adapted from model-viewer protected setInitialPosition( frame: XRFrame ) { const hitSource = this.initialHitTestSource; if (hitSource == null) { return; } const hitTestResults = frame.getHitTestResults(hitSource); if (hitTestResults.length == 0) { return; } const hit = hitTestResults[0]; const hitPt = this.getHitPoint(hit); if (hitPt == null) { return; } this.placeModel(hitPt); hitSource.cancel(); this.initialHitTestSource = null; const {session} = frame; session.addEventListener('selectstart', this.onSelectStart); session.addEventListener('selectend', this.onSelectEnd); session.requestHitTestSourceForTransientInput({profile: 'generic-touchscreen'}) .then(hitTestSource => { this.transientHitTestSource = hitTestSource; }); this.shadow.updateMatrices(); } protected getHitPoint( hitResult: XRHitTestResult): Vector3|null { const pose = hitResult.getPose(this.refSpace!); if (pose == null) { return null; } const hitMatrix = _matrix4.fromArray(pose.transform.matrix); // Check that the y-coordinate of the normal is large enough that the normal // is pointing up. return hitMatrix.elements[5] > 0.75 ? _hitPosition.setFromMatrixPosition(hitMatrix) : null; } protected onSelectStart = (event: Event) => { if (ENV_DEVELOPMENT) { //console.log("WebXR Select Start"); } const scene = this.vScene.scene!; const hitSource = this.transientHitTestSource; if (hitSource == null) { return; } this.targetOpacity = 0.5; const fingers = this.frame!.getHitTestResultsForTransientInput(hitSource); if (fingers.length === 1) { this.inputSource = (event as XRInputSourceEvent).inputSource; const {axes} = this.inputSource!.gamepad; const raycaster = this.raycaster; raycaster.setFromCamera({x: axes[0], y: -axes[1]}, this.xrCamera); const intersections = raycaster.intersectObject(this.hitPlane); if (intersections.length > 0) { this.isTranslating = true; this.lastHitPosition.copy(intersections[0].point); } else { this.isRotating = true; } this.lastDragValueX = axes[0]; this.lastDragValueY = axes[1]; } else if (fingers.length === 2 /*&& scene.canScale*/) { this.isScaling = true; this.lastScale = this.getFingerSeparation(fingers) / scene.scale.x; } } protected onSelectEnd = () => { if (ENV_DEVELOPMENT) { //console.log("WebXR Select End"); } this.targetOpacity = 0.0; this.totalDrag = 0.0; this.isTranslating = false; this.isRotating = false; this.isScaling = false; this.inputSource = null; } protected handleInput( frame: XRFrame ) { const hitSource = this.transientHitTestSource; if (hitSource == null) { return; } if (!this.isTranslating && !this.isScaling && !this.isRotating) { return; } const fingers = frame.getHitTestResultsForTransientInput(hitSource); const scene = this.vScene.scene; const scale = scene.scale.x; // Rotating, translating and scaling are mutually exclusive operations; only // one can happen at a time, but we can switch during a gesture. if (this.isScaling) { if (fingers.length < 2) { // If we lose the second finger, stop scaling (in fact, stop processing // input altogether until a new gesture starts). this.isScaling = false; } else { // calculate and update scale const separation = this.getFingerSeparation(fingers); const scale = separation / this.lastScale; scene.scale.setScalar(scale); scene.position.y = this.lastHitPosition.y - this.modelFloorOffset * scene.scale.y; // set back on floor scene.updateMatrix(); scene.updateMatrixWorld(); this.shadow.setScaleAndOffset(scale, 0); this.updateBoundingBox(); } return; } else if (fingers.length === 2 /*&& scene.canScale*/) { // If we were rotating or translating and we get a second finger, switch // to scaling instead. this.isTranslating = false; this.isRotating = false; this.isScaling = true; this.lastScale = this.getFingerSeparation(fingers) / scale; return; } if (this.isRotating) { const currentDragX = this.inputSource!.gamepad.axes[0]; scene.rotation.y += (currentDragX - this.lastDragValueX) * ROTATION_RATE; scene.updateMatrix(); // undo rotation on lights _quat.copy(scene.quaternion); _quat.invert(); this.lightTransform.object3D.rotation.setFromQuaternion(_quat); this.lightTransform.object3D.updateMatrix(); this.shadow.setRotation(scene.rotation.y); this.lastDragValueX = currentDragX; } else if (this.isTranslating) { const currentDrag = this.inputSource!.gamepad.axes; const offsetX = currentDrag[0] - this.lastDragValueX; const offsetY = currentDrag[1] - this.lastDragValueY; this.totalDrag += Math.hypot(offsetX, offsetY); fingers.forEach(finger => { if (this.totalDrag < 0.01 ||finger.inputSource !== this.inputSource || finger.results.length < 1) { return; } const hit = this.getHitPoint(finger.results[0]); if (hit == null) { return; } // add difference from last hit _vector3.copy(hit); _vector3.sub(this.lastHitPosition); scene.position.add(_vector3); scene.updateMatrix(); scene.updateMatrixWorld(); this.lastHitPosition.copy(hit); this.updateBoundingBox(); }); this.shadow.updateMatrices(); } } protected getFingerSeparation(fingers: XRTransientInputHitTestResult[]): number { const fingerOne = fingers[0].inputSource.gamepad.axes; const fingerTwo = fingers[1].inputSource.gamepad.axes; const deltaX = fingerTwo[0] - fingerOne[0]; const deltaY = fingerTwo[1] - fingerOne[1]; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); } protected placeModel( hit: Vector3 ) { const scene = this.vScene.scene!; const {min, max} = _boundingBox; const boundingRadius = this.sceneNode.outs.boundingRadius.value; const width = Math.max((max.x-min.x)*1.25, 0.15); const height = Math.max((max.z-min.z)*1.25, 0.15); const centerOffsetX = (min.x+max.x)/2.0; const centerOffsetZ = (min.z+max.z)/2.0; this.lastHitPosition.copy(hit); // add interaction plane const hitPlane = this.hitPlane = new Mesh( new PlaneBufferGeometry(width, height), new MeshBasicMaterial() ); hitPlane.position.set(centerOffsetX, min.y, centerOffsetZ); hitPlane.rotation.set(-Math.PI / 2.0, 0, 0); hitPlane.visible = false; scene.add(hitPlane); // add selection visualization const roundedRectShape = new Shape(); const cutOut = new Shape(); const thickness = width > height ? width*0.025 : height*0.025; this.roundedRect(roundedRectShape, -width/2.0, -height/2.0, width, height, thickness*0.5); this.roundedRect(cutOut, -width/2.0 + thickness, -height/2.0 + thickness, width-2*thickness, height-2*thickness, thickness*0.4); roundedRectShape.holes.push(cutOut); let geometry = new ShapeBufferGeometry(roundedRectShape); const selectionRing = this.selectionRing = new Mesh( geometry, new MeshBasicMaterial({ side: DoubleSide, opacity: 0.0 }) ); selectionRing.position.set(centerOffsetX, min.y, centerOffsetZ); selectionRing.rotation.set(-Math.PI / 2.0, 0, 0); (selectionRing.material as Material).transparent = true; selectionRing.visible = false; scene.add(selectionRing); this.modelFloorOffset = min.y; //console.log("Placing in AR: " + hit.x + " " + (hit.y-min.y) + " " + hit.z); scene.position.set(hit.x, hit.y-min.y, hit.z); scene.updateMatrix(); scene.updateMatrixWorld(true); this.updateBoundingBox(); this.pulse.pulse(Date.now()); // if we are not far enough away from the model, shift // edge of bounding box to hitpoint so it is in view const origin = this.camera.position.clone(); const placementVector = hit.clone().sub(origin); if(placementVector.length() < boundingRadius) { const direction = placementVector.normalize(); // Pull camera back enough to be outside of large models. origin.sub(direction.multiplyScalar(boundingRadius * 1.5)); const ray = new Ray(origin, direction.normalize()); const modelPosition = new Vector3(); // Make the box tall so that we don't intersect the top face. max.y += 10; ray.intersectBox(this.sceneNode.outs.boundingBox.value, modelPosition); max.y -= 10; if (modelPosition != null) { scene.position.x += hit.x - modelPosition.x; scene.position.z += hit.z - modelPosition.z; scene.updateMatrix(); scene.updateMatrixWorld(true); //console.log("Pushing in AR: " + scene.position.x + " " + (hit.y-min.y) + " " + scene.position.z ); } } this.updateBoundingBox(); this.outs.isPlaced.setValue(true); } protected launchSceneViewer() { const models = this.sceneNode.getGraphComponents(CVModel2); const svIndex = models.findIndex(model => {return model.derivatives.get(EDerivativeUsage.App3D, EDerivativeQuality.AR) !== null}); const derivative = svIndex > -1 ? models[svIndex].derivatives.get(EDerivativeUsage.App3D, EDerivativeQuality.AR) : null; if(derivative) { const linkElement = this.arLink; const modelAsset = derivative.findAsset(EAssetType.Model); const url = this.assetManager.getAssetUrl(modelAsset.data.uri); const intent = `intent://arvr.google.com/scene-viewer/1.0?file=${url}&mode=ar_only#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`; linkElement.setAttribute('href', intent); linkElement.click(); } } protected launchQuickLook() { const models = this.sceneNode.getGraphComponents(CVModel2); const iOSIndex = models.findIndex(model => {return model.derivatives.get(EDerivativeUsage.iOSApp3D, EDerivativeQuality.AR) !== null}); const derivative = iOSIndex > -1 ? models[iOSIndex].derivatives.get(EDerivativeUsage.iOSApp3D, EDerivativeQuality.AR) : null; if(derivative) { const linkElement = this.arLink; const modelAsset = derivative.findAsset(EAssetType.Model); const url = this.assetManager.getAssetUrl(modelAsset.data.uri); linkElement.setAttribute('rel', 'ar'); const img = document.createElement('img'); linkElement.appendChild(img); linkElement.setAttribute('href', url.toString()); linkElement.click(); linkElement.removeChild(img); } } // Update scene bounding box to ensure dependent functionality works correctly protected updateBoundingBox() { this.sceneNode.ins.sceneTransformed.set(); } // Animate opacity based on time delta protected updateOpacity( deltaT: number, target: number) { const material = this.selectionRing.material as Material; const currentOpacity = material.opacity; if(target === currentOpacity) { return; } const deltaO = target - currentOpacity; material.opacity = deltaO > 0 ? Math.min(currentOpacity + 0.002*deltaT, target) : Math.max(currentOpacity - 0.002*deltaT, target); this.selectionRing.visible = material.opacity > 0; } // Helper function to generate rounded rectangle shape from Three.js example: // https://github.com/mrdoob/three.js/blob/dev/examples/webgl_geometry_shapes.html protected roundedRect( ctx, x, y, width, height, radius ) { ctx.moveTo( x, y + radius ); ctx.lineTo( x, y + height - radius ); ctx.quadraticCurveTo( x, y + height, x + radius, y + height ); ctx.lineTo( x + width - radius, y + height ); ctx.quadraticCurveTo( x + width, y + height, x + width, y + height - radius ); ctx.lineTo( x + width, y + radius ); ctx.quadraticCurveTo( x + width, y, x + width - radius, y ); ctx.lineTo( x + radius, y ); ctx.quadraticCurveTo( x, y, x, y + radius ); } }
the_stack
import { LoanMasterNodeRegTestContainer } from './loan_container' import BigNumber from 'bignumber.js' import { Testing } from '@defichain/jellyfish-testing' import { GenesisKeys } from '@defichain/testcontainers' import { TokenInfo } from '../../../src/category/token' describe('Loan updateLoanToken', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) let loanTokenId: string beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() const oracleId = await testing.container.call('appointoracle', [await testing.generateAddress(), [{ token: 'Token1', currency: 'USD' }], 1]) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '0.5@Token1', currency: 'USD' }] }) await testing.generate(1) loanTokenId = await testing.container.call('setloantoken', [{ symbol: 'Token1', name: 'Token1', fixedIntervalPriceId: 'Token1/USD', mintable: true, interest: new BigNumber(0.01) }, []]) await testing.generate(1) }) afterEach(async () => { const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo if (tokenInfo.symbol === 'Token1') { // If Token1, always update its name, fixedIntervalPriceId, mintable and interest values back to their original values await testing.rpc.loan.updateLoanToken('Token1', { name: 'Token1', fixedIntervalPriceId: 'Token1/USD', mintable: true, interest: new BigNumber(0.01) }) } else if (tokenInfo.symbol === 'Token2') { // If Token2, always update it back to Token1 await testing.rpc.loan.updateLoanToken('Token2', { symbol: 'Token1', name: 'Token1', fixedIntervalPriceId: 'Token1/USD', mintable: true, interest: new BigNumber(0.01) }) } await testing.generate(1) }) afterAll(async () => { await testing.container.stop() }) it('should updateLoanToken by symbol as token', async () => { await testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2' }) // Update by symbol await testing.generate(1) const data = await testing.container.call('listloantokens', []) expect(data).toStrictEqual([{ token: { 1: { symbol: 'Token2', symbolKey: 'Token2', name: 'Token1', decimal: 8, limit: 0, mintable: true, tradeable: true, isDAT: true, isLPS: false, finalized: false, isLoanToken: true, minted: 0, creationTx: loanTokenId, creationHeight: await testing.container.getBlockCount() - 1, destructionTx: '0000000000000000000000000000000000000000000000000000000000000000', destructionHeight: -1, collateralAddress: expect.any(String) } }, fixedIntervalPriceId: 'Token1/USD', interest: 0.01 }]) }) it('should updateLoanToken by id as token', async () => { await testing.rpc.loan.updateLoanToken('1', { symbol: 'Token2' }) // Update by id await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.symbol).toStrictEqual('Token2') }) it('should updateLoanToken by creationTx as token', async () => { await testing.rpc.loan.updateLoanToken(loanTokenId, { symbol: 'Token2' }) // Update by creationTx await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.symbol).toStrictEqual('Token2') }) it('should not updateLoanToken if token does not exist', async () => { const promise = testing.rpc.loan.updateLoanToken('Token2', { symbol: 'Token2' }) // Does not exist await expect(promise).rejects.toThrow('RpcApiError: \'Token Token2 does not exist!\', code: -8, method: updateloantoken') }) it('should updateLoanToken if symbol is more than 8 letters', async () => { const oracleId = await testing.container.call('appointoracle', [await testing.generateAddress(), [{ token: 'Token3', currency: 'USD' }], 1]) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '0.5@Token3', currency: 'USD' }] }) await testing.generate(1) const loanTokenId = await testing.container.call('setloantoken', [{ symbol: 'Token3', fixedIntervalPriceId: 'Token3/USD' }, []]) await testing.generate(1) await testing.rpc.loan.updateLoanToken('Token3', { symbol: 'x'.repeat(9) }) // 9 letters await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.symbol).toStrictEqual('x'.repeat(8)) // Only remain the first 8 letters }) it('should not updateLoanToken if symbol is an empty string', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: '' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test UpdateLoanTokenTx execution failed:\ntoken symbol should be non-empty and starts with a letter\', code: -32600, method: updateloantoken') }) it('should not updateLoanToken if the symbol is used in other token', async () => { const oracleId = await testing.container.call('appointoracle', [await testing.generateAddress(), [{ token: 'Token4', currency: 'USD' }], 1]) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '0.5@Token4', currency: 'USD' }] }) await testing.generate(1) await testing.container.call('setloantoken', [{ symbol: 'Token4', name: 'Token4', fixedIntervalPriceId: 'Token4/USD' }, []]) await testing.generate(1) const promise = testing.rpc.loan.updateLoanToken('Token4', { symbol: 'Token1' }) // Same as Token1's symbol await expect(promise).rejects.toThrow('RpcApiError: \'Test UpdateLoanTokenTx execution failed:\ntoken with key \'Token1\' already exists!\', code: -32600, method: updateloantoken') }) it('should updateLoanToken with the given name', async () => { await testing.rpc.loan.updateLoanToken('Token1', { name: 'Token2' }) await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.name).toStrictEqual('Token2') }) it('should updateLoanToken if name is more than 128 letters', async () => { await testing.rpc.loan.updateLoanToken('Token1', { name: 'x'.repeat(129) }) // 129 letters await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.name).toStrictEqual('x'.repeat(128)) }) it('should updateLoanToken if two loan tokens have the same name', async () => { const oracleId = await testing.container.call('appointoracle', [await testing.generateAddress(), [{ token: 'Token5', currency: 'USD' }], 1]) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '0.5@Token5', currency: 'USD' }] }) await testing.generate(1) const loanTokenId = await testing.rpc.loan.setLoanToken({ symbol: 'Token5', fixedIntervalPriceId: 'Token5/USD' }) await testing.generate(1) await testing.rpc.loan.updateLoanToken('Token5', { name: 'Token1' }) // Same name as Token1's name await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.name).toStrictEqual('Token1') }) it('should updateLoanToken with given fixedIntervalPriceId', async () => { const oracleId = await testing.container.call('appointoracle', [await testing.generateAddress(), [{ token: 'Token6', currency: 'USD' }], 1]) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '0.5@Token6', currency: 'USD' }] }) await testing.generate(1) const loanTokenId = await testing.rpc.loan.setLoanToken({ symbol: 'Token6', fixedIntervalPriceId: 'Token6/USD' }) await testing.generate(1) await testing.rpc.loan.updateLoanToken('Token6', { fixedIntervalPriceId: 'Token1/USD' }) await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) expect(data.fixedIntervalPriceId).toStrictEqual('Token1/USD') }) it('should not updateLoanToken if fixedIntervalPriceId does not belong to any oracle', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2', fixedIntervalPriceId: 'X/USD' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test UpdateLoanTokenTx execution failed:\nPrice feed X/USD does not belong to any oracle\', code: -32600, method: updateloantoken') }) it('should not updateLoanToken if fixedIntervalPriceId is not in correct format', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2', fixedIntervalPriceId: 'X' }) // Must be in token/currency format await expect(promise).rejects.toThrow('RpcApiError: \'price feed not in valid format - token/currency!\', code: -8, method: updateloantoken') }) it('should not updateLoanToken if fixedIntervalPriceId is an empty string', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2', fixedIntervalPriceId: '' }) await expect(promise).rejects.toThrow('RpcApiError: \'Invalid parameters, argument "fixedIntervalPriceId" must be non-null\', code: -8, method: updateloantoken') }) it('should not updateLoanToken if token/currency of fixedIntervalPriceId contains empty string', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2', fixedIntervalPriceId: '/' }) await expect(promise).rejects.toThrow('RpcApiError: \'token/currency contains empty string\', code: -8, method: updateloantoken') }) it('should updateLoanToken with given mintable flag', async () => { { await testing.rpc.loan.updateLoanToken('Token1', { mintable: false }) await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.mintable).toStrictEqual(false) } { await testing.rpc.loan.updateLoanToken('Token1', { mintable: true }) await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.mintable).toStrictEqual(true) } }) it('should updateLoanToken if interest number is greater than 0 and has less than 9 digits in the fractional part', async () => { await testing.rpc.loan.updateLoanToken('Token1', { interest: new BigNumber(15.12345678) }) // 8 digits in the fractional part await testing.generate(1) const data = await testing.container.call('getloantoken', [loanTokenId]) expect(data.interest).toStrictEqual(15.12345678) }) it('should not updateLoanToken if interest number is greater than 0 and has more than 8 digits in the fractional part', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { interest: new BigNumber(15.123456789) }) // 9 digits in the fractional part await expect(promise).rejects.toThrow('RpcApiError: \'Invalid amount\', code: -3, method: updateloantoken') }) it('should not updateLoanToken if interest number is less than 0', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { interest: new BigNumber(-15.12345678) }) await expect(promise).rejects.toThrow('RpcApiError: \'Amount out of range\', code: -3, method: updateloantoken') }) it('should not updateLoanToken if interest number is greater than 1200000000', async () => { const promise = testing.rpc.loan.updateLoanToken('Token1', { interest: new BigNumber('1200000000').plus('0.00000001') }) await expect(promise).rejects.toThrow('RpcApiError: \'Amount out of range\', code: -3, method: updateloantoken') }) it('should updateLoanToken with utxos', async () => { const { txid, vout } = await testing.container.fundAddress(GenesisKeys[0].owner.address, 10) const loanTokenId2 = await testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2' }, [{ txid, vout }]) expect(typeof loanTokenId).toStrictEqual('string') expect(loanTokenId.length).toStrictEqual(64) await testing.generate(1) const rawtx = await testing.container.call('getrawtransaction', [loanTokenId2, true]) expect(rawtx.vin[0].txid).toStrictEqual(txid) expect(rawtx.vin[0].vout).toStrictEqual(vout) const data = await testing.container.call('getloantoken', [loanTokenId]) const tokenInfo = Object.values(data.token)[0] as TokenInfo expect(tokenInfo.symbol).toStrictEqual('Token2') }) it('should updateLoanToken with utxos not from foundation member', async () => { const utxo = await testing.container.fundAddress(await testing.generateAddress(), 10) const promise = testing.rpc.loan.updateLoanToken('Token1', { symbol: 'Token2' }, [utxo]) await expect(promise).rejects.toThrow('RpcApiError: \'Test UpdateLoanTokenTx execution failed:\ntx not from foundation member!\', code: -32600, method: updateloantoken') }) })
the_stack
import { Global } from '../../global' import { isInDocument } from '../../util/dom' import { Hook } from './hook' import { CSSProperties } from './types' export type MockedCSSName = 'left' export namespace Util { export function getComputedStyle<TElement extends Element>(node: TElement) { const view = node.ownerDocument.defaultView || Global.window return view.getComputedStyle(node) } export function getComputedStyleValue<TElement extends Element>( node: TElement, name: string, styles: Record<string, string> | CSSStyleDeclaration = getComputedStyle( node, ), ) { let result: string | number = styles.getPropertyValue ? (styles as CSSStyleDeclaration).getPropertyValue(name) : (styles as Record<string, string>)[name] if (result === '' && !isInDocument(node)) { result = style(node, name) } return result !== undefined ? `${result}` : result } export function isValidNode<TElement extends Element>(node: TElement) { // Don't set styles on text and comment nodes if (!node || node.nodeType === 3 || node.nodeType === 8) { return false } const style = (node as any as HTMLElement).style if (!style) { return false } return true } export function isCustomStyleName(styleName: string) { return styleName.indexOf('--') === 0 } // Convert dashed to camelCase, handle vendor prefixes. // Used by the css & effects modules. // Support: IE <=9 - 11+ // Microsoft forgot to hump their vendor prefix export function camelCase(str: string) { const to = (s: string) => s .replace(/^-ms-/, 'ms-') .replace(/-([a-z])/g, (input) => input[1].toUpperCase()) if (isCustomStyleName(str)) { return `--${to(str.substring(2))}` } return to(str) } export function kebabCase(str: string) { return ( str .replace(/([a-z])([A-Z])/g, '$1-$2') // vendor .replace(/^([A-Z])/g, '-$1') .toLowerCase() .replace(/^ms-/, '-ms-') ) } export function tryConvertToNumber(value: string | number) { if (typeof value === 'number') { return value } const numReg = /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i return numReg.test(value) ? +value : value } } export namespace Util { /** * CSS properties which accept numbers but are not in units of "px". */ export const isUnitlessNumber: Record<string, boolean> = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridArea: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ const prefixes = ['Webkit', 'ms', 'Moz', 'O'] function prefixKey(prefix: string, key: string) { return prefix + key.charAt(0).toUpperCase() + key.substring(1) } // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach((prop) => { prefixes.forEach((prefix) => { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop] }) }) const style = document.createElement('div').style const cache: Record<string, string> = {} // Return a vendor-prefixed property or undefined function vendor(styleName: string) { for (let i = 0, l = prefixes.length; i < l; i += 1) { const prefixed = prefixKey(prefixes[i], styleName) if (prefixed in style) { return prefixed } } return styleName } // Return a potentially-mapped vendor prefixed property export function tryVendor(styleName: string) { const final = cache[styleName] if (final) { return final } if (styleName in style) { return styleName } const prefixed = vendor(styleName) cache[styleName] = prefixed return prefixed } } export namespace Util { export function css<TElement extends Element>( node: TElement, name: string, presets?: Record<string, string> | CSSStyleDeclaration, ) { const styleName = camelCase(name) const isCustom = isCustomStyleName(name) // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if (!isCustom) { name = tryVendor(styleName) // eslint-disable-line } let val: string | number | undefined const hook = Hook.get(name) || Hook.get(styleName) // If a hook was provided get the computed value from there if (hook && hook.get) { val = hook.get(node, true) } // Otherwise, if a way to get the computed value exists, use that if (val === undefined) { val = getComputedStyleValue(node, kebabCase(name), presets) } return tryConvertToNumber(val) } } export namespace Util { function normalizeValue( name: string, value: string | number, isCustomProperty: boolean, ) { const isEmpty = value == null || typeof value === 'boolean' || value === '' if (isEmpty) { return '' } if ( !isCustomProperty && typeof value === 'number' && value !== 0 && !isUnitlessNumber[name] ) { return `${value}px` } return `${value}`.trim() } export function style<TElement extends Element>(node: TElement): CSSProperties export function style<TElement extends Element>( node: TElement, name: string, ): string | number export function style<TElement extends Element>( node: TElement, name: string, value: string | number, ): void export function style<TElement extends Element>( node: TElement, name?: string, value?: string | number, ) { if (!isValidNode(node)) { return typeof name === 'undefined' ? {} : undefined } const styleDeclaration = (node as any as HTMLElement).style if (typeof name === 'undefined') { const result: CSSProperties = {} styleDeclaration.cssText .split(/\s*;\s*/) .filter((str) => str.length > 0) .forEach((str) => { const parts = str.split(/\s*:\s*/) result[camelCase(parts[0]) as MockedCSSName] = style(node, parts[0]) }) return result } // Make sure that we're working with the right name const styleName = camelCase(name) const isCustom = isCustomStyleName(name) // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if (!isCustom) { name = tryVendor(styleName) // eslint-disable-line } // Gets hook for the prefixed version, then unprefixed version const hook = Hook.get(name) || Hook.get(styleName) // Setting a value if (value !== undefined) { let val = value // If a hook was provided, use that value, otherwise just set the specified value let setting = true if (hook && hook.set) { const result = hook.set(node, val) setting = result !== undefined if (setting) { val = result! } } if (setting) { val = normalizeValue(name, val, isCustom) if (name === 'float') { name = 'cssFloat' // eslint-disable-line } if (isCustom) { styleDeclaration.setProperty(kebabCase(name), val) } else { styleDeclaration[name as MockedCSSName] = val } } } else { let ret: string | number | undefined // If a hook was provided get the non-computed value from there if (hook && hook.get) { ret = hook.get(node, false) } // Otherwise just get the value from the style object if (ret === undefined) { ret = styleDeclaration.getPropertyValue(kebabCase(name)) } return tryConvertToNumber(ret) } } } export namespace Util { const cache: WeakMap<Node, string> = new WeakMap() export function isHiddenWithinTree<TElement extends Element>(node: TElement) { const style = (node as any as HTMLElement).style return ( style.display === 'none' || (style.display === '' && css(node, 'display') === 'none') ) } const defaultDisplayMap: Record<string, string> = {} export function getDefaultDisplay<TElement extends Node>(node: TElement) { const nodeName = node.nodeName let display = defaultDisplayMap[nodeName] if (display) { return display } const doc = node.ownerDocument || Global.document const temp = doc.body.appendChild(doc.createElement(nodeName)) display = css(temp, 'display') as string if (temp.parentNode) { temp.parentNode.removeChild(temp) } if (display === 'none') { display = 'block' } defaultDisplayMap[nodeName] = display return display } export function showHide<TElement extends Element>( node: TElement, show: boolean, ) { const style = (node as any as HTMLElement).style if (!style) { return } const display = style.display let val: string | undefined if (show) { if (display === 'none') { val = cache.get(node) if (!val) { style.display = '' } } // for cascade-hidden if (style.display === '' && isHiddenWithinTree(node)) { val = getDefaultDisplay(node) } } else if (display !== 'none') { val = 'none' // Remember what we're overwriting cache.set(node, display) } if (val != null) { style.display = val } } }
the_stack
'use strict'; import { Store as RelayModernStore, RecordSource, Environment as RelayModernEnvironment } from '../src'; import { Network as RelayNetwork, Observable as RelayObservable, createOperationDescriptor, createReaderSelector } from 'relay-runtime'; import { createPersistedStorage } from './Utils'; const { generateAndCompile } = require('./TestCompiler'); const RelayRecordSource = { create: (data?: any) => new RecordSource({ storage: createPersistedStorage(), initialState: { ...data } }), }; describe('executeMutation()', () => { let callbacks; let commentID; let CommentFragment; let CommentQuery; let complete; let CreateCommentMutation; let CreateCommentWithSpreadMutation; let environment; let error; let fetch; let operation; let queryOperation; let source; let store; let subject; let variables; let queryVariables; beforeEach(async () => { jest.resetModules(); commentID = 'comment-id'; ({ CreateCommentMutation, CreateCommentWithSpreadMutation, CommentFragment, CommentQuery } = generateAndCompile(` mutation CreateCommentMutation($input: CommentCreateInput!) { commentCreate(input: $input) { comment { id body { text } } } } fragment CommentFragment on Comment { id body { text } } mutation CreateCommentWithSpreadMutation($input: CommentCreateInput!) { commentCreate(input: $input) { comment { ...CommentFragment } } } query CommentQuery($id: ID!) { node(id: $id) { id ...CommentFragment } } `)); variables = { input: { clientMutationId: '0', feedbackId: '1', }, }; queryVariables = { id: commentID, }; operation = createOperationDescriptor(CreateCommentMutation, variables); queryOperation = createOperationDescriptor(CommentQuery, queryVariables); fetch = jest.fn((_query, _variables, _cacheConfig) => RelayObservable.create((sink) => { subject = sink; }), ); source = RelayRecordSource.create(); store = new RelayModernStore(source); environment = new RelayModernEnvironment({ network: RelayNetwork.create(fetch), store, }); await environment.hydrate(); complete = jest.fn(); error = jest.fn(); callbacks = { complete, error }; }); it('fetches the mutation with the provided fetch function', () => { environment.executeMutation({ operation }).subscribe({}); expect(fetch.mock.calls.length).toBe(1); expect(fetch.mock.calls[0][0]).toEqual(CreateCommentMutation.params); expect(fetch.mock.calls[0][1]).toEqual(variables); expect(fetch.mock.calls[0][2]).toEqual({ force: true }); }); it('executes the optimistic updater immediately', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); expect(complete).not.toBeCalled(); expect(error).not.toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ id: commentID, body: { text: 'Give Relay', }, }); }); it('executes the optimistic updater immediately, does not mark mutation as being in flight in operation tracker', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); expect(complete).not.toBeCalled(); expect(error).not.toBeCalled(); expect(callback).toBeCalledTimes(1); // result tested in previous test // The mutation affecting the query should not be marked as in flight yet expect(environment.getOperationTracker().getPromiseForPendingOperationsAffectingOwner(queryOperation.request)).toBe(null); }); it('reverts the optimistic update if disposed', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); const subscription = environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); callback.mockClear(); subscription.unsubscribe(); expect(complete).not.toBeCalled(); expect(error).not.toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual(undefined); }); it('reverts the optimistic update and commits the server payload', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); callback.mockClear(); subject.next({ data: { commentCreate: { comment: { id: commentID, body: { text: 'Gave Relay', }, }, }, }, }); subject.complete(); expect(complete).toBeCalled(); expect(error).not.toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ id: commentID, body: { text: 'Gave Relay', }, }); }); it('commits the server payload and runs the updater', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, updater: (_store) => { const comment = _store.get(commentID); if (!comment) { throw new Error('Expected comment to be in the store'); } const body = comment.getLinkedRecord('body'); if (!body) { throw new Error('Expected comment to have a body'); } const bodyValue: string | null = body.getValue('text'); if (bodyValue == null) { throw new Error('Expected comment body to have text'); } body.setValue(bodyValue.toUpperCase(), 'text'); }, }) .subscribe(callbacks); callback.mockClear(); subject.next({ data: { commentCreate: { comment: { id: commentID, body: { text: 'Gave Relay', // server data is lowercase }, }, }, }, }); subject.complete(); expect(complete).toBeCalled(); expect(error).not.toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ id: commentID, body: { text: 'GAVE RELAY', // converted to uppercase by updater }, }); }); it('reverts the optimistic update if the fetch is rejected', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); callback.mockClear(); subject.error(new Error('wtf')); expect(complete).not.toBeCalled(); expect(error).toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual(undefined); }); it('commits optimistic response with fragment spread', () => { operation = createOperationDescriptor(CreateCommentWithSpreadMutation, variables); const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); environment .executeMutation({ operation, optimisticResponse: { commentCreate: { comment: { id: commentID, body: { text: 'Give Relay', }, }, }, }, }) .subscribe(callbacks); expect(complete).not.toBeCalled(); expect(error).not.toBeCalled(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ id: commentID, body: { text: 'Give Relay', }, }); }); it('does not commit the server payload if disposed', () => { const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request); const snapshot = environment.lookup(selector); const callback = jest.fn(); environment.subscribe(snapshot, callback); const subscription = environment .executeMutation({ operation, optimisticUpdater: (_store) => { const comment = _store.create(commentID, 'Comment'); comment.setValue(commentID, 'id'); const body = _store.create(commentID + '.text', 'Text'); comment.setLinkedRecord(body, 'body'); body.setValue('Give Relay', 'text'); }, }) .subscribe(callbacks); subscription.unsubscribe(); callback.mockClear(); subject.next({ data: { commentCreate: { comment: { id: commentID, body: { text: 'Gave Relay', }, }, }, }, }); subject.complete(); expect(complete).not.toBeCalled(); expect(error).not.toBeCalled(); // The optimistic update has already been reverted expect(callback.mock.calls.length).toBe(0); // The mutation affecting the query should not be marked as in flight // since it was disposed expect(environment.getOperationTracker().getPromiseForPendingOperationsAffectingOwner(queryOperation.request)).toBe(null); }); });
the_stack
export default function makeDashboard(integrationId: string) { return { __inputs: [], __requires: [], annotations: { list: [] }, editable: false, gnetId: null, graphTooltip: 1, hideControls: false, id: null, links: [], refresh: "", panels: [ { datasource: "$datasource", fieldConfig: { defaults: { custom: {} }, overrides: [] }, gridPos: { h: 10, w: 24, x: 0, y: 0 }, id: 1, options: { showLabels: false, showTime: false, sortOrder: "Descending", wrapLogMessage: false }, pluginVersion: "7.4.3", targets: [ { expr: `{integration_id="${integrationId}"} |= "error"`, maxLines: 100, queryType: "randomWalk", refId: "A" } ], title: "Recent errors", type: "logs" }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", description: "", fieldConfig: { defaults: { custom: {} }, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 10, w: 12, x: 0, y: 10 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "7.4.3", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum by (job) (rate({integration_id="${integrationId}"} |= "error" | line_format "{{.job}}"[1m]))`, legendFormat: "{{job}}", maxLines: null, refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Errors by pod", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: "lines/s", logBase: 1, max: null, min: null, show: true }, { 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: "$datasource", description: "", fieldConfig: { defaults: { color: {}, custom: {}, thresholds: { mode: "absolute", steps: [] } }, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 10, w: 12, x: 12, y: 10 }, hiddenSeries: false, id: 3, 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: "7.4.3", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum by (namespace, controller) (rate(({integration_id="${integrationId}"})[1m]))`, legendFormat: "{{namespace}}/{{controller}}", maxLines: null, refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Errors by statefulset/daemonset/replicaset", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { decimals: null, format: "short", label: "lines/s", logBase: 1, max: null, min: "0", show: true }, { format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { datasource: "$datasource", fieldConfig: { defaults: { custom: {} }, overrides: [] }, gridPos: { h: 10, w: 24, x: 0, y: 20 }, id: 4, options: { showLabels: false, showTime: false, sortOrder: "Descending", wrapLogMessage: false }, pluginVersion: "7.4.3", targets: [ { expr: `{integration_id="${integrationId}"}`, maxLines: 100, queryType: "randomWalk", refId: "A" } ], title: "Recent logs", type: "logs" }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "$datasource", description: "", fieldConfig: { defaults: { color: {}, custom: {}, thresholds: { mode: "absolute", steps: [] } }, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 10, w: 12, x: 0, y: 30 }, hiddenSeries: false, id: 5, 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: "7.4.3", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum by (job) (rate(({integration_id="${integrationId}"})[1m]))`, legendFormat: "{{job}}", maxLines: null, refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Logs by pod", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { format: "short", label: "lines/s", logBase: 1, max: null, min: null, show: true }, { 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: "$datasource", description: "", fieldConfig: { defaults: { color: {}, custom: {}, thresholds: { mode: "absolute", steps: [] } }, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 10, w: 12, x: 12, y: 30 }, hiddenSeries: false, id: 6, 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: "7.4.3", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum by (namespace) (rate(({integration_id="${integrationId}"})[1m]))`, legendFormat: "{{namespace}}", maxLines: null, refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Logs by namespace", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { decimals: null, format: "short", label: "lines/s", logBase: 1, max: null, min: "0", show: true }, { format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], schemaVersion: 27, style: "dark", tags: ["kubernetes-integration"], templating: { list: [ { current: { text: "Loki", value: "Loki" }, hide: 0, label: null, name: "datasource", options: [], query: "loki", refresh: 1, regex: "", type: "datasource" } ] }, time: { from: "now-1h", to: "now" }, timepicker: { refresh_intervals: [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], time_options: ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"] }, timezone: "", title: "Kubernetes / Logs summary", uid: `sum-${integrationId}`, version: 0 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import crypto from 'crypto'; import { EventEmitter } from 'events'; import invariant from 'invariant'; import warning from 'warning'; import { JsonObject } from 'type-fest'; import { LineClient } from 'messaging-api-line'; import Session from '../session/Session'; import { Connector } from '../bot/Connector'; import { RequestContext } from '../types'; import LineContext from './LineContext'; import LineEvent from './LineEvent'; import { LineRawEvent, LineRequestBody, LineRequestContext } from './LineTypes'; type CommonConnectorOptions = { getConfig?: GetConfigFunction; getSessionKeyPrefix?: GetSessionKeyPrefixFunction; shouldBatch?: boolean; sendMethod?: string; skipLegacyProfile?: boolean; }; type Credential = { accessToken: string; channelSecret: string }; type GetConfigFunction = ({ params, }: { params: Record<string, string>; }) => Credential | Promise<Credential>; export type GetSessionKeyPrefixFunction = ( event: LineEvent, requestContext?: RequestContext ) => string; type CredentialOptions = | Credential | { getConfig: GetConfigFunction; }; type ConnectorOptionsWithoutClient = CredentialOptions & { origin?: string; } & CommonConnectorOptions; type ConnectorOptionsWithClient = { client: LineClient; channelSecret: string; } & CommonConnectorOptions; export type LineConnectorOptions = | ConnectorOptionsWithoutClient | ConnectorOptionsWithClient; export default class LineConnector implements Connector<LineRequestBody, LineClient> { _client: LineClient | undefined; _channelSecret: string | undefined; _origin: string | undefined; _skipLegacyProfile: boolean; _getConfig: GetConfigFunction | undefined; _getSessionKeyPrefix: GetSessionKeyPrefixFunction | undefined; _shouldBatch: boolean; /** * @deprecated */ _sendMethod: string; constructor(options: LineConnectorOptions) { const { getConfig, shouldBatch, sendMethod, skipLegacyProfile, getSessionKeyPrefix, } = options; if ('client' in options) { this._client = options.client; this._channelSecret = options.channelSecret; } else { const { origin } = options; if ('getConfig' in options) { this._getConfig = getConfig; } else { const { accessToken, channelSecret } = options; invariant( accessToken, 'LINE access token is required. Please make sure you have filled it correctly in your `bottender.config.js` or `.env` file.' ); invariant( channelSecret, 'LINE channel secret is required. Please make sure you have filled it correctly in your `bottender.config.js` or the `.env` file.' ); this._client = new LineClient({ accessToken, channelSecret, origin, }); this._channelSecret = channelSecret; } this._origin = origin; } this._shouldBatch = typeof shouldBatch === 'boolean' ? shouldBatch : true; warning( !sendMethod || sendMethod === 'reply' || sendMethod === 'push', 'sendMethod should be one of `reply` or `push`' ); if (sendMethod) { warning( false, '`sendMethod` is deprecated. The value will always be `reply` in v2.' ); this._sendMethod = sendMethod; } else { this._sendMethod = 'reply'; } this._getSessionKeyPrefix = getSessionKeyPrefix; this._skipLegacyProfile = typeof skipLegacyProfile === 'boolean' ? skipLegacyProfile : true; } _isWebhookVerifyEvent(event: LineRawEvent): boolean { return ( 'replyToken' in event && (event.replyToken === '00000000000000000000000000000000' || event.replyToken === 'ffffffffffffffffffffffffffffffff') ); } isWebhookVerifyRequest(body: LineRequestBody): boolean { return ( body && Array.isArray(body.events) && body.events.length > 0 && body.events.every(this._isWebhookVerifyEvent) ); } get platform(): 'line' { return 'line'; } get client(): LineClient | undefined { return this._client; } getUniqueSessionKey( bodyOrEvent: LineRequestBody | LineEvent, requestContext?: RequestContext ): string { const rawEvent = bodyOrEvent instanceof LineEvent ? bodyOrEvent.rawEvent : bodyOrEvent.events[0]; let prefix = ''; if (this._getSessionKeyPrefix) { const event = bodyOrEvent instanceof LineEvent ? bodyOrEvent : new LineEvent(rawEvent, { destination: bodyOrEvent.destination }); prefix = this._getSessionKeyPrefix(event, requestContext); } const { source } = rawEvent; if (source.type === 'user') { return `${prefix}${source.userId}`; } if (source.type === 'group') { return `${prefix}${source.groupId}`; } if (source.type === 'room') { return `${prefix}${source.roomId}`; } throw new TypeError( 'LineConnector: sender type should be one of user, group, room.' ); } async updateSession( session: Session, bodyOrEvent: LineRequestBody | LineEvent ): Promise<void> { const rawEvent = bodyOrEvent instanceof LineEvent ? bodyOrEvent.rawEvent : bodyOrEvent.events[0]; const { source } = rawEvent; if (!session.type) { session.type = source.type; } if (source.type === 'group') { let user = null; if (source.userId) { user = this._skipLegacyProfile || !this._client ? { id: source.userId, _updatedAt: new Date().toISOString(), } : { id: source.userId, _updatedAt: new Date().toISOString(), ...(await this._client.getGroupMemberProfile( source.groupId, source.userId )), }; } session.user = user; let memberIds: string[] = []; try { if (this._client) { memberIds = await this._client.getAllGroupMemberIds(source.groupId); } } catch (err) { // FIXME: handle no memberIds // only LINE@ Approved accounts or official accounts can use this API // https://developers.line.me/en/docs/messaging-api/reference/#get-group-member-user-ids } session.group = { id: source.groupId, members: memberIds.map((id) => ({ id })), _updatedAt: new Date().toISOString(), }; } else if (source.type === 'room') { let user = null; if (source.userId) { user = this._skipLegacyProfile || !this._client ? { id: source.userId, _updatedAt: new Date().toISOString(), } : { id: source.userId, _updatedAt: new Date().toISOString(), ...(await this._client.getRoomMemberProfile( source.roomId, source.userId )), }; } session.user = user; let memberIds: string[] = []; try { if (this._client) { memberIds = await this._client.getAllRoomMemberIds(source.roomId); } } catch (err) { // FIXME: handle no memberIds // only LINE@ Approved accounts or official accounts can use this API // https://developers.line.me/en/docs/messaging-api/reference/#get-room-member-user-ids } session.room = { id: source.roomId, members: memberIds.map((id) => ({ id })), _updatedAt: new Date().toISOString(), }; } else if (source.type === 'user') { if (!session.user) { const user = this._skipLegacyProfile || !this._client ? {} : await this._client.getUserProfile(source.userId); session.user = { id: source.userId, _updatedAt: new Date().toISOString(), ...user, }; } } if (session.group) { Object.freeze(session.group); } Object.defineProperty(session, 'group', { configurable: false, enumerable: true, writable: false, value: session.group, }); if (session.room) { Object.freeze(session.room); } Object.defineProperty(session, 'room', { configurable: false, enumerable: true, writable: false, value: session.room, }); if (session.user) { Object.freeze(session.user); } Object.defineProperty(session, 'user', { configurable: false, enumerable: true, writable: false, value: session.user, }); } mapRequestToEvents(body: LineRequestBody): LineEvent[] { const { destination } = body; return body.events .filter((event) => !this._isWebhookVerifyEvent(event)) .map((event) => new LineEvent(event, { destination })); } async createContext(params: { event: LineEvent; session?: Session | null; initialState?: JsonObject | null; requestContext?: LineRequestContext; emitter?: EventEmitter | null; }): Promise<LineContext> { const { requestContext } = params; let client: LineClient; if (this._getConfig) { invariant( requestContext, 'getConfig: `requestContext` is required to execute the function.' ); const config = await this._getConfig({ params: requestContext.params, }); invariant( config.accessToken, 'getConfig: `accessToken` is missing in the resolved value.' ); invariant( config.channelSecret, 'getConfig: `accessToken` is missing in the resolved value.' ); client = new LineClient({ accessToken: config.accessToken, channelSecret: config.channelSecret, origin: this._origin, }); } else { client = this._client as LineClient; } return new LineContext({ ...params, client, shouldBatch: this._shouldBatch, sendMethod: this._sendMethod, }); } verifySignature( rawBody: string, signature: string, { channelSecret }: { channelSecret: string } ): boolean { const hashBufferFromBody = crypto .createHmac('sha256', channelSecret) .update(rawBody, 'utf8') .digest(); const bufferFromSignature = Buffer.from(signature, 'base64'); // return early here if buffer lengths are not equal since timingSafeEqual // will throw if buffer lengths are not equal if (bufferFromSignature.length !== hashBufferFromBody.length) { return false; } return crypto.timingSafeEqual(bufferFromSignature, hashBufferFromBody); } async preprocess({ method, headers, rawBody, body, params, }: LineRequestContext) { if (method.toLowerCase() !== 'post') { return { shouldNext: true, }; } let channelSecret: string; if (this._getConfig) { const config = await this._getConfig({ params }); invariant( config.channelSecret, 'getConfig: `accessToken` is missing in the resolved value.' ); channelSecret = config.channelSecret; } else { channelSecret = this._channelSecret as string; } if ( !headers['x-line-signature'] || !this.verifySignature(rawBody, headers['x-line-signature'], { channelSecret, }) ) { const error = { message: 'LINE Signature Validation Failed!', request: { rawBody, headers: { 'x-line-signature': headers['x-line-signature'], }, }, }; return { shouldNext: false, response: { status: 400, body: { error }, }, }; } if (this.isWebhookVerifyRequest(body)) { return { shouldNext: false, response: { status: 200, body: 'OK', }, }; } return { shouldNext: true, }; } }
the_stack
import { Context, ContextProviderRecord, createContext, derivedContext, ExtractContextRecordTypes, isDerviedContext, OmitDerivedContextFromRecord } from '../base/context'; import { keysOf } from '../utils/object'; import { MediaType } from './MediaType'; import { createTimeRanges } from './time-ranges'; import { ViewType } from './ViewType'; // Decalred here as they are used within derived contexts below. const buffered = createContext(createTimeRanges()); const duration = createContext(NaN); const mediaType = createContext(MediaType.Unknown); const seekable = createContext(createTimeRanges()); const viewType = createContext(ViewType.Unknown); const isLiveVideo = derivedContext( [mediaType], ([m]) => m === MediaType.LiveVideo ); /** * The media context record contains a collection of contexts that map 1:1 with media * state. This context enables state to be passed down to elements lower in the media * subtree. It's updated by the media controller. If you're creating your own elements to place * inside the media container you can use it like so... * * ```js * import { LitElement } from 'lit'; * import { consumeContext, mediaContext } from "@vidstack/elements"; * * class MyElement extends LitElement { * \@consumeConsumeContext(mediaContext.paused) * mediaPaused = mediaContext.paused.initialValue; * } * ``` */ export const mediaContext = { /** * Whether playback should automatically begin as soon as enough media is available to do so * without interruption. * * Sites which automatically play audio (or videos with an audio track) can be an unpleasant * experience for users, so it should be avoided when possible. If you must offer autoplay * functionality, you should make it opt-in (requiring a user to specifically enable it). * * However, autoplay can be useful when creating media elements whose source will be set at a * later time, under user control. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/autoplay */ autoplay: createContext(false), /** * Set to an `Error` object when autoplay has failed to begin playback. This * can be used to determine when to show a recovery UI in the event autoplay fails. * * @default undefined */ autoplayError: createContext<Error | undefined>(undefined), /** * Returns a `TimeRanges` object that indicates the ranges of the media source that the * browser has buffered (if any) at the moment the buffered property is accessed. This is usually * contiguous but if the user jumps about while media is buffering, it may contain holes. * * @link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered * @default TimeRanges */ buffered, /** * A `double` indicating the total playback length of the media in seconds. If no media data is * available, the returned value is `NaN`. If the media is of indefinite length (such as * streamed live media, a WebRTC call's media, or similar), the value is `+Infinity`. * * @default NaN * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/duration */ duration, /** * Converts the `buffered` time ranges into an absolute value to indicate the amount of * media that has buffered from `0` to `duration`. * * @default 0 */ bufferedAmount: derivedContext( [buffered, duration], ([buffered, duration]) => { const end = buffered.length === 0 ? 0 : buffered.end(buffered.length - 1); return end > duration ? duration : end; } ), /** * Whether the native browser fullscreen API is available, or the current provider can * toggle fullscreen mode. This does not mean that the operation is guaranteed to be successful, * only that it can be attempted. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API */ canRequestFullscreen: createContext(false), /** * Whether the user agent can play the media, but estimates that **not enough** data has been * loaded to play the media up to its end without having to stop for further buffering of * content. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event */ canPlay: createContext(false), /** * Whether the user agent can play the media, and estimates that enough data has been * loaded to play the media up to its end without having to stop for further buffering * of content. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event */ canPlayThrough: createContext(false), /** * Indicates whether a user interface should be shown for controlling the resource. Set this to * `false` when you want to provide your own custom controls, and `true` if you want the current * provider to supply its own default controls. Depending on the provider, changing this prop * may cause the player to completely reset. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controls */ controls: createContext(false), /** * Indicates whether a custom user interface should be shown for controlling the resource. If * `true`, it is expected that `controls` is set to `false` (the default) to avoid double * controls. The `controls` property refers to native controls. * * @default false */ customControls: createContext(false), /** * The URL of the current poster. Defaults to `''` if no media/poster has been given or * loaded. * * @default '' */ currentPoster: createContext(''), /** * The absolute URL of the media resource that has been chosen. Defaults to `''` if no * media has been loaded. * * @default '' * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentSrc */ currentSrc: createContext(''), /** * A `double` indicating the current playback time in seconds. Defaults to `0` if the media has * not started to play and has not seeked. Setting this value seeks the media to the new * time. The value can be set to a minimum of `0` and maximum of the total length of the * media (indicated by the duration prop). * * @default 0 * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime */ currentTime: createContext(0), /** * Whether media playback has reached the end. In other words it'll be true * if `currentTime === duration`. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended */ ended: createContext(false), /** * Contains the most recent error or undefined if there's been none. You can listen for * `vds-error` event updates and examine this object to debug further. The error could be a * native `MediaError` object or something else. * * @default undefined * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error */ error: createContext(undefined) as Context<unknown>, /** * Whether the player is currently in fullscreen mode. * * @default false */ fullscreen: createContext(false), /** * Whether there is no user activity for a set period of time (default is `3000ms`). Activity * is measured by any action occurring inside the media such as toggling controls, seeking * etc. * * @default false */ idle: createContext(false), /** * Whether media should automatically start playing from the beginning (replay) every time * it ends. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loop */ loop: createContext(false), /** * Whether the current media is a live stream. */ live: derivedContext([isLiveVideo], ([d]) => d), /** * The type of media that is currently active, whether it's audio or video. Defaults * to `unknown` when no media has been loaded or the type cannot be determined. * * @default MediaType.Unknown */ mediaType, /** * Whether the current media type is of type audio. Derived from `mediaType`, shorthand for * `mediaType === MediaType.Audio`. * * @default false */ isAudio: derivedContext([mediaType], ([m]) => m === MediaType.Audio), /** * Whether the current media type is of type video. Derived from `mediaType`, shorthand for * `mediaType === MediaType.Video`. * * @default false */ isVideo: derivedContext([mediaType], ([m]) => m === MediaType.Video), /** * Whether the current media type is of type live video. Derived from `mediaType`, shorthand for * `mediaType === MediaType.LiveVideo`. * * @default false */ isLiveVideo, /** * Whether the audio is muted or not. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/muted */ muted: createContext(false), /** * Whether playback should be paused. Defaults to `true` if no media has loaded or playback has * not started. Setting this to `false` will begin/resume playback. * * @default true * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/paused */ paused: createContext(true), /** * Contains the ranges of the media source that the browser has played, if any. * * @default TimeRanges */ played: createContext(createTimeRanges()), /** * Whether media is actively playing back. Defaults to `false` if no media has * loaded or playback has not started. * * @default false */ playing: createContext(false), /** * Whether the video is to be played "inline", that is within the element's playback area. Note * that setting this to `false` does not imply that the video will always be played in fullscreen. * Depending on the provider, changing this prop may cause the player to completely reset. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-playsinline */ playsinline: createContext(false), /** * Contains the time ranges that the user is able to seek to, if any. This tells us which parts * of the media can be played without delay; this is irrespective of whether that part has * been downloaded or not. * * Some parts of the media may be seekable but not buffered if byte-range * requests are enabled on the server. Byte range requests allow parts of the media file to * be delivered from the server and so can be ready to play almost immediately — thus they are * seekable. * * @default TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seekable */ seekable, /** * Converts the `seekable` time ranges into an absolute value to indicate the amount of * media that is seekable from `0` to `duration`. * * @default 0 */ seekableAmount: derivedContext( [seekable, duration], ([seekable, duration]) => { const end = seekable.length === 0 ? 0 : seekable.end(seekable.length - 1); return end > duration ? duration : end; } ), /** * Whether media is actively seeking to an new playback position. * * @default false */ seeking: createContext(false), /** * Whether media playback has started. In other words it will be true if `currentTime > 0`. * * @default false */ started: createContext(false), /** * The type of player view that is being used, whether it's an audio player view or * video player view. Normally if the media type is of audio then the view is of type audio, but * in some cases it might be desirable to show a different view type. For example, when playing * audio with a poster. This is subject to the provider allowing it. Defaults to `unknown` * when no media has been loaded. * * @default ViewType.Unknown */ viewType, /** * Whether the current view type is of type audio. Derived from `viewType`, shorthand for * `viewType === ViewType.Audio`. * * @default false */ isAudioView: derivedContext([viewType], ([v]) => v === ViewType.Audio), /** * Whether the current view type is of type video. Derived from `viewType`, shorthand for * `viewType === ViewType.Video`. * * @default false */ isVideoView: derivedContext([viewType], ([v]) => v === ViewType.Video), /** * An `int` between `0` (silent) and `1` (loudest) indicating the audio volume. Defaults to `1`. * * @default 1 * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volume */ volume: createContext(1), /** * Whether playback has temporarily stopped because of a lack of temporary data. * * @default false */ waiting: createContext(false) }; export type MediaContextRecord = typeof mediaContext; export type MediaContextProviderRecord = ContextProviderRecord<MediaContextRecord>; export type MediaContextRecordValues = ExtractContextRecordTypes<MediaContextRecord>;
the_stack
const k = stylex.create({ base: { backgroundColor: "var(--divider)", display: "none", height: "100%", opacity: 0, position: "absolute", right: 0, top: 0, transitionDuration: ".5s", transitionProperty: "opacity", transitionTimingFunction: "ease", width: 16, ":hover": { opacity: 0.3 } } }); const i = stylex.create({ animationFillModeAndTimingFn: { animationFillMode: "both", animationTimingFunction: "cubic-bezier(0,0,1,1)", }, foregroundCircle: { animationDuration: "2s", animationFillMode: "both", animationIterationCount: "infinite", animationTimingFunction: "cubic-bezier(.33,0,.67,1)", transformOrigin: "50% 50%" }, foregroundCircle12: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 6.3, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 28.3, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 14.1, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 28.3, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 6.3, transform: 'rotate(-90deg)', }, }) }, foregroundCircle12Optimized: { strokeDashoffset: 6.3 }, foregroundCircle16: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 8.8, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 39.6, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 19.8, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 39.6, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 8.8, transform: 'rotate(-90deg)', }, }) }, foregroundCircle16Optimized: { strokeDashoffset: 8.8 }, foregroundCircle20: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 11.3, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 50.9, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 25.4, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 50.9, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 11.3, transform: 'rotate(-90deg)', }, }) }, foregroundCircle20Optimized: { strokeDashoffset: 11.3 }, foregroundCircle24: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 13.8, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 62.2, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 31.1, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 62.2, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 13.8, transform: 'rotate(-90deg)', }, }) }, foregroundCircle24Optimized: { strokeDashoffset: 13.8 }, foregroundCircle32: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 18.8, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 84.8, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 42.4, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 84.8, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 18.8, transform: 'rotate(-90deg)', }, }) }, foregroundCircle32Optimized: { strokeDashoffset: 18.8 }, foregroundCircle48: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 28.9, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 130, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 65, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 130, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 28.9, transform: 'rotate(-90deg)', }, }) }, foregroundCircle48Optimized: { strokeDashoffset: 28.9 }, foregroundCircle60: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 36.4, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 164, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 82, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 164, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 36.4, transform: 'rotate(-90deg)', }, }) }, foregroundCircle60Optimized: { strokeDashoffset: 36.4, }, foregroundCircle72: { animationName: stylex.keyframes({ '0%': { strokeDashoffset: 43.98, transform: 'rotate(-90deg)', }, '25%': { strokeDashoffset: 197.9, transform: 'rotate(162deg)', }, '50%': { strokeDashoffset: 98.9, transform: 'rotate(72deg)', }, '75%': { strokeDashoffset: 197.9, transform: 'rotate(162deg)', }, '100%': { strokeDashoffset: 43.98, transform: 'rotate(-90deg)', }, }) }, foregroundCircle72Optimized: { strokeDashoffset: 43.98 }, hideOutline: { outline: "none" }, rotationCircle: { animationDuration: "2s", animationIterationCount: "infinite", animationName: stylex.keyframes({ '0%': { transform: "rotate(-90deg)" }, '25%': { transform: "rotate(90deg)" }, '50%': { transform: "rotate(270deg)" }, '75%': { transform: "rotate(450deg)" }, '100%': { transform: "rotate(990deg)" }, }), animationTimingFunction: "steps(10,end)", transformOrigin: "50% 50%" } }); let i = stylex.create({ backgroundContainerDialog: { "@media (max-width: 899px)": { height: "calc(50vh)" } }, backgroundContainerDialogWithFooter: { height: "calc(100vh - 52px)", "@media (max-width: 899px)": { height: "calc(50vh - 52px)" } }, backgroundContainerResponsive: { alignItems: "center", display: "flex", position: "relative", "@media (max-width: 899px)": { height: "auto" } }, backgroundContainerTabs: { height: "calc(100vh - var(--header-height))", "@media (max-width: 899px)": { height: "calc(50vh - var(--header-height))" } }, backgroundContainerTabsWithFooter: { height: "calc(100vh - var(--header-height) - 52px)", "@media (max-width: 899px)": { height: "calc(50vh - var(--header-height) - 52px)" } }, image: { maxWidth: "100%", "@media (max-width: 899px)": { maxHeight: "50vh" } }, maxImageHeightDialog: { maxHeight: "100vh", "@media (max-width: 899px)": { maxHeight: "calc(50vh - var(--header-height))" } }, maxImageHeightDialogWithFooter: { maxHeight: "calc(100vh - 52px)", "@media (max-width: 899px)": { maxHeight: "calc(50vh - 52px)" } }, maxImageHeightTabs: { maxHeight: "calc(100vh - var(--header-height))", "@media (max-width: 899px)": { maxHeight: "calc(50vh - var(--header-height))" } }, maxImageHeightTabsWithFooter: { maxHeight: "kgqd366c", "@media (max-width: 899px)": { maxHeight: "calc(50vh - var(--header-height) - 52px)" } }, passthroughImage: { backgroundPosition: "center center", backgroundRepeat: "no-repeat", backgroundSize: "contain", height: "100%", width: "100%" }, photoWrapperPlaceholder: { height: "100%", width: "100%" }, photoWrapperResponsive: { alignItems: "center", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative" }, placeholderContainer: { height: "100%", width: "100%" } }); function aaaa() { return ( <CheckMarkIcon size={18} UNSAFE_className={stylex.dedupe( { display: 'inline-block', pointerEvents: 'none', fill: 'currentColor', width: 18, height: 18, position: 'absolute', color: 'var(--always-white)', transition: 'opacity 100ms ease-in-out, transform 100ms ease-in-out', }, state.isSelected ? { opacity: 1, } : { opacity: 0, }, )} /> ) } function aaa() { return ( <div {...hoverProps} key={`${bodyId}-row-${index}`} className={joinClasses( stylex.dedupe( { boxSizing: 'border-box', }, !isHovered ? { backgroundColor: 'var(--card-background)', } : { backgroundColor: 'var(--light-light-color)', }, !state.noBorders ? { borderStyle: 'solid', borderColor: 'var(--divider)' } : null, !state.noBorders && (index > 0 || !state.noHeader && index === 0) ? { borderBottomWidth: 1, borderLeftWidth: 0, borderRightWidth: 0, borderTopWidth: 0, } : null, !state.noBorders && state.noHeader && index === 0 ? { borderTopWidth: 1, borderBottomWidth: 1, borderLeftWidth: 0, borderRightWidth: 0, } : null, ), state.rowClassName, )} style={{display: 'flex'}} > aa </div> ); } function aaa() { return React.createElement("svg", { className: stylex.dedupe({ position: "absolute" }, a === 36 ? { left: -3, top: -3 } : null, a === 60 ? { left: -3, top: -3 } : null, a === 40 ? { left: -3, top: -3 } : null), height: d, width: d, children: React.createElement("g", { className: stylex.dedupe({ transformOrigin: '50% 50%', animationTimingFunction: 'linear', animationName: stylex.keyframes({ to: { transform: 'rotate(1turn)', }, }), animationIterationCount: 'infinite', animationDuration: '4s', }, c ? { animationPlayState: 'paused', } : null, ), children: React.createElement("circle", { className: stylex.dedupe({ animationDirection: "reverse", animationDuration: "16s", animationIterationCount: "infinite", animationTimingFunction: "linear", transformOrigin: "50% 50%" }, a === 36 ? { animationDirection: "reverse", animationDuration: "4s", animationIterationCount: "infinite", animationTimingFunction: "linear", transformOrigin: "50% 50%", animationName: stylex.keyframes({ '0%': { animationTimingFunction: 'cubic-bezier(.895, .03, .685, .22)', strokeDasharray: '71 95', strokeDashoffset: 0, }, '49.999%': { strokeDasharray: '0 95', strokeDashoffset: 0 }, '50.001%': { animationTimingFunction: 'cubic-bezier(.165, .84, .44, 1)', strokeDasharray: '0 95', strokeDashoffset: -95, }, '100%': { strokeDasharray: '71 95', strokeDashoffset: 0 } }), strokeWidth: 2 } : null, a === 40 ? { animationDirection: "reverse", animationDuration: "4s", animationIterationCount: "infinite", animationTimingFunction: "linear", transformOrigin: "50% 50%", animationName: stylex.keyframes({ '0%': { animationTimingFunction: 'cubic-bezier(.895, .03, .685, .22)', strokeDasharray: '79 106', strokeDashoffset: 0 }, '49.999%': { strokeDasharray: '0 106', strokeDashoffset: 0 }, '50.001%': { animationTimingFunction: 'cubic-bezier(.165, .84, .44, 1)', strokeDasharray: '0 106', strokeDashoffset: -106 }, '100%': { strokeDasharray: '79 106', strokeDashoffset: 0 } }), strokeWidth: 3 } : null, a === 60 ? { animationDirection: "reverse", animationDuration: "4s", animationIterationCount: "infinite", animationTimingFunction: "linear", transformOrigin: "50% 50%", animationName: stylex.keyframes({ '0%': { animationTimingFunction: 'cubic-bezier(.895, .03, .685, .22)', strokeDasharray: '118 158', strokeDashoffset: 0, }, '49.999%': { strokeDasharray: '0 158', strokeDashoffset: 0, }, '50.001%': { animationTimingFunction: 'cubic-bezier(.165, .84, .44, 1)', strokeDasharray: '0 158', strokeDashoffset: -158, }, '100%': { strokeDasharray: '118 158', strokeDashoffset: 0, } }), strokeWidth: 4 } : null, c ? { animationPlayState: 'paused', } : null), cx: e, cy: e, fill: "none", r: f, stroke: "#1877F2", strokeWidth: a === 36 ? m : a === 40 ? n : o }) }) }) }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/spectrum/v1explorer/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Spectrum Database API v1explorer */ function load(name: "spectrum", version: "v1explorer"): PromiseLike<void>; function load(name: "spectrum", version: "v1explorer", callback: () => any): void; const paws: spectrum.PawsResource; namespace spectrum { interface AntennaCharacteristics { /** * The antenna height in meters. Whether the antenna height is required depends on the device type and the regulatory domain. Note that the height may be * negative. */ height?: number; /** If the height is required, then the height type (AGL for above ground level or AMSL for above mean sea level) is also required. The default is AGL. */ heightType?: string; /** The height uncertainty in meters. Whether this is required depends on the regulatory domain. */ heightUncertainty?: number; } interface DatabaseSpec { /** The display name for a database. */ name?: string; /** The corresponding URI of the database. */ uri?: string; } interface DbUpdateSpec { /** * A required list of one or more databases. A device should update its preconfigured list of databases to replace (only) the database that provided the * response with the specified entries. */ databases?: DatabaseSpec[]; } interface DeviceCapabilities { /** * An optional list of frequency ranges supported by the device. Each element must contain start and stop frequencies in which the device can operate. * Channel identifiers are optional. When specified, the database should not return available spectrum that falls outside these ranges or channel IDs. */ frequencyRanges?: FrequencyRange[]; } interface DeviceDescriptor { /** * Specifies the ETSI white space device category. Valid values are the strings master and slave. This field is case-insensitive. Consult the ETSI * documentation for details about the device types. */ etsiEnDeviceCategory?: string; /** * Specifies the ETSI white space device emissions class. The values are represented by numeric strings, such as 1, 2, etc. Consult the ETSI documentation * for details about the device types. */ etsiEnDeviceEmissionsClass?: string; /** * Specifies the ETSI white space device type. Valid values are single-letter strings, such as A, B, etc. Consult the ETSI documentation for details about * the device types. */ etsiEnDeviceType?: string; /** * Specifies the ETSI white space device technology identifier. The string value must not exceed 64 characters in length. Consult the ETSI documentation * for details about the device types. */ etsiEnTechnologyId?: string; /** * Specifies the device's FCC certification identifier. The value is an identifier string whose length should not exceed 32 characters. Note that, in * practice, a valid FCC ID may be limited to 19 characters. */ fccId?: string; /** Specifies the TV Band White Space device type, as defined by the FCC. Valid values are FIXED, MODE_1, MODE_2. */ fccTvbdDeviceType?: string; /** * The manufacturer's ID may be required by the regulatory domain. This should represent the name of the device manufacturer, should be consistent across * all devices from the same manufacturer, and should be distinct from that of other manufacturers. The string value must not exceed 64 characters in * length. */ manufacturerId?: string; /** The device's model ID may be required by the regulatory domain. The string value must not exceed 64 characters in length. */ modelId?: string; /** * The list of identifiers for rulesets supported by the device. A database may require that the device provide this list before servicing the device * requests. If the database does not support any of the rulesets specified in the list, the database may refuse to service the device requests. If * present, the list must contain at least one entry. * * For information about the valid requests, see section 9.2 of the PAWS specification. Currently, FccTvBandWhiteSpace-2010 is the only supported ruleset. */ rulesetIds?: string[]; /** The manufacturer's device serial number; required by the applicable regulatory domain. The length of the value must not exceed 64 characters. */ serialNumber?: string; } interface DeviceOwner { /** The vCard contact information for the device operator is optional, but may be required by specific regulatory domains. */ operator?: Vcard; /** The vCard contact information for the individual or business that owns the device is required. */ owner?: Vcard; } interface DeviceValidity { /** The descriptor of the device for which the validity check was requested. It will always be present. */ deviceDesc?: DeviceDescriptor; /** The validity status: true if the device is valid for operation, false otherwise. It will always be present. */ isValid?: boolean; /** * If the device identifier is not valid, the database may include a reason. The reason may be in any language. The length of the value should not exceed * 128 characters. */ reason?: string; } interface EventTime { /** The inclusive start of the event. It will be present. */ startTime?: string; /** The exclusive end of the event. It will be present. */ stopTime?: string; } interface FrequencyRange { /** * The database may include a channel identifier, when applicable. When it is included, the device should treat it as informative. The length of the * identifier should not exceed 16 characters. */ channelId?: string; /** * The maximum total power level (EIRP)—computed over the corresponding operating bandwidth—that is permitted within the frequency range. Depending on the * context in which the frequency-range element appears, this value may be required. For example, it is required in the available-spectrum response, * available-spectrum-batch response, and spectrum-use notification message, but it should not be present (it is not applicable) when the frequency range * appears inside a device-capabilities message. */ maxPowerDBm?: number; /** The required inclusive start of the frequency range (in Hertz). */ startHz?: number; /** The required exclusive end of the frequency range (in Hertz). */ stopHz?: number; } interface GeoLocation { /** * The location confidence level, as an integer percentage, may be required, depending on the regulatory domain. When the parameter is optional and not * provided, its value is assumed to be 95. Valid values range from 0 to 99, since, in practice, 100-percent confidence is not achievable. The confidence * value is meaningful only when geolocation refers to a point with uncertainty. */ confidence?: number; /** * If present, indicates that the geolocation represents a point. Paradoxically, a point is parameterized using an ellipse, where the center represents * the location of the point and the distances along the major and minor axes represent the uncertainty. The uncertainty values may be required, depending * on the regulatory domain. */ point?: GeoLocationEllipse; /** If present, indicates that the geolocation represents a region. Database support for regions is optional. */ region?: GeoLocationPolygon; } interface GeoLocationEllipse { /** A required geo-spatial point representing the center of the ellipse. */ center?: GeoLocationPoint; /** * A floating-point number that expresses the orientation of the ellipse, representing the rotation, in degrees, of the semi-major axis from North towards * the East. For example, when the uncertainty is greatest along the North-South direction, orientation is 0 degrees; conversely, if the uncertainty is * greatest along the East-West direction, orientation is 90 degrees. When orientation is not present, the orientation is assumed to be 0. */ orientation?: number; /** * A floating-point number that expresses the location uncertainty along the major axis of the ellipse. May be required by the regulatory domain. When the * uncertainty is optional, the default value is 0. */ semiMajorAxis?: number; /** * A floating-point number that expresses the location uncertainty along the minor axis of the ellipse. May be required by the regulatory domain. When the * uncertainty is optional, the default value is 0. */ semiMinorAxis?: number; } interface GeoLocationPoint { /** * A required floating-point number that expresses the latitude in degrees using the WGS84 datum. For details on this encoding, see the National Imagery * and Mapping Agency's Technical Report TR8350.2. */ latitude?: number; /** * A required floating-point number that expresses the longitude in degrees using the WGS84 datum. For details on this encoding, see the National Imagery * and Mapping Agency's Technical Report TR8350.2. */ longitude?: number; } interface GeoLocationPolygon { /** * When the geolocation describes a region, the exterior field refers to a list of latitude/longitude points that represent the vertices of a polygon. The * first and last points must be the same. Thus, a minimum of four points is required. The following polygon restrictions from RFC5491 apply: * - A connecting line shall not cross another connecting line of the same polygon. * - The vertices must be defined in a counterclockwise order. * - The edges of a polygon are defined by the shortest path between two points in space (not a geodesic curve). Consequently, the length between two * adjacent vertices should be restricted to a maximum of 130 km. * - All vertices are assumed to be at the same altitude. * - Polygon shapes should be restricted to a maximum of 15 vertices (16 points that include the repeated vertex). */ exterior?: GeoLocationPoint[]; } interface GeoSpectrumSchedule { /** The geolocation identifies the location at which the spectrum schedule applies. It will always be present. */ location?: GeoLocation; /** * A list of available spectrum profiles and associated times. It will always be present, and at least one schedule must be included (though it may be * empty if there is no available spectrum). More than one schedule may be included to represent future changes to the available spectrum. */ spectrumSchedules?: SpectrumSchedule[]; } interface PawsGetSpectrumBatchRequest { /** Depending on device type and regulatory domain, antenna characteristics may be required. */ antenna?: AntennaCharacteristics; /** * The master device may include its device capabilities to limit the available-spectrum batch response to the spectrum that is compatible with its * capabilities. The database should not return spectrum that is incompatible with the specified capabilities. */ capabilities?: DeviceCapabilities; /** * When the available spectrum request is made on behalf of a specific device (a master or slave device), device descriptor information for the device on * whose behalf the request is made is required (in such cases, the requestType parameter must be empty). When a requestType value is specified, device * descriptor information may be optional or required according to the rules of the applicable regulatory domain. */ deviceDesc?: DeviceDescriptor; /** * A geolocation list is required. This allows a device to specify its current location plus additional anticipated locations when allowed by the * regulatory domain. At least one location must be included. Geolocation must be given as the location of the radiation center of the device's antenna. * If a location specifies a region, rather than a point, the database may return an UNIMPLEMENTED error if it does not support query by region. * * There is no upper limit on the number of locations included in a available spectrum batch request, but the database may restrict the number of * locations it supports by returning a response with fewer locations than specified in the batch request. Note that geolocations must be those of the * master device (a device with geolocation capability that makes an available spectrum batch request), whether the master device is making the request on * its own behalf or on behalf of a slave device (one without geolocation capability). */ locations?: GeoLocation[]; /** * When an available spectrum batch request is made by the master device (a device with geolocation capability) on behalf of a slave device (a device * without geolocation capability), the rules of the applicable regulatory domain may require the master device to provide its own device descriptor * information (in addition to device descriptor information for the slave device in a separate parameter). */ masterDeviceDesc?: DeviceDescriptor; /** * Depending on device type and regulatory domain, device owner information may be included in an available spectrum batch request. This allows the device * to register and get spectrum-availability information in a single request. */ owner?: DeviceOwner; /** * The request type parameter is an optional parameter that can be used to modify an available spectrum batch request, but its use depends on applicable * regulatory rules. For example, It may be used to request generic slave device parameters without having to specify the device descriptor for a specific * device. When the requestType parameter is missing, the request is for a specific device (master or slave), and the device descriptor parameter for the * device on whose behalf the batch request is made is required. */ requestType?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsGetSpectrumBatchResponse { /** * A database may include the databaseChange parameter to notify a device of a change to its database URI, providing one or more alternate database URIs. * The device should use this information to update its list of pre-configured databases by (only) replacing its entry for the responding database with * the list of alternate URIs. */ databaseChange?: DbUpdateSpec; /** * The database must return in its available spectrum response the device descriptor information it received in the master device's available spectrum * batch request. */ deviceDesc?: DeviceDescriptor; /** * The available spectrum batch response must contain a geo-spectrum schedule list, The list may be empty if spectrum is not available. The database may * return more than one geo-spectrum schedule to represent future changes to the available spectrum. How far in advance a schedule may be provided depends * upon the applicable regulatory domain. The database may return available spectrum for fewer geolocations than requested. The device must not make * assumptions about the order of the entries in the list, and must use the geolocation value in each geo-spectrum schedule entry to match available * spectrum to a location. */ geoSpectrumSchedules?: GeoSpectrumSchedule[]; /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsGetSpectrumBatchResponse". */ kind?: string; /** * The database may return a constraint on the allowed maximum contiguous bandwidth (in Hertz). A regulatory domain may require the database to return * this parameter. When this parameter is present in the response, the device must apply this constraint to its spectrum-selection logic to ensure that no * single block of spectrum has bandwidth that exceeds this value. */ maxContiguousBwHz?: number; /** * The database may return a constraint on the allowed maximum total bandwidth (in Hertz), which does not need to be contiguous. A regulatory domain may * require the database to return this parameter. When this parameter is present in the available spectrum batch response, the device must apply this * constraint to its spectrum-selection logic to ensure that total bandwidth does not exceed this value. */ maxTotalBwHz?: number; /** * For regulatory domains that require a spectrum-usage report from devices, the database must return true for this parameter if the geo-spectrum * schedules list is not empty; otherwise, the database should either return false or omit this parameter. If this parameter is present and its value is * true, the device must send a spectrum use notify message to the database; otherwise, the device should not send the notification. */ needsSpectrumReport?: boolean; /** * The database should return ruleset information, which identifies the applicable regulatory authority and ruleset for the available spectrum batch * response. If included, the device must use the corresponding ruleset to interpret the response. Values provided in the returned ruleset information, * such as maxLocationChange, take precedence over any conflicting values provided in the ruleset information returned in a prior initialization response * sent by the database to the device. */ rulesetInfo?: RulesetInfo; /** * The database includes a timestamp of the form, YYYY-MM-DDThh:mm:ssZ (Internet timestamp format per RFC3339), in its available spectrum batch response. * The timestamp should be used by the device as a reference for the start and stop times specified in the response spectrum schedules. */ timestamp?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsGetSpectrumRequest { /** Depending on device type and regulatory domain, the characteristics of the antenna may be required. */ antenna?: AntennaCharacteristics; /** * The master device may include its device capabilities to limit the available-spectrum response to the spectrum that is compatible with its * capabilities. The database should not return spectrum that is incompatible with the specified capabilities. */ capabilities?: DeviceCapabilities; /** * When the available spectrum request is made on behalf of a specific device (a master or slave device), device descriptor information for that device is * required (in such cases, the requestType parameter must be empty). When a requestType value is specified, device descriptor information may be optional * or required according to the rules of the applicable regulatory domain. */ deviceDesc?: DeviceDescriptor; /** * The geolocation of the master device (a device with geolocation capability that makes an available spectrum request) is required whether the master * device is making the request on its own behalf or on behalf of a slave device (one without geolocation capability). The location must be the location * of the radiation center of the master device's antenna. To support mobile devices, a regulatory domain may allow the anticipated position of the master * device to be given instead. If the location specifies a region, rather than a point, the database may return an UNIMPLEMENTED error code if it does not * support query by region. */ location?: GeoLocation; /** * When an available spectrum request is made by the master device (a device with geolocation capability) on behalf of a slave device (a device without * geolocation capability), the rules of the applicable regulatory domain may require the master device to provide its own device descriptor information * (in addition to device descriptor information for the slave device, which is provided in a separate parameter). */ masterDeviceDesc?: DeviceDescriptor; /** * Depending on device type and regulatory domain, device owner information may be included in an available spectrum request. This allows the device to * register and get spectrum-availability information in a single request. */ owner?: DeviceOwner; /** * The request type parameter is an optional parameter that can be used to modify an available spectrum request, but its use depends on applicable * regulatory rules. It may be used, for example, to request generic slave device parameters without having to specify the device descriptor for a * specific device. When the requestType parameter is missing, the request is for a specific device (master or slave), and the deviceDesc parameter for * the device on whose behalf the request is made is required. */ requestType?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsGetSpectrumResponse { /** * A database may include the databaseChange parameter to notify a device of a change to its database URI, providing one or more alternate database URIs. * The device should use this information to update its list of pre-configured databases by (only) replacing its entry for the responding database with * the list of alternate URIs. */ databaseChange?: DbUpdateSpec; /** * The database must return, in its available spectrum response, the device descriptor information it received in the master device's available spectrum * request. */ deviceDesc?: DeviceDescriptor; /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsGetSpectrumResponse". */ kind?: string; /** * The database may return a constraint on the allowed maximum contiguous bandwidth (in Hertz). A regulatory domain may require the database to return * this parameter. When this parameter is present in the response, the device must apply this constraint to its spectrum-selection logic to ensure that no * single block of spectrum has bandwidth that exceeds this value. */ maxContiguousBwHz?: number; /** * The database may return a constraint on the allowed maximum total bandwidth (in Hertz), which need not be contiguous. A regulatory domain may require * the database to return this parameter. When this parameter is present in the available spectrum response, the device must apply this constraint to its * spectrum-selection logic to ensure that total bandwidth does not exceed this value. */ maxTotalBwHz?: number; /** * For regulatory domains that require a spectrum-usage report from devices, the database must return true for this parameter if the spectrum schedule * list is not empty; otherwise, the database will either return false or omit this parameter. If this parameter is present and its value is true, the * device must send a spectrum use notify message to the database; otherwise, the device must not send the notification. */ needsSpectrumReport?: boolean; /** * The database should return ruleset information, which identifies the applicable regulatory authority and ruleset for the available spectrum response. * If included, the device must use the corresponding ruleset to interpret the response. Values provided in the returned ruleset information, such as * maxLocationChange, take precedence over any conflicting values provided in the ruleset information returned in a prior initialization response sent by * the database to the device. */ rulesetInfo?: RulesetInfo; /** * The available spectrum response must contain a spectrum schedule list. The list may be empty if spectrum is not available. The database may return more * than one spectrum schedule to represent future changes to the available spectrum. How far in advance a schedule may be provided depends on the * applicable regulatory domain. */ spectrumSchedules?: SpectrumSchedule[]; /** * The database includes a timestamp of the form YYYY-MM-DDThh:mm:ssZ (Internet timestamp format per RFC3339) in its available spectrum response. The * timestamp should be used by the device as a reference for the start and stop times specified in the response spectrum schedules. */ timestamp?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsInitRequest { /** * The DeviceDescriptor parameter is required. If the database does not support the device or any of the rulesets specified in the device descriptor, it * must return an UNSUPPORTED error code in the error response. */ deviceDesc?: DeviceDescriptor; /** A device's geolocation is required. */ location?: GeoLocation; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsInitResponse { /** * A database may include the databaseChange parameter to notify a device of a change to its database URI, providing one or more alternate database URIs. * The device should use this information to update its list of pre-configured databases by (only) replacing its entry for the responding database with * the list of alternate URIs. */ databaseChange?: DbUpdateSpec; /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsInitResponse". */ kind?: string; /** * The rulesetInfo parameter must be included in the response. This parameter specifies the regulatory domain and parameters applicable to that domain. * The database must include the authority field, which defines the regulatory domain for the location specified in the INIT_REQ message. */ rulesetInfo?: RulesetInfo; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsNotifySpectrumUseRequest { /** Device descriptor information is required in the spectrum-use notification message. */ deviceDesc?: DeviceDescriptor; /** * The geolocation of the master device (the device that is sending the spectrum-use notification) to the database is required in the spectrum-use * notification message. */ location?: GeoLocation; /** * A spectrum list is required in the spectrum-use notification. The list specifies the spectrum that the device expects to use, which includes frequency * ranges and maximum power levels. The list may be empty if the device decides not to use any of spectrum. For consistency, the psdBandwidthHz value * should match that from one of the spectrum elements in the corresponding available spectrum response previously sent to the device by the database. * Note that maximum power levels in the spectrum element must be expressed as power spectral density over the specified psdBandwidthHz value. The actual * bandwidth to be used (as computed from the start and stop frequencies) may be different from the psdBandwidthHz value. As an example, when regulatory * rules express maximum power spectral density in terms of maximum power over any 100 kHz band, then the psdBandwidthHz value should be set to 100 kHz, * even though the actual bandwidth used can be 20 kHz. */ spectra?: SpectrumMessage[]; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsNotifySpectrumUseResponse { /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsNotifySpectrumUseResponse". */ kind?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsRegisterRequest { /** Antenna characteristics, including its height and height type. */ antenna?: AntennaCharacteristics; /** A DeviceDescriptor is required. */ deviceDesc?: DeviceDescriptor; /** Device owner information is required. */ deviceOwner?: DeviceOwner; /** A device's geolocation is required. */ location?: GeoLocation; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsRegisterResponse { /** * A database may include the databaseChange parameter to notify a device of a change to its database URI, providing one or more alternate database URIs. * The device should use this information to update its list of pre-configured databases by (only) replacing its entry for the responding database with * the list of alternate URIs. */ databaseChange?: DbUpdateSpec; /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsRegisterResponse". */ kind?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsVerifyDeviceRequest { /** A list of device descriptors, which specifies the slave devices to be validated, is required. */ deviceDescs?: DeviceDescriptor[]; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface PawsVerifyDeviceResponse { /** * A database may include the databaseChange parameter to notify a device of a change to its database URI, providing one or more alternate database URIs. * The device should use this information to update its list of pre-configured databases by (only) replacing its entry for the responding database with * the list of alternate URIs. */ databaseChange?: DbUpdateSpec; /** * A device validities list is required in the device validation response to report whether each slave device listed in a previous device validation * request is valid. The number of entries must match the number of device descriptors listed in the previous device validation request. */ deviceValidities?: DeviceValidity[]; /** Identifies what kind of resource this is. Value: the fixed string "spectrum#pawsVerifyDeviceResponse". */ kind?: string; /** * The message type (e.g., INIT_REQ, AVAIL_SPECTRUM_REQ, ...). * * Required field. */ type?: string; /** * The PAWS version. Must be exactly 1.0. * * Required field. */ version?: string; } interface RulesetInfo { /** * The regulatory domain to which the ruleset belongs is required. It must be a 2-letter country code. The device should use this to determine additional * device behavior required by the associated regulatory domain. */ authority?: string; /** * The maximum location change in meters is required in the initialization response, but optional otherwise. When the device changes location by more than * this specified distance, it must contact the database to get the available spectrum for the new location. If the device is using spectrum that is no * longer available, it must immediately cease use of the spectrum under rules for database-managed spectrum. If this value is provided within the context * of an available-spectrum response, it takes precedence over the value within the initialization response. */ maxLocationChange?: number; /** * The maximum duration, in seconds, between requests for available spectrum. It is required in the initialization response, but optional otherwise. The * device must contact the database to get available spectrum no less frequently than this duration. If the new spectrum information indicates that the * device is using spectrum that is no longer available, it must immediately cease use of those frequencies under rules for database-managed spectrum. If * this value is provided within the context of an available-spectrum response, it takes precedence over the value within the initialization response. */ maxPollingSecs?: number; /** * The identifiers of the rulesets supported for the device's location. The database should include at least one applicable ruleset in the initialization * response. The device may use the ruleset identifiers to determine parameters to include in subsequent requests. Within the context of the * available-spectrum responses, the database should include the identifier of the ruleset that it used to determine the available-spectrum response. If * included, the device must use the specified ruleset to interpret the response. If the device does not support the indicated ruleset, it must not * operate in the spectrum governed by the ruleset. */ rulesetIds?: string[]; } interface SpectrumMessage { /** * The bandwidth (in Hertz) for which permissible power levels are specified. For example, FCC regulation would require only one spectrum specification at * 6MHz bandwidth, but Ofcom regulation would require two specifications, at 0.1MHz and 8MHz. This parameter may be empty if there is no available * spectrum. It will be present otherwise. */ bandwidth?: number; /** The list of frequency ranges and permissible power levels. The list may be empty if there is no available spectrum, otherwise it will be present. */ frequencyRanges?: FrequencyRange[]; } interface SpectrumSchedule { /** The event time expresses when the spectrum profile is valid. It will always be present. */ eventTime?: EventTime; /** A list of spectrum messages representing the usable profile. It will always be present, but may be empty when there is no available spectrum. */ spectra?: SpectrumMessage[]; } interface Vcard { /** The street address of the entity. */ adr?: VcardAddress; /** An email address that can be used to reach the contact. */ email?: VcardTypedText; /** The full name of the contact person. For example: John A. Smith. */ fn?: string; /** The organization associated with the registering entity. */ org?: VcardTypedText; /** A telephone number that can be used to call the contact. */ tel?: VcardTelephone; } interface VcardAddress { /** The postal code associated with the address. For example: 94423. */ code?: string; /** The country name. For example: US. */ country?: string; /** The city or local equivalent portion of the address. For example: San Jose. */ locality?: string; /** An optional post office box number. */ pobox?: string; /** The state or local equivalent portion of the address. For example: CA. */ region?: string; /** The street number and name. For example: 123 Any St. */ street?: string; } interface VcardTelephone { /** A nested telephone URI of the form: tel:+1-123-456-7890. */ uri?: string; } interface VcardTypedText { /** The text string associated with this item. For example, for an org field: ACME, inc. For an email field: smith@example.com. */ text?: string; } interface PawsResource { /** * Requests information about the available spectrum for a device at a location. Requests from a fixed-mode device must include owner information so the * device can be registered with the database. */ getSpectrum(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsGetSpectrumResponse>; /** The Google Spectrum Database does not support batch requests, so this method always yields an UNIMPLEMENTED error. */ getSpectrumBatch(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsGetSpectrumBatchResponse>; /** Initializes the connection between a white space device and the database. */ init(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsInitResponse>; /** * Notifies the database that the device has selected certain frequency ranges for transmission. Only to be invoked when required by the regulator. The * Google Spectrum Database does not operate in domains that require notification, so this always yields an UNIMPLEMENTED error. */ notifySpectrumUse(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsNotifySpectrumUseResponse>; /** The Google Spectrum Database implements registration in the getSpectrum method. As such this always returns an UNIMPLEMENTED error. */ register(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsRegisterResponse>; /** * Validates a device for white space use in accordance with regulatory rules. The Google Spectrum Database does not support master/slave configurations, * so this always yields an UNIMPLEMENTED error. */ verifyDevice(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PawsVerifyDeviceResponse>; } } }
the_stack
import React from 'react' import { List } from 'immutable' import { NavLink as Link } from 'react-router-dom' import { DndProvider } from 'react-dnd' import { MultiBackend } from 'react-dnd-multi-backend' import { HTML5toTouch } from 'rdndmb-html5-to-touch' import { DndValueList } from '@ui-schema/kit-dnd/KitDnd' import { useOnIntent } from '@ui-schema/kit-dnd/useOnIntent' import { KitDndProvider, KitDndProviderContextType } from '@ui-schema/kit-dnd/KitDndProvider' import { moveDraggedValue } from '@ui-schema/kit-dnd/Utils/moveDraggedValue' import { addNestKey } from '@ui-schema/kit-dnd/Utils/addNestKey' import { genId } from '@ui-schema/kit-dnd/genId' import { DraggableAny } from './components/DraggableAny' const KitDndAreas = () => { const [areas, setAreas] = React.useState<DndValueList>( List([ { id: 'a-4', list: List([ /*{id: 'ar-d-1'}, {id: 'ar-d-2'},*/ ]), }, { id: 'a-2', list: List([ {id: 'ar-b-1'}, { id: 'a-1', list: List([ {id: 'ar-a-1'}, {id: 'ar-a-2'}, ]), }, {id: 'ar-b-2'}, {id: 'ar-b-3'}, {id: 'ar-b-4'}, ]), }, { id: 'a-3', list: List([ {id: 'ar-c-1'}, {id: 'ar-c-2'}, {id: 'ar-c-3'}, ]), }, ]) ) const dataKeys: List<number> = React.useMemo(() => List([]), []) const {onIntent} = useOnIntent<HTMLDivElement>({edgeSize: 12}) const lastMergeTag = React.useRef<{ time: number timer: number | undefined merge: undefined | string id: string | undefined }>({time: 0, timer: undefined, merge: undefined, id: undefined}) const onMove: KitDndProviderContextType<HTMLDivElement>['onMove'] = React.useCallback((details) => { onIntent(( { fromItem, toItem, }, intent, intentKeys, done, ) => { if (!intent || !intentKeys) { return } if (lastMergeTag.current.timer) { window.clearTimeout(lastMergeTag.current.timer) } const { type: fromType, dataKeys: fromKeys, index: fromIndex, } = fromItem const { type: toType, index: toIndex, dataKeys: toDataKeys, id: targetId, } = toItem const fromIsDroppable = fromType === 'AREA' const toIsDroppable = toType === 'AREA' if ( // an area can not be dragged deeper into itself: (fromIsDroppable && intentKeys.willBeParent && intentKeys.level === 'down') ) { //console.log(' IGNO from ' + fromType + ' to ' + toType, intent, intentKeys) return } console.log(' from ' + fromType + ' to ' + toType, intent, intentKeys) console.log(' from ' + fromType + ' to ' + toType, fromKeys?.toJS(), fromIndex, toDataKeys.toJS(), toIndex) if (!toIsDroppable) { // - BLOCK > BLOCK // - AREA > BLOCK if ( intentKeys.level === 'up' || intentKeys.level === 'same' || intentKeys.level === 'switch' ) { if (intent.edgeX || intent.edgeY) { return } // - switching within one array or between different relative roots setAreas((areas) => { return moveDraggedValue( areas, addNestKey('list', fromKeys), fromIndex, addNestKey('list', toDataKeys), toIndex, ) }) done() return } if ( intentKeys.level === 'down' && (toDataKeys.size - fromKeys.size) >= 1 ) { if (intentKeys.isParent || intentKeys.willBeParent) { return } // ONLY when moving `down`, from outside the same list let dk = toDataKeys if (intentKeys.wasBeforeRelative) { // was before this block in the relative store order // thus the last relative key needs to be decreased dk = dk.update(fromKeys.size, (toIndexRelativeFirst) => (toIndexRelativeFirst as number) - 1) } setAreas((areas) => { areas = moveDraggedValue( areas, addNestKey('list', fromKeys), fromIndex, addNestKey('list', dk), toIndex, ) done(dk, toIndex) return areas }) return } } if ( toIsDroppable && ( intentKeys.level === 'down' || intentKeys.level === 'up' || intentKeys.level === 'same' || intentKeys.level === 'switch' ) ) { // - any > AREA if ( ( // ignoring dragging to own area, when it's not dragging up and on any edge intentKeys.isParent && intentKeys.level !== 'up'// && !intent.edgeY && !intent.edgeX ) || ( // ignoring on y-edges when not dragging up, // to allow adding blocks at the end of an area from within another area in that area intentKeys.level !== 'up' && intent.edgeY ) || ( // ignoring x-edges for every action to make it possible to drag in-between nested blocks !fromIsDroppable && intent.edgeX && intentKeys.level !== 'up' ) ) { return } const setter = (doMerge: string | undefined) => { setAreas((areas) => { let dk = toDataKeys const orgTks = addNestKey<string | number>('list', toDataKeys.push(toIndex)) let ti = intent.posQuarter === 'top-left' || intent.posQuarter === 'top-right' ? 0 : ((areas.getIn(orgTks) as List<any>)?.size || 0) // when level up, adjust the dataKeys parent according to the new nested index // and either add to `0` or last index if (intentKeys.level === 'same' && intentKeys.container === 'down' && intentKeys.wasBeforeRelative) { dk = dk.push(toIndex - 1 || 0) } else if (intentKeys.level === 'down' && intentKeys.wasBeforeRelative) { // was before this block in the relative store order // thus the last relative key needs to be decreased dk = dk.update(fromKeys.size, (toIndexRelativeFirst) => (toIndexRelativeFirst as number) - 1) dk = dk.push(toIndex) } else if (doMerge) { if (doMerge === 'next') { //dk = dk.push(toIndex + 1) ti = toIndex + 1 } else if (doMerge === 'prev') { //dk = dk.push(toIndex) ti = toIndex } else { throw new Error('merge not implemented: ' + JSON.stringify(doMerge)) //dk = dk.push(toIndex) } } else { dk = dk.push(toIndex) } const tks = addNestKey<string | number>('list', dk) areas = moveDraggedValue( areas, addNestKey('list', fromKeys), fromIndex, tks, ti, ) done(dk, ti) return areas }) } let doMerge: string | undefined = undefined if (intentKeys.level === 'up' && intentKeys.isParent) { // handling AREA > AREA that are not siblings to get siblings if (!intent.edgeY && !intent.edgeX) { // no edges active return } // todo: only respects X-axis or Y-axis flow for blocks, in XY-axis flow it would need to find the related area below it's own area if (intent.edgeX) { if (intent.edgeX === 'right') { // move to right of parent doMerge = 'next' } else if (intent.edgeX === 'left') { // move to left of parent doMerge = 'prev' } } else if (intent.edgeY) { if (intent.edgeY === 'bottom') { // move to bottom of parent doMerge = 'next' } else if (intent.edgeY === 'top') { // move to top of parent doMerge = 'prev' } } if (!doMerge) { return } if (doMerge) { const ts = new Date().getTime() if ( lastMergeTag.current.merge !== doMerge || lastMergeTag.current.id !== targetId ) { window.clearTimeout(lastMergeTag.current.timer) lastMergeTag.current.time = ts lastMergeTag.current.merge = doMerge lastMergeTag.current.id = targetId return } const sinceLastMerge = (ts - lastMergeTag.current.time) if (sinceLastMerge > 450) { window.clearTimeout(lastMergeTag.current.timer) lastMergeTag.current.time = 0 setter(doMerge) return } else if (!lastMergeTag.current.timer) { lastMergeTag.current.timer = window.setTimeout(() => { setter(doMerge) }, 450) return } else { return } } else { return } } setter(undefined) return } })(details) }, [setAreas, onIntent, lastMergeTag]) return <> <div> <h2>Area Draggable</h2> <button onClick={() => setAreas(a => a.push({id: genId(), list: List([])}))}>Add Area</button> <button onClick={() => setAreas(a => a.push({id: genId(6)}))}>Add Block</button> </div> <div style={{display: 'flex', flexDirection: 'row'}}> <DndProvider backend={MultiBackend} options={HTML5toTouch}> <KitDndProvider<HTMLDivElement> onMove={onMove} scope={'a2'}> {areas.map((area, j) => <DraggableAny key={area.id} dataKeys={dataKeys} index={j} isLast={j >= (areas.size - 1)} isFirst={j === 0} {...area} /> )} </KitDndProvider> </DndProvider> </div> <div> <pre><code>{JSON.stringify(areas?.toJS(), undefined, 4)}</code></pre> </div> </> } // eslint-disable-next-line react/display-name export default (): React.ReactElement => { return <div style={{maxWidth: '95%', marginLeft: 'auto', marginRight: 'auto'}}> <h1>Kit DnD Area Grid</h1> <Link to={'/kit-dnd'}>Kit DnD Plain</Link> <KitDndAreas/> </div> }
the_stack
import React from 'react'; import {Animated, Dimensions, PanResponder, PanResponderInstance, PixelRatio, StyleSheet, View,} from 'react-native' const pixelRatio = PixelRatio.get(); function pointToPixel(points: number) { return points * pixelRatio; } function pixelToPoint(pixels: number) { return pixels / pixelRatio; } type RulerType = { screenWidth: number; screenHeight: number; minSize: number; valueTop: Animated.Value; valueLeft: Animated.Value; valueWidth: Animated.Value; valueHeigth: Animated.Value; valueBottom: Animated.Value; valueRight: Animated.Value; valueTopCP: Animated.Value; valueLeftCP: Animated.Value; valueWidthCP: Animated.Value; valueHeigthCP: Animated.Value; valueBottomCP: Animated.Value; valueRightCP: Animated.Value; panCenter: PanResponderInstance; panTopLeft: PanResponderInstance; panTopRight: PanResponderInstance; panBottomLeft: PanResponderInstance; panBottomRight: PanResponderInstance; } class CustomText extends React.PureComponent<any> { state: any = {}; setText(text: string) { this.setState({ text: text }); } render(): React.ReactNode { return ( <Animated.Text {...this.props} > {this.state.text || this.props.text || ''} </Animated.Text> ) } }; /** * Render drag corner * * @param props * @constructor */ const DragCorner = (props: { ruler: RulerType, right?: boolean, bottom?: boolean }) => { const {ruler, right, bottom} = props; const DEBUG = false; const DEBUG_COLOR_A = '#dedeff'; const DEBUG_COLOR_B = '#ffdede'; return ( <React.Fragment> {/*Corner*/} <Animated.View style={{ position: 'absolute', left: right ? -15 : -35, top: bottom ? -15 : -35, width: 50, height: 50, transform: [ { translateX: Animated.subtract( right ? ruler.valueRightCP : ruler.valueLeftCP, ruler.valueWidthCP.interpolate({ inputRange: [50, 141], outputRange: right ? [-15, 0] : [15, 0], extrapolate: 'clamp' }) ) }, { translateY: Animated.subtract( bottom ? ruler.valueBottomCP : ruler.valueTopCP, ruler.valueHeigthCP.interpolate({ inputRange: [50, 141], outputRange: bottom ? [-15, 0] : [15, 0], extrapolate: 'clamp' }) ) } ], opacity: DEBUG ? 0.5 : 0, backgroundColor: DEBUG ? DEBUG_COLOR_A : undefined }} { ...( bottom ? (right ? ruler.panBottomRight : ruler.panBottomLeft) : (right ? ruler.panTopRight : ruler.panTopLeft) ).panHandlers } pointerEvents={'box-only'} /> {/*Left/Right*/} <Animated.View style={{ position: 'absolute', left: right ? -15 : -35, top: 0, width: 50, height: 35, transform: [ { translateX: Animated.subtract( right ? ruler.valueRightCP : ruler.valueLeftCP, ruler.valueWidthCP.interpolate({ inputRange: [50, 141], outputRange: right ? [-15, 0] : [15, 0], extrapolate: 'clamp' }) ) }, { translateY: Animated.subtract( bottom ? ruler.valueBottomCP : ruler.valueTopCP, ruler.valueHeigthCP.interpolate({ inputRange: [50, 141], outputRange: bottom ? [0, 50] : [35, -15], extrapolate: 'clamp' }) ) } ], opacity: DEBUG ? 0.5 : 0, backgroundColor: DEBUG ? DEBUG_COLOR_B : undefined }} { ...( bottom ? (right ? ruler.panBottomRight : ruler.panBottomLeft) : (right ? ruler.panTopRight : ruler.panTopLeft) ).panHandlers } pointerEvents={'box-only'} /> {/*Top/Bottom*/} <Animated.View style={{ position: 'absolute', left: 0, top: bottom ? -15 : -35, width: 35, height: 50, transform: [ { translateX: Animated.subtract( right ? ruler.valueRightCP : ruler.valueLeftCP, ruler.valueWidthCP.interpolate({ inputRange: [50, 141], outputRange: right ? [0, 50] : [35, -15], extrapolate: 'clamp' }) ) }, { translateY: Animated.subtract( bottom ? ruler.valueBottomCP : ruler.valueTopCP, ruler.valueHeigthCP.interpolate({ inputRange: [50, 141], outputRange: bottom ? [-15, 0] : [15, 0], extrapolate: 'clamp' }) ) } ], opacity: DEBUG ? 0.5 : 0, backgroundColor: DEBUG ? DEBUG_COLOR_B : undefined }} { ...( bottom ? (right ? ruler.panBottomRight : ruler.panBottomLeft) : (right ? ruler.panTopRight : ruler.panTopLeft) ).panHandlers } pointerEvents={'box-only'} /> </React.Fragment> ) }; /** * Add guidelines on screen */ export default class Ruler extends React.PureComponent { private ruler: any; private verticalTextTop?: CustomText; private verticalTextBottom?: CustomText; private horizontalTextLeft?: CustomText; private horizontalTextRight?: CustomText; private textWidthTop?: CustomText; private textWidthBottom?: CustomText; private textHeightLeft?: CustomText; private textHeightRight?: CustomText; /** * dp = Density-independent Pixel */ private unit: 'dp' | 'px' | '%' = 'dp'; private sensitivity = 1; public changeSensitivity = () => { this.sensitivity = this.sensitivity === 1 ? 0.5 : this.sensitivity === 0.5 ? 0.1 : 1; }; public changeUnit() { if (this.unit === 'dp') { this.unit = 'px'; } else if (this.unit === 'px') { this.unit = '%'; } else { this.unit = 'dp'; } this.updateTextInformation(); } private updateTextInformation = () => { }; private getRuler(): RulerType { if (this.ruler) { return this.ruler; } const MIN_SIZE = 8; const MIN_SIZE_PX = pointToPixel(MIN_SIZE); const dimentions = Dimensions.get('screen'); const screenWidth = dimentions.width; const screenHeight = dimentions.height; let top = screenHeight / 2 - 50; let topInit = 0; let height = 100; let heightInit = 0; let left = screenWidth / 2 - 50; let leftInit = 0; let width = 100; let widthInit = 0; const valueLeft = new Animated.Value(left); const valueWidth = new Animated.Value(width); const valueTop = new Animated.Value(top); const valueHeigth = new Animated.Value(height); const valueBottom = Animated.add( valueTop.interpolate({ inputRange: [0, screenHeight], outputRange: [0, screenHeight] }), valueHeigth.interpolate({ inputRange: [0, screenHeight], outputRange: [0, screenHeight] }) ); const valueRight = Animated.add( valueLeft.interpolate({ inputRange: [0, screenWidth], outputRange: [0, screenWidth] }), valueWidth.interpolate({ inputRange: [0, screenWidth], outputRange: [0, screenWidth] }) ); const valueLeftCP = new Animated.Value(left); const valueWidthCP = new Animated.Value(width); const valueTopCP = new Animated.Value(top); const valueHeigthCP = new Animated.Value(height); const valueBottomCP = Animated.add( valueTopCP.interpolate({ inputRange: [0, screenHeight], outputRange: [0, screenHeight] }), valueHeigthCP.interpolate({ inputRange: [0, screenHeight], outputRange: [0, screenHeight] }) ); const valueRightCP = Animated.add( valueLeftCP.interpolate({ inputRange: [0, screenWidth], outputRange: [0, screenWidth] }), valueWidthCP.interpolate({ inputRange: [0, screenWidth], outputRange: [0, screenWidth] }) ); this.updateTextInformation = () => { // dp to px = PixelRatio.getPixelSizeForLayoutSize() const convert = (valueDP: number, maxDP: number): string => { let value: string = ''; if (this.unit === 'dp') { value = valueDP.toFixed(2); } else if (this.unit === 'px') { // Converts a layout size (dp) to pixel size (px). value = '' + PixelRatio.getPixelSizeForLayoutSize(valueDP); } else { let maxPx = PixelRatio.getPixelSizeForLayoutSize(maxDP); let valuePx = PixelRatio.getPixelSizeForLayoutSize(valueDP); value = (valuePx / maxPx * 100).toFixed(2); } return `${value}${this.unit}`; }; requestAnimationFrame(() => { if (this.verticalTextTop) { this.verticalTextTop.setText(convert(top, screenHeight)); } if (this.verticalTextBottom) { this.verticalTextBottom.setText(convert(screenHeight - (top + height), screenHeight)); } if (this.horizontalTextLeft) { this.horizontalTextLeft.setText(convert(left, screenWidth)); } if (this.horizontalTextRight) { this.horizontalTextRight.setText(convert(screenWidth - (left + width), screenWidth)); } if (this.textWidthTop) { this.textWidthTop.setText(convert(width, screenWidth)); } if (this.textWidthBottom) { this.textWidthBottom.setText(convert(width, screenWidth)); } if (this.textHeightLeft) { this.textHeightLeft.setText(convert(height, screenHeight)); } if (this.textHeightRight) { this.textHeightRight.setText(convert(height, screenHeight)); } }) }; let onPanResponderEnd = () => { valueLeftCP.setValue(left); valueWidthCP.setValue(width); valueTopCP.setValue(top); valueHeigthCP.setValue(height); }; this.ruler = { screenWidth: screenWidth, screenHeight: screenHeight, minSize: pixelToPoint(MIN_SIZE_PX), valueTop: valueTop, valueLeft: valueLeft, valueWidth: valueWidth, valueHeigth: valueHeigth, valueBottom: valueBottom, valueRight: valueRight, // valueTopCP: valueTopCP, valueLeftCP: valueLeftCP, valueWidthCP: valueWidthCP, valueHeigthCP: valueHeigthCP, valueBottomCP: valueBottomCP, valueRightCP: valueRightCP, panCenter: PanResponder.create({ onPanResponderGrant: () => { topInit = top; leftInit = left; widthInit = width; heightInit = height; }, onPanResponderMove: (event, gestureState) => { const maxLeft = (screenWidth - width); const maxTop = (screenHeight - height); top = Math.max(0, Math.min(maxTop, (topInit + gestureState.dy * this.sensitivity))); valueTop.setValue(top); left = Math.max(0, Math.min(maxLeft, (leftInit + gestureState.dx * this.sensitivity))); valueLeft.setValue(left); this.updateTextInformation(); }, onPanResponderEnd: onPanResponderEnd, onStartShouldSetPanResponder: (event, gestureState) => true, }), panTopLeft: PanResponder.create({ onPanResponderGrant: () => { topInit = top; leftInit = left; widthInit = width; heightInit = height; }, onPanResponderMove: (event, gestureState) => { const maxRight = (leftInit + widthInit) - MIN_SIZE; const maxBottom = (topInit + heightInit) - MIN_SIZE; top = Math.max(0, Math.min(maxBottom, (topInit + gestureState.dy * this.sensitivity))); valueTop.setValue(top); left = Math.max(0, Math.min(maxRight, (leftInit + gestureState.dx * this.sensitivity))); valueLeft.setValue(left); width = maxRight - left + MIN_SIZE; valueWidth.setValue(width); height = maxBottom - top + MIN_SIZE; valueHeigth.setValue(height); this.updateTextInformation(); }, onPanResponderEnd: onPanResponderEnd, onStartShouldSetPanResponder: (event, gestureState) => true, }), panTopRight: PanResponder.create({ onPanResponderGrant: () => { topInit = top; widthInit = width; heightInit = height; }, onPanResponderMove: (event, gestureState) => { const maxWidth = (screenWidth - left); const maxBottom = (topInit + heightInit) - MIN_SIZE; top = Math.max(0, Math.min(maxBottom, (topInit + gestureState.dy * this.sensitivity))); valueTop.setValue(top); height = maxBottom - top + MIN_SIZE; valueHeigth.setValue(height); width = Math.max(MIN_SIZE, Math.min(maxWidth, (widthInit + gestureState.dx * this.sensitivity))); valueWidth.setValue(width); this.updateTextInformation(); }, onPanResponderEnd: onPanResponderEnd, onStartShouldSetPanResponder: (event, gestureState) => true, }), panBottomLeft: PanResponder.create({ onPanResponderGrant: () => { leftInit = left; widthInit = width; heightInit = height; }, onPanResponderMove: (event, gestureState) => { const maxRight = (leftInit + widthInit) - MIN_SIZE; const maxHeight = (screenHeight - top); left = Math.max(0, Math.min(maxRight, (leftInit + gestureState.dx * this.sensitivity))); valueLeft.setValue(left); width = maxRight - left + MIN_SIZE; valueWidth.setValue(width); height = Math.max(MIN_SIZE, Math.min(maxHeight, (heightInit + gestureState.dy * this.sensitivity))); valueHeigth.setValue(height); this.updateTextInformation(); }, onPanResponderEnd: onPanResponderEnd, onStartShouldSetPanResponder: (event, gestureState) => true, }), panBottomRight: PanResponder.create({ onPanResponderGrant: () => { widthInit = width; heightInit = height; }, onPanResponderMove: (event, gestureState) => { const maxWidth = (screenWidth - left); const maxHeight = (screenHeight - top); width = Math.max(MIN_SIZE, Math.min(maxWidth, (widthInit + gestureState.dx * this.sensitivity))); valueWidth.setValue(width); height = Math.max(MIN_SIZE, Math.min(maxHeight, (heightInit + gestureState.dy * this.sensitivity))); valueHeigth.setValue(height); this.updateTextInformation(); }, onPanResponderEnd: onPanResponderEnd, onStartShouldSetPanResponder: (event, gestureState) => true, }) }; return this.ruler; }; render() { const ruler = this.getRuler(); const screenWidth = ruler.screenWidth; const screenHeight = ruler.screenHeight; const color = '#18A0FB'; const colorBG = '#18A0FB33'; const verticalCenterSquare = Animated.add( ruler.valueLeft, ruler.valueWidth.interpolate({ inputRange: [0, screenWidth], outputRange: [0, screenWidth / 2] }) ); const verticalCenterSquareText = verticalCenterSquare.interpolate({ inputRange: [0, 30, 33, screenWidth - 33, screenWidth - 30, screenWidth], outputRange: [2, 33, 3, screenWidth - 62, screenWidth - 92, screenWidth - 62] }); const verticalCenterSquareTextLeft = verticalCenterSquareText; const horizontalCenterSquare = Animated.add( ruler.valueTop, ruler.valueHeigth.interpolate({ inputRange: [0, screenHeight], outputRange: [0, screenHeight / 2] }) ); const horizontalCenterSquareText = horizontalCenterSquare.interpolate({ inputRange: [0, screenHeight - 63, screenHeight - 60, screenHeight], outputRange: [3, screenHeight - 60, screenHeight - 73, screenHeight - 12] }); const verticalTextStyle = { position: 'absolute', fontSize: 9, lineHeight: 11, width: 60, color: '#fff', fontFamily: 'System', textAlignVertical: 'center', textAlign: 'center', backgroundColor: color, borderRadius: 2, }; const horizontalTextStyle = { ...verticalTextStyle, top: 0, left: -20 }; const sideVerticalY = Animated.add( ruler.valueTop, ruler.valueHeigth.interpolate({ inputRange: [0, screenHeight], outputRange: [-screenHeight / 2, 0] }) ); const sideVerticalScale = ruler.valueHeigth.interpolate({ inputRange: [0, screenHeight], outputRange: [0, 1] }); let sideHorizontalX = Animated.add( ruler.valueLeft, ruler.valueWidth.interpolate({ inputRange: [0, screenWidth], outputRange: [-screenWidth / 2, 0] }) ); let sideHorizontalScale = ruler.valueWidth.interpolate({ inputRange: [0, screenWidth], outputRange: [0, 1] }); return ( <View style={[StyleSheet.absoluteFill, {zIndex: 5000}]}> <Animated.View style={ [ { position: 'absolute', transform: [ {translateX: verticalCenterSquare} ], } ] } > {/*Vertical Line Top*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, height: screenHeight * 1.5, top: -(screenHeight * 1.5), borderRightWidth: 1, transform: [ {translateY: ruler.valueTop} ] } ] } /> {/*Vertical Line Bottom*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, height: screenHeight * 1.5, top: 0, borderRightWidth: 1, transform: [ {translateY: ruler.valueBottom} ] } ] } /> </Animated.View> <Animated.View style={ [ { position: 'absolute', transform: [ {translateY: horizontalCenterSquare}, ], } ] } > {/*Horizontal Line Left*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: screenWidth * 1.5, left: -(screenWidth * 1.5), borderTopWidth: 1, transform: [ {translateX: ruler.valueLeft} ], } ] } /> {/*Horizontal Line Right*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: screenWidth * 1.5, left: 0, borderTopWidth: 1, transform: [ {translateX: ruler.valueRight} ], } ] } /> </Animated.View> {/*Side Left*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, height: screenHeight, left: -1, top: 0, borderLeftWidth: 1, transform: [ {translateX: ruler.valueLeft}, {translateY: sideVerticalY}, {scaleY: sideVerticalScale} ], } ] } /> {/*Side Right*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, height: screenHeight, left: 0, top: 0, borderRightWidth: 1, transform: [ {translateX: ruler.valueRight}, {translateY: sideVerticalY}, {scaleY: sideVerticalScale} ], } ] } /> {/*Side Top*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: screenWidth, left: 0, top: -1, borderTopWidth: 1, transform: [ {translateY: ruler.valueTop}, {translateX: sideHorizontalX}, {scaleX: sideHorizontalScale} ], } ] } /> {/*Side Bottom*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: screenWidth, left: 0, top: 0, borderBottomWidth: 1, transform: [ {translateY: ruler.valueBottom}, {translateX: sideHorizontalX}, {scaleX: sideHorizontalScale} ], } ] } /> <Animated.View style={ [ { position: 'absolute', transform: [ {translateY: ruler.valueTop} ], } ] } > {/*Square Top Left*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: 8, height: 8, left: -8, top: -8, borderWidth: 1, backgroundColor: colorBG, transform: [ {translateX: ruler.valueLeft} ] } ] } /> {/*Square Top Right*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: 8, height: 8, left: 0, top: -8, borderWidth: 1, backgroundColor: colorBG, transform: [ {translateX: ruler.valueRight} ] } ] } /> </Animated.View> <Animated.View style={ [ { position: 'absolute', transform: [ {translateY: ruler.valueBottom} ] } ] } > {/*Square Bottom Left*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: 8, height: 8, top: 0, left: -8, borderWidth: 1, backgroundColor: colorBG, transform: [ {translateX: ruler.valueLeft} ] } ] } /> {/*Square Bottom Right*/} <Animated.View style={ [ { position: 'absolute', borderColor: color, width: 8, height: 8, top: 0, left: 0, borderWidth: 1, backgroundColor: colorBG, transform: [ {translateX: ruler.valueRight} ] } ] } /> </Animated.View> <Animated.View style={{ position: 'absolute', top: 0, left: 0, transform: [ {translateX: verticalCenterSquareText} ] }} > <Animated.View style={{ position: 'absolute', top: 0, left: 0, height: screenHeight, backgroundColor: 'blue', transform: [ {translateX: verticalCenterSquareText} ] }} > </Animated.View> {/*Vertical Text Top*/} <CustomText ref={(ref) => { if (this.verticalTextTop !== ref) { this.verticalTextTop = ref || undefined; this.updateTextInformation(); } }} style={[ verticalTextStyle, { transform: [ { translateY: Animated.subtract( ruler.valueTop.interpolate({ inputRange: [0, 27, screenHeight], outputRange: [-27, 0, screenHeight / 2] }), ruler.valueWidth.interpolate({ inputRange: [60, 65], outputRange: [6, 0], extrapolate: 'clamp' }) ) } ], } ]} /> {/*Vertical Text Bottom*/} <CustomText ref={(ref) => { if (this.verticalTextBottom !== ref) { this.verticalTextBottom = ref || undefined; this.updateTextInformation(); } }} style={[ verticalTextStyle, { transform: [ { translateY: Animated.subtract( ruler.valueBottom.interpolate({ inputRange: [0, screenHeight - 27, screenHeight], outputRange: [screenHeight / 2, screenHeight - 11, screenHeight + 15] }), ruler.valueWidth.interpolate({ inputRange: [60, 65], outputRange: [-7, 0], extrapolate: 'clamp' }) ) }, ], } ]} /> {/*Text Width Top*/} <CustomText ref={(ref) => { if (this.textWidthTop !== ref) { this.textWidthTop = ref || undefined; this.updateTextInformation(); } }} style={[ verticalTextStyle, { transform: [ { translateY: Animated.subtract( ruler.valueTop.interpolate({ inputRange: [0, screenHeight], outputRange: [-14, screenHeight - 15] }), ruler.valueWidth.interpolate({ inputRange: [60, 65], outputRange: [6, 0], extrapolate: 'clamp' }) ) }, ], } ]} /> {/*Text Width Bottom*/} <CustomText ref={(ref) => { if (this.textWidthBottom !== ref) { this.textWidthBottom = ref || undefined; this.updateTextInformation(); } }} style={[ verticalTextStyle, { transform: [ { translateY: Animated.subtract( ruler.valueBottom.interpolate({ inputRange: [0, screenHeight], outputRange: [3, screenHeight + 3] }), ruler.valueWidth.interpolate({ inputRange: [60, 65], outputRange: [-8, 0], extrapolate: 'clamp' }) ) }, ], } ]} /> </Animated.View> <Animated.View style={{ position: 'absolute', top: 0, left: 0, transform: [ {translateY: horizontalCenterSquareText} ] }} > {/*Horizontal Text left*/} <CustomText ref={(ref) => { if (this.horizontalTextLeft !== ref) { this.horizontalTextLeft = ref || undefined; this.updateTextInformation(); } }} style={[ horizontalTextStyle, { transform: [ { translateX: Animated.subtract( ruler.valueLeft.interpolate({ inputRange: [0, 60, screenWidth], outputRange: [-44, 17, screenWidth / 2] }), ruler.valueHeigth.interpolate({ inputRange: [30, 35], outputRange: [7, 0], extrapolate: 'clamp' }) ) } ], } ]} /> {/*Horizontal Text Right*/} <CustomText ref={(ref) => { if (this.horizontalTextRight !== ref) { this.horizontalTextRight = ref || undefined; this.updateTextInformation(); } }} style={[ horizontalTextStyle, { transform: [ { translateX: Animated.add( ruler.valueRight.interpolate({ inputRange: [0, screenWidth - 60, screenWidth], outputRange: [screenWidth / 2, screenWidth - 38, screenWidth + 24] }), ruler.valueHeigth.interpolate({ inputRange: [30, 35], outputRange: [8, 0], extrapolate: 'clamp' }) ) } ], } ]} /> {/*Text Height Left*/} <CustomText ref={(ref) => { if (this.textHeightLeft !== ref) { this.textHeightLeft = ref || undefined; this.updateTextInformation(); } }} style={[ horizontalTextStyle, { top: -16, transform: [ { translateX: Animated.subtract( ruler.valueLeft.interpolate({ inputRange: [0, 60, screenWidth], outputRange: [-44, 17, screenWidth - 44] }), ruler.valueHeigth.interpolate({ inputRange: [30, 35], outputRange: [7, 0], extrapolate: 'clamp' }) ) } ], } ]} /> {/*Text Height Right*/} <CustomText ref={(ref) => { if (this.textHeightRight !== ref) { this.textHeightRight = ref || undefined; this.updateTextInformation(); } }} style={[ horizontalTextStyle, { top: -16, transform: [ { translateX: Animated.add( ruler.valueRight.interpolate({ inputRange: [0, screenWidth - 60, screenWidth], outputRange: [24, screenWidth - 38, screenWidth + 24] }), ruler.valueHeigth.interpolate({ inputRange: [30, 35], outputRange: [8, 0], extrapolate: 'clamp' }) ) } ], } ]} /> </Animated.View> {/*Drag - Background*/} <Animated.View style={ [ { position: 'absolute', height: screenHeight, width: screenWidth, left: 0, top: 0, // opacity: 0.2, // backgroundColor: '#ccc', transform: [ { translateX: Animated.add( ruler.valueLeftCP, ruler.valueWidthCP.interpolate({ inputRange: [0, screenWidth], outputRange: [-screenWidth / 2, 0] }) ) }, { scaleX: ruler.valueWidthCP.interpolate({ inputRange: [0, screenWidth], outputRange: [0, 1] }) }, { translateY: Animated.add( ruler.valueTopCP, ruler.valueHeigthCP.interpolate({ inputRange: [0, screenHeight], outputRange: [-screenHeight / 2, 0] }) ) }, { scaleY: ruler.valueHeigthCP.interpolate({ inputRange: [0, screenHeight], outputRange: [0, 1] }) } ], } ] } { ...ruler.panCenter.panHandlers } pointerEvents={'box-only'} /> {/*Drag - Corner Top Left*/} <DragCorner ruler={ruler} bottom={false} right={false}/> {/*Drag - Corner Top Right*/} <DragCorner ruler={ruler} bottom={false} right={true}/> {/*Drag - Corner Bottom Left*/} <DragCorner ruler={ruler} bottom={true} right={false}/> {/*Drag - Corner Bottom Right*/} <DragCorner ruler={ruler} bottom={true} right={true}/> </View> ) } }
the_stack
import * as NFPlayer from '../../src/'; import * as NFGrapher from 'nf-grapher'; import { SmartPlayer } from '../../src/'; import * as TNGEngines from '../../fixtures/TNG-Crysknife007-16-899-s.wav'; // Returns a promise since a type cannot use the `async` keyword. // export type PlaygroundScript = ( // player: SmartPlayer, // GrapherExports: typeof NFGrapher, // PlayerExports: typeof NFPlayer, // ) => void; export type PlaygroundScript = string; export type CompiledPlaygroundScript = ( player: SmartPlayer, GrapherExports: typeof NFGrapher, PlayerExports: typeof NFPlayer ) => Promise<void>; export type ExampleScript = { name: string; script: PlaygroundScript; }; const examplePreamble = ``; export const examples: ExampleScript[] = [ { name: 'Star Trek TNG Infinite Ambient Engine Noise (scripted)', script: ` const filePath = '${TNGEngines.default}'; // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant } = NFPlayer; const { Score, FileNode, GainNode, LoopNode } = NFGrapher; // This is complicated to get the math right! In this diagram, // | indicates the start or end time of a node // ) indicates a fade out // ( indicates a fade in // |-| indicates an arbitrary unit of time // file1 |( )| // file2 |( )| // loop1 | | // loop2 | | // timeline |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-| // t0 // The overlap below is used to position the start/end times of each file, // which is relatively independent of the fades. The loops are of length: // (file duration - overlap) * 2 // The second loop starts at t0 + overlap. // The first file starts at t0. the second file starts at: // file duration - overlap // Some AudioParam commands cannot handle a zero due to math. So this allows // "near enough" to zero to be imperceptible / negligible. const AUDIBLE_ZERO = 0.0001; // We're using two file nodes, but only one unique file. const offset = TimeInstant.fromSeconds(0); const duration = TimeInstant.fromSeconds(16.899); // These tend to sound even as long as fade is 1/2 of loop overlap duration. // How much the two file nodes should overlap during their crossfade. const overlap = TimeInstant.fromSeconds(0.6); // How long the actual fading operation should last. const fade = TimeInstant.fromSeconds(0.3); const f1 = FileNode.create({ // Buy this track! // https://cheesynirvosa.bandcamp.com/track/star-trek-tng-ambient-engine-noise // Creative Commons Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) // https://creativecommons.org/licenses/by-sa/3.0/ file: filePath, when: TimeInstant.ZERO.asNanos(), duration: duration.asNanos(), offset: offset.asNanos(), }); const g1 = GainNode.create(); g1.gain.setValueAtTime(0, 0); g1.gain.setValueAtTime(AUDIBLE_ZERO, 0.0001); g1.gain.exponentialRampToValueAtTime(1, fade.asNanos()); g1.gain.setValueAtTime(1, duration.sub(fade).asNanos()); g1.gain.exponentialRampToValueAtTime(AUDIBLE_ZERO, duration.asNanos()); const l1 = LoopNode.create({ when: TimeInstant.ZERO.asNanos(), duration: duration.sub(overlap).add(duration).sub(overlap).asNanos(), loopCount: -1, // infinite }) // The second file node begins playing just before the first node ends. const f2When = duration.sub(overlap); const f2 = FileNode.create({ // Buy this track! // https://cheesynirvosa.bandcamp.com/track/star-trek-tng-ambient-engine-noise // Creative Commons Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) // https://creativecommons.org/licenses/by-sa/3.0/ file: filePath, when: f2When.asNanos(), duration: duration.asNanos(), offset: offset.asNanos(), }); const g2 = GainNode.create(); g2.gain.setValueAtTime(0, 0); g2.gain.setValueAtTime(AUDIBLE_ZERO, f2When.asNanos()); g2.gain.exponentialRampToValueAtTime(1, f2When.add(fade).asNanos()); g2.gain.setValueAtTime(1, f2When.add(duration.sub(fade)).asNanos()) g2.gain.exponentialRampToValueAtTime(AUDIBLE_ZERO, f2When.add(duration).asNanos()); const l2 = LoopNode.create({ when: overlap.asNanos(), duration: duration.sub(overlap).add(duration).sub(overlap).asNanos(), loopCount: -1, // infinite }) const edges = [ f1.connectToTarget(g1), f2.connectToTarget(g2), g1.connectToTarget(l1), g2.connectToTarget(l2), ] const nodes = [ f1, f2, g1, g2, l1, l2 ]; let s = new Score() s.graph.nodes.push(...nodes); s.graph.edges.push(...edges); await p.enqueueScore(s); p.playing = true; ` }, { name: 'Roxanne, but pitched on every "Roxanne" (infinite scripted version)', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant } = NFPlayer; const { Score, FileNode, LoopNode, StretchNode } = NFGrapher; const loopWhen = TimeInstant.fromSeconds(9.593); const loopDuration = TimeInstant.fromSeconds(26.908).sub(loopWhen); // https://github.com/spotify/NFGrapher/blob/master/doc/smartplayer.md#loop const loop = LoopNode.create({ when: loopWhen.asNanos(), duration: loopDuration.asNanos(), loopCount: -1, }); // https://github.com/spotify/NFGrapher/blob/master/doc/smartplayer.md#file const file = FileNode.create({ // Roxanne: spotify:track:0SYRVn2YF7HBscQEmlkpTI via Spotify MP3 Audio Preview file: 'https://p.scdn.co/mp3-preview/6975d56d8fb372f33a9b6414899fa9c5bc4cb8e1?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), offset: TimeInstant.fromSeconds(0).asNanos(), // When looped, a file node needs it's duration + the length of at least // one complete loop. Otherwise it will not provide samples to the loop node! duration: TimeInstant.fromSeconds(30).add(loopDuration).asNanos() }); const HALF_STEP_RATIO = Math.pow(2, 1 / 12); // https://github.com/spotify/NFGrapher/blob/master/doc/smartplayer.md#stretch const stretch = StretchNode.create(); stretch.pitchRatio.setValueAtTime(1, 0); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 1), TimeInstant.fromSeconds(2.574).asNanos()); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 2), TimeInstant.fromSeconds(9.554).asNanos()); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 3), TimeInstant.fromSeconds(13.064).asNanos()); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 4), TimeInstant.fromSeconds(16.535).asNanos()); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 5), TimeInstant.fromSeconds(20.006).asNanos()); stretch.pitchRatio.setValueAtTime(Math.pow(HALF_STEP_RATIO, 6), TimeInstant.fromSeconds(23.476).asNanos()); const s = new Score(); s.graph.nodes.push(file, stretch, loop); s.graph.edges.push( file.connectToTarget(stretch), stretch.connectToTarget(loop), ); // Enqueue the score, which will cause the player to begin loading // the files. await p.enqueueScore(s); // Start rendering, aka allow p.renderTime to progress. p.playing = true; ` }, { name: 'Load and play seconds 10 through 20 of a single file', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant } = NFPlayer; const { Score, FileNode } = NFGrapher; // https://github.com/spotify/NFGrapher/blob/master/doc/smartplayer.md#file const f = FileNode.create({ // Roxanne: spotify:track:0SYRVn2YF7HBscQEmlkpTI via Spotify MP3 Audio Preview file: 'https://p.scdn.co/mp3-preview/6975d56d8fb372f33a9b6414899fa9c5bc4cb8e1?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), offset: TimeInstant.fromSeconds(20).asNanos(), duration: TimeInstant.fromSeconds(10).asNanos() }); const s = new Score(); s.graph.nodes.push(f); // Enqueue the score, which will cause the player to begin loading // the files. await p.enqueueScore(s); // Start rendering, aka allow p.renderTime to progress. p.playing = true; ` }, { name: 'Play the first 10 seconds of a file, then loop a single 4 beat bar forever.', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant } = NFPlayer; const { Score, FileNode, LoopNode } = NFGrapher; const f = FileNode.create({ // Roxanne: spotify:track:0SYRVn2YF7HBscQEmlkpTI via Spotify MP3 Audio Preview file: 'https://p.scdn.co/mp3-preview/6975d56d8fb372f33a9b6414899fa9c5bc4cb8e1?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), // Duration needs to include time for at least one complete loop, // so this is 14.25s instead of 10s duration: TimeInstant.fromSeconds(14.25).asNanos(), }); const l = LoopNode.create({ when: TimeInstant.fromSeconds(10.044).asNanos(), duration: TimeInstant.fromSeconds(3.456).asNanos(), loopCount: -1, }) const s = new Score(); s.graph.nodes.push(f); s.graph.nodes.push(l); // Make sure you register the edges with the score! s.graph.edges.push(f.connectToTarget(l)); await p.enqueueScore(s); p.playing = true; ` }, { name: 'Play a track, then quickly fade out on user interaction', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant, MutationNames } = NFPlayer; const { Score, GainNode, FileNode } = NFGrapher; const f = FileNode.create({ // Roxanne: spotify:track:0SYRVn2YF7HBscQEmlkpTI via Spotify MP3 Audio Preview file: 'https://p.scdn.co/mp3-preview/6975d56d8fb372f33a9b6414899fa9c5bc4cb8e1?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), duration: TimeInstant.fromSeconds(30).asNanos() }); const g = GainNode.create() const s = new Score(); s.graph.nodes.push(f); s.graph.nodes.push(g); s.graph.edges.push(f.connectToTarget(g)); await p.enqueueScore(s); p.playing = true; // Pretend this is a click handler. This playground is imperfect, so // setting a real listener wouldn't behave well across multiple evals. // document.addEventListener('click', () => { setTimeout(() => { // Enqueuing a mutation to the graph means that this mutation // will be applied in the next render quantum of the player. // The "mutation" is actually adding a new command to the Score, // and commands have their own notion of scheduling, just like the // Web Audio API. p.enqueueMutation({ name: MutationNames.PushCommands, nodeId: g.id, paramName: 'gain', commands: [ { name: 'setValueAtTime', args: { value: 1, startTime: p.renderTime.asNanos() } } as NFPlayer.SetValueAtTimeCmd, { name: 'linearRampToValueAtTime', args: { value: 0, endTime: p.renderTime.add(TimeInstant.fromSeconds(1)).asNanos(), } } as NFPlayer.LinearRampToValueAtTimeCmd, ] } as NFPlayer.PushCommandsMutation); }, 5000); ` }, { name: 'Loop and Pitch Shift a track, then swap it with a modified score on User Interaction', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant, MutationNames } = NFPlayer; const { Score, GainNode, FileNode, StretchNode, LoopNode, Graph } = NFGrapher; // The duration of our loop. const duration = TimeInstant.fromSeconds(22.063270000000003); const f1 = FileNode.create({ // Mad World: spotify:track:77xZaHf3YSiSAllj4aI7ih file: 'https://p.scdn.co/mp3-preview/fd9318346f36c7e235a664ceef791b0f2743b399?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), duration: duration.asNanos(), }); const l1 = LoopNode.create({ when: TimeInstant.ZERO.asNanos(), duration: duration.asNanos(), loopCount: -1, // infinite }) const s1 = StretchNode.create(); s1.pitchRatio.setValueAtTime(1, 0); const s = new Score(); s.graph.nodes.push(f1, s1, l1); s.graph.edges.push( f1.connectToTarget(l1), l1.connectToTarget(s1), ); await p.enqueueScore(s); p.playing = true; // Pretend this is a user click, instead of a setTimeout setTimeout(async () => { // Grab the current renderTime for relative calculations later. const now = p.renderTime; // We _could_ pull the running Score JSON out of the player, and // modify it, but we happen to have it above. // The player copies all Scores it is given, so it's safe to modify // our copy defined above. // Stash this to later deactivate the current Score. const runningId = s.graph.id; // IDs can be any string, but default to UUIDs. To generate a new one // "easily", we create a new graph from the existing one. This is SUPER // clunky right now but will hopefully get easier in the future. Another // option is to simply change the id to a new, user-defined string :D s.graph = new Graph(undefined, s.graph.loadingPolicy, s.graph.nodes, s.graph.edges); // Alternative: // s.id = s.id + '-arbitrary-string'; const s2 = StretchNode.create(); // Give ourselves a base value to start with. s2.stretch.setValueAtTime(1, now.add(TimeInstant.fromSeconds(1)).asNanos()); // Make the effect begin 1 second from now. s2.stretch.setTargetAtTime(2, now.add(TimeInstant.fromSeconds(1)).asNanos(), 0.99); s.graph.nodes.push(s2); s.graph.edges.push(s1.connectToTarget(s2)); // Remember, the Score, Nodes, Edges, etc above are not "live". The only // relation they have to the running score is that they may share IDs. This // is OK since the player only cares about unique Graph IDs, mostly. await p.enqueueScore(s); // The modified Score _should_ seamlessly handle playback, because // everything is already cached and loaded. So it's safe to dequeue the // old score as soon as possible. Having both scores in the player is fine, // but both will be processed and output to the speaker! p.dequeueScore(runningId); }, 15000); ` }, { name: 'Pitchshift a piano down, with a voice over the top. 30 seconds in slow both down (derail!).', script: ` // These Globals are provided by this playground, and act as imported namespaces // A player instance is also provided as "p" const { TimeInstant, MutationNames } = NFPlayer; const { Score, GainNode, FileNode, StretchNode, LoopNode } = NFGrapher; const f1 = FileNode.create({ // Mad World: spotify:track:77xZaHf3YSiSAllj4aI7ih file: 'https://p.scdn.co/mp3-preview/fd9318346f36c7e235a664ceef791b0f2743b399?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), duration: TimeInstant.fromSeconds(30).asNanos(), }); const l1 = LoopNode.create({ when: TimeInstant.ZERO.asNanos(), duration: TimeInstant.fromSeconds(22.063270000000003).asNanos(), loopCount: -1, // infinite }) const f2 = FileNode.create({ // Shatner, War of the Worlds spotify:track:55fyDzZJVj3EAnV81RAjlT file: 'https://p.scdn.co/mp3-preview/7434b8a84b6fbe68558cfd8565762b0f4688ec75?cid=774b29d4f13844c495f206cafdad9c86', when: TimeInstant.ZERO.asNanos(), duration: TimeInstant.fromSeconds(30).asNanos() }); const g2 = GainNode.create(); g2.gain.setValueAtTime(1.5, 0); const s1 = StretchNode.create(); s1.pitchRatio.setValueAtTime(0.5, 0); s1.pitchRatio.setTargetAtTime(0.4, TimeInstant.fromSeconds(28).asNanos(), 0.99999999); const s2 = StretchNode.create(); s2.stretch.setTargetAtTime(2, TimeInstant.fromSeconds(30).asNanos(), 0.9999999999); const s = new Score(); s.graph.nodes.push(f1, f2, g2, s1, s2, l1); s.graph.edges.push( f1.connectToTarget(l1), // pitch shift the first loop l1.connectToTarget(s1), // stretch the tempo of the first file (included pitch change). s1.connectToTarget(s2), // Stretch the tempo of the second file too, after applying some gain. f2.connectToTarget(g2), g2.connectToTarget(s2), ); await p.enqueueScore(s); p.playing = true; ` } ];
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Animated, TouchableWithoutFeedback, StatusBar, ViewPagerAndroid, Platform } from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' import { connect } from 'react-redux' import { changeSegmentIndex, changeCommunityType, changeGeneType } from '../redux/action/app' import { getRecommend } from '../redux/action/recommend' import { standardColor } from '../constant/colorConfig' import Tab, { routes } from './Tab' // import RightDrawer from './RightDrawer' let title = 'PSNINE' const searchAction = { title: '搜索', iconName: 'md-search', value: '', show: 'always' } let recommendActions = [ searchAction ] let communityActions = [ { title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 }, searchAction, { title: '全部', value: '', show: 'never' }, { title: '新闻', value: 'news', show: 'never' }, { title: '攻略', value: 'guide', show: 'never' }, { title: '测评', value: 'review', show: 'never' }, { title: '心得', value: 'exp', show: 'never' }, { title: 'Plus', value: 'plus', show: 'never' }, { title: '开箱', value: 'openbox', show: 'never' }, { title: '游列', value: 'gamelist', show: 'never' }, { title: '活动', value: 'event', show: 'never' } ] let qaActions = [ { title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 }, searchAction ] let gameActions = [ searchAction ] let rankActions = [ searchAction ] let battleActions = [ { title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 } ] let geneActions = [ { title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 }, searchAction, { title: '综合排序', value: 'obdate', show: 'never' }, { title: '最新', value: 'date', show: 'never' } ] let storeActions = [ searchAction ] let tradeActions = [ { title: '新建', iconName: 'md-create', value: '', show: 'always', iconSize: 22 }, searchAction ] let discountActions = [ searchAction ] let toolbarActions = [ recommendActions, communityActions, qaActions, geneActions, gameActions, discountActions, battleActions, rankActions, /*circleActions,*/ storeActions, tradeActions ] let toolbarHeight = Platform.OS === 'ios' ? 64 : 56 class Toolbar extends Component<any, any> { constructor(props) { super(props) this.state = { search: '', rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), marginTop: new Animated.Value(0), openVal: new Animated.Value(0), innerMarginTop: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), topicMarginTop: new Animated.Value(0), tabMode: this.props.modeInfo.settingInfo.tabMode, _scrollHeight: this.props.modeInfo.height - (StatusBar.currentHeight || 0) - 38 + 1 // _scrollHeight: } } searchMapper = Object.keys(routes).reduce((prev, curr) => (prev[curr] = '', prev), {}) afterEachHooks = [] componentWillMount() { this.props.dispatch(getRecommend()) } componentWillReceiveProps(nextProps) { if (this.state.tabMode !== nextProps.modeInfo.settingInfo.tabMode) { this.setState({ tabMode: nextProps.modeInfo.settingInfo.tabMode }) } else if (this.props.modeInfo.width !== nextProps.modeInfo.width) { this.setState({ _scrollHeight: nextProps.modeInfo.height - (StatusBar.currentHeight || 0) - 38 + 1 }) } } _onSearch = (text) => { this.setState({ search: text }) const currentIndex = this.props.app.segmentedIndex const callback = this.afterEachHooks[currentIndex] typeof callback === 'function' && callback(text) const currentRouteName = Object.keys(routes)[currentIndex] this.searchMapper[currentRouteName] = text } _onSearchClicked = () => { this.props.navigation.navigate('Search', { shouldSeeBackground: true, content: this.state.search, callback: this._onSearch }) } onActionSelected = (index) => { const { segmentedIndex, communityType } = this.props.app // console.log(segmentedIndex) const { dispatch } = this.props if (segmentedIndex === 1) { if (index !== 0 && index !== 1) { let type = toolbarActions[segmentedIndex][index].value dispatch(changeCommunityType(type)) } else { index === 1 && this._onSearchClicked() const obj: any = {} if (communityType) { obj.URL = `https://psnine.com/node/${communityType}/add` } index === 0 && this.props.navigation.navigate('NewTopic', obj) } } else if (segmentedIndex === 2) { index === 0 && this.props.navigation.navigate('NewQa', {}) index === 1 && this._onSearchClicked() } else if (segmentedIndex === 3) { if (index !== 0 && index !== 1) { let type = toolbarActions[segmentedIndex][index].value dispatch(changeGeneType(type)) } else { index === 1 && this._onSearchClicked() index === 0 && this.props.navigation.navigate('NewGene', {}) } } else if (segmentedIndex === 6) { this.props.navigation.navigate('NewBattle', {}) } else if (segmentedIndex === 9) { index === 0 && this.props.navigation.navigate('NewTrade', {}) index === 1 && this._onSearchClicked() } else { this._onSearchClicked() } } _renderDrawerView = () => { return ( <Tab onNavigationStateChange={(prevRoute, nextRoute, action) => { if (prevRoute.index !== nextRoute.index && action.type === 'Navigation/NAVIGATE') { /*setTimeout(() => {*/ this.props.dispatch(changeSegmentIndex(nextRoute.index)) /*}, 100)*/ } }} screenProps={{ communityType: this.props.app.communityType, geneType: this.props.app.geneType, circleType: this.props.app.circleType, navigation: this.props.navigation, toolbarDispatch: this.props.dispatch, segmentedIndex: this.props.app.segmentedIndex, modeInfo: this.props.modeInfo, setMarginTop: null, modalVisible: this.state.modalVisible, searchTitle: this.state.search, registerAfterEach: componentDidFocus => { if (componentDidFocus) { const { index, handler } = componentDidFocus this.afterEachHooks = [...this.afterEachHooks] this.afterEachHooks[index] = handler } } }}/> ) } render() { const { app: appReducer, modeInfo, drawerWidth, position } = this.props // alert(appReducer.segmentedIndex) return ( <View style={{ flex: 1 }}> {/* <global.ToolbarIOS modeInfo={modeInfo} actions={toolbarActions[appReducer.segmentedIndex]} onActionSelected={this.onActionSelected} onIconClicked={this.props._callDrawer()} /> */} <View style={styles.toolbar}> <Icon.ToolbarAndroid navIconName='md-menu' style={[styles.toolbar, { backgroundColor: modeInfo.standardColor, elevation: 0 }]} overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} actions={toolbarActions[appReducer.segmentedIndex]} key={appReducer.segmentedIndex} onActionSelected={this.onActionSelected} onIconClicked={this.props._callDrawer()} > <TouchableWithoutFeedback> <View style={{ height: 56, flex: 1, flexDirection: 'column', justifyContent: 'center' }}> <Text style={{ fontSize: 20, fontWeight: '500', color: modeInfo.isNightMode ? '#000' : '#fff' }} onPress={() => { const index = this._currentViewPagerPageIndex const callback = this.afterEachHooks[index] {/*log(callback, this.state.afterEachHooks, index)*/ } typeof callback === 'function' && callback() }}> {title} </Text> {this.state.search && <Text onPress={() => { this._onSearch('') }} style={{ fontSize: 15, color: modeInfo.isNightMode ? '#000' : '#fff' }}> {`当前搜索: ${this.state.search}`} </Text> || undefined} </View> </TouchableWithoutFeedback> </Icon.ToolbarAndroid> </View> { this._renderDrawerView() } </View> ) } } function mapStateToProps(state) { return { app: state.app } } export default connect( mapStateToProps )(Toolbar) const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: toolbarHeight, elevation: 0 }, segmentedView: { backgroundColor: '#F5FCFF' }, selectedTitle: {}, appbar: { backgroundColor: '#2278F6' }, avatar: { width: 50, height: 50 }, navbar: { height: 56 // alignItems: "center", // justifyContent: "center", // backgroundColor: "transparent", // position: 'relative' }, backBtn: { top: 0, left: 0, height: 56, position: 'absolute' }, caption: { color: '#fff', fontSize: 20 }, actionBar: { position: 'absolute', top: 0, right: 0, height: 56, flexDirection: 'column', flexWrap: 'nowrap', justifyContent: 'center', paddingLeft: 10 }, actionBtn: { flex: 1, alignItems: 'center', justifyContent: 'center' }, menuBtn: { width: 34, paddingRight: 10 }, menuBtnIcon: { width: 16, height: 16, tintColor: 'rgba(255, 255, 255, .8)' }, menu: { width: 150, backgroundColor: 'rgba(0, 0, 0, 0.8)' }, tabBar: { height: 38, backgroundColor: '#4889F1' }, scrollView: { backgroundColor: '#f2f2f2' }, viewPager: { flex: 1, backgroundColor: 'transparent' }, pageItem: { borderRadius: 2, height: 200, marginLeft: 10, marginRight: 10, marginTop: 5, marginBottom: 5, justifyContent: 'center', alignItems: 'center' }, pageItemContent: { fontSize: 30, color: '#FFF' } })
the_stack
import { expect } from 'chai'; import { MockContainerRuntimeFactory } from '@fluidframework/test-runtime-utils'; import { NodeId } from '../Identifiers'; import { ChangeNode, TraitLocation } from '../generic'; import { StablePlace, StableRange, ConstraintEffect, revert } from '../default-edits'; import { AnchoredChange, AnchoredDelete, AnchoredInsert, AnchoredMove, PlaceAnchor, PlaceAnchorSemanticsChoice, RangeAnchor, SharedTreeWithAnchors, } from '../anchored-edits'; import { fail } from '../Common'; import { makeEmptyNode, setUpTestSharedTreeWithAnchors, leftTraitLabel, rightTraitLabel, setUpLocalServerTestSharedTreeWithAnchors, } from './utilities/TestUtilities'; import { runSharedTreeOperationsTests } from './utilities/SharedTreeTests'; import { runSummaryTests } from './utilities/SummaryFormatCompatibilityTests'; /** * This file contains tests that verify the behavior or anchors by checking how they are resolved in the face of concurrent edits. * There are two batteries of tests: * - The first is defined by the cartesian product of a representative set of concurrent edits (see `insertScenarios`) and a variety of * anchor types--each anchor type is associated with an instance of `AnchorCaseOutcomes` which describe how that anchor should respond to * concurrent edits (see `anchorCases`). * - The second checks the behavior of a specific anchor in the face of more special/corner-case concurrent edits. */ /** * The expected contents of the `parent` node's traits after a test. */ interface Outcome { /** * The expected contents of the left trait. * Defaults to [left]. */ leftTrait?: ChangeNode[]; /** * The expected contents of the right trait. * Defaults to [right]. */ rightTrait?: ChangeNode[]; } /** * The expected contents of the `parent` node's traits for a given anchor after each scenario. * Each field represents an expected outcome for a different set of concurrent edits in `insertScenarios`. */ interface AnchorCaseOutcomes { onNoConcurrency: Outcome; onMove: Outcome; onTeleport?: Outcome; onDelete: Outcome; onUndoDelete?: Outcome; onUndoRedoDelete?: Outcome; onDeleteParent?: Outcome; onDroppedEdit: Outcome; onInsert: Outcome; } /** * An anchor with specific semantics and in a specific contexts. * Includes the expected outcome of inserting the `inserted` node at the given anchor for various test scenarios. */ interface AnchorCase extends AnchorCaseOutcomes { name: string; insertionPlace: PlaceAnchor; } /** * The changes to apply concurrently to the change whose anchor is being tested. */ type ConcurrentChanges = | AnchoredChange | readonly AnchoredChange[] | ((tree: SharedTreeWithAnchors, anchorCase: AnchorCase) => AnchoredChange[]); /** * A scenario that an `AnchorCase` could be put through. */ interface TestScenario { title: string; /** * Where to find the expected outcome for this scenario on a given `AnchorCase`. */ outcomeKey: keyof AnchorCaseOutcomes; concurrent?: ConcurrentChanges; } const left: ChangeNode = makeEmptyNode('left' as NodeId); const right: ChangeNode = makeEmptyNode('right' as NodeId); const parent: ChangeNode = { ...makeEmptyNode('parent' as NodeId), traits: { [leftTraitLabel]: [left], [rightTraitLabel]: [right] }, }; const initialTree: ChangeNode = { ...makeEmptyNode('root' as NodeId), traits: { parentTraitLabel: [parent], }, }; const leftTraitLocation = { parent: parent.identifier, label: leftTraitLabel, }; const rightTraitLocation = { parent: parent.identifier, label: rightTraitLabel, }; /** * Used for tests that require more than the left and right nodes. */ const extra = makeEmptyNode('extra' as NodeId); /** * The node inserted by the change whose anchors are being tested. * Tests outcomes are decided based on where this node ends up (if present at all). */ const inserted = makeEmptyNode('inserted' as NodeId); /** * Used for tests cases where we check `inserted`'s final location with respect to another node that is concurrently inserted. */ const concurrentlyInserted = makeEmptyNode('concurrently inserted' as NodeId); const treeOptions = { initialTree, localMode: false, enableAnchors: true, allowInvalid: true, }; const secondTreeOptions = { id: 'secondTestSharedTree', localMode: false, enableAnchors: true, allowInvalid: true, }; const thirdTreeOptions = { id: 'thirdTestSharedTree', localMode: false, enableAnchors: true, allowInvalid: true, }; const boundToNodeBefore = { name: 'BoundToNode Before(left)', insertionPlace: PlaceAnchor.before(left, PlaceAnchorSemanticsChoice.BoundToNode), onNoConcurrency: { leftTrait: [inserted, left] }, onMove: { leftTrait: [], rightTrait: [inserted, left, right] }, onDelete: { leftTrait: [] }, onDroppedEdit: { leftTrait: [inserted, left] }, onInsert: { leftTrait: [concurrentlyInserted, inserted, left] }, }; const boundToNodeAfter = { ...boundToNodeBefore, name: 'BoundToNode After(left)', insertionPlace: PlaceAnchor.after(left, PlaceAnchorSemanticsChoice.BoundToNode), onNoConcurrency: { leftTrait: [left, inserted] }, onMove: { leftTrait: [], rightTrait: [left, inserted, right] }, onDroppedEdit: { leftTrait: [left, inserted] }, onInsert: { leftTrait: [left, inserted, concurrentlyInserted] }, }; const boundToNodeStart = { ...boundToNodeBefore, name: 'BoundToNode Start(left trait)', insertionPlace: PlaceAnchor.atStartOf(leftTraitLocation, PlaceAnchorSemanticsChoice.BoundToNode), onMove: { leftTrait: [inserted], rightTrait: [left, right] }, onDelete: { leftTrait: [inserted] }, onInsert: { leftTrait: [inserted, concurrentlyInserted, left] }, }; const boundToNodeEnd = { ...boundToNodeAfter, name: 'BoundToNode End(left trait)', insertionPlace: PlaceAnchor.atEndOf(leftTraitLocation, PlaceAnchorSemanticsChoice.BoundToNode), onMove: { leftTrait: [inserted], rightTrait: [left, right] }, onDelete: { leftTrait: [inserted] }, onInsert: { leftTrait: [left, concurrentlyInserted, inserted] }, }; const relativeToNodeBefore = { ...boundToNodeBefore, name: 'RelativeToNode Before(left)', insertionPlace: PlaceAnchor.before(left, PlaceAnchorSemanticsChoice.RelativeToNode), onDelete: { leftTrait: [inserted] }, }; const relativeToNodeAfter = { ...boundToNodeAfter, name: 'RelativeToNode After(left)', insertionPlace: PlaceAnchor.after(left, PlaceAnchorSemanticsChoice.RelativeToNode), onDelete: relativeToNodeBefore.onDelete, }; const relativeToNodeStart = { ...boundToNodeStart, name: 'RelativeToNode Start(left trait)', insertionPlace: PlaceAnchor.atStartOf(leftTraitLocation, PlaceAnchorSemanticsChoice.RelativeToNode), }; const relativeToNodeEnd = { ...boundToNodeEnd, name: 'RelativeToNode End(left trait)', insertionPlace: PlaceAnchor.atEndOf(leftTraitLocation, PlaceAnchorSemanticsChoice.RelativeToNode), }; /** * A representative set of possible anchors with a variety of semantics and in a variety of contexts. * Includes the expected outcome of inserting the `inserted` node at the given anchor for various test scenarios. */ const anchorCases: readonly AnchorCase[] = [ boundToNodeBefore, boundToNodeAfter, boundToNodeStart, boundToNodeEnd, relativeToNodeBefore, relativeToNodeAfter, relativeToNodeStart, relativeToNodeEnd, ]; /** * A set of test scenario where `inserted` is inserted at a given anchor. */ const insertScenarios: TestScenario[] = [ { title: 'when there are no concurrent edits', outcomeKey: 'onNoConcurrency', }, { title: 'when target sibling is moved to a different trait', outcomeKey: 'onMove', concurrent: AnchoredMove.create(StableRange.only(left), StablePlace.before(right)), }, { title: 'when target sibling is deleted then re-inserted in a different trait', outcomeKey: 'onTeleport', concurrent: [ AnchoredDelete.create(StableRange.only(left)), ...AnchoredInsert.create([left], StablePlace.before(right)), ], }, { title: 'when target sibling is deleted with (before, before) range', outcomeKey: 'onDelete', concurrent: AnchoredDelete.create({ start: StablePlace.before(left), end: StablePlace.atEndOf(leftTraitLocation), }), }, { title: 'when target sibling is deleted with (before, after) range', outcomeKey: 'onDelete', concurrent: AnchoredDelete.create({ start: StablePlace.before(left), end: StablePlace.after(left), }), }, { title: 'when target sibling is deleted with (after, before) range', outcomeKey: 'onDelete', concurrent: AnchoredDelete.create({ start: StablePlace.atStartOf(leftTraitLocation), end: StablePlace.atEndOf(leftTraitLocation), }), }, { title: 'when target sibling is deleted with (after, after) range', outcomeKey: 'onDelete', concurrent: AnchoredDelete.create({ start: StablePlace.atStartOf(leftTraitLocation), end: StablePlace.after(left), }), }, { title: 'when target sibling is deleted then un-deleted', outcomeKey: 'onUndoDelete', concurrent: (tree: SharedTreeWithAnchors) => { const deletionEditId = tree.editor.delete(StableRange.only(left)); const deletionEditIndex = tree.edits.getIndexOfId(deletionEditId); const deletionEdit = tree.edits.getEditInSessionAtIndex(deletionEditIndex); return revert(deletionEdit.changes, tree.logViewer.getSnapshotInSession(deletionEditIndex)); }, }, { title: 'when target sibling is deleted then un-deleted and re-deleted', outcomeKey: 'onUndoRedoDelete', concurrent: (tree: SharedTreeWithAnchors) => { const deletionEditId = tree.editor.delete(StableRange.only(left)); const deletionEditIndex = tree.edits.getIndexOfId(deletionEditId); const deletionEdit = tree.edits.getEditInSessionAtIndex(deletionEditIndex); const undoEditId = tree.editor.revert(deletionEdit, tree.logViewer.getSnapshotInSession(deletionEditIndex)); const undoEditIndex = tree.edits.getIndexOfId(undoEditId); const undoEdit = tree.edits.getEditInSessionAtIndex(undoEditIndex); return revert(undoEdit.changes, tree.logViewer.getSnapshotInSession(undoEditIndex)); }, }, { title: 'when target sibling parent is deleted', outcomeKey: 'onDeleteParent', concurrent: AnchoredDelete.create(StableRange.only(parent)), }, { title: 'when target sibling is moved in an edit that is dropped', outcomeKey: 'onDroppedEdit', concurrent: [ // Valid move ...AnchoredMove.create(StableRange.only(left), StablePlace.before(right)), // Invalid constraint AnchoredChange.constraint(StableRange.only(left), ConstraintEffect.InvalidAndDiscard, undefined, 0), ], }, { title: 'when target sibling is deleted in an edit that is dropped', outcomeKey: 'onDroppedEdit', concurrent: [ // Valid delete AnchoredDelete.create(StableRange.only(left)), // Invalid constraint AnchoredChange.constraint(StableRange.only(left), ConstraintEffect.InvalidAndDiscard, undefined, 0), ], }, { title: 'when target place is inserted at', outcomeKey: 'onInsert', concurrent: (_: unknown, anchorCase: AnchorCase) => AnchoredInsert.create([concurrentlyInserted], anchorCase.insertionPlace), }, ]; describe('SharedTreeWithAnchors', () => { describe('Fulfills the SharedTree contract', () => { runSharedTreeOperationsTests<SharedTreeWithAnchors>('SharedTree Operations', setUpTestSharedTreeWithAnchors); runSummaryTests<SharedTreeWithAnchors>( 'SharedTree Summary', setUpTestSharedTreeWithAnchors, setUpLocalServerTestSharedTreeWithAnchors ); }); it('PlaceAnchor builders default to RelativeToNode semantics', () => { const start = PlaceAnchor.atStartOf(leftTraitLocation); const end = PlaceAnchor.atEndOf(leftTraitLocation); const before = PlaceAnchor.before(left); const after = PlaceAnchor.after(left); expect(start.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); expect(end.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); expect(before.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); expect(after.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); }); it('RangeAnchor builders default to RelativeToNode semantics', () => { const range = RangeAnchor.only(left); expect(range.start.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); expect(range.end.semantics).equals(PlaceAnchorSemanticsChoice.RelativeToNode); }); // This is the main battery of tests. // These tests insert the `inserted` node at a given PlaceAnchor in different scenarios and check where that node ends up. // The scenarios cover the various ways concurrent change might affect an anchor. describe('Basic scenarios', () => { for (const insertScenario of insertScenarios) { describe(insertScenario.title, () => { insertTestsWithExtraChanges(insertScenario.outcomeKey, insertScenario.concurrent); }); } }); // These tests exercise special scenarios that the main battery of tests (above) does not cover. // They are mainly aimed at uncovering invalid assumptions that the anchor resolution implementation might make. // While these tests could be made exhaustive like the main battery, doing so would just add redundant coverage. describe(`Special scenarios`, () => { it('when target place is invalid', () => { const { treeA, treeB, container } = setupTrees(); treeA.editor.insert(inserted, PlaceAnchor.before(inserted)); container.processAllMessages(); expectChangedTraits(treeA, treeB, {}); }); // For each scenario we test with: // groupInEdit=true: the concurrent changes that introduced the conflict were applied in a single edit // groupInEdit=false: the concurrent changes that introduced the conflict were applied in separate edits for (const groupInEdit of [true, false]) { describe(groupInEdit ? 'In one edit' : 'In separate edits', () => { // These tests verify that re-anchoring works even when more than one place anchor needs updating. it('when target place and source range both need updating due to two deletes', () => { const { treeA, treeB, container } = setupTrees(); treeA.editor.insert(extra, StablePlace.before(left)); container.processAllMessages(); if (groupInEdit) { treeB.editor.applyChanges([ AnchoredDelete.create(RangeAnchor.only(left)), AnchoredDelete.create(RangeAnchor.all(rightTraitLocation)), ]); } else { treeB.editor.delete(RangeAnchor.only(left)); treeB.editor.delete(RangeAnchor.all(rightTraitLocation)); } const beforeExtra = PlaceAnchor.before(extra); const afterExtra = PlaceAnchor.after(extra); treeA.editor.move(RangeAnchor.from(beforeExtra).to(afterExtra), PlaceAnchor.before(right)); container.processAllMessages(); expectChangedTraits(treeA, treeB, { leftTrait: [], rightTrait: [extra] }); }); }); } // This test covers the scenario that yields different results depending on whether the front-biased approach // seeks backward to find the most recent offending change at the granularity of changes or at the granularity of edits // and then proceeds through changes forward. it('when target place is teleported then deleted in a single edit', () => { const { treeA, treeB, container } = setupTrees(); treeB.editor.applyChanges([ // The reanchor will happen on this change if seeking backward through edits and then forward through changes AnchoredDelete.create(RangeAnchor.only(left)), ...AnchoredInsert.create([left], PlaceAnchor.atStartOf(rightTraitLocation)), // The reanchor will happen on this change if seeking backward through changes AnchoredDelete.create(RangeAnchor.only(left)), ]); treeA.editor.insert(inserted, PlaceAnchor.before(left)); container.processAllMessages(); expectChangedTraits(treeA, treeB, { leftTrait: [], rightTrait: [inserted, right] }); }); // This test covers the scenario that yields different results depending on whether the front-biased approach // seeks backward to find the most recent offending change at the granularity of changes or at the granularity of edits. it('when target place is teleported then deleted across edits', () => { const { treeA, treeB, container } = setupTrees(); // The reanchor will happen on this change if seeking backward through edits treeB.editor.delete(left); treeB.editor.applyChanges([ ...AnchoredInsert.create([left], StablePlace.atStartOf(rightTraitLocation)), // The reanchor will happen on this change if seeking backward through changes AnchoredDelete.create(StableRange.only(left)), ]); treeA.editor.insert(inserted, PlaceAnchor.before(left)); container.processAllMessages(); expectChangedTraits(treeA, treeB, { leftTrait: [], rightTrait: [inserted, right] }); }); // This test covers the scenario that yields different results depending on whether the changes of the edit being applied are // included in the reconciliation path or not. it('when target place is deleted by the edit being rebased', () => { const { treeA, treeB, container } = setupTrees(); treeB.editor.move(left, PlaceAnchor.before(right)); treeA.editor.applyChanges([ // The reanchor will happen on this change if changes for this edit are included in the reconciliation path AnchoredDelete.create(RangeAnchor.all(rightTraitLocation)), // This change will fail if changes for this edit are not included in the reconciliation path ...AnchoredInsert.create([inserted], PlaceAnchor.before(left)), ]); container.processAllMessages(); expectChangedTraits(treeA, treeB, { leftTrait: [], rightTrait: [inserted] }); }); // These tests cover the scenario that yields different results depending on whether the change application performed on the // reconciliation path is itself using anchor resolution for (const extraChange of [false, true]) { it(`when target place resolution requires resolution of a different place in another edit${ extraChange ? ' (with extra change)' : '' }`, () => { const { treeA, treeB, container } = setupTrees(); const { tree: treeC } = setUpTestSharedTreeWithAnchors({ containerRuntimeFactory: container, ...thirdTreeOptions, }); treeA.editor.insert(extra, StablePlace.before(right)); treeA.editor.move(left, StablePlace.before(extra)); container.processAllMessages(); // State of right trait: [left, extra, right] treeB.editor.move(left, StablePlace.after(extra)); // State of right trait: [extra, left, right] treeB.editor.delete(left); // State of right trait: [extra, left-tombstone, right] treeC.editor.applyChanges([ // Will be re-anchored to delete [right] instead of [left, extra, right] AnchoredDelete.create( RangeAnchor.from(PlaceAnchor.before(left)).to(StablePlace.atEndOf(rightTraitLocation)) ), // When present, the no-op change after the change of interest to ensures the anchor resolution uses resolved // changes in the reconciliation path (or derives them). // When not present, the above delete is the only change in the edit so there's a possibility that the anchor // resolution would use cached edit results (which reflect the resolved changes) and therefore don't require // the actual use of resolved changes. // We still want to test without this extra change to ensure that such a possibility, if leveraged, does work // properly. ...(extraChange ? [AnchoredChange.clearPayload(parent.identifier)] : []), ]); // State of right trait: [extra, left-tombstone, right-tombstone] treeA.editor.insert(inserted, PlaceAnchor.after(right)); // State of right trait: [extra, left-tombstone, right-tombstone, inserted] // Unless anchor resolution is not performed which case the edit will fail when it tries to apply the // "delete everything before left" edit because it will not take into account the resolved location for "before left". container.processAllMessages(); expectChangedTraits(treeA, treeB, { leftTrait: [], rightTrait: [extra, inserted] }); }); } }); }); /** * Runs an insertion test scenario on all possible anchors. */ function insertTestsWithExtraChanges( outcomeField: keyof AnchorCaseOutcomes, concurrentSteps?: ConcurrentChanges ): void { for (const anchorCase of anchorCases) { const outcome = outcomeFromCaseAndField(anchorCase, outcomeField); insertTest(anchorCase, outcome, concurrentSteps); } } /** * Provides the expected outcome for a particular `AnchorCase` instance and scenario (described by its `outcomeField`) * This helps reduce cruft in the `AnchorCase` by providing general expectations (e.g., concurrently deleting a node and undoing the * deletion is expected, unless otherwise specified, to yield the same outcome as through no concurrent changes were made). */ function outcomeFromCaseAndField(anchorCase: AnchorCase, outcomeField: keyof AnchorCaseOutcomes): Outcome { if (anchorCase[outcomeField] !== undefined) { return anchorCase[outcomeField] as Outcome; } switch (outcomeField) { case 'onUndoDelete': return outcomeFromCaseAndField(anchorCase, 'onNoConcurrency'); case 'onUndoRedoDelete': return outcomeFromCaseAndField(anchorCase, 'onDelete'); case 'onTeleport': return outcomeFromCaseAndField(anchorCase, 'onMove'); case 'onDeleteParent': return { leftTrait: [], rightTrait: [] }; default: fail('The expected outcome for this case has not been specified'); } } /** * Runs the insertion test characterized by the anchor as which to insert, the expected outcome, and the concurrent changes to apply. */ function insertTest(anchorCase: AnchorCase, expected: Outcome, concurrentSteps?: ConcurrentChanges): void { it(anchorCase.name, () => { const { tree: treeA, containerRuntimeFactory } = setUpTestSharedTreeWithAnchors(treeOptions); const { tree: treeB } = setUpTestSharedTreeWithAnchors({ containerRuntimeFactory, ...secondTreeOptions, }); // Sync initial tree containerRuntimeFactory.processAllMessages(); const concurrentChanges = concurrentSteps === undefined ? [] : typeof concurrentSteps === 'function' ? concurrentSteps(treeB, anchorCase) : Array.isArray(concurrentSteps) ? concurrentSteps : [concurrentSteps as AnchoredChange]; // Perform the concurrent edit(s) to be sequenced first if (concurrentSteps) { treeB.editor.applyChanges(concurrentChanges); } // Make the insertion at the anchored place treeA.editor.insert(inserted, anchorCase.insertionPlace); containerRuntimeFactory.processAllMessages(); // Test the outcome matches expectations expectChangedTraits(treeA, treeB, expected); }); } function expectChangedTraits(treeA: SharedTreeWithAnchors, treeB: SharedTreeWithAnchors, expected: Outcome) { const leftIds = (expected.leftTrait ?? [left]).map((node) => node.identifier); const rightIds = (expected.rightTrait ?? [right]).map((node) => node.identifier); expect(tryGetTrait(treeA, leftTraitLocation)).deep.equal(leftIds); expect(tryGetTrait(treeB, leftTraitLocation)).deep.equal(leftIds); expect(tryGetTrait(treeA, rightTraitLocation)).deep.equal(rightIds); expect(tryGetTrait(treeB, rightTraitLocation)).deep.equal(rightIds); } function tryGetTrait(tree: SharedTreeWithAnchors, location: TraitLocation): readonly NodeId[] { return tree.currentView.hasNode(location.parent) ? tree.currentView.getTrait(location) : []; } function setupTrees(): { treeA: SharedTreeWithAnchors; treeB: SharedTreeWithAnchors; container: MockContainerRuntimeFactory; } { const { tree: treeA, containerRuntimeFactory: container } = setUpTestSharedTreeWithAnchors(treeOptions); const { tree: treeB } = setUpTestSharedTreeWithAnchors({ containerRuntimeFactory: container, ...secondTreeOptions, }); container.processAllMessages(); return { treeA, treeB, container }; }
the_stack
export = utility; export as namespace utility; // --------------------------------- /** * @description Types definition by github@ddzy * @see https://github.com/node-modules/utility */ // ------------------------------------ declare namespace utility { /** * ---------------0_0---------------- * @description Defines For Array * @see https://github.com/node-modules/utility * ---------------0^0---------------- */ /** * Static object define */ type ObjStatic = { [key: string]: any }; /** * Array random slice with items count. * @param {Array} arr * @param {Number} num, number of sub items. * @return {Array} */ function randomSlice( arr: any[], num?: number, ): any[]; /** * Remove one exists element from an array * @param {Array} arr * @param {Number} index - remove element index * @return {Array} the array instance */ function spliceOne( arr: any[], index: number, ): any[]; /** * --------------------0_0---------------- * @description Defines For Crypto * @see https://github.com/node-modules/utility#md5 * --------------0^0------------------ */ /** * hash * * @param {String} method hash method, e.g.: 'md5', 'sha1' * @param {String|Buffer|Object} s * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'. * @return {String} md5 hash string * @public */ function hash( method: 'md5' | 'sha1', s: string | Buffer | Object, format?: 'hex' | 'base64', ): string; /** * md5 hash * * @param {String|Buffer|Object} s * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'. * @return {String} md5 hash string * @public */ function md5( s: string | Buffer | Object, format?: 'hex' | 'base64', ): string; /** * sha1 hash * * @param {String|Buffer|Object} s * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'. * @return {String} sha1 hash string * @public */ function sha1( s: string | Buffer | Object, format?: 'hex' | 'base64', ): string; /** * sha256 hash * * @param {String|Buffer|Object} s * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'. * @return {String} sha256 hash string * @public */ function sha256( s: string | Buffer | Object, format?: 'hex' | 'base64', ): string; /** * HMAC algorithm. * * Equal bash: * * ```bash * $ echo -n "$data" | openssl dgst -binary -$algorithm -hmac "$key" | openssl $encoding * ``` * * @param {String} algorithm, dependent on the available algorithms supported by the version of OpenSSL on the platform. * Examples are 'sha1', 'md5', 'sha256', 'sha512', etc. * On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms. * @param {String} key, the hmac key to be used. * @param {String|Buffer} data, content string. * @param {String} [encoding='base64'] * @return {String} digest string. */ function hmac( algorithm: string, key: string, data: string | Buffer, encoding?: 'base64' | string, ): string; /** * Base64 encode string. * * @param {String|Buffer} s * @param {Boolean} [urlsafe=false] Encode string s using a URL-safe alphabet, * which substitutes - instead of + and _ instead of / in the standard Base64 alphabet. * @return {String} base64 encode format string. */ function base64encode( s: string | Buffer, urlsafe?: boolean, ): string; /** * Base64 string decode. * * @param {String} encode, base64 encoding string. * @param {Boolean} [urlsafe=false] Decode string s using a URL-safe alphabet, * which substitutes - instead of + and _ instead of / in the standard Base64 alphabet. * @param {encoding} [encoding=utf8] if encoding = buffer, will return Buffer instance * @return {String|Buffer} plain text. */ function base64decode( encode: string, urlsafe?: boolean, encoding?: 'utf8' | 'buffer', ): string | Buffer; /** * ----------------0_0----------------- * @description Defines For Date * @see https://github.com/node-modules/utility#date-utils * ---------------0^0------------------ */ interface IYYYYMMDDHHmmssStaticOptions { dateSep?: string, timeSep?: string, } interface IDateStructStaticReturns { YYYYMMDD: number, H: number, } /** * Access log format date. format: `moment().format('DD/MMM/YYYY:HH:mm:ss ZZ')` * * @return {String} */ function accessLogDate(d: Date): string; /** * Normal log format date. format: `moment().format('YYYY-MM-DD HH:mm:ss.SSS')` * * @return {String} */ function logDate( d: string | Date, msSep?: string, ): string; /** * `moment().format('YYYY-MM-DD HH:mm:ss')` format date string. * * @return {String} */ function YYYYMMDDHHmmss( d: Date | string, options?: IYYYYMMDDHHmmssStaticOptions, ): string; /** * `moment().format('YYYY-MM-DD')` format date string. * * @return {String} */ function YYYYMMDD( d: string | Date, sep?: string, ): string; /** * return datetime struct. * * @return {Object} date * - {Number} YYYYMMDD, 20130401 * - {Number} H, 0, 1, 9, 12, 23 */ function datestruct( now?: Date, ): IDateStructStaticReturns; /** * Get Unix's timestamp in seconds. * @return {Number} */ function timestamp( t?: string | number, ): number | Date; /** * ---------------0_0------------------- * @description Defines For Function Method * @see https://github.com/node-modules/utility#others * ---------------0^0-------------------- */ /** * A empty function. * * @return {Function} * @public */ function noop(): () => any; /** * Get a function parameter's names. * * @param {Function} func * @param {Boolean} [useCache], default is true * @return {Array} names */ function getParamNames( func: (...args: any[]) => any, cache?: boolean, ): string[]; /** * ----------------0_0----------------------- * @description Defines For JSON methods * @see https://github.com/node-modules/utility#json * -----------------0^0----------------------- */ interface IJSONStaticOptions { space?: number | string, replacer?: ( key: string, value: any, ) => any, } function strictJSONParse( str: string, ): ObjStatic; function readJSONSync( filepath: string, ): ObjStatic; function writeJSONSync( filepath: string, str: string | ObjStatic, options?: IJSONStaticOptions, ): void; function readJSON( filepath: string, ): Promise<any>; function writeJSON( filepath: string, str: string | ObjStatic, options?: IJSONStaticOptions, ): Promise<any>; function mkdir( dir: string, ): Promise<any>; /** * ------------------0_0------------------------ * @description Defines For Number Methods * @see https://github.com/node-modules/utility#number-utils * --------------------0^0---------------------- */ /** * CONSTANTS STATIC */ const MAX_SAFE_INTEGER: number; const MIN_SAFE_INTEGER: number; const MAX_SAFE_INTEGER_STR: string; const MAX_SAFE_INTEGER_STR_LENGTH: number; /** * Detect a number string can safe convert to Javascript Number. * * @param {String} s number format string, like `"123"`, `"-1000123123123123123123"` * @return {Boolean} */ function isSafeNumberString( s: string, ): boolean; /** * Convert string to Number if string in safe Number scope. * * @param {String} s number format string. * @return {Number|String} success will return Number, otherise return the original string. */ function toSafeNumber( s: string | number, ): number | string; /** * Produces a random integer between the inclusive `lower` and `upper` bounds. * * @param {Number} lower The lower bound. * @param {Number} upper The upper bound. * @return {Number} Returns the random number. */ function random( lower?: number, upper?: number, ): number; /** * ------------------0_0-------------------------- * @description Defines For Object Methods * @see https://github.com/node-modules/utility#objectassign * -------------------0^0------------------------ */ /** * High performance assign before node6 * @param {Object} target - target object * @param {Object | Array} objects - object assign from * @return {Object} - return target object */ function assign( target: ObjStatic, objects: ObjStatic | any[], ): ObjStatic; function has( obj: ObjStatic, prop: string, ): boolean; function getOwnEnumerables( obj: ObjStatic, ignoreNull?: boolean, ): string[]; /** * generate a real map object(clean object), no constructor, no __proto__ * @param {Object} [obj] - init object, optional * @return {Object} */ function map( obj?: ObjStatic, ): ObjStatic; /** * -----------------0_0--------------------------- * @description Defines For Optimize Methods * @see https://github.com/node-modules/utility#argumentstoarray * -----------------0^0------------------------ */ interface ITryStaticReturns { error: Error | undefined, value: any, } const UNSTABLE_METHOD: { /** * optimize try catch * @param {Function} fn * @return {Object} * - {Error} error * - {Mix} value */ try: ( fn: (...args: any[]) => any, ) => ITryStaticReturns, }; /** * avoid if (a && a.b && a.b.c) * @param {Object} obj * @param {...String} keys * @return {Object} */ function dig( obj: ObjStatic, ...args: any[], ): any; /** * optimize arguments to array * @param {Arguments} args * @return {Array} */ function argumentsToArray( ...args: any[], ): any[]; /** * -------------------0_0--------------------- * @description Defines For Polyfill Methods * @see https://github.com/node-modules/utility#timers * -------------------0^0------------------- */ function setImmediate( callback: (...args: any[]) => void, ...args: any[], ): NodeJS.Immediate; function setImmediate( fn: (...args: any[]) => any, ...args: any[], ): void; /** * ------------------0_0-------------------- * @description Defines For String Methods * @see https://github.com/node-modules/utility#others * -------------------0^0--------------------- */ interface IReplaceInvalidHttpHeaderCharReturns { val: string, invalid: boolean, } function randomString( length?: number, charSet?: string | string[], ): string; /** * split string to array * @param {String} str * @param {String} [sep] default is ',' * @return {Array} */ function split( str: string, sep?: string, ): string[]; /** * always optimized */ function splitAlwaysOptimized( ...args: any[], ): string[]; /** * Replace string * * @param {String} str * @param {String|RegExp} substr * @param {String|Function} newSubstr * @return {String} */ function replace( str: string, substr: string | RegExp, newSubstr: string | ((...args: any[]) => any), ): string; /** * Replace invalid http header characters with replacement * * @param {String} val * @param {String|Function} replacement - can be `function(char)` * @return {Object} */ function replaceInvalidHttpHeaderChar( val: string, replacement?: string | ((...args: any[]) => any) ): IReplaceInvalidHttpHeaderCharReturns; /** * Detect invalid http header characters in a string * * @param {String} val * @return {Boolean} */ function includesInvalidHttpHeaderChar( val: string, ): boolean; /** * ------------------0_0---------------------- * @description Defines For Web Methods * @see https://github.com/node-modules/utility#decode-and-encode * ------------------0^0------------------------ */ /** * Escape the given string of `html`. * * @param {String} html * @return {String} * @public */ function escape( test: string, ): string; /** * Unescape the given string from html * @param {String} html * @param {String} type * @return {String} * @public */ function unescape( html: string, type?: string, ): string | ObjStatic; /** * Safe encodeURIComponent, won't throw any error. * If `encodeURIComponent` error happen, just return the original value. * * @param {String} text * @return {String} URL encode string. */ function encodeURIComponent( text: string, ): string; /** * Safe decodeURIComponent, won't throw any error. * If `decodeURIComponent` error happen, just return the original value. * * @param {String} encodeText * @return {String} URL decode original string. */ function decodeURIComponent( encodeText: string, ): string; }
the_stack
import { Wiql, WorkItemExpand, WorkItemRelation, WorkItemErrorPolicy } from 'TFS/WorkItemTracking/Contracts'; import { WorkItemTrackingHttpClient4_1, getClient } from 'TFS/WorkItemTracking/RestClient'; import { JsonPatchDocument, Operation } from 'VSS/WebApi/Contracts'; import { IRetrospectiveItemCreate, IRetrospectiveItemsQuery, RelationshipType } from '../interfaces/workItem'; class WorkItemService { public static readonly retrospective_type = 'Retrospective'; public static readonly task_type = 'Task'; public ProjectId = ''; private _httpClient: WorkItemTrackingHttpClient4_1; constructor() { if (!this._httpClient) { this._httpClient = getClient(); } this.ProjectId = VSS.getWebContext().project.id; } public getAllFields = () => { return this._httpClient.getFields(); } /** * Gets the work item states for the given work item type in the current project. */ public getWorkItemStates = async (workItemType: string) => { return await this._httpClient.getWorkItemTypeStates(VSS.getWebContext().project.id, workItemType); } /** * Gets the work item types for the current project. */ public getWorkItemTypesForCurrentProject = async () => { return await this._httpClient.getWorkItemTypes(VSS.getWebContext().project.id); } /** * Gets the list of work item type references for hidden work item types */ public getHiddenWorkItemTypes = async () => { const hiddenWorkItemTypeCategory = await this._httpClient.getWorkItemTypeCategory( VSS.getWebContext().project.id, 'Microsoft.HiddenCategory'); return hiddenWorkItemTypeCategory.workItemTypes; } /** * Creates a new item of type 'Retrospective'. * @param title The title of the work item. */ public createRetrospectiveItemOfType = (createFields: IRetrospectiveItemCreate) => { const operation = [ { op: Operation.Add, path: '/fields/System.Title', value: createFields.title, }, { op: 'add', path: '/fields/System.IterationPath', value: createFields.iteration, }, { op: 'add', path: '/fields/System.AreaPath', value: createFields.areaPath, }, { op: 'add', path: '/fields/AgilewithRetrospective.FeedbackType', value: createFields.feedbackType.toString(), }, { op: 'add', path: '/fields/AgilewithRetrospective.IsAnonymous', value: createFields.isAnonymous, }, { op: Operation.Add, path: '/fields/AgilewithRetrospective.Votes', value: 0, // zero votes }, ]; return this._httpClient.createWorkItem(operation, VSS.getWebContext().project.id, WorkItemService.retrospective_type); } /** * Adds a vote to the existing retrospective item * @param id The id of the workitem * @param currentVotes The number of votes a workitem has got so far */ public addUpvoteToRetrospectiveItem = (id: number, currentVotes: number) => { const updatedVotes = currentVotes + 1; return this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/fields/AgilewithRetrospective.Votes', value: updatedVotes, }, ], id); } /** * Updates the title of a retrospective item * @param id The id of the workitem * @param newTitle The new title of the retrospective item */ public updateRetrospectiveItemTitle = (id: number, newTitle: string) => { this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/fields/System.Title', value: newTitle, }, ], id); } /** * Creates a 'Reference' relationship between two Retrospective items. Updating their own * groupings as necessary. * @param sourceReferencingId The id of the referencer(dragged item) * @param targetReferencedById The id of the referencee(target item) */ public AddReferenceRelationshipBetweenRetrospectiveItems(sourceReferencingId: number, targetReferencedById: number) { return this.getWorkItemsByIds([sourceReferencingId]) // Check to see if the retrospectiveItemReferencing has any relations that also need to link // to the retrospectiveItemReferencedBy. .then((workItems) => { const referenceRelationshipItemIds = workItems[0].relations ? workItems[0].relations.filter((relation) => relation.rel === RelationshipType.ReferencedByReverse).map((relation) => Number(relation.url.split('/').pop() || '-1')).filter((id) => id >= 0) : []; return referenceRelationshipItemIds.length ? this.getWorkItemsByIds(referenceRelationshipItemIds) : Promise.resolve([]); }) // If they exist, remove these existing links and create new ones. // Operation.Update doesn't seem to support this scenario. .then((referenceRelationshipItems) => { if (referenceRelationshipItems.length) { referenceRelationshipItems.map((referenceRelationshipItem) => { const relationIndexToRemove = referenceRelationshipItem.relations.findIndex( (relation: WorkItemRelation) => relation.rel === RelationshipType.ReferencedByForward && relation.url === `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${sourceReferencingId}`); return this.UpdateRetrospectiveItem([ { op: Operation.Remove, path: `/relations/${relationIndexToRemove}`, }, ], referenceRelationshipItem.id) .then(() => { return this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/relations/-', value: { attributes: { comment: 'linked via reflect retrospective', }, rel: RelationshipType.ReferencedByForward, url: `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${targetReferencedById}`, }, }, ], referenceRelationshipItem.id); }); }); // Bug in Typescript https://github.com/Microsoft/TypeScript/issues/17862 prevents us // from using Promise.all() here. Instead, we fetch all the items again. // return Promise.all(referenceRelationshipItemUpdates).then(workItems => workItems); return this.getWorkItemsByIds(referenceRelationshipItems.map((item) => item.id)).then((workItems) => workItems); } return Promise.resolve([]); }) // Link the main two items, only one operation is needed. .then((previouslyUpdatedItems) => { return this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/relations/-', value: { attributes: { comment: 'linked via reflect retrospective', }, rel: RelationshipType.ReferencedByForward, url: `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${targetReferencedById}`, }, }, ], sourceReferencingId) .then((updatedRetrospectiveItemReferencingId) => previouslyUpdatedItems.concat(updatedRetrospectiveItemReferencingId)); }) // Return all the items that were updated by the service calls. .then((previouslyUpdatedItems) => { return this.getWorkItemsByIds([targetReferencedById]) .then((workItems) => previouslyUpdatedItems.concat(workItems)); }); } /** * Removes a 'Reference' relationship between the two items. * @param retrospectiveItemReferencingId The id of the referencer * @param retrospectiveItemReferencedById The ide of the referencee */ public RemovesReferenceRelationshipBetweenRetrospectiveItems(retrospectiveItemReferencingId: number, retrospectiveItemReferencedById: number) { return this.getWorkItemsByIds([retrospectiveItemReferencingId]) // Find and remove the relation between the two items. .then((workItems) => { const relationIndexToRemove = workItems[0].relations.findIndex( (relation) => relation.rel === RelationshipType.ReferencedByForward && relation.url === `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${retrospectiveItemReferencedById}`); return this.UpdateRetrospectiveItem([ { op: Operation.Remove, path: `/relations/${relationIndexToRemove}`, }, ], retrospectiveItemReferencingId); }) // Return all the items that were updated by the service calls. .then((previouslyUpdatedItem) => { return this.getWorkItemsByIds([retrospectiveItemReferencedById]) .then((workItems) => [previouslyUpdatedItem].concat(workItems)); }); } /** * Gets the work items by given ids. * @param ids The ids of the work items to fetch. */ public async getWorkItemsByIds(ids: number[]) { const workItems = await this._httpClient.getWorkItems(ids, undefined, undefined, WorkItemExpand.All, WorkItemErrorPolicy.Omit, VSS.getWebContext().project.id); return workItems.filter(wi => wi != null); } public getReferencedByReverseItemIds(itemId: number) { return this.getWorkItemsByIds([itemId]).then((workItems) => { return workItems[0].relations.filter((relation) => relation.rel === RelationshipType.ReferencedByReverse) .map((relation) => Number(relation.url.split('/').pop() || '')) .filter((id) => id); }); } /** * Gets the work items that the given work item ids have a 'Related' relationship with * @param itemIds */ public getRelatedItemsForItemsIds(itemIds: number[]) { return this.getWorkItemsByIds(itemIds) .then((workItems) => { const actionItemIds = new Set<string>(); workItems.forEach((retrospectiveItem) => { if (retrospectiveItem.relations) { retrospectiveItem.relations.filter((relation) => relation.rel === RelationshipType.Related) .forEach((relation) => { // TODO improve to just get json directly from url const id = relation.url.split('/').pop() || ''; if (id) { actionItemIds.add(id); } }); } }); if (actionItemIds.size) { return this.getWorkItemsByIds(Array.from(actionItemIds).map((e) => Number(e))); } return Promise.resolve([]); }); } /** * * @param item1_id * @param item2_id */ public linkItemsAsRelated(item1_id: number, item2_id: number) { const item2Update = this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/relations/-', value: { attributes: { comment: 'linked via reflect retrospective', }, rel: RelationshipType.Related, url: `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${item1_id}`, }, }, ], item2_id); const item1Update = this.UpdateRetrospectiveItem([ { op: Operation.Add, path: '/relations/-', value: { attributes: { comment: 'linked via reflect retrospective', }, rel: RelationshipType.Related, url: `https://reflect-retrospective-hackathon.visualstudio.com/_apis/wit/workItems/${item2_id}`, }, }, ], item1_id); return Promise.all([item1Update, item2Update]); } /** * Gets the ids of items of type Retrospective. */ public getRetrospectiveItems = (queryFields: IRetrospectiveItemsQuery) => { // TODO: Handle case for dynamic type name i.e. replace the static [AgilewithRetrospective.FeedbackType] with dynamic content. const wiqlQuery: Wiql = { query: "SELECT [System.Id], [System.Title], [System.CreatedBy], [System.IterationPath] " + "FROM WorkItems " + "WHERE [System.WorkItemType] = '" + WorkItemService.retrospective_type + "' " + "AND [AgilewithRetrospective.FeedbackType] = '" + queryFields.feedbackType.toString() + "' " + "AND [System.IterationPath] = '" + queryFields.iteration + "' " + "AND [System.AreaPath] = '" + queryFields.areaPath + "' " }; return this._httpClient.queryByWiql(wiqlQuery, VSS.getWebContext().project.id) .then((queryResult) => { const workItems = queryResult.workItems; const ids = new Array<number>(); workItems.forEach((item) => { ids.push(item.id); }); return ids; }) .then((workItemIds) => { if (workItemIds.length > 0) { return this._httpClient.getWorkItems(workItemIds, undefined, undefined, WorkItemExpand.All, undefined, VSS.getWebContext().project.id) .then((workItems) => workItems); } else { return []; } }); } private createTaskItem = (title: string) => { const operation = [ { op: Operation.Add, path: '/fields/System.Title', value: title, }, ]; return this._httpClient.createWorkItem(operation, VSS.getWebContext().project.id, WorkItemService.task_type); } private UpdateRetrospectiveItem(patchDocument: JsonPatchDocument, id: number) { return this._httpClient.updateWorkItem(patchDocument, id, VSS.getWebContext().project.id); } } export const workItemService = new WorkItemService();
the_stack
import { MeshTopology } from "@oasis-engine/core"; /** * The datatype of the components in the attribute */ export enum AccessorComponentType { /** * Byte */ BYTE = 5120, /** * Unsigned Byte */ UNSIGNED_BYTE = 5121, /** * Short */ SHORT = 5122, /** * Unsigned Short */ UNSIGNED_SHORT = 5123, /** * Unsigned Int */ UNSIGNED_INT = 5125, /** * Float */ FLOAT = 5126 } /** * Specifies if the attirbute is a scalar, vector, or matrix */ export enum AccessorType { /** * Scalar */ SCALAR = "SCALAR", /** * Vector2 */ VEC2 = "VEC2", /** * Vector3 */ VEC3 = "VEC3", /** * Vector4 */ VEC4 = "VEC4", /** * Matrix2x2 */ MAT2 = "MAT2", /** * Matrix3x3 */ MAT3 = "MAT3", /** * Matrix4x4 */ MAT4 = "MAT4" } /** * The name of the node's TRS property to modify, or the weights of the Morph Targets it instantiates */ export enum AnimationChannelTargetPath { /** * Translation */ TRANSLATION = "translation", /** * Rotation */ ROTATION = "rotation", /** * Scale */ SCALE = "scale", /** * Weights */ WEIGHTS = "weights" } /** * Interpolation algorithm */ export enum AnimationSamplerInterpolation { /** * The animated values are linearly interpolated between keyframes */ Linear = "LINEAR", /** * The animated values remain constant to the output of the first keyframe, until the next keyframe */ Step = "STEP", /** * The animation's interpolation is computed using a cubic spline with specified tangents */ CubicSpine = "CUBICSPLINE" } /** * A camera's projection. A node can reference a camera to apply a transform to place the camera in the scene */ export enum CameraType { /** * A perspective camera containing properties to create a perspective projection matrix */ PERSPECTIVE = "perspective", /** * An orthographic camera containing properties to create an orthographic projection matrix */ ORTHOGRAPHIC = "orthographic" } /** * The mime-type of the image */ export enum ImageMimeType { /** * JPEG Mime-type */ JPEG = "image/jpeg", /** * PNG Mime-type */ PNG = "image/png" } /** * The alpha rendering mode of the material */ export enum MaterialAlphaMode { /** * The alpha value is ignored and the rendered output is fully opaque */ OPAQUE = "OPAQUE", /** * The rendered output is either fully opaque or fully transparent depending on the alpha value and the specified alpha cutoff value */ MASK = "MASK", /** * The alpha value is used to composite the source and destination areas. The rendered output is combined with the background using the normal painting operation (i.e. the Porter and Duff over operator) */ BLEND = "BLEND" } /** * Magnification filter. Valid values correspond to WebGL enums: 9728 (NEAREST) and 9729 (LINEAR) */ export enum TextureMagFilter { /** * Nearest */ NEAREST = 9728, /** * Linear */ LINEAR = 9729 } /** * Minification filter. All valid values correspond to WebGL enums */ export enum TextureMinFilter { /** * Nearest */ NEAREST = 9728, /** * Linear */ LINEAR = 9729, /** * Nearest Mip-Map Nearest */ NEAREST_MIPMAP_NEAREST = 9984, /** * Linear Mipmap Nearest */ LINEAR_MIPMAP_NEAREST = 9985, /** * Nearest Mipmap Linear */ NEAREST_MIPMAP_LINEAR = 9986, /** * Linear Mipmap Linear */ LINEAR_MIPMAP_LINEAR = 9987 } /** * S (U) wrapping mode. All valid values correspond to WebGL enums */ export enum TextureWrapMode { /** * Clamp to Edge */ CLAMP_TO_EDGE = 33071, /** * Mirrored Repeat */ MIRRORED_REPEAT = 33648, /** * Repeat */ REPEAT = 10497 } /** * glTF Property */ export interface IProperty { /** * Dictionary object with extension-specific objects */ extensions?: { [key: string]: any; }; /** * Application-Specific data */ extras?: any; } /** * glTF Child of Root Property */ export interface IChildRootProperty extends IProperty { /** * The user-defined name of this object */ name?: string; } /** * Indices of those attributes that deviate from their initialization value */ export interface IAccessorSparseIndices extends IProperty { /** * The index of the bufferView with sparse indices. Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target */ bufferView: number; /** * The offset relative to the start of the bufferView in bytes. Must be aligned */ byteOffset?: number; /** * The indices data type. Valid values correspond to WebGL enums: 5121 (UNSIGNED_BYTE), 5123 (UNSIGNED_SHORT), 5125 (UNSIGNED_INT) */ componentType: AccessorComponentType; } /** * Array of size accessor.sparse.count times number of components storing the displaced accessor attributes pointed by accessor.sparse.indices */ export interface IAccessorSparseValues extends IProperty { /** * The index of the bufferView with sparse values. Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target */ bufferView: number; /** * The offset relative to the start of the bufferView in bytes. Must be aligned */ byteOffset?: number; } /** * Sparse storage of attributes that deviate from their initialization value */ export interface IAccessorSparse extends IProperty { /** * The number of attributes encoded in this sparse accessor */ count: number; /** * Index array of size count that points to those accessor attributes that deviate from their initialization value. Indices must strictly increase */ indices: IAccessorSparseIndices; /** * Array of size count times number of components, storing the displaced accessor attributes pointed by indices. Substituted values must have the same componentType and number of components as the base accessor */ values: IAccessorSparseValues; } /** * A typed view into a bufferView. A bufferView contains raw binary data. An accessor provides a typed view into a bufferView or a subset of a bufferView similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer */ export interface IAccessor extends IChildRootProperty { /** * The index of the bufferview */ bufferView?: number; /** * The offset relative to the start of the bufferView in bytes */ byteOffset?: number; /** * The datatype of components in the attribute */ componentType: AccessorComponentType; /** * Specifies whether integer data values should be normalized */ normalized?: boolean; /** * The number of attributes referenced by this accessor */ count: number; /** * Specifies if the attribute is a scalar, vector, or matrix */ type: AccessorType; /** * Maximum value of each component in this attribute */ max?: number[]; /** * Minimum value of each component in this attribute */ min?: number[]; /** * Sparse storage of attributes that deviate from their initialization value */ sparse?: IAccessorSparse; } /** * Targets an animation's sampler at a node's property */ export interface IAnimationChannel extends IProperty { /** * The index of a sampler in this animation used to compute the value for the target */ sampler: number; /** * The index of the node and TRS property to target */ target: IAnimationChannelTarget; } /** * The index of the node and TRS property that an animation channel targets */ export interface IAnimationChannelTarget extends IProperty { /** * The index of the node to target */ node: number; /** * The name of the node's TRS property to modify, or the weights of the Morph Targets it instantiates */ path: AnimationChannelTargetPath; } /** * Combines input and output accessors with an interpolation algorithm to define a keyframe graph (but not its target) */ export interface IAnimationSampler extends IProperty { /** * The index of an accessor containing keyframe input values, e.g., time */ input: number; /** * Interpolation algorithm */ interpolation?: AnimationSamplerInterpolation; /** * The index of an accessor, containing keyframe output values */ output: number; } /** * A keyframe animation */ export interface IAnimation extends IChildRootProperty { /** * An array of channels, each of which targets an animation's sampler at a node's property */ channels: IAnimationChannel[]; /** * An array of samplers that combines input and output accessors with an interpolation algorithm to define a keyframe graph (but not its target) */ samplers: IAnimationSampler[]; } /** * Metadata about the glTF asset */ export interface IAsset extends IChildRootProperty { /** * A copyright message suitable for display to credit the content creator */ copyright?: string; /** * Tool that generated this glTF model. Useful for debugging */ generator?: string; /** * The glTF version that this asset targets */ version: string; /** * The minimum glTF version that this asset targets */ minVersion?: string; } /** * A buffer points to binary geometry, animation, or skins */ export interface IBuffer extends IChildRootProperty { /** * The uri of the buffer. Relative paths are relative to the .gltf file. Instead of referencing an external file, the uri can also be a data-uri */ uri?: string; /** * The length of the buffer in bytes */ byteLength: number; } /** * A view into a buffer generally representing a subset of the buffer */ export interface IBufferView extends IChildRootProperty { /** * The index of the buffer */ buffer: number; /** * The offset into the buffer in bytes */ byteOffset?: number; /** * The lenth of the bufferView in bytes */ byteLength: number; /** * The stride, in bytes */ byteStride?: number; } /** * An orthographic camera containing properties to create an orthographic projection matrix */ export interface ICameraOrthographic extends IProperty { /** * The floating-point horizontal magnification of the view. Must not be zero */ xmag: number; /** * The floating-point vertical magnification of the view. Must not be zero */ ymag: number; /** * The floating-point distance to the far clipping plane. zfar must be greater than znear */ zfar: number; /** * The floating-point distance to the near clipping plane */ znear: number; } /** * A perspective camera containing properties to create a perspective projection matrix */ export interface ICameraPerspective extends IProperty { /** * The floating-point aspect ratio of the field of view */ aspectRatio?: number; /** * The floating-point vertical field of view in radians */ yfov: number; /** * The floating-point distance to the far clipping plane */ zfar?: number; /** * The floating-point distance to the near clipping plane */ znear: number; } /** * A camera's projection. A node can reference a camera to apply a transform to place the camera in the scene */ export interface ICamera extends IChildRootProperty { /** * An orthographic camera containing properties to create an orthographic projection matrix */ orthographic?: ICameraOrthographic; /** * A perspective camera containing properties to create a perspective projection matrix */ perspective?: ICameraPerspective; /** * Specifies if the camera uses a perspective or orthographic projection */ type: CameraType; } /** * Image data used to create a texture. Image can be referenced by URI or bufferView index. mimeType is required in the latter case */ export interface IImage extends IChildRootProperty { /** * The uri of the image. Relative paths are relative to the .gltf file. Instead of referencing an external file, the uri can also be a data-uri. The image format must be jpg or png */ uri?: string; /** * The image's MIME type */ mimeType?: ImageMimeType; /** * The index of the bufferView that contains the image. Use this instead of the image's uri property */ bufferView?: number; } /** * Material Normal Texture Info */ export interface IMaterialNormalTextureInfo extends ITextureInfo { /** * The scalar multiplier applied to each normal vector of the normal texture */ scale?: number; } /** * Material Occlusion Texture Info */ export interface IMaterialOcclusionTextureInfo extends ITextureInfo { /** * A scalar multiplier controlling the amount of occlusion applied */ strength?: number; } /** * A set of parameter values that are used to define the metallic-roughness material model from Physically-Based Rendering (PBR) methodology */ export interface IMaterialPbrMetallicRoughness { /** * The material's base color factor */ baseColorFactor?: number[]; /** * The base color texture */ baseColorTexture?: ITextureInfo; /** * The metalness of the material */ metallicFactor?: number; /** * The roughness of the material */ roughnessFactor?: number; /** * The metallic-roughness texture */ metallicRoughnessTexture?: ITextureInfo; } /** * The material appearance of a primitive */ export interface IMaterial extends IChildRootProperty { /** * A set of parameter values that are used to define the metallic-roughness material model from Physically-Based Rendering (PBR) methodology. When not specified, all the default values of pbrMetallicRoughness apply */ pbrMetallicRoughness?: IMaterialPbrMetallicRoughness; /** * The normal map texture */ normalTexture?: IMaterialNormalTextureInfo; /** * The occlusion map texture */ occlusionTexture?: IMaterialOcclusionTextureInfo; /** * The emissive map texture */ emissiveTexture?: ITextureInfo; /** * The RGB components of the emissive color of the material. These values are linear. If an emissiveTexture is specified, this value is multiplied with the texel values */ emissiveFactor?: number[]; /** * The alpha rendering mode of the material */ alphaMode?: MaterialAlphaMode; /** * The alpha cutoff value of the material */ alphaCutoff?: number; /** * Specifies whether the material is double sided */ doubleSided?: boolean; } /** * Geometry to be rendered with the given material */ export interface IMeshPrimitive extends IProperty { /** * A dictionary object, where each key corresponds to mesh attribute semantic and each value is the index of the accessor containing attribute's data */ attributes: { [name: string]: number; }; /** * The index of the accessor that contains the indices */ indices?: number; /** * The index of the material to apply to this primitive when rendering */ material?: number; /** * The type of primitives to render. All valid values correspond to WebGL enums */ mode?: MeshTopology; /** * An array of Morph Targets, each Morph Target is a dictionary mapping attributes (only POSITION, NORMAL, and TANGENT supported) to their deviations in the Morph Target */ targets?: { [name: string]: number; }[]; } /** * A set of primitives to be rendered. A node can contain one mesh. A node's transform places the mesh in the scene */ export interface IMesh extends IChildRootProperty { /** * An array of primitives, each defining geometry to be rendered with a material */ primitives: IMeshPrimitive[]; /** * Array of weights to be applied to the Morph Targets */ weights?: number[]; } /** * A node in the node hierarchy */ export interface INode extends IChildRootProperty { /** * The index of the camera referenced by this node */ camera?: number; /** * The indices of this node's children */ children?: number[]; /** * The index of the skin referenced by this node */ skin?: number; /** * A floating-point 4x4 transformation matrix stored in column-major order */ matrix?: number[]; /** * The index of the mesh in this node */ mesh?: number; /** * The node's unit quaternion rotation in the order (x, y, z, w), where w is the scalar */ rotation?: number[]; /** * The node's non-uniform scale, given as the scaling factors along the x, y, and z axes */ scale?: number[]; /** * The node's translation along the x, y, and z axes */ translation?: number[]; /** * The weights of the instantiated Morph Target. Number of elements must match number of Morph Targets of used mesh */ weights?: number[]; } /** * Texture sampler properties for filtering and wrapping modes */ export interface ISampler extends IChildRootProperty { /** * Magnification filter. Valid values correspond to WebGL enums: 9728 (NEAREST) and 9729 (LINEAR) */ magFilter?: TextureMagFilter; /** * Minification filter. All valid values correspond to WebGL enums */ minFilter?: TextureMinFilter; /** * S (U) wrapping mode. All valid values correspond to WebGL enums */ wrapS?: TextureWrapMode; /** * T (V) wrapping mode. All valid values correspond to WebGL enums */ wrapT?: TextureWrapMode; } /** * The root nodes of a scene */ export interface IScene extends IChildRootProperty { /** * The indices of each root node */ nodes: number[]; } /** * Joints and matrices defining a skin */ export interface ISkin extends IChildRootProperty { /** * The index of the accessor containing the floating-point 4x4 inverse-bind matrices. The default is that each matrix is a 4x4 identity matrix, which implies that inverse-bind matrices were pre-applied */ inverseBindMatrices?: number; /** * The index of the node used as a skeleton root. When undefined, joints transforms resolve to scene root */ skeleton?: number; /** * Indices of skeleton nodes, used as joints in this skin. The array length must be the same as the count property of the inverseBindMatrices accessor (when defined) */ joints: number[]; } /** * A texture and its sampler */ export interface ITexture extends IChildRootProperty { /** * The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used */ sampler?: number; /** * The index of the image used by this texture */ source: number; } /** * Reference to a texture */ export interface ITextureInfo extends IProperty { /** * The index of the texture */ index: number; /** * The set index of texture's TEXCOORD attribute used for texture coordinate mapping */ texCoord?: number; } /** * The root object for a glTF asset */ export interface IGLTF extends IProperty { /** * An array of accessors. An accessor is a typed view into a bufferView */ accessors?: IAccessor[]; /** * An array of keyframe animations */ animations?: IAnimation[]; /** * Metadata about the glTF asset */ asset: IAsset; /** * An array of buffers. A buffer points to binary geometry, animation, or skins */ buffers?: IBuffer[]; /** * An array of bufferViews. A bufferView is a view into a buffer generally representing a subset of the buffer */ bufferViews?: IBufferView[]; /** * An array of cameras */ cameras?: ICamera[]; /** * Names of glTF extensions used somewhere in this asset */ extensionsUsed?: string[]; /** * Names of glTF extensions required to properly load this asset */ extensionsRequired?: string[]; /** * An array of images. An image defines data used to create a texture */ images?: IImage[]; /** * An array of materials. A material defines the appearance of a primitive */ materials?: IMaterial[]; /** * An array of meshes. A mesh is a set of primitives to be rendered */ meshes?: IMesh[]; /** * An array of nodes */ nodes?: INode[]; /** * An array of samplers. A sampler contains properties for texture filtering and wrapping modes */ samplers?: ISampler[]; /** * The index of the default scene */ scene?: number; /** * An array of scenes */ scenes?: IScene[]; /** * An array of skins. A skin is defined by joints and matrices */ skins?: ISkin[]; /** * An array of textures */ textures?: ITexture[]; }
the_stack
import * as assert from 'assert'; import { IIdentityProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { CompressibleObjectTree, ICompressibleTreeRenderer, ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; suite('ObjectTree', function () { suite('TreeNavigator', function () { let tree: ObjectTree<number>; let filter = (_: number) => true; setup(() => { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const delegate = new class implements IListVirtualDelegate<number> { getHeight() { return 20; } getTemplateId(): string { return 'default'; } }; const renderer = new class implements ITreeRenderer<number, void, HTMLElement> { readonly templateId = 'default'; renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: ITreeNode<number, void>, index: number, templateData: HTMLElement): void { templateData.textContent = `${element.element}`; } disposeTemplate(): void { } }; tree = new ObjectTree<number>('test', container, delegate, [renderer], { filter: { filter: (el) => filter(el) } }); tree.layout(200); }); teardown(() => { tree.dispose(); filter = (_: number) => true; }); test('should be able to navigate', () => { tree.setChildren(null, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); const navigator = tree.navigate(); assert.strictEqual(navigator.current(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.current(), 0); assert.strictEqual(navigator.next(), 10); assert.strictEqual(navigator.current(), 10); assert.strictEqual(navigator.next(), 11); assert.strictEqual(navigator.current(), 11); assert.strictEqual(navigator.next(), 12); assert.strictEqual(navigator.current(), 12); assert.strictEqual(navigator.next(), 1); assert.strictEqual(navigator.current(), 1); assert.strictEqual(navigator.next(), 2); assert.strictEqual(navigator.current(), 2); assert.strictEqual(navigator.previous(), 1); assert.strictEqual(navigator.current(), 1); assert.strictEqual(navigator.previous(), 12); assert.strictEqual(navigator.previous(), 11); assert.strictEqual(navigator.previous(), 10); assert.strictEqual(navigator.previous(), 0); assert.strictEqual(navigator.previous(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.next(), 10); assert.strictEqual(navigator.first(), 0); assert.strictEqual(navigator.last(), 2); }); test('should skip collapsed nodes', () => { tree.setChildren(null, [ { element: 0, collapsed: true, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); const navigator = tree.navigate(); assert.strictEqual(navigator.current(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.next(), 1); assert.strictEqual(navigator.next(), 2); assert.strictEqual(navigator.next(), null); assert.strictEqual(navigator.previous(), 2); assert.strictEqual(navigator.previous(), 1); assert.strictEqual(navigator.previous(), 0); assert.strictEqual(navigator.previous(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.first(), 0); assert.strictEqual(navigator.last(), 2); }); test('should skip filtered elements', () => { filter = el => el % 2 === 0; tree.setChildren(null, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); const navigator = tree.navigate(); assert.strictEqual(navigator.current(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.next(), 10); assert.strictEqual(navigator.next(), 12); assert.strictEqual(navigator.next(), 2); assert.strictEqual(navigator.next(), null); assert.strictEqual(navigator.previous(), 2); assert.strictEqual(navigator.previous(), 12); assert.strictEqual(navigator.previous(), 10); assert.strictEqual(navigator.previous(), 0); assert.strictEqual(navigator.previous(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.next(), 10); assert.strictEqual(navigator.first(), 0); assert.strictEqual(navigator.last(), 2); }); test('should be able to start from node', () => { tree.setChildren(null, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); const navigator = tree.navigate(1); assert.strictEqual(navigator.current(), 1); assert.strictEqual(navigator.next(), 2); assert.strictEqual(navigator.current(), 2); assert.strictEqual(navigator.previous(), 1); assert.strictEqual(navigator.current(), 1); assert.strictEqual(navigator.previous(), 12); assert.strictEqual(navigator.previous(), 11); assert.strictEqual(navigator.previous(), 10); assert.strictEqual(navigator.previous(), 0); assert.strictEqual(navigator.previous(), null); assert.strictEqual(navigator.next(), 0); assert.strictEqual(navigator.next(), 10); assert.strictEqual(navigator.first(), 0); assert.strictEqual(navigator.last(), 2); }); }); test('traits are preserved according to string identity', function () { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const delegate = new class implements IListVirtualDelegate<number> { getHeight() { return 20; } getTemplateId(): string { return 'default'; } }; const renderer = new class implements ITreeRenderer<number, void, HTMLElement> { readonly templateId = 'default'; renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: ITreeNode<number, void>, index: number, templateData: HTMLElement): void { templateData.textContent = `${element.element}`; } disposeTemplate(): void { } }; const identityProvider = new class implements IIdentityProvider<number> { getId(element: number): { toString(): string } { return `${element % 100}`; } }; const tree = new ObjectTree<number>('test', container, delegate, [renderer], { identityProvider }); tree.layout(200); tree.setChildren(null, [{ element: 0 }, { element: 1 }, { element: 2 }, { element: 3 }]); tree.setFocus([1]); assert.deepStrictEqual(tree.getFocus(), [1]); tree.setChildren(null, [{ element: 100 }, { element: 101 }, { element: 102 }, { element: 103 }]); assert.deepStrictEqual(tree.getFocus(), [101]); }); }); function getRowsTextContent(container: HTMLElement): string[] { const rows = [...container.querySelectorAll('.monaco-list-row')]; rows.sort((a, b) => parseInt(a.getAttribute('data-index')!) - parseInt(b.getAttribute('data-index')!)); return rows.map(row => row.querySelector('.monaco-tl-contents')!.textContent!); } suite('CompressibleObjectTree', function () { class Delegate implements IListVirtualDelegate<number> { getHeight() { return 20; } getTemplateId(): string { return 'default'; } } class Renderer implements ICompressibleTreeRenderer<number, void, HTMLElement> { readonly templateId = 'default'; renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(node: ITreeNode<number, void>, _: number, templateData: HTMLElement): void { templateData.textContent = `${node.element}`; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<number>, void>, _: number, templateData: HTMLElement): void { templateData.textContent = `${node.element.elements.join('/')}`; } disposeTemplate(): void { } } test('empty', function () { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const tree = new CompressibleObjectTree<number>('test', container, new Delegate(), [new Renderer()]); tree.layout(200); assert.strictEqual(getRowsTextContent(container).length, 0); }); test('simple', function () { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const tree = new CompressibleObjectTree<number>('test', container, new Delegate(), [new Renderer()]); tree.layout(200); tree.setChildren(null, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); assert.deepStrictEqual(getRowsTextContent(container), ['0', '10', '11', '12', '1', '2']); }); test('compressed', () => { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const tree = new CompressibleObjectTree<number>('test', container, new Delegate(), [new Renderer()]); tree.layout(200); tree.setChildren(null, [ { element: 1, children: [{ element: 11, children: [{ element: 111, children: [ { element: 1111 }, { element: 1112 }, { element: 1113 }, ] }] }] } ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11/111', '1111', '1112', '1113']); tree.setChildren(11, [ { element: 111 }, { element: 112 }, { element: 113 }, ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11', '111', '112', '113']); tree.setChildren(113, [ { element: 1131 } ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11', '111', '112', '113/1131']); tree.setChildren(1131, [ { element: 1132 } ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11', '111', '112', '113/1131/1132']); tree.setChildren(1131, [ { element: 1132 }, { element: 1133 }, ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11', '111', '112', '113/1131', '1132', '1133']); }); test('enableCompression', () => { const container = document.createElement('div'); container.style.width = '200px'; container.style.height = '200px'; const tree = new CompressibleObjectTree<number>('test', container, new Delegate(), [new Renderer()]); tree.layout(200); tree.setChildren(null, [ { element: 1, children: [{ element: 11, children: [{ element: 111, children: [ { element: 1111 }, { element: 1112 }, { element: 1113 }, ] }] }] } ]); assert.deepStrictEqual(getRowsTextContent(container), ['1/11/111', '1111', '1112', '1113']); tree.updateOptions({ compressionEnabled: false }); assert.deepStrictEqual(getRowsTextContent(container), ['1', '11', '111', '1111', '1112', '1113']); tree.updateOptions({ compressionEnabled: true }); assert.deepStrictEqual(getRowsTextContent(container), ['1/11/111', '1111', '1112', '1113']); }); });
the_stack
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions'; import { warnLog } from 'app/utils/log'; import { DestinyItemChangeResponse, DestinyItemComponent, DestinyProfileResponse, ItemLocation, } from 'bungie-api-ts/destiny2'; import produce, { Draft, original } from 'immer'; import _ from 'lodash'; import { Reducer } from 'redux'; import { ActionType, getType } from 'typesafe-actions'; import { setCurrentAccount } from '../accounts/actions'; import type { AccountsAction } from '../accounts/reducer'; import * as actions from './actions'; import { mergeCollectibles } from './d2-stores'; import { InventoryBuckets } from './inventory-buckets'; import { DimItem } from './item-types'; import { AccountCurrency, DimStore } from './store-types'; import { makeItem, makeItemSingle } from './store/d2-item-factory'; import { createItemIndex } from './store/item-index'; import { findItemsByBucket, getCurrentStore, getStore, getVault } from './stores-helpers'; // TODO: Should this be by account? Accounts need IDs export interface InventoryState { // The same stores as before - these are regenerated anew // when stores reload or change, so they're safe for now. // Updates to items need to deeply modify their store though. // TODO: ReadonlyArray<Readonly<DimStore>> readonly stores: DimStore[]; /** * Account-wide currencies (glimmer, shards, etc.). Silver is only available * while the player is in game. */ readonly currencies: AccountCurrency[]; readonly profileResponse?: DestinyProfileResponse; readonly profileError?: Error; /** * The inventoryItemIds of all items that are "new". */ readonly newItems: Set<string>; readonly newItemsLoaded: boolean; } export type InventoryAction = ActionType<typeof actions>; const initialState: InventoryState = { stores: [], currencies: [], newItems: new Set(), newItemsLoaded: false, }; export const inventory: Reducer<InventoryState, InventoryAction | AccountsAction> = ( state: InventoryState = initialState, action: InventoryAction | AccountsAction ): InventoryState => { switch (action.type) { case getType(actions.update): return updateInventory(state, action.payload); case getType(actions.charactersUpdated): return updateCharacters(state, action.payload); case getType(actions.itemMoved): { const { item, source, target, equip, amount } = action.payload; return produce(state, (draft) => itemMoved(draft, item, source.id, target.id, equip, amount)); } case getType(actions.itemLockStateChanged): { const { item, state: lockState, type } = action.payload; return produce(state, (draft) => itemLockStateChanged(draft, item, lockState, type)); } case getType(actions.awaItemChanged): { const { changes, defs, buckets } = action.payload; return produce(state, (draft) => awaItemChanged(draft, changes, defs, buckets)); } case getType(actions.error): return { ...state, profileError: action.payload, }; // *** New items *** case getType(actions.setNewItems): return { ...state, newItems: action.payload, newItemsLoaded: true, }; case getType(actions.clearNewItem): if (state.newItems.has(action.payload)) { const newItems = new Set(state.newItems); newItems.delete(action.payload); return { ...state, newItems, }; } else { return state; } case getType(actions.clearAllNewItems): return { ...state, newItems: new Set(), }; case getType(setCurrentAccount): return initialState; default: return state; } }; function updateInventory( state: InventoryState, { stores, profileResponse, currencies, }: { stores: DimStore[]; currencies: AccountCurrency[]; profileResponse?: DestinyProfileResponse; } ) { // TODO: we really want to decompose these, drive out all deep mutation // TODO: mark DimItem, DimStore properties as Readonly const newState = { ...state, stores, currencies, newItems: computeNewItems(state.stores, state.newItems, stores), profileError: undefined, }; if (profileResponse) { newState.profileResponse = profileResponse; } return newState; } /** * Merge in new top-level character info (stats, etc) */ function updateCharacters(state: InventoryState, characters: actions.CharacterInfo[]) { return { ...state, stores: state.stores.map((store) => { const character = characters.find((c) => c.characterId === store.id); if (!character) { return store; } const { characterId, ...characterInfo } = character; return { ...store, ...characterInfo, stats: { ...store.stats, ...characterInfo.stats, }, }; }), }; } /** Can an item be marked as new? */ const canBeNew = (item: DimItem) => item.equipment && item.id !== '0' && item.type !== 'Class'; /** * Given an old inventory, a new inventory, and all the items that were previously marked as new, * calculate the new set of new items. */ function computeNewItems(oldStores: DimStore[], oldNewItems: Set<string>, newStores: DimStore[]) { if (oldStores === newStores) { return oldNewItems; } // Get the IDs of all old items const allOldItems = new Set<string>(); for (const store of oldStores) { for (const item of store.items) { if (canBeNew(item)) { allOldItems.add(item.id); } } } // If we didn't have any items before, don't suddenly mark everything new if (!allOldItems.size) { return oldNewItems; } // Get the IDs of all new items const allNewItems = new Set<string>(); for (const store of newStores) { for (const item of store.items) { if (canBeNew(item)) { allNewItems.add(item.id); } } } const newItems = new Set<string>(); // Add all previous new items that are still in the new inventory for (const itemId of oldNewItems) { if (allNewItems.has(itemId)) { newItems.add(itemId); } } // Add all new items that aren't in old items for (const itemId of allNewItems) { if (!allOldItems.has(itemId)) { newItems.add(itemId); } } return setsEqual(newItems, oldNewItems) ? oldNewItems : newItems; } /** * Compute if two sets are equal by seeing that every item of each set is present in the other. */ function setsEqual<T>(first: Set<T>, second: Set<T>) { if (first.size !== second.size) { return false; } let equal = true; for (const itemId of first) { if (!second.has(itemId)) { equal = false; break; } } if (equal) { for (const itemId of second) { if (!first.has(itemId)) { equal = false; break; } } } return equal; } /** * Update our item and store models after an item has been moved (or equipped/dequipped). */ function itemMoved( draft: Draft<InventoryState>, item: DimItem, sourceStoreId: string, targetStoreId: string, equip: boolean, amount: number ): void { // Refresh all the items - they may have been reloaded! const stores = draft.stores; const source = getStore(stores, sourceStoreId); const target = getStore(stores, targetStoreId); if (!source || !target) { warnLog('move', 'Either source or target store not found', source, target); return; } item = source.items.find( (i) => i.hash === item.hash && i.id === item.id && i.location.hash === item.location.hash )!; if (!item) { warnLog('move', 'Moved item not found', item); return; } // If we've moved to a new place if (source.id !== target.id || item.location.inPostmaster) { // We handle moving stackable and nonstackable items almost exactly the same! const stackable = item.maxStackSize > 1; // Items to be decremented const sourceItems = stackable ? // For stackables, pull from all the items as a pool _.sortBy( findItemsByBucket(source, item.location.hash).filter( (i) => i.hash === item.hash && i.id === item.id ), (i) => i.amount ) : // Otherwise we're moving the exact item we passed in [item]; // Items to be incremented. There's really only ever at most one of these, but // it's easier to deal with as a list. An empty list means we'll vivify a new item there. const targetItems = stackable ? _.sortBy( findItemsByBucket(target, item.bucket.hash).filter( (i) => i.hash === item.hash && i.id === item.id && // Don't consider full stacks as targets i.amount !== i.maxStackSize ), (i) => i.amount ) : []; // moveAmount could be more than maxStackSize if there is more than one stack on a character! const moveAmount = amount || item.amount || 1; let addAmount = moveAmount; let removeAmount = moveAmount; let removedSourceItem = false; // Remove inventory from the source while (removeAmount > 0) { const sourceItem = sourceItems.shift(); if (!sourceItem) { warnLog('move', 'Source item missing', item); return; } const amountToRemove = Math.min(removeAmount, sourceItem.amount); sourceItem.amount -= amountToRemove; // Completely remove the source item if (sourceItem.amount <= 0 && removeItem(source, sourceItem)) { removedSourceItem = sourceItem.index === item.index; } removeAmount -= amountToRemove; } // Add inventory to the target (destination) let targetItem = item; while (addAmount > 0) { targetItem = targetItems.shift()!; if (!targetItem) { targetItem = item; if (!removedSourceItem) { // This assumes (as we shouldn't) that we have no nested mutable state in the item targetItem = { ...item }; targetItem.index = createItemIndex(targetItem); } removedSourceItem = false; // only move without cloning once targetItem.amount = 0; // We'll increment amount below if (targetItem.location.inPostmaster) { targetItem.location = targetItem.bucket; } addItem(target, targetItem); } const amountToAdd = Math.min(addAmount, targetItem.maxStackSize - targetItem.amount); targetItem.amount += amountToAdd; addAmount -= amountToAdd; } item = targetItem; // The item we're operating on switches to the last target } if (equip) { for (const i of target.items) { // Set equipped for all items in the bucket if (i.location.hash === item.bucket.hash) { i.equipped = i.index === item.index; } } } } function itemLockStateChanged( draft: Draft<InventoryState>, item: DimItem, state: boolean, type: 'lock' | 'track' ) { const source = getStore(draft.stores, item.owner); if (!source) { warnLog('move', 'Store', item.owner, 'not found'); return; } // Only instanced items can be locked/tracked item = source.items.find((i) => i.id === item.id)!; if (!item) { warnLog('move', 'Item not found in stores', item); return; } if (type === 'lock') { item.locked = state; } else if (type === 'track') { item.tracked = state; } } /** * Handle the changes that come from messing with perks/sockets via AWA. The item * itself is recreated, while various currencies and tokens get consumed or created. */ function awaItemChanged( draft: Draft<InventoryState>, changes: DestinyItemChangeResponse, defs: D2ManifestDefinitions, buckets: InventoryBuckets ) { const { stores, profileResponse } = original(draft)!; const mergedCollectibles = profileResponse ? mergeCollectibles(profileResponse.profileCollectibles, profileResponse.characterCollectibles) : {}; const item = makeItemSingle(defs, buckets, changes.item, stores, mergedCollectibles); // Replace item if (!item) { warnLog('awaChange', 'No item produced from change'); return; } const owner = getStore(draft.stores, item.owner); if (!owner) { return; } const sourceIndex = owner.items.findIndex((i) => i.index === item.index); if (sourceIndex >= 0) { owner.items[sourceIndex] = item; } else { addItem(owner, item); } const getSource = (component: DestinyItemComponent) => { let realOwner = owner; if (component.location === ItemLocation.Vault) { // I don't think this can happen realOwner = getVault(draft.stores)! as Draft<DimStore>; } else { const itemDef = defs.InventoryItem.get(component.itemHash); if (itemDef.inventory && buckets.byHash[itemDef.inventory.bucketTypeHash].accountWide) { realOwner = getCurrentStore(draft.stores)!; } } return realOwner; }; // Remove items // TODO: Question - does the API just completely remove a stack and add a new stack, or does it just // say it deleted a stack representing the difference? for (const removedItemComponent of changes.removedInventoryItems) { // Currencies (glimmer, shards) are easy! const currency = draft.currencies.find((c) => c.itemHash === removedItemComponent.itemHash); if (currency) { currency.quantity = Math.max(0, currency.quantity - removedItemComponent.quantity); } else if (removedItemComponent.itemInstanceId) { for (const store of draft.stores) { const removedItemIndex = store.items.findIndex( (i) => i.id === removedItemComponent.itemInstanceId ); if (removedItemIndex >= 0) { store.items.splice(removedItemIndex, 1); break; } } } else { // uninstanced (stacked, likely) item. const source = getSource(removedItemComponent); const sourceItems = _.sortBy( source.items.filter((i) => i.hash === removedItemComponent.itemHash), (i) => i.amount ); // TODO: refactor! let removeAmount = removedItemComponent.quantity; // Remove inventory from the source while (removeAmount > 0) { const sourceItem = sourceItems.shift(); if (!sourceItem) { warnLog('move', 'Source item missing', item, removedItemComponent); return; } const amountToRemove = Math.min(removeAmount, sourceItem.amount); sourceItem.amount -= amountToRemove; if (sourceItem.amount <= 0) { // Completely remove the source item removeItem(source, sourceItem); } removeAmount -= amountToRemove; } } } // Add items for (const addedItemComponent of changes.addedInventoryItems) { // Currencies (glimmer, shards) are easy! const currency = draft.currencies.find((c) => c.itemHash === addedItemComponent.itemHash); if (currency) { const max = defs.InventoryItem.get(addedItemComponent.itemHash).inventory?.maxStackSize || Number.MAX_SAFE_INTEGER; currency.quantity = Math.min(max, currency.quantity + addedItemComponent.quantity); } else if (addedItemComponent.itemInstanceId) { const addedOwner = getSource(addedItemComponent); const addedItem = makeItem( defs, buckets, undefined, addedItemComponent, addedOwner, mergedCollectibles ); if (addedItem) { addItem(addedOwner, addedItem); } } else { // Uninstanced (probably stacked) item const target = getSource(addedItemComponent); const targetItems = _.sortBy( target.items.filter((i) => i.hash === addedItemComponent.itemHash), (i) => i.amount ); let addAmount = addedItemComponent.quantity; const addedItem = makeItem( defs, buckets, undefined, addedItemComponent, target, mergedCollectibles ); if (!addedItem) { continue; } // TODO: refactor out "increment/decrement item amounts"? while (addAmount > 0) { let targetItem = targetItems.shift(); if (!targetItem) { targetItem = addedItem; targetItem.amount = 0; // We'll increment amount below addItem(target, targetItem); } const amountToAdd = Math.min(addAmount, targetItem.maxStackSize - targetItem.amount); targetItem.amount += amountToAdd; addAmount -= amountToAdd; } } } } // Remove an item from this store. Returns whether it actually removed anything. function removeItem(store: Draft<DimStore>, item: Draft<DimItem>) { // Completely remove the source item const sourceIndex = store.items.findIndex((i: DimItem) => item.index === i.index); if (sourceIndex >= 0) { store.items.splice(sourceIndex, 1); return true; } return false; } function addItem(store: Draft<DimStore>, item: Draft<DimItem>) { item.owner = store.id; // Originally this was just "store.items.push(item)" but it caused Immer to think we had circular references store.items = [...store.items, item]; }
the_stack
import * as React from "react"; import { PlaceholderComponent, DefaultComponentNames } from "../api/registry/component"; import { DEFAULT_TOOLBAR_SIZE } from "../components/toolbar"; import { ToolbarContainer } from "../containers/toolbar"; import { ViewerApiShim } from "../containers/viewer-shim"; import { ModalLauncher } from "../containers/modal-launcher"; import { FlyoutRegionContainer } from "../containers/flyout-region"; import { RndModalDialog } from "../components/modal-dialog"; import { tr } from "../api/i18n"; import { RuntimeMap } from "../api/contracts/runtime-map"; import { IConfigurationReducerState, ITemplateReducerState, IViewerCapabilities } from "../api/common"; import { InitWarningDisplay } from "../containers/init-warning-display"; import { ActionType } from '../constants/actions'; import { ViewerAction } from '../actions/defs'; import { useCommonTemplateState } from './hooks'; import { useTemplateInitialInfoPaneWidth, useTemplateInitialTaskPaneWidth } from '../containers/hooks'; import { setLegendVisibility, setSelectionPanelVisibility, setTaskPaneVisibility } from '../actions/template'; import { useActiveMapState } from '../containers/hooks-mapguide'; import { useActiveMapSubjectLayer } from "../containers/hooks-generic"; function aquaTemplateReducer(origState: ITemplateReducerState, state: ITemplateReducerState, action: ViewerAction): ITemplateReducerState { switch (action.type) { case ActionType.MAP_SET_SELECTION: { //This is the only template that does not conform to the selection/legend/taskpane is a mutually //exclusive visible set. We take advantage of the custom template reducer function to apply the //correct visibility state against the *original state* effectively discarding whatever the root //template reducer has done against this action. const { selection } = action.payload; if (selection && selection.SelectedFeatures) { if (selection.SelectedFeatures.SelectedLayer.length && origState.autoDisplaySelectionPanelOnSelection) { return { ...origState, ...{ selectionPanelVisible: true } } } } return state; //No action taken: Return "current" state } case ActionType.MAP_ADD_CLIENT_SELECTED_FEATURE: { //This is the only template that does not conform to the selection/legend/taskpane is a mutually //exclusive visible set. We take advantage of the custom template reducer function to apply the //correct visibility state against the *original state* effectively discarding whatever the root //template reducer has done against this action. const { feature } = action.payload; if (feature?.properties) { return { ...origState, ...{ selectionPanelVisible: true } } } return state; //No action taken: Return "current" state } case ActionType.FUSION_SET_LEGEND_VISIBILITY: { const data = action.payload; if (typeof (data) == "boolean") { let state1: Partial<ITemplateReducerState> = { legendVisible: data }; return { ...state, ...state1 }; } } case ActionType.FUSION_SET_SELECTION_PANEL_VISIBILITY: { const data = action.payload; if (typeof (data) == "boolean") { let state1: Partial<ITemplateReducerState> = { selectionPanelVisible: data }; return { ...state, ...state1 }; } } case ActionType.TASK_INVOKE_URL: { let state1: Partial<ITemplateReducerState> = { taskPaneVisible: true }; return { ...state, ...state1 }; } case ActionType.FUSION_SET_TASK_PANE_VISIBILITY: { const data = action.payload; if (typeof (data) == "boolean") { let state1: Partial<ITemplateReducerState> = { taskPaneVisible: data }; return { ...state, ...state1 }; } } } return state; } const SELECTION_DIALOG_HEIGHT = 300; const LEGEND_DIALOG_HEIGHT = 400; const TASK_DIALOG_HEIGHT = 500; const STATUS_BAR_HEIGHT = 18; /** * A viewer template that resembles the Aqua Fusion template */ export const AquaTemplateLayout = () => { const { locale, capabilities, showSelection, showLegend, showTaskPane, dispatch } = useCommonTemplateState(aquaTemplateReducer); const map = useActiveMapState(); const subject = useActiveMapSubjectLayer(); const hideLegend = () => dispatch(setLegendVisibility(false)); const hideSelection = () => dispatch(setSelectionPanelVisibility(false)); const hideTaskPane = () => dispatch(setTaskPaneVisibility(false)); const onHideTaskPane = () => hideTaskPane(); const onHideLegend = () => hideLegend(); const onHideSelection = () => hideSelection(); let hasTaskPane = false; let hasStatusBar = false; let hasNavigator = false; let hasSelectionPanel = false; let hasLegend = false; if (capabilities) { hasTaskPane = capabilities.hasTaskPane; hasStatusBar = capabilities.hasStatusBar; hasNavigator = capabilities.hasNavigator; hasSelectionPanel = capabilities.hasSelectionPanel; hasLegend = capabilities.hasLegend; } const bottomOffset = hasStatusBar ? STATUS_BAR_HEIGHT : 0; let left = DEFAULT_TOOLBAR_SIZE; let right = 0; /* if (hasLegend || hasSelectionPanel) { left = sbWidth; } if (hasTaskPane) { right = tpWidth; }*/ const TB_Z_INDEX = 0; const initInfoPaneWidth = useTemplateInitialInfoPaneWidth(); const initTaskPaneWidth = useTemplateInitialTaskPaneWidth(); return <div style={{ width: "100%", height: "100%" }}> <ToolbarContainer id="FileMenu" containerClass="aqua-file-menu" containerStyle={{ position: "absolute", left: 0, top: 0, zIndex: TB_Z_INDEX, right: 0 }} /> <ToolbarContainer id="Toolbar" containerClass="aqua-toolbar" containerStyle={{ position: "absolute", left: 0, top: DEFAULT_TOOLBAR_SIZE, height: DEFAULT_TOOLBAR_SIZE, zIndex: TB_Z_INDEX, right: 0 }} /> <ToolbarContainer id="ToolbarVertical" containerClass="aqua-toolbar-vertical" vertical={true} containerStyle={{ position: "absolute", left: 0, top: ((DEFAULT_TOOLBAR_SIZE * 2) - 1), zIndex: TB_Z_INDEX, bottom: bottomOffset }} /> <div style={{ position: "absolute", left: left, top: (DEFAULT_TOOLBAR_SIZE * 2), bottom: bottomOffset, right: right }}> {(() => { //NOTE: We have to delay render this behind an IIFE because otherwise this component may be mounted with //sidebar elements not being ready, which may result in a distorted OL map when it mounts, requiring a updateSize() //call to fix const theMap = map ?? subject; if (theMap) { return <PlaceholderComponent id={DefaultComponentNames.Map} locale={locale} />; } })()} {(() => { if (hasNavigator) { return <PlaceholderComponent id={DefaultComponentNames.Navigator} locale={locale} />; } })()} </div> {(() => { if (hasStatusBar) { return <div className="aqua-status-bar" style={{ position: "absolute", left: 0, bottom: 0, right: 0, height: bottomOffset }}> <PlaceholderComponent id={DefaultComponentNames.MouseCoordinates} locale={locale} /> <PlaceholderComponent id={DefaultComponentNames.ScaleDisplay} locale={locale} /> <PlaceholderComponent id={DefaultComponentNames.SelectedFeatureCount} locale={locale} /> <PlaceholderComponent id={DefaultComponentNames.ViewSize} locale={locale} /> <PlaceholderComponent id={DefaultComponentNames.PoweredByMapGuide} locale={locale} /> </div>; } })()} <ViewerApiShim /> <ModalLauncher> {(() => { if (hasSelectionPanel) { return <RndModalDialog icon="th" locale={locale} isOpen={!!showSelection} onClose={onHideSelection} title={tr("TPL_TITLE_SELECTION_PANEL", locale)} x={40} y={500} width={initInfoPaneWidth} height={SELECTION_DIALOG_HEIGHT} disableYOverflow={true} enableInteractionMask={true}> {([, h]) => <PlaceholderComponent locale={locale} id={DefaultComponentNames.SelectionPanel} componentProps={{ maxHeight: h }} />} </RndModalDialog> } })()} {(() => { if (hasLegend) { return <RndModalDialog icon="layers" locale={locale} isOpen={!!showLegend} onClose={onHideLegend} title={tr("TPL_TITLE_LEGEND", locale)} x={40} y={70} width={initInfoPaneWidth} height={LEGEND_DIALOG_HEIGHT} enableInteractionMask={true}> {([, h]) => <PlaceholderComponent locale={locale} id={DefaultComponentNames.Legend} componentProps={{ inlineBaseLayerSwitcher: false, maxHeight: h }} />} </RndModalDialog> } })()} {(() => { if (hasTaskPane) { return <RndModalDialog icon="application" locale={locale} isOpen={!!showTaskPane} onClose={onHideTaskPane} width={initTaskPaneWidth} height={TASK_DIALOG_HEIGHT} title={tr("TPL_TITLE_TASKPANE", locale)} x={document.body.clientWidth - initTaskPaneWidth - 70} y={80} disableYOverflow={true} enableInteractionMask={false}> {([, h]) => <PlaceholderComponent locale={locale} id={DefaultComponentNames.TaskPane} componentProps={{ maxHeight: h - 15 /* some height breathing space */ }} />} </RndModalDialog>; } })()} </ModalLauncher> <FlyoutRegionContainer /> <InitWarningDisplay /> </div>; };
the_stack
import { AzureWizardExecuteStep, IActionContext } from '@microsoft/vscode-azext-utils'; import * as fse from 'fs-extra'; import * as path from 'path'; import { DebugConfiguration, MessageItem, TaskDefinition, WorkspaceFolder } from 'vscode'; import { deploySubpathSetting, extensionId, func, funcVersionSetting, gitignoreFileName, launchFileName, preDeployTaskSetting, ProjectLanguage, projectLanguageSetting, projectSubpathSetting, settingsFileName, tasksFileName } from '../../../constants'; import { ext } from '../../../extensionVariables'; import { FuncVersion } from '../../../FuncVersion'; import { localize } from '../../../localize'; import { confirmEditJsonFile, isPathEqual, isSubpath } from '../../../utils/fs'; import { nonNullProp } from '../../../utils/nonNull'; import { isMultiRootWorkspace } from '../../../utils/workspace'; import { IExtensionsJson } from '../../../vsCodeConfig/extensions'; import { getDebugConfigs, getLaunchVersion, ILaunchJson, isDebugConfigEqual, launchVersion, updateDebugConfigs, updateLaunchVersion } from '../../../vsCodeConfig/launch'; import { updateWorkspaceSetting } from '../../../vsCodeConfig/settings'; import { getTasks, getTasksVersion, ITask, ITasksJson, tasksVersion, updateTasks, updateTasksVersion } from '../../../vsCodeConfig/tasks'; import { IProjectWizardContext } from '../../createNewProject/IProjectWizardContext'; export abstract class InitVSCodeStepBase extends AzureWizardExecuteStep<IProjectWizardContext> { public priority: number = 20; protected preDeployTask?: string; protected settings: ISettingToAdd[] = []; public async execute(context: IProjectWizardContext): Promise<void> { await this.executeCore(context); const version: FuncVersion = nonNullProp(context, 'version'); context.telemetry.properties.projectRuntime = version; const language: ProjectLanguage = nonNullProp(context, 'language'); context.telemetry.properties.projectLanguage = language; context.telemetry.properties.isProjectInSubDir = String(isSubpath(context.workspacePath, context.projectPath)); const vscodePath: string = path.join(context.workspacePath, '.vscode'); await fse.ensureDir(vscodePath); await this.writeTasksJson(context, vscodePath, language); await this.writeLaunchJson(context, context.workspaceFolder, vscodePath, version); await this.writeSettingsJson(context, vscodePath, language, version); await this.writeExtensionsJson(context, vscodePath, language); // Remove '.vscode' from gitignore if applicable const gitignorePath: string = path.join(context.workspacePath, gitignoreFileName); if (await fse.pathExists(gitignorePath)) { let gitignoreContents: string = (await fse.readFile(gitignorePath)).toString(); gitignoreContents = gitignoreContents.replace(/^\.vscode(\/|\\)?\s*$/gm, ''); await fse.writeFile(gitignorePath, gitignoreContents); } } public shouldExecute(_context: IProjectWizardContext): boolean { return true; } protected abstract executeCore(context: IProjectWizardContext): Promise<void>; protected abstract getTasks(language: ProjectLanguage): TaskDefinition[]; protected getDebugConfiguration?(version: FuncVersion): DebugConfiguration; protected getRecommendedExtensions?(language: ProjectLanguage): string[]; protected setDeploySubpath(context: IProjectWizardContext, deploySubpath: string): string { deploySubpath = this.addSubDir(context, deploySubpath); this.settings.push({ key: deploySubpathSetting, value: deploySubpath }); return deploySubpath; } protected addSubDir(context: IProjectWizardContext, fsPath: string): string { const subDir: string = path.relative(context.workspacePath, context.projectPath); // always use posix for debug config return path.posix.join(subDir, fsPath); } private async writeTasksJson(context: IProjectWizardContext, vscodePath: string, language: ProjectLanguage): Promise<void> { const newTasks: TaskDefinition[] = this.getTasks(language); for (const task of newTasks) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access let cwd: string = (task.options && task.options.cwd) || '.'; cwd = this.addSubDir(context, cwd); if (!isPathEqual(cwd, '.')) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment task.options = task.options || {}; // always use posix for debug config // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access task.options.cwd = path.posix.join('${workspaceFolder}', cwd); } } const versionMismatchError: Error = new Error(localize('versionMismatchError', 'The version in your {0} must be "{1}" to work with Azure Functions.', tasksFileName, tasksVersion)); // Use VS Code api to update config if folder is open and it's not a multi-root workspace (https://github.com/Microsoft/vscode-azurefunctions/issues/1235) // The VS Code api is better for several reasons, including: // 1. It handles comments in json files // 2. It sends the 'onDidChangeConfiguration' event if (context.workspaceFolder && !isMultiRootWorkspace()) { const currentVersion: string | undefined = getTasksVersion(context.workspaceFolder); if (!currentVersion) { await updateTasksVersion(context.workspaceFolder, tasksVersion); } else if (currentVersion !== tasksVersion) { throw versionMismatchError; } await updateTasks(context.workspaceFolder, await this.insertNewTasks(context, getTasks(context.workspaceFolder), newTasks)); } else { // otherwise manually edit json const tasksJsonPath: string = path.join(vscodePath, tasksFileName); await confirmEditJsonFile( context, tasksJsonPath, async (data: ITasksJson): Promise<ITasksJson> => { if (!data.version) { data.version = tasksVersion; } else if (data.version !== tasksVersion) { throw versionMismatchError; } data.tasks = await this.insertNewTasks(context, data.tasks, newTasks); return data; } ); } } private async insertNewTasks(context: IActionContext, existingTasks: ITask[] | undefined, newTasks: ITask[]): Promise<ITask[]> { existingTasks = existingTasks || []; // remove new tasks that have an identical existing task newTasks = newTasks.filter(t1 => { const t1String = JSON.stringify(t1); return !existingTasks?.some(t2 => t1String === JSON.stringify(t2)); }); const nonMatchingTasks: ITask[] = []; const matchingTaskLabels: string[] = []; for (const existingTask of existingTasks) { const existingLabel = this.getTaskLabel(existingTask); if (existingLabel && newTasks.some(newTask => existingLabel === this.getTaskLabel(newTask))) { matchingTaskLabels.push(existingLabel); } else { nonMatchingTasks.push(existingTask); } } if (matchingTaskLabels.length > 0) { const message = localize('confirmOverwriteTasks', 'This will overwrite the following tasks in your tasks.json: "{0}"', matchingTaskLabels.join('", "')); const overwrite: MessageItem = { title: localize('overwrite', 'Overwrite') }; await context.ui.showWarningMessage(message, { modal: true, stepName: 'confirmOverwriteTasks' }, overwrite) } return nonMatchingTasks.concat(...newTasks); } private getTaskLabel(task: ITask): string | undefined { switch (task.type) { case func: return `${task.type}: ${task.command}`; case 'shell': case 'process': return task.label; default: return undefined; } } private async writeLaunchJson(context: IActionContext, folder: WorkspaceFolder | undefined, vscodePath: string, version: FuncVersion): Promise<void> { if (this.getDebugConfiguration) { const newDebugConfig: DebugConfiguration = this.getDebugConfiguration(version); const versionMismatchError: Error = new Error(localize('versionMismatchError', 'The version in your {0} must be "{1}" to work with Azure Functions.', launchFileName, launchVersion)); // Use VS Code api to update config if folder is open and it's not a multi-root workspace (https://github.com/Microsoft/vscode-azurefunctions/issues/1235) // The VS Code api is better for several reasons, including: // 1. It handles comments in json files // 2. It sends the 'onDidChangeConfiguration' event if (folder && !isMultiRootWorkspace()) { const currentVersion: string | undefined = getLaunchVersion(folder); if (!currentVersion) { await updateLaunchVersion(folder, launchVersion); } else if (currentVersion !== launchVersion) { throw versionMismatchError; } await updateDebugConfigs(folder, this.insertLaunchConfig(getDebugConfigs(folder), newDebugConfig)); } else { // otherwise manually edit json const launchJsonPath: string = path.join(vscodePath, launchFileName); await confirmEditJsonFile( context, launchJsonPath, (data: ILaunchJson): ILaunchJson => { if (!data.version) { data.version = launchVersion; } else if (data.version !== launchVersion) { throw versionMismatchError; } data.configurations = this.insertLaunchConfig(data.configurations, newDebugConfig); return data; } ); } } } private insertLaunchConfig(existingConfigs: DebugConfiguration[] | undefined, newConfig: DebugConfiguration): DebugConfiguration[] { existingConfigs = existingConfigs || []; existingConfigs = existingConfigs.filter(l1 => !isDebugConfigEqual(l1, newConfig)); existingConfigs.push(newConfig); return existingConfigs; } private async writeSettingsJson(context: IProjectWizardContext, vscodePath: string, language: string, version: FuncVersion): Promise<void> { const settings: ISettingToAdd[] = this.settings.concat( { key: projectLanguageSetting, value: language }, { key: funcVersionSetting, value: version }, // We want the terminal to be open after F5, not the debug console (Since http triggers are printed in the terminal) { prefix: 'debug', key: 'internalConsoleOptions', value: 'neverOpen' } ); // Add "projectSubpath" setting if project is far enough down that we won't auto-detect it if (path.posix.relative(context.projectPath, context.workspacePath).startsWith('../..')) { settings.push({ key: projectSubpathSetting, value: path.posix.relative(context.workspacePath, context.projectPath) }); } if (this.preDeployTask) { settings.push({ key: preDeployTaskSetting, value: this.preDeployTask }); } if (context.workspaceFolder) { // Use VS Code api to update config if folder is open for (const setting of settings) { await updateWorkspaceSetting(setting.key, setting.value, context.workspacePath, setting.prefix); } } else { // otherwise manually edit json const settingsJsonPath: string = path.join(vscodePath, settingsFileName); await confirmEditJsonFile( context, settingsJsonPath, (data: {}): {} => { for (const setting of settings) { const key: string = `${setting.prefix || ext.prefix}.${setting.key}`; data[key] = setting.value; } return data; } ); } } private async writeExtensionsJson(context: IActionContext, vscodePath: string, language: ProjectLanguage): Promise<void> { const extensionsJsonPath: string = path.join(vscodePath, 'extensions.json'); await confirmEditJsonFile( context, extensionsJsonPath, (data: IExtensionsJson): {} => { const recommendations: string[] = [extensionId]; if (this.getRecommendedExtensions) { recommendations.push(...this.getRecommendedExtensions(language)); } if (data.recommendations) { recommendations.push(...data.recommendations); } // de-dupe array data.recommendations = recommendations.filter((rec: string, index: number) => recommendations.indexOf(rec) === index); return data; } ); } } interface ISettingToAdd { key: string; value: string | {}; prefix?: string; }
the_stack
import BSON from "bson"; import { CoreStitchServiceClientImpl, Stream } from "mongodb-stitch-core-sdk"; import { anything, capture, instance, mock, verify, when } from "ts-mockito"; import { CoreRemoteMongoClientImpl, CoreRemoteMongoCollectionImpl, RemoteInsertManyResult } from "../src"; import ResultDecoders from "../src/internal/ResultDecoders"; import { getCollection } from "./TestUtils"; describe("CoreRemoteMongoCollection", () => { it("should get namespace", () => { const coll1 = getCollection(); expect(coll1.namespace).toEqual("dbName1.collName1"); const coll2 = getCollection("collName2"); expect(coll2.namespace).toEqual("dbName1.collName2"); }); it("should test count", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); when(serviceMock.callFunction(anything(), anything())).thenResolve( 42 ); expect(await coll.count()).toEqual(42); const [funcNameArg, funcArgsArg, resultClassArg]: any = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("count"); expect((funcArgsArg as any[]).length).toBe(1); const expectedArgs = { collection: "collName1", database: "dbName1", query: {} }; expect(funcArgsArg[0]).toEqual(expectedArgs); expect(resultClassArg).toBeUndefined(); const expectedFilter = { one: 23 }; expect(await coll.count(expectedFilter, { limit: 5 })).toEqual(42); verify(serviceMock.callFunction(anything(), anything())).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any = capture( serviceMock.callFunction ).last(); expect(funcNameArg2).toEqual("count"); expect(funcArgsArg2.length).toBe(1); expectedArgs.database = "dbName1"; expectedArgs.collection = "collName1"; expectedArgs.query = expectedFilter; expectedArgs.limit = 5; expect(funcArgsArg2[0]).toEqual(expectedArgs); expect(resultClassArg2).toBeUndefined(); // Should pass along errors when(serviceMock.callFunction(anything(), anything())).thenReject( new Error("whoops") ); try { await coll.count(); fail(); } catch (_) { // Do nothing } }); it("should find", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc1 = { one: 2 }; const doc2 = { three: 4 }; const docs = [doc1, doc2]; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(docs); let iter = await coll.find().iterator(); expect(iter.next().value).toEqual(docs[0]); expect(iter.next().value).toEqual(docs[1]); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("find"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = { collection: "collName1", database: "dbName1", query: {} }; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedFilter = { one: 23 }; const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; iter = await coll .find(expectedFilter, { limit: 5, projection: expectedProject, sort: expectedSort }) .iterator(); expect(iter.next().value).toEqual(docs[0]); expect(iter.next().value).toEqual(docs[1]); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("find").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.query = expectedFilter; expectedArgs.project = expectedProject; expectedArgs.sort = expectedSort; expectedArgs.limit = 5; expect(funcArgsArg2[0]).toEqual(expectedArgs); when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve([1, 2, 3]); iter = await coll.find(expectedFilter).iterator(); expect(iter.next().value).toEqual(1); expect(iter.next().value).toEqual(2); expect(iter.next().value).toEqual(3); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.find().first(); fail(); } catch (_) { // Do nothing } }); it("should find one", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc = { one: 1, two: 2 }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(doc); let result = await coll.findOne(); expect(result).toBeDefined(); expect(result).toEqual(doc); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("findOne"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = { collection: "collName1", database: "dbName1", query: {} }; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedFilter = { one: 1 }; const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; result = await coll.findOne(expectedFilter, {projection: expectedProject, sort: expectedSort}); expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOne").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.query = expectedFilter; expectedArgs.project = expectedProject; expectedArgs.sort = expectedSort; expect(funcArgsArg2[0]).toEqual(expectedArgs); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.find().first(); fail(); } catch (_) { // Do nothing } }); it("should find one and update", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc = { one: 1, two: 2 }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(doc); let result = await coll.findOneAndUpdate({}, {}); expect(result).toBeDefined(); expect(result).toEqual(doc); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("findOneAndUpdate"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = { collection: "collName1", database: "dbName1", filter: {}, update: {}, }; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedFilter = { one: 1 }; const expectedUpdate = { $inc: {one: 3} } const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; let expectedOptions = { projection : expectedProject, returnNewDocument: true, sort: expectedSort, upsert: true, } result = await coll.findOneAndUpdate(expectedFilter, expectedUpdate, expectedOptions) expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOneAndUpdate").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.filter = expectedFilter; expectedArgs.projection = expectedProject; expectedArgs.sort = expectedSort; expectedArgs.update = expectedUpdate; expectedArgs.upsert = true; expectedArgs.returnNewDocument = true; expect(funcArgsArg2[0]).toEqual(expectedArgs); expectedOptions = { projection : expectedProject, returnNewDocument: false, sort: expectedSort, upsert: false, } result = await coll.findOneAndUpdate(expectedFilter, expectedUpdate, expectedOptions) expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(3); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOneAndUpdate").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); delete expectedArgs.upsert; delete expectedArgs.returnNewDocument; expect(funcArgsArg2[0]).toEqual(expectedArgs); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.findOneAndUpdate({}, {}) fail(); } catch (_) { // Do nothing } }); it("should find one and replace", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc = { one: 1, two: 2 }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(doc); let result = await coll.findOneAndReplace({}, {}); expect(result).toBeDefined(); expect(result).toEqual(doc); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("findOneAndReplace"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = { collection: "collName1", database: "dbName1", filter: {}, update: {}, }; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedFilter = { one: 1 }; const expectedUpdate = { hello: 2 } const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; let expectedOptions = { projection : expectedProject, returnNewDocument: true, sort: expectedSort, upsert: true, } result = await coll.findOneAndReplace(expectedFilter, expectedUpdate, expectedOptions) expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOneAndReplace").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.filter = expectedFilter; expectedArgs.projection = expectedProject; expectedArgs.sort = expectedSort; expectedArgs.update = expectedUpdate; expectedArgs.upsert = true; expectedArgs.returnNewDocument = true; expect(funcArgsArg2[0]).toEqual(expectedArgs); expectedOptions = { projection : expectedProject, returnNewDocument: false, sort: expectedSort, upsert: false, } result = await coll.findOneAndReplace(expectedFilter, expectedUpdate, expectedOptions) expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(3); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOneAndReplace").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); delete expectedArgs.upsert; delete expectedArgs.returnNewDocument; expect(funcArgsArg2[0]).toEqual(expectedArgs); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.findOneAndReplace({}, {}) fail(); } catch (_) { // Do nothing } }); it("should find one and delete", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc = { one: 1, two: 2 }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(doc); let result = await coll.findOneAndDelete({}); expect(result).toBeDefined(); expect(result).toEqual(doc); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("findOneAndDelete"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = { collection: "collName1", database: "dbName1", filter: {}, }; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedFilter = { one: 1 }; const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; const expectedOptions = { projection : expectedProject, sort: expectedSort, } result = await coll.findOneAndDelete(expectedFilter, expectedOptions) expect(result).toEqual(doc); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("findOneAndDelete").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.filter = expectedFilter; expectedArgs.projection = expectedProject; expectedArgs.sort = expectedSort; expect(funcArgsArg2[0]).toEqual(expectedArgs); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.findOneAndUpdate({}, {}) fail(); } catch (_) { // Do nothing } }); it("should aggregate", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const doc1 = { one: 2 }; const doc2 = { three: 4 }; const docs = [doc1, doc2]; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve(docs); let iter = await coll.aggregate([]).iterator(); expect(iter.next().value).toEqual(docs[0]); expect(iter.next().value).toEqual(docs[1]); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect(funcNameArg).toEqual("aggregate"); expect(funcArgsArg.length).toEqual(1); const expectedArgs = {}; expectedArgs.database = "dbName1"; expectedArgs.collection = "collName1"; expectedArgs.pipeline = []; expect(funcArgsArg[0]).toEqual(expectedArgs); const expectedProject = { two: "four" }; const expectedSort = { _id: -1 }; iter = await coll.aggregate([{ $match: 1 }, { sort: 2 }]).iterator(); const expectedPipeline = [{ $match: 1 }, { sort: 2 }]; expect(iter.next().value).toEqual(docs[0]); expect(iter.next().value).toEqual(docs[1]); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("aggregate").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.pipeline = expectedPipeline; expect(expectedArgs).toEqual(funcArgsArg2[0]); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.aggregate([]).first(); fail(); } catch (_) { // Do nothing } }); it("should insert one", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id = new BSON.ObjectID(); const doc1 = { one: 2, _id: id.toHexString() }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ insertedId: id }); const result = await coll.insertOne(doc1); expect(id).toEqual(result.insertedId); expect(id.toHexString()).toEqual(doc1._id); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("insertOne").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = { collection: "collName1", database: "dbName1", document: doc1 }; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteInsertOneResultDecoder).toEqual(resultClassArg); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.insertOne({}); fail(); } catch (_) { // Do nothing } }); it("should insert many", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id1 = new BSON.ObjectID(); const id2 = new BSON.ObjectID(); const doc1 = { one: 2, _id: id1.toHexString() }; const doc2 = { three: 4, _id: id2.toHexString() }; const ids = { 0: id1.toHexString(), 1: id2.toHexString() }; when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ insertedIds: ids }); const result = await coll.insertMany([doc1, doc2]); expect(ids).toEqual(result.insertedIds); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("insertMany").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = { collection: "collName1", database: "dbName1", documents: [doc1, doc2] }; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteInsertManyResultDecoder).toEqual( resultClassArg ); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.insertMany([{}]); fail(); } catch (_) { // Do nothing } }); it("should delete one", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ deletedCount: 1 }); const expectedFilter = { one: 2 }; const result = await coll.deleteOne(expectedFilter); expect(1).toEqual(result.deletedCount); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("deleteOne").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = { collection: "collName1", database: "dbName1", query: expectedFilter }; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteDeleteResultDecoder).toEqual(resultClassArg); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.deleteOne({}); fail(); } catch (_) { // Do nothing } }); it("should delete many", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ deletedCount: 1 }); const expectedFilter = { one: 2 }; const result = await coll.deleteMany(expectedFilter); expect(1).toEqual(result.deletedCount); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("deleteMany").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = { collection: "collName1", database: "dbName1", query: expectedFilter }; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteDeleteResultDecoder).toEqual(resultClassArg); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.deleteMany({}); fail(); } catch (_) { // Do nothing } }); it("should update one", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id = new BSON.ObjectID(); when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ matchedCount: 1, modifiedCount: 1, upsertedId: id.toHexString() }); const expectedFilter = { one: 2 }; const expectedUpdate = { three: 4 }; let result = await coll.updateOne(expectedFilter, expectedUpdate); expect(1).toEqual(result.matchedCount); expect(1).toEqual(result.modifiedCount); expect(id.toHexString()).toEqual(result.upsertedId); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("updateOne").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = { collection: "collName1", database: "dbName1", query: expectedFilter, update: expectedUpdate }; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteUpdateResultDecoder).toEqual(resultClassArg); result = await coll.updateOne(expectedFilter, expectedUpdate, { upsert: true }); expect(1).toEqual(result.matchedCount); expect(1).toEqual(result.modifiedCount); expect(id.toHexString()).toEqual(result.upsertedId); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("updateOne").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.upsert = true; expect(expectedArgs).toEqual(funcArgsArg2[0]); expect(ResultDecoders.remoteUpdateResultDecoder).toEqual(resultClassArg2); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.updateOne({}, {}); fail(); } catch (_) { // Do nothing } }); it("should update many", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id = new BSON.ObjectID(); when( serviceMock.callFunction(anything(), anything(), anything()) ).thenResolve({ matchedCount: 1, modifiedCount: 1, upsertedId: id.toHexString() }); const expectedFilter = { one: 2 }; const expectedUpdate = { three: 4 }; let result = await coll.updateMany(expectedFilter, expectedUpdate); expect(1).toEqual(result.matchedCount); expect(1).toEqual(result.modifiedCount); expect(id.toHexString()).toEqual(result.upsertedId); const [funcNameArg, funcArgsArg, resultClassArg]: any[] = capture( serviceMock.callFunction ).last(); expect("updateMany").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = {}; expectedArgs.database = "dbName1"; expectedArgs.collection = "collName1"; expectedArgs.query = expectedFilter; expectedArgs.update = expectedUpdate; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(ResultDecoders.remoteUpdateResultDecoder).toEqual(resultClassArg); result = await coll.updateMany(expectedFilter, expectedUpdate, { upsert: true }); expect(1).toEqual(result.matchedCount); expect(1).toEqual(result.modifiedCount); expect(id.toHexString()).toEqual(result.upsertedId); verify( serviceMock.callFunction(anything(), anything(), anything()) ).times(2); const [funcNameArg2, funcArgsArg2, resultClassArg2]: any[] = capture( serviceMock.callFunction ).last(); expect("updateMany").toEqual(funcNameArg2); expect(1).toEqual(funcArgsArg2.length); expectedArgs.upsert = true; expect(expectedArgs).toEqual(funcArgsArg2[0]); expect(ResultDecoders.remoteUpdateResultDecoder).toEqual(resultClassArg); // Should pass along errors when( serviceMock.callFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.updateMany({}, {}); fail(); } catch (_) { // Do nothing } }); it("should watch", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id = new BSON.ObjectID(); const fakeStream = new Stream( undefined, undefined ); when( serviceMock.streamFunction(anything(), anything(), anything()) ).thenResolve(fakeStream); // Watch with array of ids let result = await coll.watch([id]); expect(result).toBe(fakeStream); let [funcNameArg, funcArgsArg, decoderArg]: any[] = capture( serviceMock.streamFunction ).last(); expect("watch").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); let expectedArgs: object = { collection: "collName1", database: "dbName1", ids: [id], useCompactEvents: false } expect(expectedArgs).toEqual(funcArgsArg[0]); expect(decoderArg).toBeInstanceOf(ResultDecoders.ChangeEventDecoder); // Watch with filter result = await coll.watch({foo: "bar"}); expect(result).toBe(fakeStream); [funcNameArg, funcArgsArg, decoderArg] = capture( serviceMock.streamFunction ).last(); expect("watch").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); expectedArgs = { collection: "collName1", database: "dbName1", filter: {foo: "bar"}, useCompactEvents: false } expect(expectedArgs).toEqual(funcArgsArg[0]); expect(decoderArg).toBeInstanceOf(ResultDecoders.ChangeEventDecoder); // Watch collection (no argument) result = await coll.watch(); expect(result).toBe(fakeStream); [funcNameArg, funcArgsArg, decoderArg] = capture( serviceMock.streamFunction ).last(); expect("watch").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); expectedArgs = { collection: "collName1", database: "dbName1", useCompactEvents: false } expect(expectedArgs).toEqual(funcArgsArg[0]); expect(decoderArg).toBeInstanceOf(ResultDecoders.ChangeEventDecoder); // Watch collection (empty array of ids) result = await coll.watch([]); expect(result).toBe(fakeStream); [funcNameArg, funcArgsArg, decoderArg] = capture( serviceMock.streamFunction ).last(); expect("watch").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); expectedArgs = { collection: "collName1", database: "dbName1", useCompactEvents: false } expect(expectedArgs).toEqual(funcArgsArg[0]); expect(decoderArg).toBeInstanceOf(ResultDecoders.ChangeEventDecoder); verify( serviceMock.streamFunction(anything(), anything(), anything()) ).times(4); // Should pass along errors when( serviceMock.streamFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.watch([id]); fail(); } catch (_) { // Do nothing } }); it("should watchCompact", async () => { const serviceMock = mock(CoreStitchServiceClientImpl); const service = instance(serviceMock); const client = new CoreRemoteMongoClientImpl(service); const coll = getCollection(undefined, client); const id = new BSON.ObjectID(); const fakeStream = new Stream( undefined, undefined ); when( serviceMock.streamFunction(anything(), anything(), anything()) ).thenResolve(fakeStream); const result = await coll.watchCompact([id]); expect(result).toBe(fakeStream); const [funcNameArg, funcArgsArg, decoderArg]: any[] = capture( serviceMock.streamFunction ).last(); expect("watch").toEqual(funcNameArg); expect(1).toEqual(funcArgsArg.length); const expectedArgs = {}; expectedArgs.database = "dbName1"; expectedArgs.collection = "collName1"; expectedArgs.ids = [id]; expectedArgs.useCompactEvents = true; expect(expectedArgs).toEqual(funcArgsArg[0]); expect(decoderArg).toBeInstanceOf(ResultDecoders.CompactChangeEventDecoder); verify( serviceMock.streamFunction(anything(), anything(), anything()) ).times(1); // Should pass along errors when( serviceMock.streamFunction(anything(), anything(), anything()) ).thenReject(new Error("whoops")); try { await coll.watch([id]); fail(); } catch (_) { // Do nothing } }); });
the_stack
import { Assignable } from "vis-util/esnext"; import { DataSet } from "./data-set"; import { DataStream } from "./data-stream"; type ValueOf<T> = T[keyof T]; /** Valid id type. */ export type Id = number | string; /** Nullable id type. */ export type OptId = undefined | null | Id; /** * Determine whether a value can be used as an id. * * @param value - Input value of unknown type. * * @returns True if the value is valid id, false otherwise. */ export function isId(value: unknown): value is Id { return typeof value === "string" || typeof value === "number"; } /** * Make an object deeply partial. */ export type DeepPartial<T> = T extends any[] | Function | Node ? T : T extends object ? { [key in keyof T]?: DeepPartial<T[key]> } : T; /** * An item that may ([[Id]]) or may not (absent, undefined or null) have an id property. * * @typeParam IdProp - Name of the property that contains the id. */ export type PartItem<IdProp extends string> = Partial<Record<IdProp, OptId>>; /** * An item that has a property containing an id and all other required properties of given item type. * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export type FullItem< Item extends PartItem<IdProp>, IdProp extends string > = Item & Record<IdProp, Id>; /** * An item that has a property containing an id and optionally other properties of given item type. * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export type UpdateItem< Item extends PartItem<IdProp>, IdProp extends string > = Assignable<FullItem<Item, IdProp>> & Record<IdProp, Id>; /** * Test whether an item has an id (is a [[FullItem]]). * * @param item - The item to be tested. * @param idProp - Name of the id property. * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. * * @returns True if this value is a [[FullItem]], false otherwise. */ export function isFullItem< Item extends PartItem<IdProp>, IdProp extends string >(item: Item, idProp: IdProp): item is FullItem<Item, IdProp> { return item[idProp] != null; } /** Add event payload. */ export interface AddEventPayload { /** Ids of added items. */ items: Id[]; } /** Update event payload. */ export interface UpdateEventPayload<Item, IdProp extends string> { /** Ids of updated items. */ items: Id[]; /** Items as they were before this update. */ oldData: FullItem<Item, IdProp>[]; /** * Items as they are now. * * @deprecated Just get the data from the data set or data view. */ data: FullItem<Item, IdProp>[]; } /** Remove event payload. */ export interface RemoveEventPayload<Item, IdProp extends string> { /** Ids of removed items. */ items: Id[]; /** Items as they were before their removal. */ oldData: FullItem<Item, IdProp>[]; } /** * Map of event payload types (event name → payload). * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export interface EventPayloads<Item, IdProp extends string> { add: AddEventPayload; update: UpdateEventPayload<Item, IdProp>; remove: RemoveEventPayload<Item, IdProp>; } /** * Map of event payload types including any event (event name → payload). * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export interface EventPayloadsWithAny<Item, IdProp extends string> extends EventPayloads<Item, IdProp> { "*": ValueOf<EventPayloads<Item, IdProp>>; } /** * Map of event callback types (event name → callback). * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export interface EventCallbacks<Item, IdProp extends string> { /** * @param name - The name of the event ([[EventName]]). * @param payload - Data about the items affected by this event. * @param senderId - A senderId, optionally provided by the application code which triggered the event. If senderId is not provided, the argument will be `null`. */ add(name: "add", payload: AddEventPayload | null, senderId?: Id | null): void; /** * @param name - The name of the event ([[EventName]]). * @param payload - Data about the items affected by this event. * @param senderId - A senderId, optionally provided by the application code which triggered the event. If senderId is not provided, the argument will be `null`. */ update( name: "update", payload: UpdateEventPayload<Item, IdProp> | null, senderId?: Id | null ): void; /** * @param name - The name of the event ([[EventName]]). * @param payload - Data about the items affected by this event. * @param senderId - A senderId, optionally provided by the application code which triggered the event. If senderId is not provided, the argument will be `null`. */ remove( name: "remove", payload: RemoveEventPayload<Item, IdProp> | null, senderId?: Id | null ): void; } /** * Map of event callback types including any event (event name → callback). * * @typeParam Item - Item type that may or may not have an id. * @typeParam IdProp - Name of the property that contains the id. */ export interface EventCallbacksWithAny<Item, IdProp extends string> extends EventCallbacks<Item, IdProp> { /** * @param name - The name of the event ([[EventName]]). * @param payload - Data about the items affected by this event. * @param senderId - A senderId, optionally provided by the application code which triggered the event. If senderId is not provided, the argument will be `null`. */ "*"<N extends keyof EventCallbacks<Item, IdProp>>( name: N, payload: EventPayloads<Item, IdProp>[N], senderId?: Id | null ): void; } /** Available event names. */ export type EventName = keyof EventPayloads<never, "">; /** Available event names and '*' to listen for all. */ export type EventNameWithAny = keyof EventPayloadsWithAny<never, "">; /** * Data interface order parameter. * - A string value determines which property will be used for sorting (using < and > operators for numeric comparison). * - A function will be used the same way as in Array.sort. * * @typeParam Item - Item type that may or may not have an id. */ export type DataInterfaceOrder<Item> = | keyof Item | ((a: Item, b: Item) => number); /** * Data interface get options (return type independent). * * @typeParam Item - Item type that may or may not have an id. */ export interface DataInterfaceGetOptionsBase<Item> { /** * An array with field names, or an object with current field name and new field name that the field is returned as. By default, all properties of the items are emitted. When fields is defined, only the properties whose name is specified in fields will be included in the returned items. * * @remarks * **Warning**: There is no TypeScript support for this. */ fields?: string[] | Record<string, string>; /** Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. */ filter?: (item: Item) => boolean; /** Order the items by a field name or custom sort function. */ order?: DataInterfaceOrder<Item>; } /** * Data interface get options (returns a single item or an array). * * @remarks * Whether an item or and array of items is returned is determined by the type of the id(s) argument. * If an array of ids is requested an array of items will be returned. * If a single id is requested a single item (or null if the id doesn't correspond to any item) will be returned. * * @typeParam Item - Item type that may or may not have an id. */ export interface DataInterfaceGetOptionsArray<Item> extends DataInterfaceGetOptionsBase<Item> { /** Items will be returned as a single item (if invoked with an id) or an array of items (if invoked with an array of ids). */ returnType?: undefined | "Array"; } /** * Data interface get options (returns an object). * * @remarks * The returned object has ids as keys and items as values of corresponding ids. * * @typeParam Item - Item type that may or may not have an id. */ export interface DataInterfaceGetOptionsObject<Item> extends DataInterfaceGetOptionsBase<Item> { /** Items will be returned as an object map (id → item). */ returnType: "Object"; } /** * Data interface get options (returns single item, an array or object). * * @typeParam Item - Item type that may or may not have an id. */ export type DataInterfaceGetOptions<Item> = | DataInterfaceGetOptionsArray<Item> | DataInterfaceGetOptionsObject<Item>; /** * Data interface get ids options. * * @typeParam Item - Item type that may or may not have an id. */ export interface DataInterfaceGetIdsOptions<Item> { /** Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. */ filter?: (item: Item) => boolean; /** Order the items by a field name or custom sort function. */ order?: DataInterfaceOrder<Item>; } /** * Data interface for each options. * * @typeParam Item - Item type that may or may not have an id. */ export interface DataInterfaceForEachOptions<Item> { /** An array with field names, or an object with current field name and new field name that the field is returned as. By default, all properties of the items are emitted. When fields is defined, only the properties whose name is specified in fields will be included in the returned items. */ fields?: string[] | Record<string, string>; /** Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. */ filter?: (item: Item) => boolean; /** Order the items by a field name or custom sort function. */ order?: DataInterfaceOrder<Item>; } /** * Data interface map oprions. * * @typeParam Original - The original item type in the data. * @typeParam Mapped - The type after mapping. */ export interface DataInterfaceMapOptions<Original, Mapped> { /** An array with field names, or an object with current field name and new field name that the field is returned as. By default, all properties of the items are emitted. When fields is defined, only the properties whose name is specified in fields will be included in the returned items. */ fields?: string[] | Record<string, string>; /** Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. */ filter?: (item: Original) => boolean; /** Order the items by a field name or custom sort function. */ order?: DataInterfaceOrder<Mapped>; } /** * Common interface for data sets and data view. * * @typeParam Item - Item type that may or may not have an id (missing ids will be generated upon insertion). * @typeParam IdProp - Name of the property on the Item type that contains the id. */ export interface DataInterface< Item extends PartItem<IdProp>, IdProp extends string = "id" > { /** The number of items. */ length: number; /** The key of id property. */ idProp: IdProp; /** * Add a universal event listener. * * @remarks The `*` event is triggered when any of the events `add`, `update`, and `remove` occurs. * * @param event - Event name. * @param callback - Callback function. */ on(event: "*", callback: EventCallbacksWithAny<Item, IdProp>["*"]): void; /** * Add an `add` event listener. * * @remarks The `add` event is triggered when an item or a set of items is added, or when an item is updated while not yet existing. * * @param event - Event name. * @param callback - Callback function. */ on(event: "add", callback: EventCallbacksWithAny<Item, IdProp>["add"]): void; /** * Add a `remove` event listener. * * @remarks The `remove` event is triggered when an item or a set of items is removed. * * @param event - Event name. * @param callback - Callback function. */ on( event: "remove", callback: EventCallbacksWithAny<Item, IdProp>["remove"] ): void; /** * Add an `update` event listener. * * @remarks The `update` event is triggered when an existing item or a set of existing items is updated. * * @param event - Event name. * @param callback - Callback function. */ on( event: "update", callback: EventCallbacksWithAny<Item, IdProp>["update"] ): void; /** * Remove a universal event listener. * * @param event - Event name. * @param callback - Callback function. */ off(event: "*", callback: EventCallbacksWithAny<Item, IdProp>["*"]): void; /** * Remove an `add` event listener. * * @param event - Event name. * @param callback - Callback function. */ off(event: "add", callback: EventCallbacksWithAny<Item, IdProp>["add"]): void; /** * Remove a `remove` event listener. * * @param event - Event name. * @param callback - Callback function. */ off( event: "remove", callback: EventCallbacksWithAny<Item, IdProp>["remove"] ): void; /** * Remove an `update` event listener. * * @param event - Event name. * @param callback - Callback function. */ off( event: "update", callback: EventCallbacksWithAny<Item, IdProp>["update"] ): void; /** * Get all the items. * * @returns An array containing all the items. */ get(): FullItem<Item, IdProp>[]; /** * Get all the items. * * @param options - Additional options. * * @returns An array containing requested items. */ get(options: DataInterfaceGetOptionsArray<Item>): FullItem<Item, IdProp>[]; /** * Get all the items. * * @param options - Additional options. * * @returns An object map of items (may be an empty object if there are no items). */ get( options: DataInterfaceGetOptionsObject<Item> ): Record<Id, FullItem<Item, IdProp>>; /** * Get all the items. * * @param options - Additional options. * * @returns An array containing requested items or if requested an object map of items (may be an empty object if there are no items). */ get( options: DataInterfaceGetOptions<Item> ): FullItem<Item, IdProp>[] | Record<Id, FullItem<Item, IdProp>>; /** * Get one item. * * @param id - The id of the item. * * @returns The item or null if the id doesn't correspond to any item. */ get(id: Id): null | FullItem<Item, IdProp>; /** * Get one item. * * @param id - The id of the item. * @param options - Additional options. * * @returns The item or null if the id doesn't correspond to any item. */ get( id: Id, options: DataInterfaceGetOptionsArray<Item> ): null | FullItem<Item, IdProp>; /** * Get one item. * * @param id - The id of the item. * @param options - Additional options. * * @returns An object map of items (may be an empty object if no item was found). */ get( id: Id, options: DataInterfaceGetOptionsObject<Item> ): Record<Id, FullItem<Item, IdProp>>; /** * Get one item. * * @param id - The id of the item. * @param options - Additional options. * * @returns The item if found or null otherwise. If requested an object map with 0 to 1 items. */ get( id: Id, options: DataInterfaceGetOptions<Item> ): null | FullItem<Item, IdProp> | Record<Id, FullItem<Item, IdProp>>; /** * Get multiple items. * * @param ids - An array of requested ids. * * @returns An array of found items (ids that do not correspond to any item are omitted). */ get(ids: Id[]): FullItem<Item, IdProp>[]; /** * Get multiple items. * * @param ids - An array of requested ids. * @param options - Additional options. * * @returns An array of found items (ids that do not correspond to any item are omitted). */ get( ids: Id[], options: DataInterfaceGetOptionsArray<Item> ): FullItem<Item, IdProp>[]; /** * Get multiple items. * * @param ids - An array of requested ids. * @param options - Additional options. * * @returns An object map of items (may be an empty object if no item was found). */ get( ids: Id[], options: DataInterfaceGetOptionsObject<Item> ): Record<Id, FullItem<Item, IdProp>>; /** * Get multiple items. * * @param ids - An array of requested ids. * @param options - Additional options. * * @returns An array of found items (ids that do not correspond to any item are omitted). * If requested an object map of items (may be an empty object if no item was found). */ get( ids: Id[], options: DataInterfaceGetOptions<Item> ): FullItem<Item, IdProp>[] | Record<Id, FullItem<Item, IdProp>>; /** * Get items. * * @param ids - Id or ids to be returned. * @param options - Options to specify iteration details. * * @returns The items (format is determined by ids (single or array) and the options. */ get( ids: Id | Id[], options?: DataInterfaceGetOptions<Item> ): | null | FullItem<Item, IdProp> | FullItem<Item, IdProp>[] | Record<Id, FullItem<Item, IdProp>>; /** * Get the DataSet to which the instance implementing this interface is connected. * In case there is a chain of multiple DataViews, the root DataSet of this chain is returned. * * @returns The data set that actually contains the data. */ getDataSet(): DataSet<Item, IdProp>; /** * Get ids of items. * * @remarks * No guarantee is given about the order of returned ids unless an ordering function is supplied. * * @param options - Additional configuration. * * @returns An array of requested ids. */ getIds(options?: DataInterfaceGetIdsOptions<Item>): Id[]; /** * Execute a callback function for each item. * * @remarks * No guarantee is given about the order of iteration unless an ordering function is supplied. * * @param callback - Executed in similar fashion to Array.forEach callback, but instead of item, index, array receives item, id. * @param options - Options to specify iteration details. */ forEach( callback: (item: Item, id: Id) => void, options?: DataInterfaceForEachOptions<Item> ): void; /** * Map each item into different item and return them as an array. * * @remarks * No guarantee is given about the order of iteration even if ordering function is supplied (the items are sorted after the mapping). * * @param callback - Array.map-like callback, but only with the first two params. * @param options - Options to specify iteration details. * * @returns The mapped items. */ map<T>( callback: (item: Item, id: Id) => T, options?: DataInterfaceMapOptions<Item, T> ): T[]; /** * Stream. * * @param ids - Ids of the items to be included in this stream (missing are ignored), all if omitted. * * @returns The data stream for this data set. */ stream(ids?: Iterable<Id>): DataStream<Item>; }
the_stack
import { ExchangeFeed, ExchangeFeedConfig } from '../ExchangeFeed'; import { LevelMessage, SnapshotMessage, TickerMessage, TradeMessage } from '../../core/Messages'; import { BittrexAPI } from './BittrexAPI'; import { Side } from '../../lib/sides'; import { Big } from '../../lib/types'; import { OrderPool } from '../../lib/BookBuilder'; import { Level3Order, PriceLevelWithOrders } from '../../lib/Orderbook'; const Bittrex = require('node-bittrex-api'); export class BittrexFeed extends ExchangeFeed { private client: any; private connection: any; private readonly counters: { [product: string]: MessageCounter }; constructor(config: ExchangeFeedConfig) { super(config); const auth = config.auth || { key: 'APIKEY', secret: 'APISECRET' }; this.url = config.wsUrl || 'wss://socket.bittrex.com/signalr'; this.counters = {}; Bittrex.options({ websockets_baseurl: this.url, apikey: auth.key, apisecret: auth.secret, inverse_callback_arguments: true, stream: false, cleartext: false, verbose: true }); this.connect(); } get owner(): string { return 'Bittrex'; } subscribe(products: string[]): Promise<boolean> { if (!this.connection) { return Promise.reject(false); } return Promise.all(products.map((product: string) => { return new Promise<boolean>((resolve, reject) => { this.client.call('CoreHub', 'SubscribeToExchangeDeltas', product).done((err: Error, result: boolean) => { if (err) { return reject(err); } if (!result) { const msg = `Failed to subscribeExchangeDeltas to ${product} on ${this.owner}`; this.log('info', msg); return reject(new Error(msg)); } this.client.call('CoreHub', 'queryExchangeState', product).done((queryErr: Error, data: any) => { if (queryErr) { return reject(queryErr); } if (!data) { const msg = `failed to queryExchangeState to ${product} on ${this.owner}`; this.log('error', msg); return reject(new Error(msg)); } const snapshot: SnapshotMessage = this.processSnapshot(product, data); this.push(snapshot); process.nextTick(() => { this.emit('snapshot', snapshot.productId); }); return resolve(true); }); }); }); })).then(() => { // Every result is guaranteed to be true return true; }); } protected connect() { Bittrex.websockets.client( (client: any) => { this.client = client; client.serviceHandlers.messageReceived = (msg: any) => this.handleMessage(msg); client.serviceHandlers.bound = () => this.onNewConnection(); client.serviceHandlers.disconnected = (code: number, reason: string) => this.onClose(code, reason); client.serviceHandlers.onerror = (err: Error) => this.onError(err); client.serviceHandlers.connected = (connection: any) => { this.connection = connection; this.emit('websocket-connection'); }; } ); } protected handleMessage(msg: any): void { if (msg.type !== 'utf8' || !msg.utf8Data) { return; } let data; try { data = JSON.parse(msg.utf8Data); } catch (err) { this.log('debug', 'Error parsing feed message', msg.utf8Data); return; } if (!Array.isArray(data.M)) { return; } this.confirmAlive(); data.M.forEach((message: any) => { this.processMessage(message); }); } protected onOpen(): void { // no-op } protected onClose(_code: number, _reason: string): void { this.emit('websocket-closed'); this.connection = null; } protected close() { this.client.end(); } private nextSequence(product: string): number { let counter: MessageCounter = this.counters[product]; if (!counter) { counter = this.counters[product] = { base: -1, offset: 0 }; } if (counter.base < 1) { return -1; } counter.offset += 1; return counter.base + counter.offset; } private setSnapshotSequence(product: string, sequence: number): void { let counter: MessageCounter = this.counters[product]; if (!counter) { counter = this.counters[product] = { base: -1, offset: 0 }; } counter.base = sequence; } private getSnapshotSequence(product: string): number { const counter: MessageCounter = this.counters[product]; return counter ? counter.base : -1; } private processMessage(message: any) { switch (message.M) { case 'updateExchangeState': this.updateExchangeState(message.A as BittrexExchangeState[]); break; case 'updateSummaryState': const tickers: BittrexTicker[] = message.A[0].Deltas || []; this.updateTickers(tickers); break; default: this.log('debug', `Unknown message type: ${message.M}`); } } private updateExchangeState(states: BittrexExchangeState[]) { const createUpdateMessage = (product: string, side: Side, nonce: number, delta: BittrexOrder): LevelMessage => { const seq = this.nextSequence(product); const message: LevelMessage = { type: 'level', time: new Date(), sequence: seq, sourceSequence: nonce, productId: product, side: side, price: delta.Rate, size: delta.Quantity, count: 1 }; return message; }; states.forEach((state: BittrexExchangeState) => { const product = state.MarketName; const snaphotSeq = this.getSnapshotSequence(product); if (state.Nounce <= snaphotSeq) { return; } state.Buys.forEach((delta: BittrexOrder) => { const msg: LevelMessage = createUpdateMessage(product, 'buy', state.Nounce, delta); this.push(msg); }); state.Sells.forEach((delta: BittrexOrder) => { const msg: LevelMessage = createUpdateMessage(product, 'sell', state.Nounce, delta); this.push(msg); }); state.Fills.forEach((fill: BittrexFill) => { if (!fill.TimeStamp.endsWith('Z')) { fill.TimeStamp += 'Z'; } const message: TradeMessage = { type: 'trade', productId: product, time: new Date(fill.TimeStamp), tradeId: '0', price: fill.Rate, size: fill.Quantity, side: Side(fill.OrderType) }; this.push(message); }); }); } private updateTickers(tickers: BittrexTicker[]) { tickers.forEach((bittrexTicker: BittrexTicker) => { const ticker: TickerMessage = { type: 'ticker', productId: BittrexAPI.normalizeProduct(bittrexTicker.MarketName), bid: Big(bittrexTicker.Bid), ask: Big(bittrexTicker.Ask), time: new Date(bittrexTicker.TimeStamp), price: Big(bittrexTicker.Last), volume: Big(bittrexTicker.Volume) }; this.push(ticker); }); } private processSnapshot(product: string, state: BittrexExchangeState): SnapshotMessage { const orders: OrderPool = {}; const snapshotMessage: SnapshotMessage = { type: 'snapshot', time: new Date(), productId: product, sequence: state.Nounce, asks: [], bids: [], orderPool: orders }; state.Buys.forEach((order: BittrexOrder) => { addOrder(order, 'buy', snapshotMessage.bids); }); state.Sells.forEach((order: BittrexOrder) => { addOrder(order, 'sell', snapshotMessage.asks); }); this.setSnapshotSequence(product, state.Nounce); return snapshotMessage; function addOrder(order: BittrexOrder, side: Side, levelArray: PriceLevelWithOrders[]) { const size = Big(order.Quantity); const newOrder: Level3Order = { id: String(order.Rate), price: Big(order.Rate), size: size, side: side }; const newLevel: PriceLevelWithOrders = { price: newOrder.price, totalSize: size, orders: [newOrder] }; levelArray.push(newLevel); } } } interface MessageCounter { base: number; offset: number; } interface BittrexFill { OrderType: string; Rate: string; Quantity: string; TimeStamp: string; } interface BittrexOrder { Rate: string; Quantity: string; Type: number; } interface BittrexExchangeState { MarketName: string; Nounce: number; Buys: any[]; Sells: any[]; Fills: any[]; } interface BittrexTicker { MarketName: string; High: number; Low: number; Volume: number; Last: number; BaseVolume: number; TimeStamp: string; Bid: number; Ask: number; OpenBuyOrders: number; OpenSellOrders: number; PrevDay: number; Created: string; }
the_stack
// The linter must be relaxed on this imported file. /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable eqeqeq */ /* eslint-disable no-inner-declarations */ /* eslint-disable prefer-arrow-callback */ import CodeMirror from 'codemirror'; import { diff_match_patch, DIFF_EQUAL, DIFF_DELETE, DIFF_INSERT } from 'diff-match-patch'; export const GutterID = 'CodeMirror-patchgutter'; enum DiffStatus { Equal = DIFF_EQUAL, Delete = DIFF_DELETE, Insert = DIFF_INSERT } export namespace MergeView { /** * Options available to MergeView. */ export interface IMergeViewEditorConfiguration extends CodeMirror.EditorConfiguration { /** * Determines whether the original editor allows editing. Defaults to false. */ allowEditingOriginals?: boolean; /** * When true stretches of unchanged text will be collapsed. When a number is given, this indicates the amount * of lines to leave visible around such stretches (which defaults to 2). Defaults to false. */ collapseIdentical?: boolean | number; /** * Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align", * the smaller chunk is padded to align with the bigger chunk instead. */ connect?: string; /** * Should the whitespace be ignored when comparing text */ ignoreWhitespace?: boolean; /** * Callback for when stretches of unchanged text are collapsed. */ onCollapse?( mergeView: IMergeViewEditor, line: number, size: number, mark: CodeMirror.TextMarker ): void; /** * Provides original version of the document to be shown on the right of the editor. */ orig: any; /** * Provides original version of the document to be shown on the left of the editor. * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. */ origLeft?: any; /** * Provides original version of document to be shown on the right of the editor. * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. */ origRight?: any; /** * Determines whether buttons that allow the user to revert changes are shown. Defaults to true. */ revertButtons?: boolean; /** * When true, changed pieces of text are highlighted. Defaults to true. */ showDifferences?: boolean; revertChunk?: ( mergeView: IMergeViewEditor, from: CodeMirror.Editor, origStart: CodeMirror.Position, origEnd: CodeMirror.Position, to: CodeMirror.Editor, editStart: CodeMirror.Position, editEnd: CodeMirror.Position ) => void; } export interface IMergeViewEditor { /** * Returns the editor instance. */ editor(): CodeMirror.Editor; /** * Left side of the merge view. */ left: IDiffView; leftChunks(): IMergeViewDiffChunk[]; leftOriginal(): CodeMirror.Editor; /** * Right side of the merge view. */ right: IDiffView; rightChunks(): IMergeViewDiffChunk[]; rightOriginal(): CodeMirror.Editor; /** * Sets whether or not the merge view should show the differences between the editor views. */ setShowDifferences(showDifferences: boolean): void; } /** * Tracks changes in chunks from oroginal to new. */ export interface IMergeViewDiffChunk { editFrom: number; editTo: number; origFrom: number; origTo: number; } export interface IDiffView { /** * Forces the view to reload. */ forceUpdate(): (mode: string) => void; /** * Sets whether or not the merge view should show the differences between the editor views. */ setShowDifferences(showDifferences: boolean): void; } export type Diff = [DiffStatus, string]; export interface IClasses { chunk: string; start: string; end: string; insert: string; del: string; connect: string; classLocation?: string[]; } export type PanelType = 'left' | 'right'; export interface IState { from: number; to: number; marked: CodeMirror.LineHandle[]; } } const Pos = CodeMirror.Pos; const svgNS = 'http://www.w3.org/2000/svg'; class DiffView implements MergeView.IDiffView { constructor(mv: MergeView, type: MergeView.PanelType) { this.mv = mv; this.type = type; this.classes = type == 'left' ? { chunk: 'CodeMirror-merge-l-chunk', start: 'CodeMirror-merge-l-chunk-start', end: 'CodeMirror-merge-l-chunk-end', insert: 'CodeMirror-merge-l-inserted', del: 'CodeMirror-merge-l-deleted', connect: 'CodeMirror-merge-l-connect' } : { chunk: 'CodeMirror-merge-r-chunk', start: 'CodeMirror-merge-r-chunk-start', end: 'CodeMirror-merge-r-chunk-end', insert: 'CodeMirror-merge-r-inserted', del: 'CodeMirror-merge-r-deleted', connect: 'CodeMirror-merge-r-connect' }; } init( pane: HTMLElement, orig: string | CodeMirror.Doc, options: MergeView.IMergeViewEditorConfiguration ): void { this.edit = this.mv.edit; (this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this); this.orig = CodeMirror(pane, { ...options, value: orig, readOnly: !this.mv.options.allowEditingOriginals }); if (this.mv.options.connect == 'align') { if (!this.edit.state.trackAlignable) { this.edit.state.trackAlignable = new TrackAlignable(this.edit); } this.orig.state.trackAlignable = new TrackAlignable(this.orig); } // @ts-ignore this.lockButton.title = this.edit.phrase('Toggle locked scrolling'); this.orig.state.diffViews = [this]; // @ts-ignore let classLocation = options.chunkClassLocation || 'background'; if (Object.prototype.toString.call(classLocation) != '[object Array]') { classLocation = [classLocation]; } this.classes.classLocation = classLocation; this.diff = getDiff( asString(orig), asString(options.value), this.mv.options.ignoreWhitespace ); this.chunks = getChunks(this.diff); this.diffOutOfDate = this.dealigned = false; this.needsScrollSync = null; this.showDifferences = options.showDifferences !== false; } registerEvents(otherDv: DiffView): void { this.forceUpdate = DiffView.registerUpdate(this); DiffView.setScrollLock(this, true, false); DiffView.registerScroll(this, otherDv); } setShowDifferences(val: boolean): void { val = val !== false; if (val != this.showDifferences) { this.showDifferences = val; this.forceUpdate('full'); } } static setScrollLock(dv: DiffView, val: boolean, action?: boolean): void { dv.lockScroll = val; if (val && action != false) { if (DiffView.syncScroll(dv, true)) { makeConnections(dv); } } // @ts-ignore (val ? CodeMirror.addClass : CodeMirror.rmClass)( dv.lockButton, 'CodeMirror-merge-scrolllock-enabled' ); } private static registerUpdate(dv: DiffView): (mode?: string) => void { const edit: MergeView.IState = { from: 0, to: 0, marked: [] }; const orig: MergeView.IState = { from: 0, to: 0, marked: [] }; let debounceChange: number; let updatingFast = false; function update(mode?: string): void { DiffView.updating = true; updatingFast = false; if (mode == 'full') { // @ts-ignore if (dv.svg) { Private.clear(dv.svg); } // @ts-ignore if (dv.copyButtons) { Private.clear(dv.copyButtons); } clearMarks(dv.edit, edit.marked, dv.classes); clearMarks(dv.orig, orig.marked, dv.classes); edit.from = edit.to = orig.from = orig.to = 0; } ensureDiff(dv); if (dv.showDifferences) { updateMarks(dv.edit, dv.diff, edit, DiffStatus.Insert, dv.classes); updateMarks(dv.orig, dv.diff, orig, DiffStatus.Delete, dv.classes); } if (dv.mv.options.connect == 'align') { alignChunks(dv); } makeConnections(dv); if (dv.needsScrollSync != null) { DiffView.syncScroll(dv, dv.needsScrollSync); } DiffView.updating = false; } function setDealign(fast: boolean): void { if (DiffView.updating) { return; } dv.dealigned = true; set(fast); } function set(fast: boolean): void { if (DiffView.updating || updatingFast) { return; } window.clearTimeout(debounceChange); if (fast === true) { updatingFast = true; } debounceChange = window.setTimeout(update, fast === true ? 20 : 250); } function change( _cm: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList ): void { if (!dv.diffOutOfDate) { dv.diffOutOfDate = true; edit.from = edit.to = orig.from = orig.to = 0; } // Update faster when a line was added/removed setDealign(change.text.length - 1 != change.to.line - change.from.line); } function swapDoc(): void { dv.diffOutOfDate = true; dv.dealigned = true; update('full'); } dv.edit.on('change', change); dv.orig.on('change', change); dv.edit.on('swapDoc', swapDoc); dv.orig.on('swapDoc', swapDoc); if (dv.mv.options.connect === 'align') { CodeMirror.on(dv.edit.state.trackAlignable, 'realign', setDealign); CodeMirror.on(dv.orig.state.trackAlignable, 'realign', setDealign); } dv.edit.on('viewportChange', function () { set(false); }); dv.orig.on('viewportChange', function () { set(false); }); update(); return update; } private static registerScroll(dv: DiffView, otherDv: DiffView): void { dv.edit.on('scroll', function () { if (DiffView.syncScroll(dv, true)) { makeConnections(dv); } }); dv.orig.on('scroll', function () { if (DiffView.syncScroll(dv, false)) { makeConnections(dv); } if (otherDv) { if (DiffView.syncScroll(otherDv, true)) { makeConnections(otherDv); } } }); } private static syncScroll(dv: DiffView, toOrig: boolean): boolean { // Change handler will do a refresh after a timeout when diff is out of date if (dv.diffOutOfDate) { if (dv.lockScroll && dv.needsScrollSync == null) { dv.needsScrollSync = toOrig; } return false; } dv.needsScrollSync = null; if (!dv.lockScroll) { return true; } let editor: CodeMirror.Editor; let other: CodeMirror.Editor; const now = +new Date(); if (toOrig) { editor = dv.edit; other = dv.orig; } else { editor = dv.orig; other = dv.edit; } // Don't take action if the position of this editor was recently set // (to prevent feedback loops) if ( editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 250 > now ) { return false; } const sInfo = editor.getScrollInfo(); let targetPos = 0; if (dv.mv.options.connect == 'align') { targetPos = sInfo.top; } else { const halfScreen = 0.5 * sInfo.clientHeight; const midY = sInfo.top + halfScreen; const mid = editor.lineAtHeight(midY, 'local'); const around = chunkBoundariesAround(dv.chunks, mid, toOrig); const off = DiffView.getOffsets( editor, toOrig ? around.edit : around.orig ); const offOther = DiffView.getOffsets( other, toOrig ? around.orig : around.edit ); const ratio = (midY - off.top) / (off.bot - off.top); targetPos = offOther.top - halfScreen + ratio * (offOther.bot - offOther.top); let botDist: number; let mix: number; // Some careful tweaking to make sure no space is left out of view // when scrolling to top or bottom. if (targetPos > sInfo.top) { mix = sInfo.top / halfScreen; if (mix < 1) { targetPos = targetPos * mix + sInfo.top * (1 - mix); } } else { botDist = sInfo.height - sInfo.clientHeight - sInfo.top; if (botDist < halfScreen) { const otherInfo = other.getScrollInfo(); const botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos; if (botDistOther > botDist) { mix = botDist / halfScreen; if (mix < 1) { targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix); } } } } } other.scrollTo(sInfo.left, targetPos); other.state.scrollSetAt = now; other.state.scrollSetBy = dv; return true; } private static getOffsets( editor: CodeMirror.Editor, around: { before: number | null; after: number | null } ): { top: number; bot: number } { let bot = around.after; if (bot == null) { // @ts-ignore bot = editor.lastLine() + 1; } return { top: editor.heightAtLine(around.before || 0, 'local'), bot: editor.heightAtLine(bot, 'local') }; } mv: MergeView; type: MergeView.PanelType; classes: MergeView.IClasses; edit: CodeMirror.Editor; orig: CodeMirror.Editor; lockButton: HTMLElement; copyButtons: HTMLDivElement; svg: SVGSVGElement; gap: HTMLDivElement; lockScroll: boolean; diff: MergeView.Diff[]; chunks: MergeView.IMergeViewDiffChunk[]; dealigned: boolean; diffOutOfDate: boolean; needsScrollSync: boolean; showDifferences: boolean; forceUpdate: (mode?: string) => any; private static updating = false; } function ensureDiff(dv: DiffView): void { if (dv.diffOutOfDate) { dv.diff = getDiff( dv.orig.getValue(), dv.edit.getValue(), dv.mv.options.ignoreWhitespace ); dv.chunks = getChunks(dv.diff); dv.diffOutOfDate = false; CodeMirror.signal(dv.edit, 'updateDiff', dv.diff); } } // Updating the marks for editor content function removeClass( editor: CodeMirror.Editor, line: any, classes: MergeView.IClasses ): void { const locs = classes.classLocation; for (let i = 0; i < locs.length; i++) { editor.removeLineClass(line, locs[i], classes.chunk); editor.removeLineClass(line, locs[i], classes.start); editor.removeLineClass(line, locs[i], classes.end); } } function isTextMarker( marker: CodeMirror.TextMarker | CodeMirror.LineHandle ): marker is CodeMirror.TextMarker { return 'clear' in marker; } function clearMarks( editor: CodeMirror.Editor, arr: CodeMirror.TextMarker[] | CodeMirror.LineHandle[], classes: MergeView.IClasses ): void { for (let i = 0; i < arr.length; ++i) { const mark = arr[i]; if (isTextMarker(mark)) { mark.clear(); // @ts-ignore } else if (mark.parent) { removeClass(editor, mark, classes); } } arr.length = 0; editor.clearGutter(GutterID); } // FIXME maybe add a margin around viewport to prevent too many updates function updateMarks( editor: CodeMirror.Editor, diff: MergeView.Diff[], state: MergeView.IState, type: DiffStatus, classes: MergeView.IClasses ): void { const vp = editor.getViewport(); editor.operation(function () { if ( state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20 ) { clearMarks(editor, state.marked, classes); markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes); state.from = vp.from; state.to = vp.to; } else { if (vp.from < state.from) { markChanges( editor, diff, type, state.marked, vp.from, state.from, classes ); state.from = vp.from; } if (vp.to > state.to) { markChanges(editor, diff, type, state.marked, state.to, vp.to, classes); state.to = vp.to; } } }); } function addClass( editor: CodeMirror.Editor, lineNr: number, classes: MergeView.IClasses, main: boolean, start: boolean, end: boolean ): CodeMirror.LineHandle { const locs = classes.classLocation; // @ts-ignore const line: CodeMirror.LineHandle = editor.getLineHandle(lineNr); for (let i = 0; i < locs.length; i++) { if (main) { editor.addLineClass(line, locs[i], classes.chunk); } if (start) { editor.addLineClass(line, locs[i], classes.start); } if (end) { editor.addLineClass(line, locs[i], classes.end); } } return line; } function makeGutter(isDelete: boolean): HTMLDivElement { const marker = document.createElement('div'); marker.className = isDelete ? 'CodeMirror-patchgutter-delete' : 'CodeMirror-patchgutter-insert'; return marker; } function markChanges( editor: CodeMirror.Editor, diff: MergeView.Diff[], type: DiffStatus, marks: CodeMirror.LineHandle[], from: number, to: number, classes: MergeView.IClasses ): void { let pos = Pos(0, 0); const top = Pos(from, 0); // @ts-ignore const bot = editor.clipPos(Pos(to - 1)); const cls = type == DiffStatus.Delete ? classes.del : classes.insert; function markChunk(start: number, end: number): void { const bfrom = Math.max(from, start); const bto = Math.min(to, end); for (let i = bfrom; i < bto; ++i) { marks.push(addClass(editor, i, classes, true, i == start, i == end - 1)); editor.setGutterMarker( i, GutterID, makeGutter(type == DiffStatus.Delete) ); } // When the chunk is empty, make sure a horizontal line shows up if (start == end && bfrom == end && bto == end) { if (bfrom) { marks.push(addClass(editor, bfrom - 1, classes, false, false, true)); } else { marks.push(addClass(editor, bfrom, classes, false, true, false)); } } } let chunkStart = 0; let pending = false; for (let i = 0; i < diff.length; ++i) { const part = diff[i]; const tp = part[0]; const str = part[1]; if (tp == DiffStatus.Equal) { const cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1); moveOver(pos, str); const cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0); if (cleanTo > cleanFrom) { if (pending) { markChunk(chunkStart, cleanFrom); pending = false; } chunkStart = cleanTo; } } else { pending = true; if (tp == type) { const end = moveOver(pos, str, true); const a = Private.posMax(top, pos); const b = Private.posMin(bot, end); if (!Private.posEq(a, b)) { // @ts-ignore marks.push(editor.markText(a, b, { className: cls })); } pos = end; } } } if (pending) { markChunk(chunkStart, pos.line + 1); } } // Updating the gap between editor and original function makeConnections(dv: DiffView): void { if (!dv.showDifferences) { return; } let w = 0; if (dv.svg) { Private.clear(dv.svg); w = dv.gap.offsetWidth; Private.attrs(dv.svg, 'width', w, 'height', dv.gap.offsetHeight); } if (dv.copyButtons) { Private.clear(dv.copyButtons); } const vpEdit = dv.edit.getViewport(); const vpOrig = dv.orig.getViewport(); const outerTop = dv.mv.wrap.getBoundingClientRect().top; const sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top; const sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top; for (let i = 0; i < dv.chunks.length; i++) { const ch = dv.chunks[i]; if ( ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from && ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from ) { drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w); } } } function getMatchingOrigLine( editLine: number, chunks: MergeView.IMergeViewDiffChunk[] ): number | null { let editStart = 0; let origStart = 0; for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; if (chunk.editTo > editLine && chunk.editFrom <= editLine) { return null; } if (chunk.editFrom > editLine) { break; } editStart = chunk.editTo; origStart = chunk.origTo; } return origStart + (editLine - editStart); } // Combines information about chunks and widgets/markers to return // an array of lines, in a single editor, that probably need to be // aligned with their counterparts in the editor next to it. function alignableFor( cm: CodeMirror.Editor, chunks: MergeView.IMergeViewDiffChunk[], isOrig: boolean ): number[] { const tracker = cm.state.trackAlignable; // @ts-ignore let start: number = cm.firstLine(); let trackI = 0; const result: number[] = []; for (let i = 0; ; i++) { const chunk = chunks[i]; const chunkStart = !chunk ? 1e9 : isOrig ? chunk.origFrom : chunk.editFrom; for (; trackI < tracker.alignable.length; trackI += 2) { const n: number = tracker.alignable[trackI] + 1; if (n <= start) { continue; } if (n <= chunkStart) { result.push(n); } else { break; } } if (!chunk) { break; } result.push((start = isOrig ? chunk.origTo : chunk.editTo)); } return result; } // Given information about alignable lines in two editors, fill in // the result (an array of three-element arrays) to reflect the // lines that need to be aligned with each other. function mergeAlignable( result: number[][], origAlignable: number[], chunks: MergeView.IMergeViewDiffChunk[], setIndex: number ): void { let rI = 0; let origI = 0; let chunkI = 0; let diff = 0; outer: for (; ; rI++) { const nextR = result[rI]; const nextO = origAlignable[origI]; if (!nextR && nextO == null) { break; } const rLine = nextR ? nextR[0] : 1e9; const oLine = nextO == null ? 1e9 : nextO; while (chunkI < chunks.length) { const chunk = chunks[chunkI]; if (chunk.origFrom <= oLine && chunk.origTo > oLine) { origI++; rI--; continue outer; } if (chunk.editTo > rLine) { if (chunk.editFrom <= rLine) { continue outer; } break; } diff += chunk.origTo - chunk.origFrom - (chunk.editTo - chunk.editFrom); chunkI++; } if (rLine == oLine - diff) { nextR[setIndex] = oLine; origI++; } else if (rLine < oLine - diff) { nextR[setIndex] = rLine + diff; } else { const record = [oLine - diff, null, null]; record[setIndex] = oLine; result.splice(rI, 0, record); origI++; } } } function findAlignedLines(dv: DiffView, other: DiffView) { const alignable = alignableFor(dv.edit, dv.chunks, false); const result = []; if (other) { for (let i = 0, j = 0; i < other.chunks.length; i++) { const n = other.chunks[i].editTo; while (j < alignable.length && alignable[j] < n) { j++; } if (j == alignable.length || alignable[j] != n) { alignable.splice(j++, 0, n); } } } for (let i = 0; i < alignable.length; i++) { result.push([alignable[i], null, null]); } mergeAlignable(result, alignableFor(dv.orig, dv.chunks, true), dv.chunks, 1); if (other) { mergeAlignable( result, alignableFor(other.orig, other.chunks, true), other.chunks, 2 ); } return result; } function alignChunks(dv: DiffView, force?: boolean) { if (!dv.dealigned && !force) { return; } // @ts-ignore if (!dv.orig.curOp) { return dv.orig.operation(function () { alignChunks(dv, force); }); } dv.dealigned = false; const other = dv.mv.left == dv ? dv.mv.right : dv.mv.left; if (other) { ensureDiff(other); other.dealigned = false; } const linesToAlign = findAlignedLines(dv, other); // Clear old aligners const aligners = dv.mv.aligners; for (let i = 0; i < aligners.length; i++) { aligners[i].clear(); } aligners.length = 0; const cm = [dv.edit, dv.orig]; const scroll = []; if (other) { cm.push(other.orig); } for (let i = 0; i < cm.length; i++) { scroll.push(cm[i].getScrollInfo().top); } for (let ln = 0; ln < linesToAlign.length; ln++) { alignLines(cm, linesToAlign[ln], aligners); } for (let i = 0; i < cm.length; i++) { cm[i].scrollTo(null, scroll[i]); } } function alignLines( cm: CodeMirror.Editor[], lines: number[], aligners: CodeMirror.LineWidget[] ): void { let maxOffset = 0; const offset = []; for (let i = 0; i < cm.length; i++) { if (lines[i] != null) { const off = cm[i].heightAtLine(lines[i], 'local'); offset[i] = off; maxOffset = Math.max(maxOffset, off); } } for (let i = 0; i < cm.length; i++) { if (lines[i] != null) { const diff = maxOffset - offset[i]; if (diff > 1) { aligners.push(padAbove(cm[i], lines[i], diff)); } } } } function padAbove(cm: CodeMirror.Editor, line: number, size: number) { let above = true; // @ts-ignore if (line > cm.lastLine()) { line--; above = false; } const elt = document.createElement('div'); elt.className = 'CodeMirror-merge-spacer'; elt.style.height = size + 'px'; elt.style.minWidth = '1px'; return cm.addLineWidget(line, elt, { // @ts-ignore height: size, above: above, mergeSpacer: true, handleMouseEvents: true }); } function drawConnectorsForChunk( dv: DiffView, chunk: MergeView.IMergeViewDiffChunk, sTopOrig: number, sTopEdit: number, w: number ) { const flip = dv.type == 'left'; const top = dv.orig.heightAtLine(chunk.origFrom, 'local', true) - sTopOrig; if (dv.svg) { let topLpx = top; let topRpx = dv.edit.heightAtLine(chunk.editFrom, 'local', true) - sTopEdit; if (flip) { const tmp = topLpx; topLpx = topRpx; topRpx = tmp; } let botLpx = dv.orig.heightAtLine(chunk.origTo, 'local', true) - sTopOrig; let botRpx = dv.edit.heightAtLine(chunk.editTo, 'local', true) - sTopEdit; if (flip) { const tmp = botLpx; botLpx = botRpx; botRpx = tmp; } const curveTop = ' C ' + w / 2 + ' ' + topRpx + ' ' + w / 2 + ' ' + topLpx + ' ' + (w + 2) + ' ' + topLpx; const curveBot = ' C ' + w / 2 + ' ' + botLpx + ' ' + w / 2 + ' ' + botRpx + ' -1 ' + botRpx; Private.attrs( dv.svg.appendChild(document.createElementNS(svgNS, 'path')), 'd', 'M -1 ' + topRpx + curveTop + ' L ' + (w + 2) + ' ' + botLpx + curveBot + ' z', 'class', dv.classes.connect ); } if (dv.copyButtons) { const copy = dv.copyButtons.appendChild( Private.elt( 'div', dv.type === 'left' ? '\u21dd' : '\u21dc', 'CodeMirror-merge-copy' ) ); const editOriginals = dv.mv.options.allowEditingOriginals; // @ts-ignore copy.title = dv.edit.phrase( editOriginals ? 'Push to left' : 'Revert chunk' ); // @ts-ignore copy.chunk = chunk; copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, 'local') - sTopEdit) + 'px'; if (editOriginals) { const topReverse = dv.edit.heightAtLine(chunk.editFrom, 'local') - sTopEdit; const copyReverse = dv.copyButtons.appendChild( Private.elt( 'div', dv.type == 'right' ? '\u21dd' : '\u21dc', 'CodeMirror-merge-copy-reverse' ) ); copyReverse.title = 'Push to right'; // @ts-ignore copyReverse.chunk = { editFrom: chunk.origFrom, editTo: chunk.origTo, origFrom: chunk.editFrom, origTo: chunk.editTo }; copyReverse.style.top = topReverse + 'px'; dv.type == 'right' ? (copyReverse.style.left = '2px') : (copyReverse.style.right = '2px'); } } } function copyChunk( dv: DiffView, to: CodeMirror.Editor, from: CodeMirror.Editor, chunk: MergeView.IMergeViewDiffChunk ) { if (dv.diffOutOfDate) { return; } const origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0); const origEnd = Pos(chunk.origTo, 0); const editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0); const editEnd = Pos(chunk.editTo, 0); const handler = dv.mv.options.revertChunk; if (handler) { handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd); } else { to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd); } } // Merge view, containing 0, 1, or 2 diff views. /** * A function that calculates either a two-way or three-way merge between different sets of content. */ export function mergeView( node: HTMLElement, options?: MergeView.IMergeViewEditorConfiguration ): MergeView.IMergeViewEditor { return new MergeView(node, options); } class MergeView implements MergeView.IMergeViewEditor { constructor( node: HTMLElement, options?: MergeView.IMergeViewEditorConfiguration ) { this.options = options; const origLeft = options.origLeft == null ? options.orig : options.origLeft; const origRight = options.origRight; const hasLeft = origLeft != null; const hasRight = origRight != null; const panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0); const wrap: HTMLDivElement[] = []; let left: DiffView | null = (this.left = null); let right: DiffView | null = (this.right = null); const self = this; let leftPane: HTMLDivElement = null; if (hasLeft) { left = this.left = new DiffView(this, 'left'); leftPane = Private.elt( 'div', null, 'CodeMirror-merge-pane CodeMirror-merge-left' ); wrap.push(leftPane); wrap.push(buildGap(left)); } const editPane = Private.elt( 'div', null, 'CodeMirror-merge-pane CodeMirror-merge-editor' ); wrap.push(editPane); let rightPane: HTMLDivElement = null; if (hasRight) { right = this.right = new DiffView(this, 'right'); wrap.push(buildGap(right)); rightPane = Private.elt( 'div', null, 'CodeMirror-merge-pane CodeMirror-merge-right' ); wrap.push(rightPane); } (hasRight ? rightPane : editPane).className += ' CodeMirror-merge-pane-rightmost'; wrap.push(Private.elt('div', null, null, 'height: 0; clear: both;')); const wrapElt = (this.wrap = node.appendChild( Private.elt( 'div', wrap, 'CodeMirror-merge CodeMirror-merge-' + panes + 'pane' ) )); this.edit = CodeMirror(editPane, { ...options }); // Add gutter const gutters = this.edit.getOption('gutters'); if (gutters.indexOf(GutterID) < 0) { const newGutters: string[] = []; if (this.edit.getOption('lineNumbers')) { newGutters.push('CodeMirror-linenumbers'); } newGutters.push(GutterID); this.edit.setOption('gutters', newGutters); options['gutters'] = newGutters; } if (left) { left.init(leftPane, origLeft, options); } if (right) { right.init(rightPane, origRight, options); } if (options.collapseIdentical) { this.editor().operation(function () { collapseIdenticalStretches(self, options.collapseIdentical); }); } if (options.connect == 'align') { this.aligners = []; alignChunks(this.left || this.right, true); } if (left) { left.registerEvents(right); } if (right) { right.registerEvents(left); } const onResize = function () { if (left) { makeConnections(left); } if (right) { makeConnections(right); } }; CodeMirror.on(window, 'resize', onResize); const resizeInterval = setInterval(function () { let p = null; for ( p = wrapElt.parentNode; p && p !== document.body; p = p.parentNode ) {} // eslint-disable-line no-empty if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, 'resize', onResize); } }, 5000); } editor(): CodeMirror.Editor { return this.edit; } rightOriginal(): CodeMirror.Editor { return this.right && this.right.orig; } leftOriginal(): CodeMirror.Editor { return this.left && this.left.orig; } setShowDifferences(val: boolean) { if (this.right) { this.right.setShowDifferences(val); } if (this.left) { this.left.setShowDifferences(val); } } rightChunks() { if (this.right) { ensureDiff(this.right); return this.right.chunks; } } leftChunks() { if (this.left) { ensureDiff(this.left); return this.left.chunks; } } options: MergeView.IMergeViewEditorConfiguration; left: DiffView | null; right: DiffView | null; wrap: HTMLDivElement; edit: CodeMirror.Editor; aligners: CodeMirror.LineWidget[]; } function buildGap(dv: DiffView) { const lock = (dv.lockButton = Private.elt( 'div', null, 'CodeMirror-merge-scrolllock' )); const lockWrap = Private.elt( 'div', [lock], 'CodeMirror-merge-scrolllock-wrap' ); CodeMirror.on(lock, 'click', function () { DiffView.setScrollLock(dv, !dv.lockScroll); }); const gapElts: Element[] = [lockWrap]; if (dv.mv.options.revertButtons !== false) { dv.copyButtons = Private.elt( 'div', null, 'CodeMirror-merge-copybuttons-' + dv.type ); CodeMirror.on(dv.copyButtons, 'click', function (e: MouseEvent) { const node = (e.target || e.srcElement) as any; if (!node.chunk) { return; } if (node.className == 'CodeMirror-merge-copy-reverse') { copyChunk(dv, dv.orig, dv.edit, node.chunk); return; } copyChunk(dv, dv.edit, dv.orig, node.chunk); }); gapElts.unshift(dv.copyButtons); } if (dv.mv.options.connect != 'align') { let svg = document.createElementNS && document.createElementNS(svgNS, 'svg'); if (svg && !svg.createSVGRect) { svg = null; } dv.svg = svg; if (svg) { gapElts.push(svg); } } return (dv.gap = Private.elt('div', gapElts, 'CodeMirror-merge-gap')); } function asString(obj: string | CodeMirror.Doc) { if (typeof obj == 'string') { return obj; } else { return obj.getValue(); } } // Operations on diffs let dmp: diff_match_patch; function getDiff( a: string, b: string, ignoreWhitespace?: boolean ): MergeView.Diff[] { if (!dmp) { dmp = new diff_match_patch(); } const diff = dmp.diff_main(a, b); dmp.diff_cleanupSemantic(diff); // The library sometimes leaves in empty parts, which confuse the algorithm for (let i = 0; i < diff.length; ++i) { const part = diff[i]; if (ignoreWhitespace ? !/[^ \t]/.test(part[1]) : !part[1]) { diff.splice(i--, 1); } else if (i && diff[i - 1][0] == part[0]) { diff.splice(i--, 1); diff[i][1] += part[1]; } } return diff; } function getChunks(diff: MergeView.Diff[]): MergeView.IMergeViewDiffChunk[] { const chunks: MergeView.IMergeViewDiffChunk[] = []; if (!diff.length) { return chunks; } let startEdit = 0; let startOrig = 0; const edit = Pos(0, 0); const orig = Pos(0, 0); for (let i = 0; i < diff.length; ++i) { const part = diff[i]; const tp = part[0]; if (tp == DiffStatus.Equal) { const startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0; const cleanFromEdit = edit.line + startOff; const cleanFromOrig = orig.line + startOff; moveOver(edit, part[1], null, orig); const endOff = endOfLineClean(diff, i) ? 1 : 0; const cleanToEdit = edit.line + endOff; const cleanToOrig = orig.line + endOff; if (cleanToEdit > cleanFromEdit) { if (i) { chunks.push({ origFrom: startOrig, origTo: cleanFromOrig, editFrom: startEdit, editTo: cleanFromEdit }); } startEdit = cleanToEdit; startOrig = cleanToOrig; } } else { moveOver(tp == DiffStatus.Insert ? edit : orig, part[1]); } } if (startEdit <= edit.line || startOrig <= orig.line) { chunks.push({ origFrom: startOrig, origTo: orig.line + 1, editFrom: startEdit, editTo: edit.line + 1 }); } return chunks; } function endOfLineClean(diff: MergeView.Diff[], i: number): boolean { if (i === diff.length - 1) { return true; } let next = diff[i + 1][1]; if ((next.length === 1 && i < diff.length - 2) || next.charCodeAt(0) !== 10) { return false; } if (i === diff.length - 2) { return true; } next = diff[i + 2][1]; return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) === 10; } function startOfLineClean(diff: MergeView.Diff[], i: number): boolean { if (i === 0) { return true; } let last = diff[i - 1][1]; if (last.charCodeAt(last.length - 1) != 10) { return false; } if (i == 1) { return true; } last = diff[i - 2][1]; return last.charCodeAt(last.length - 1) == 10; } function chunkBoundariesAround( chunks: MergeView.IMergeViewDiffChunk[], n: number, nInEdit: boolean ) { let beforeE: number; let afterE: number; let beforeO: number; let afterO: number; for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom; const toLocal = nInEdit ? chunk.editTo : chunk.origTo; if (afterE == null) { if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; } else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; } } if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; } else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; } } return { edit: { before: beforeE, after: afterE }, orig: { before: beforeO, after: afterO } }; } function collapseSingle( cm: CodeMirror.Editor, from: number, to: number ): { mark: CodeMirror.TextMarker; clear: () => void } { cm.addLineClass(from, 'wrap', 'CodeMirror-merge-collapsed-line'); const widget = document.createElement('span'); widget.className = 'CodeMirror-merge-collapsed-widget'; // @ts-ignore widget.title = cm.phrase('Identical text collapsed. Click to expand.'); // @ts-ignore const mark = cm.markText(Pos(from, 0), Pos(to - 1), { inclusiveLeft: true, inclusiveRight: true, replacedWith: widget, clearOnEnter: true }); function clear() { mark.clear(); cm.removeLineClass(from, 'wrap', 'CodeMirror-merge-collapsed-line'); } // @ts-ignore if (mark.explicitlyCleared) { clear(); } CodeMirror.on(widget, 'click', clear); mark.on('clear', clear); CodeMirror.on(widget, 'click', clear); return { mark: mark, clear: clear }; } function collapseStretch(size: number, editors: any[]): any { const marks: Array<{ mark: CodeMirror.TextMarker; clear: () => void; }> = []; function clear() { for (let i = 0; i < marks.length; i++) { marks[i].clear(); } } for (let i = 0; i < editors.length; i++) { const editor = editors[i]; const mark = collapseSingle(editor.cm, editor.line, editor.line + size); marks.push(mark); mark.mark.on('clear', clear); } return marks[0].mark; } function unclearNearChunks( dv: DiffView, margin: number, off: number, clear: boolean[] ) { for (let i = 0; i < dv.chunks.length; i++) { const chunk = dv.chunks[i]; for (let l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) { const pos = l + off; if (pos >= 0 && pos < clear.length) { clear[pos] = false; } } } } function collapseIdenticalStretches(mv: MergeView, margin: number | boolean) { if (typeof margin != 'number') { margin = 2; } const clear: boolean[] = []; const edit = mv.editor(); // @ts-ignore const off: number = edit.firstLine(); // @ts-ignore for (let l = off, e = edit.lastLine(); l <= e; l++) { clear.push(true); } if (mv.left) { unclearNearChunks(mv.left, margin, off, clear); } if (mv.right) { unclearNearChunks(mv.right, margin, off, clear); } for (let i = 0; i < clear.length; i++) { if (clear[i]) { const line = i + off; let size = 0; for (size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {} // eslint-disable-line no-empty if (size > margin) { const editors: { line: number; cm: CodeMirror.Editor }[] = [ { line: line, cm: edit } ]; if (mv.left) { editors.push({ line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig }); } if (mv.right) { editors.push({ line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig }); } const mark = collapseStretch(size, editors); if (mv.options.onCollapse) { mv.options.onCollapse(mv, line, size, mark); } } } } } function moveOver( pos: CodeMirror.Position, str: string, copy?: boolean, other?: CodeMirror.Position ): CodeMirror.Position { const out = copy ? Pos(pos.line, pos.ch) : pos; let at = 0; for (;;) { const nl = str.indexOf('\n', at); if (nl == -1) { break; } ++out.line; if (other) { ++other.line; } at = nl + 1; } out.ch = (at ? 0 : out.ch) + (str.length - at); if (other) { other.ch = (at ? 0 : other.ch) + (str.length - at); } return out; } // Tracks collapsed markers and line widgets, in order to be able to // accurately align the content of two editors. enum Alignement { F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4 } class TrackAlignable { cm: CodeMirror.Editor; alignable: Array<Alignement>; height: number; constructor(cm: CodeMirror.Editor) { this.cm = cm; this.alignable = []; // @ts-ignore this.height = cm.doc.height; const self = this; // @ts-ignore cm.on('markerAdded', function (_, marker) { if (!marker.collapsed) { return; } const found = marker.find(1); if (found != null) { self.set(found.line, Alignement.F_MARKER); } }); // @ts-ignore cm.on('markerCleared', function (_, marker, _min, max) { if (max !== null && marker.collapsed) { self.check(max, Alignement.F_MARKER, self.hasMarker); } }); cm.on('markerChanged', this.signal.bind(this)); // @ts-ignore cm.on('lineWidgetAdded', function (_, widget, lineNo) { if (widget.mergeSpacer) { return; } if (widget.above) { self.set(lineNo - 1, Alignement.F_WIDGET_BELOW); } else { self.set(lineNo, Alignement.F_WIDGET); } }); // @ts-ignore cm.on('lineWidgetCleared', function (_, widget, lineNo) { if (widget.mergeSpacer) { return; } if (widget.above) { self.check(lineNo - 1, Alignement.F_WIDGET_BELOW, self.hasWidgetBelow); } else { self.check(lineNo, Alignement.F_WIDGET, self.hasWidget); } }); cm.on('lineWidgetChanged', this.signal.bind(this)); cm.on('change', function (_, change) { const start = change.from.line; const nBefore = change.to.line - change.from.line; const nAfter = change.text.length - 1; const end = start + nAfter; if (nBefore || nAfter) { self.map(start, nBefore, nAfter); } self.check(end, Alignement.F_MARKER, self.hasMarker); if (nBefore || nAfter) { self.check(change.from.line, Alignement.F_MARKER, self.hasMarker); } }); cm.on('viewportChange', function () { // @ts-ignore if (self.cm.doc.height !== self.height) { self.signal(); } }); } signal() { CodeMirror.signal(this, 'realign'); // @ts-ignore this.height = this.cm.doc.height; } set(n: number, flags: Alignement) { let pos = -1; for (; pos < this.alignable.length; pos += 2) { const diff = this.alignable[pos] - n; if (diff == 0) { if ((this.alignable[pos + 1] & flags) == flags) { return; } this.alignable[pos + 1] |= flags; this.signal(); return; } if (diff > 0) { break; } } this.signal(); this.alignable.splice(pos, 0, n, flags); } find(n: number): number { for (let i = 0; i < this.alignable.length; i += 2) { if (this.alignable[i] == n) { return i; } } return -1; } check(n: number, flag: Alignement, pred: (n: number) => boolean) { const found = this.find(n); if (found == -1 || !(this.alignable[found + 1] & flag)) { return; } if (!pred.call(this, n)) { this.signal(); const flags = this.alignable[found + 1] & ~flag; if (flags) { this.alignable[found + 1] = flags; } else { this.alignable.splice(found, 2); } } } hasMarker(n: number): boolean { const handle = this.cm.getLineHandle(n) as any; if (handle.markedSpans) { for (let i = 0; i < handle.markedSpans.length; i++) { if ( handle.markedSpans[i].marker.collapsed && handle.markedSpans[i].to !== null ) { return true; } } } return false; } hasWidget(n: number): boolean { const handle = this.cm.getLineHandle(n) as any; if (handle.widgets) { for (let i = 0; i < handle.widgets.length; i++) { if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) { return true; } } } return false; } hasWidgetBelow(n: number): boolean { // @ts-ignore if (n == this.cm.lastLine()) { return false; } const handle = this.cm.getLineHandle(n + 1) as any; if (handle.widgets) { for (let i = 0; i < handle.widgets.length; i++) { if (handle.widgets[i].above && !handle.widgets[i].mergeSpacer) { return true; } } } return false; } map(from: number, nBefore: number, nAfter: number) { const diff = nAfter - nBefore; const to = from + nBefore; let widgetFrom = -1; let widgetTo = -1; for (let i = 0; i < this.alignable.length; i += 2) { const n = this.alignable[i]; if (n == from && this.alignable[i + 1] & Alignement.F_WIDGET_BELOW) { widgetFrom = i; } if (n == to && this.alignable[i + 1] & Alignement.F_WIDGET_BELOW) { widgetTo = i; } if (n <= from) { continue; } else if (n < to) { this.alignable.splice(i--, 2); } else { this.alignable[i] += diff; } } if (widgetFrom > -1) { const flags = this.alignable[widgetFrom + 1]; if (flags == Alignement.F_WIDGET_BELOW) { this.alignable.splice(widgetFrom, 2); } else { this.alignable[widgetFrom + 1] = flags & ~Alignement.F_WIDGET_BELOW; } } if (widgetTo > -1 && nAfter) { this.set(from + nAfter, Alignement.F_WIDGET_BELOW); } } } // @ts-ignore CodeMirror.commands.goNextDiff = function (cm: CodeMirror.Editor) { return Private.goNearbyDiff(cm, 1); }; // @ts-ignore CodeMirror.commands.goPrevDiff = function (cm: CodeMirror.Editor) { return Private.goNearbyDiff(cm, -1); }; namespace Private { // General utilities export function elt<K extends keyof HTMLElementTagNameMap>( tag: K, content: Node[] | string, className: string, style?: string ): HTMLElementTagNameMap[K] { const e = document.createElement<K>(tag); if (className) { e.className = className; } if (style) { e.style.cssText = style; } if (typeof content == 'string') { e.appendChild(document.createTextNode(content)); } else if (content) { for (let i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } return e; } export function clear(node: ChildNode): void { for (let count = node.childNodes.length; count > 0; --count) { node.removeChild(node.firstChild); } } export function attrs(elt: Element, ...args: any[]): void { for (let i = 1; i < args.length; i += 2) { elt.setAttribute(args[i], args[i + 1]); } } export function posMin( a: CodeMirror.Position, b: CodeMirror.Position ): CodeMirror.Position { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; } export function posMax( a: CodeMirror.Position, b: CodeMirror.Position ): CodeMirror.Position { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; } export function posEq( a: CodeMirror.Position, b: CodeMirror.Position ): boolean { return a.line == b.line && a.ch == b.ch; } function findPrevDiff( chunks: MergeView.IMergeViewDiffChunk[], start: number, isOrig: boolean ) { for (let i = chunks.length - 1; i >= 0; i--) { const chunk = chunks[i]; const to = (isOrig ? chunk.origTo : chunk.editTo) - 1; if (to < start) { return to; } } } function findNextDiff( chunks: MergeView.IMergeViewDiffChunk[], start: number, isOrig: boolean ) { for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const from = isOrig ? chunk.origFrom : chunk.editFrom; if (from > start) { return from; } } } export function goNearbyDiff( cm: CodeMirror.Editor, dir: number ): void | { toString(): 'CodeMirror.PASS'; } { let found = null; const views = cm.state.diffViews; // @ts-ignore const line = cm.getCursor().line; if (views) { for (let i = 0; i < views.length; i++) { const dv = views[i]; const isOrig = cm == dv.orig; ensureDiff(dv); const pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig); if ( pos != null && (found == null || (dir < 0 ? pos > found : pos < found)) ) { found = pos; } } } if (found != null) { // @ts-ignore cm.setCursor(found, 0); } else { return CodeMirror.Pass; } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; import {ARN} from ".."; /** * Manages an AWS DataSync Task, which represents a configuration for synchronization. Starting an execution of these DataSync Tasks (actually synchronizing files) is performed outside of this resource. * * ## Example Usage * ### With Scheduling * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.datasync.Task("example", { * destinationLocationArn: aws_datasync_location_s3.destination.arn, * sourceLocationArn: aws_datasync_location_nfs.source.arn, * schedule: { * scheduleExpression: "cron(0 12 ? * SUN,WED *)", * }, * }); * ``` * ### With Filtering * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.datasync.Task("example", { * destinationLocationArn: aws_datasync_location_s3.destination.arn, * sourceLocationArn: aws_datasync_location_nfs.source.arn, * excludes: { * filterType: "SIMPLE_PATTERN", * value: "/folder1|/folder2", * }, * }); * ``` * * ## Import * * `aws_datasync_task` can be imported by using the DataSync Task Amazon Resource Name (ARN), e.g. * * ```sh * $ pulumi import aws:datasync/task:Task example arn:aws:datasync:us-east-1:123456789012:task/task-12345678901234567 * ``` */ export class Task extends pulumi.CustomResource { /** * Get an existing Task 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?: TaskState, opts?: pulumi.CustomResourceOptions): Task { return new Task(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:datasync/task:Task'; /** * Returns true if the given object is an instance of Task. 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 Task { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Task.__pulumiType; } /** * Amazon Resource Name (ARN) of the DataSync Task. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Amazon Resource Name (ARN) of the CloudWatch Log Group that is used to monitor and log events in the sync task. */ public readonly cloudwatchLogGroupArn!: pulumi.Output<ARN | undefined>; /** * Amazon Resource Name (ARN) of destination DataSync Location. */ public readonly destinationLocationArn!: pulumi.Output<ARN>; /** * Filter rules that determines which files to exclude from a task. */ public readonly excludes!: pulumi.Output<outputs.datasync.TaskExcludes | undefined>; /** * Name of the DataSync Task. */ public readonly name!: pulumi.Output<string>; /** * Configuration block containing option that controls the default behavior when you start an execution of this DataSync Task. For each individual task execution, you can override these options by specifying an overriding configuration in those executions. */ public readonly options!: pulumi.Output<outputs.datasync.TaskOptions | undefined>; /** * Specifies a schedule used to periodically transfer files from a source to a destination location. */ public readonly schedule!: pulumi.Output<outputs.datasync.TaskSchedule | undefined>; /** * Amazon Resource Name (ARN) of source DataSync Location. */ public readonly sourceLocationArn!: pulumi.Output<ARN>; /** * Key-value pairs of resource tags to assign to the DataSync Task. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Create a Task 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: TaskArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: TaskArgs | TaskState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as TaskState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["cloudwatchLogGroupArn"] = state ? state.cloudwatchLogGroupArn : undefined; inputs["destinationLocationArn"] = state ? state.destinationLocationArn : undefined; inputs["excludes"] = state ? state.excludes : undefined; inputs["name"] = state ? state.name : undefined; inputs["options"] = state ? state.options : undefined; inputs["schedule"] = state ? state.schedule : undefined; inputs["sourceLocationArn"] = state ? state.sourceLocationArn : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; } else { const args = argsOrState as TaskArgs | undefined; if ((!args || args.destinationLocationArn === undefined) && !opts.urn) { throw new Error("Missing required property 'destinationLocationArn'"); } if ((!args || args.sourceLocationArn === undefined) && !opts.urn) { throw new Error("Missing required property 'sourceLocationArn'"); } inputs["cloudwatchLogGroupArn"] = args ? args.cloudwatchLogGroupArn : undefined; inputs["destinationLocationArn"] = args ? args.destinationLocationArn : undefined; inputs["excludes"] = args ? args.excludes : undefined; inputs["name"] = args ? args.name : undefined; inputs["options"] = args ? args.options : undefined; inputs["schedule"] = args ? args.schedule : undefined; inputs["sourceLocationArn"] = args ? args.sourceLocationArn : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Task.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Task resources. */ export interface TaskState { /** * Amazon Resource Name (ARN) of the DataSync Task. */ arn?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the CloudWatch Log Group that is used to monitor and log events in the sync task. */ cloudwatchLogGroupArn?: pulumi.Input<ARN>; /** * Amazon Resource Name (ARN) of destination DataSync Location. */ destinationLocationArn?: pulumi.Input<ARN>; /** * Filter rules that determines which files to exclude from a task. */ excludes?: pulumi.Input<inputs.datasync.TaskExcludes>; /** * Name of the DataSync Task. */ name?: pulumi.Input<string>; /** * Configuration block containing option that controls the default behavior when you start an execution of this DataSync Task. For each individual task execution, you can override these options by specifying an overriding configuration in those executions. */ options?: pulumi.Input<inputs.datasync.TaskOptions>; /** * Specifies a schedule used to periodically transfer files from a source to a destination location. */ schedule?: pulumi.Input<inputs.datasync.TaskSchedule>; /** * Amazon Resource Name (ARN) of source DataSync Location. */ sourceLocationArn?: pulumi.Input<ARN>; /** * Key-value pairs of resource tags to assign to the DataSync Task. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a Task resource. */ export interface TaskArgs { /** * Amazon Resource Name (ARN) of the CloudWatch Log Group that is used to monitor and log events in the sync task. */ cloudwatchLogGroupArn?: pulumi.Input<ARN>; /** * Amazon Resource Name (ARN) of destination DataSync Location. */ destinationLocationArn: pulumi.Input<ARN>; /** * Filter rules that determines which files to exclude from a task. */ excludes?: pulumi.Input<inputs.datasync.TaskExcludes>; /** * Name of the DataSync Task. */ name?: pulumi.Input<string>; /** * Configuration block containing option that controls the default behavior when you start an execution of this DataSync Task. For each individual task execution, you can override these options by specifying an overriding configuration in those executions. */ options?: pulumi.Input<inputs.datasync.TaskOptions>; /** * Specifies a schedule used to periodically transfer files from a source to a destination location. */ schedule?: pulumi.Input<inputs.datasync.TaskSchedule>; /** * Amazon Resource Name (ARN) of source DataSync Location. */ sourceLocationArn: pulumi.Input<ARN>; /** * Key-value pairs of resource tags to assign to the DataSync Task. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import * as React from 'react'; import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; import "@pnp/sp/fields"; import "@pnp/sp/views"; import { Logger, LogLevel } from "@pnp/logging"; import { hOP } from "@pnp/common"; import { IPropertyFieldCamlQueryFieldMappingPropsInternal, IField, IList, ISort, SortDirection, IMapping, SPFieldType, SPFieldRequiredLevel } from './PropertyFieldCamlQueryFieldMapping'; import { Async, Dropdown, IDropdownOption, Label, Slider, TextField, Button, ButtonType, CommandButton, Spinner, SpinnerType, Dialog, DialogType } from 'office-ui-fabric-react'; import styles from "../PropertyFields.module.scss"; import * as strings from 'propertyFieldStrings'; import { Caml, CamlBuilder } from '../../utilities/caml/camljs'; import { List } from 'linqts'; /** * @interface * PropertyFieldCamlQueryHost properties interface * */ export interface IPropertyFieldCamlQueryFieldMappingHostProps extends IPropertyFieldCamlQueryFieldMappingPropsInternal { } export interface IFilter { field?: string; fieldKind?: number; operator?: string; value?: string; } export interface IPropertyFieldCamlQueryFieldMappingHostState { lists: IList[]; fields: List<IField>; arranged: IDropdownOption[]; selectedList?: IList; sort?: ISort; max?: number; operators?: IDropdownOption[]; filters?: IFilter[]; filterType: string; fieldMappings?: IMapping[]; errorMessage?: string; loadedList: boolean; loadedFields: boolean; isCreateOpen: boolean; newListTitle: string; } /** * @class * Renders the controls for PropertyFieldCamlQuery component */ export default class PropertyFieldCamlQueryFieldMappingHost extends React.Component<IPropertyFieldCamlQueryFieldMappingHostProps, IPropertyFieldCamlQueryFieldMappingHostState> { private LOG_SOURCE = "PropertyFieldCamlQueryFieldMappingHost"; private latestValidateValue: string; //private latestMappingValidateValue: IMapping[]; private async: Async; private delayedValidate: (value: string) => void; //private delayedMappingValidate: (value: IMapping[]) => void; private _stateCopy: IPropertyFieldCamlQueryFieldMappingHostState; public get stateCopy() { return this._stateCopy; } public set stateCopy(value: IPropertyFieldCamlQueryFieldMappingHostState) { this._stateCopy = value; } /** * @function * Constructor */ constructor(props: IPropertyFieldCamlQueryFieldMappingHostProps) { super(props); try { var stateObj = { max: 30, selectedList: {}, sort: {}, fieldMappings: [], filterType: "", filters: [] }; if (this.props && this.props.properties[this.props.dataPropertyPath]) { stateObj = JSON.parse(this.props.properties[this.props.dataPropertyPath]); const currMappings = [...stateObj.fieldMappings]; stateObj.fieldMappings = []; this.props.fieldMappings.map((item: IMapping, index?: number) => { var mapping = ''; for (const map of currMappings) { if (item.name === map.name) mapping = map.mappedTo; } stateObj.fieldMappings.push({ name: item.name, type: item.type, requiredLevel: item.requiredLevel, enabled: item.requiredLevel === SPFieldRequiredLevel.Required, mappedTo: mapping }); }); for (const i of this.props.fieldMappings) { var exists = false; for (const j of stateObj.fieldMappings) { if (i.name === j.name) exists = true; continue; } if (!exists) { stateObj.fieldMappings.push(i); } } } this.state = this.stateCopy = { loadedList: false, loadedFields: false, lists: [], fields: new List<IField>(), arranged: [{ key: SortDirection.Ascending, text: 'Ascending' }, { key: SortDirection.Descending, text: 'Descending' }], selectedList: stateObj.selectedList ? stateObj.selectedList : {}, sort: stateObj.sort ? stateObj.sort : {}, operators: [ { key: 'Eq', text: strings.SPListQueryOperatorEq }, { key: 'Ne', text: strings.SPListQueryOperatorNe }, { key: 'startsWith', text: strings.SPListQueryOperatorStartsWith }, { key: 'substringof', text: strings.SPListQueryOperatorSubstringof }, { key: 'Lt', text: strings.SPListQueryOperatorLt }, { key: 'Le', text: strings.SPListQueryOperatorLe }, { key: 'Gt', text: strings.SPListQueryOperatorGt }, { key: 'Ge', text: strings.SPListQueryOperatorGe } ], filters: stateObj.filters, filterType: stateObj.filterType ? stateObj.filterType : strings.SPListFilterCompareAll, fieldMappings: stateObj.fieldMappings, max: stateObj.max ? stateObj.max : 100, errorMessage: '', isCreateOpen: false, newListTitle: "" }; this.async = new Async(this); this.delayedValidate = this.async.debounce(this._validate, this.props.deferredValidationTime); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (constructor)`, LogLevel.Error); } } public componentDidMount() { this._loadLists(); this._loadFields(this.state.selectedList); } /** * @function * Loads the list from SharePoint current web site */ private _loadLists = async (): Promise<void> => { try { let lists: ISPList[] = await sp.web.lists.select("Title", "Id", "BaseTemplate").filter("Hidden eq false").get(); let stateLists = []; lists.map((list: ISPList) => { stateLists.push({ id: list.Id, title: list.Title }); }); this.stateCopy.lists = stateLists; this.stateCopy.loadedList = true; this.setState(this.stateCopy); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_loadLists)`, LogLevel.Error); } } private _loadFields = async (list: IList): Promise<void> => { try { if (list && list.id) { let response: ISPField[] = await sp.web.lists.getById(list.id).fields.select("Title", "InternalName", "TypeAsString").filter("((Hidden eq false) or (Title eq 'PromotedState'))").orderBy("Title").get(); let fields = new List<IField>(); response.map((field: ISPField) => { const option = { internalName: field.InternalName, name: `${field.Title} - ${field.InternalName}`, kind: this._getKindForType(field.TypeAsString) }; fields.Add(option); }); this.stateCopy.fields = fields; this.stateCopy.loadedFields = true; this._saveQuery(); } } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_loadFields)`, LogLevel.Error); } } private _getKindForType = (type: string): SPFieldType => { switch (type) { case "URL": return SPFieldType.URL; case "Boolean": return SPFieldType.Boolean; case "PublishingScheduleStartDateFieldType": case "PublishingScheduleEndDateFieldType": case "Date": return SPFieldType.Date; case "DateTime": return SPFieldType.DateTime; case "User": return SPFieldType.User; case "Lookup": return SPFieldType.Lookup; case "Integer": return SPFieldType.Integer; case "Number": return SPFieldType.Number; case "Counter": return SPFieldType.Counter; case "Choice": return SPFieldType.Choice; case "TaxonomyFieldType": return SPFieldType.Taxonomy; default: return SPFieldType.Text; } } private _getFieldList = (fieldType: SPFieldType): IDropdownOption[] => { let retVal = []; try { const fields = this.stateCopy.fields.Where(f => f.kind == fieldType).ToArray(); fields.forEach(element => { retVal.push({ key: element.internalName, text: element.name }); }); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_getFieldList)`, LogLevel.Error); } return retVal; } private getFieldByInternalName = (fieldTypeName: string): IField => { let retVal; try { const fields = this.stateCopy.fields.Where(f => f.internalName == fieldTypeName).ToArray(); if (fields?.length > 0) retVal = fields[0]; } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (getFieldByInternalName)`, LogLevel.Error); } return retVal; } private _saveQuery = (): void => { try { let listViewFields: string[] = []; if (this.stateCopy.fieldMappings.length === 0) { this.stateCopy.fields.ForEach(element => { listViewFields.push(element.internalName.trim().replace(' ', '_x0020_')); }); } else { this.stateCopy.fieldMappings.map((mappedField: IMapping) => { if (typeof mappedField.mappedTo != 'undefined' && mappedField.enabled) listViewFields.push(mappedField.mappedTo.trim().replace(' ', '_x0020_')); }); } if (listViewFields.indexOf("Title") == -1 && listViewFields.length > 0) { listViewFields.push("Title"); } const conditions: Caml.IExpression[] = []; this.stateCopy.filters.forEach(element => { if (element.field == null || element.field == '' || element.operator == null || element.operator == '' || element.value == null) return; const field: IField = this.getFieldByInternalName(element.field as string); if (field === null) { this.stateCopy.filters.splice(this.stateCopy.filters.indexOf(element), 1); return; } switch (field.kind) { case SPFieldType.Boolean: const val = element.value ? element.value.toLocaleLowerCase().trim() : "false"; if (element.operator === "Ne") conditions.push(CamlBuilder.Expression().BooleanField(element.field).NotEqualTo(val === "yes" || val === "true" || val === "1")); else conditions.push(CamlBuilder.Expression().BooleanField(element.field).EqualTo(val === "yes" || val === "true" || val === "1")); break; case SPFieldType.Integer: const integerValue = parseInt(element.value); switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().IntegerField(element.field).NotEqualTo(integerValue)); break; case "Le": conditions.push(CamlBuilder.Expression().IntegerField(element.field).LessThanOrEqualTo(integerValue)); break; case "Lt": conditions.push(CamlBuilder.Expression().IntegerField(element.field).LessThan(integerValue)); break; case "Ge": conditions.push(CamlBuilder.Expression().IntegerField(element.field).GreaterThanOrEqualTo(integerValue)); break; case "Gt": conditions.push(CamlBuilder.Expression().IntegerField(element.field).GreaterThan(integerValue)); break; default: conditions.push(CamlBuilder.Expression().IntegerField(element.field).EqualTo(integerValue)); break; } break; case SPFieldType.Counter: const counterValue = parseInt(element.value); switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().CounterField(element.field).NotEqualTo(counterValue)); break; case "Le": conditions.push(CamlBuilder.Expression().CounterField(element.field).LessThanOrEqualTo(counterValue)); break; case "Lt": conditions.push(CamlBuilder.Expression().CounterField(element.field).LessThan(counterValue)); break; case "Ge": conditions.push(CamlBuilder.Expression().CounterField(element.field).GreaterThanOrEqualTo(counterValue)); break; case "Gt": conditions.push(CamlBuilder.Expression().CounterField(element.field).GreaterThan(counterValue)); break; default: conditions.push(CamlBuilder.Expression().CounterField(element.field).EqualTo(counterValue)); break; } break; case SPFieldType.Date: switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().DateField(element.field).NotEqualTo(element.value)); break; case "Le": conditions.push(CamlBuilder.Expression().DateField(element.field).LessThanOrEqualTo(element.value)); break; case "Lt": conditions.push(CamlBuilder.Expression().DateField(element.field).LessThan(element.value)); break; case "Ge": conditions.push(CamlBuilder.Expression().DateField(element.field).GreaterThanOrEqualTo(element.value)); break; case "Gt": conditions.push(CamlBuilder.Expression().DateField(element.field).GreaterThan(element.value)); break; default: conditions.push(CamlBuilder.Expression().DateField(element.field).EqualTo(element.value)); break; } break; case SPFieldType.DateTime: switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().DateTimeField(element.field).NotEqualTo(element.value)); break; case "Le": conditions.push(CamlBuilder.Expression().DateTimeField(element.field).LessThanOrEqualTo(element.value)); break; case "Lt": conditions.push(CamlBuilder.Expression().DateTimeField(element.field).LessThan(element.value)); break; case "Ge": conditions.push(CamlBuilder.Expression().DateTimeField(element.field).GreaterThanOrEqualTo(element.value)); break; case "Gt": conditions.push(CamlBuilder.Expression().DateTimeField(element.field).GreaterThan(element.value)); break; default: conditions.push(CamlBuilder.Expression().DateTimeField(element.field).EqualTo(element.value)); break; } break; case SPFieldType.Lookup: if (!isNaN(Number(element.value))) conditions.push(CamlBuilder.Expression().LookupField(element.field).Id().EqualTo(Number(element.value))); else { switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().LookupField(element.field).ValueAsText().NotEqualTo(element.value)); break; case "startsWith": conditions.push(CamlBuilder.Expression().LookupField(element.field).ValueAsText().BeginsWith(element.value)); break; case "substringOf": conditions.push(CamlBuilder.Expression().LookupField(element.field).ValueAsText().Contains(element.value)); break; default: conditions.push(CamlBuilder.Expression().LookupField(element.field).ValueAsText().EqualTo(element.value)); break; } } break; case SPFieldType.Number: const numberValue = parseFloat(element.value); switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().NumberField(element.field).NotEqualTo(numberValue)); break; case "Le": conditions.push(CamlBuilder.Expression().NumberField(element.field).LessThanOrEqualTo(numberValue)); break; case "Lt": conditions.push(CamlBuilder.Expression().NumberField(element.field).LessThan(numberValue)); break; case "Ge": conditions.push(CamlBuilder.Expression().NumberField(element.field).GreaterThanOrEqualTo(numberValue)); break; case "Gt": conditions.push(CamlBuilder.Expression().NumberField(element.field).GreaterThan(numberValue)); break; default: conditions.push(CamlBuilder.Expression().NumberField(element.field).EqualTo(numberValue)); break; } break; case SPFieldType.URL: switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().UrlField(element.field).NotEqualTo(element.value)); break; case "startsWith": conditions.push(CamlBuilder.Expression().UrlField(element.field).BeginsWith(element.value)); break; case "substringOf": conditions.push(CamlBuilder.Expression().UrlField(element.field).Contains(element.value)); break; default: conditions.push(CamlBuilder.Expression().UrlField(element.field).EqualTo(element.value)); break; } break; case SPFieldType.Choice: switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().TextField(element.field).NotEqualTo(element.value)); break; case "startsWith": conditions.push(CamlBuilder.Expression().TextField(element.field).BeginsWith(element.value)); break; case "substringOf": conditions.push(CamlBuilder.Expression().TextField(element.field).Contains(element.value)); break; default: conditions.push(CamlBuilder.Expression().TextField(element.field).EqualTo(element.value)); break; } break; case SPFieldType.User: if (element.value === "Me") { conditions.push(CamlBuilder.Expression().UserField(element.field).EqualToCurrentUser()); } else { switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().UserField(element.field).ValueAsText().NotEqualTo(element.value)); break; case "startsWith": conditions.push(CamlBuilder.Expression().UserField(element.field).ValueAsText().BeginsWith(element.value)); break; case "substringOf": conditions.push(CamlBuilder.Expression().UserField(element.field).ValueAsText().Contains(element.value)); break; default: conditions.push(CamlBuilder.Expression().UserField(element.field).ValueAsText().EqualTo(element.value)); break; } } break; default: switch (element.operator) { case "Ne": conditions.push(CamlBuilder.Expression().TextField(element.field).NotEqualTo(element.value)); break; case "startsWith": conditions.push(CamlBuilder.Expression().TextField(element.field).BeginsWith(element.value)); break; case "substringof": conditions.push(CamlBuilder.Expression().TextField(element.field).Contains(element.value)); break; default: conditions.push(CamlBuilder.Expression().TextField(element.field).EqualTo(element.value)); break; } break; } }); let queryXml: string = ''; if (this.stateCopy.filterType === strings.SPListFilterCompareAny) { if (this.stateCopy.sort && this.stateCopy.sort.title) { if (this.stateCopy.sort.direction === SortDirection.Descending) { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .Any(conditions) .OrderByDesc(this.stateCopy.sort.title) .ToString(); } else { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .Any(conditions) .OrderBy(this.stateCopy.sort.title) .ToString(); } } else { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .Any(conditions) .ToString(); } } else { if (this.stateCopy.sort != undefined && this.stateCopy.sort.title) { if (this.stateCopy.sort.direction === SortDirection.Descending) { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .All(conditions) .OrderByDesc(this.stateCopy.sort.title) .ToString(); } else { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .All(conditions) .OrderBy(this.stateCopy.sort.title) .ToString(); } } else { queryXml = new CamlBuilder() //Any orderby at this .View(listViewFields) .RowLimit(this.stateCopy.max) .Query() .Where() .All(conditions) .ToString(); } } //Order this.props.properties[this.props.dataPropertyPath] = JSON.stringify({ filters: this.stateCopy.filters, max: this.stateCopy.max, selectedList: this.stateCopy.selectedList, sort: this.stateCopy.sort, fieldMappings: this.stateCopy.fieldMappings }); if (this.delayedValidate !== null && this.delayedValidate !== undefined) { this.delayedValidate(queryXml); } this.setState(this.stateCopy); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_saveQuery)`, LogLevel.Error); } } /** * @function * Validates the new custom field value */ private _validate = (value: string): void => { try { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this._notifyAfterValidate(this.props.query, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; const result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this._notifyAfterValidate(this.props.query, value); this.setState({ errorMessage: result }); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this._notifyAfterValidate(this.props.query, value); this.setState({ errorMessage: errorMessage }); }); } } else { this._notifyAfterValidate(this.props.query, value); } } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_validate)`, LogLevel.Error); } } /** * @function * Notifies the parent Web Part of a property value change */ private _notifyAfterValidate = (oldValue: string, newValue: string): void => { try { if (this.props.onPropertyChange && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (this.props.render) this.props.render(); } } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_notifyAfterValidate)`, LogLevel.Error); } } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * @function * Raises when a list has been selected */ private _onChangedList = (option: IDropdownOption, index?: number): void => { try { const selectedList: IList = { id: option.key as string, title: option.text as string, }; this.stateCopy.selectedList = selectedList; this._loadFields(selectedList); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedList)`, LogLevel.Error); } } private _onChangedField = (option: IDropdownOption, index?: number): void => { try { let sort = JSON.parse(JSON.stringify(this.stateCopy.sort)); sort.title = option.key as string; this.stateCopy.sort = sort; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedField)`, LogLevel.Error); } } private _onChangedArranged = (option: IDropdownOption, index?: number): void => { try { let sort = JSON.parse(JSON.stringify(this.stateCopy.sort)); sort.direction = option.key as number; this.stateCopy.sort = sort; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedArranged)`, LogLevel.Error); } } private _onChangedMax = (newValue?: number): void => { this.stateCopy.max = newValue; this._saveQuery(); } private _onClickAddFilter = (elm?: any): void => { this.stateCopy.filters = [...this.stateCopy.filters, {}]; this._saveQuery(); } private _onClickRemoveFilter = (index: number): void => { if (index > -1) { this.stateCopy.filters = [...this.stateCopy.filters.splice(index, 1)]; this._saveQuery(); } } private _onChangedFilterType = (option: IDropdownOption, index?: number): void => { this.stateCopy.filterType = option.key.toString(); this._saveQuery(); } private _onChangedFilterField = (option: IDropdownOption, index?: number, selectedIndex?: number): void => { try { let filters = JSON.parse(JSON.stringify(this.stateCopy.filters)); filters[selectedIndex].field = option.key as string; this.stateCopy.filters = filters; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedFilterField)`, LogLevel.Error); } } private _onChangedFilterOperator = (option: IDropdownOption, index?: number, selectedIndex?: number): void => { try { let filters = JSON.parse(JSON.stringify(this.stateCopy.filters)); filters[selectedIndex].operator = option.key as string; this.stateCopy.filters = filters; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedFilterOperator)`, LogLevel.Error); } } private _onChangedFilterValue = (value?: string, index?: number): void => { try { let filters = JSON.parse(JSON.stringify(this.stateCopy.filters)); filters[index].value = value; this.stateCopy.filters = filters; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedFilterValue)`, LogLevel.Error); } } private _onChangedFieldMapping = (option: IDropdownOption, index?: number): void => { try { let fieldMappings = JSON.parse(JSON.stringify(this.stateCopy.fieldMappings)); fieldMappings[index].mappedTo = option.key.toString(); this.stateCopy.fieldMappings = fieldMappings; this._saveQuery(); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedFieldMapping)`, LogLevel.Error); } } // private _onChangedFieldMappingEnabled(sender: FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean, index?: number) { // try { // let fieldMappings = JSON.parse(JSON.stringify(this.stateCopy.fieldMappings)); // fieldMappings[index].enabled = checked; // this.stateCopy.fieldMappings = fieldMappings; // this._saveQuery(); // } catch (err) { // Logger.write(`${err} - ${this.LOG_SOURCE} (_onChangedFieldMappingEnabled)`, LogLevel.Error); // } // } private _openCreateNewListDialog = (element?: any): void => { this.stateCopy.isCreateOpen = true; this.setState(this.stateCopy); } private _changeNewListTitle = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => { this.stateCopy.newListTitle = newValue; this.setState(this.stateCopy); } private _createNewList = async (element?: any): Promise<void> => { try { const desc = 'List created by an SPFX webpart'; let result = await sp.web.lists.add(this.stateCopy.newListTitle, desc, 100); if (result.data && hOP(result.data, "Id") && hOP(result.data, "Title")) { this.stateCopy.selectedList.id = result.data.Id; this.stateCopy.selectedList.title = result.data.Title; this.setState(this.stateCopy); if (this.props.createTitleRequired) await result.list.fields.getByTitle('Title').update({ Required: false }); for (let f = 0; f < this.props.createFields.length; f++) { let fieldResult = await result.list.fields.createFieldAsXml(this.props.createFields[f]); let fieldViewResult = await sp.web.lists.getById(this.stateCopy.selectedList.id).defaultView.fields.add(fieldResult.data.InternalName); } this._saveAndReloadData(); } } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_createNewList)`, LogLevel.Error); } } private _saveAndReloadData = (): void => { try { this._saveQuery(); this._loadLists(); //Added boolean to trigger updating the default view. this._loadFields(this.stateCopy.selectedList); this.stateCopy.newListTitle = ""; this.stateCopy.isCreateOpen = false; this.setState(this.stateCopy); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_saveAndReloadData)`, LogLevel.Error); } } private _cancelListCreate = (element?: any): void => { try { this.stateCopy.isCreateOpen = false; this.stateCopy.newListTitle = ""; this.setState(this.stateCopy); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (_cancelListCreate)`, LogLevel.Error); } } private _openListInNewTab = async (): Promise<void> => { let data = await sp.web.lists.getById(this.stateCopy.selectedList.id).defaultView.get(); if (data.ServerRelativeUrl && data.ServerRelativeUrl.length > 0) window.open(data.ServerRelativeUrl); } /** * @function * Renders the controls */ public render(): JSX.Element { try { if (this.stateCopy.loadedList === false) { return ( <div> <Label>{this.props.label}</Label> <Spinner type={SpinnerType.normal} /> </div> ); } //Renders content return ( <div> {this.props.showCreate && <div> <Dialog type={DialogType.close} isOpen={this.state.isCreateOpen} title={strings.SPListCreate} containerClassName={styles.msDialogMainCustom} onDismiss={this._cancelListCreate} isDarkOverlay={true} isBlocking={false}> <TextField value={this.state.newListTitle} placeholder={strings.SPListCreatePlaceholder} onChange={this._changeNewListTitle} required={true}></TextField> <div style={{ marginTop: '30px', marginBottom: '30px' }}> <Button buttonType={ButtonType.primary} onClick={this._createNewList}>{strings.CreateButton}</Button> <Button buttonType={ButtonType.normal} onClick={this._cancelListCreate}>{strings.CancelButton}</Button> </div> </Dialog> <Button iconProps={{ iconName: "Add" }} disabled={this.props.disabled} buttonType={ButtonType.command} onClick={this._openCreateNewListDialog}> {strings.SPListCreate} </Button> </div> } <Label hidden={!this.props.label}>{this.props.label}</Label> <Dropdown label={strings.SPListQueryList} onChanged={this._onChangedList} options={this.state.lists.map(l => { return { key: l.id, text: l.title }; })} selectedKey={this.state.selectedList.id} disabled={this.props.disabled} /> <CommandButton iconProps={{ iconName: "Edit" }} disabled={this.props.disabled} buttonType={ButtonType.command} onClick={() => this._openListInNewTab()}> {strings.SPListQueryOpenList} </CommandButton> {this.state.fieldMappings.map((mapping: IMapping, index: number) => { return ( <Dropdown label={mapping.name} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true} options={this._getFieldList(mapping.type)} selectedKey={mapping.mappedTo} onChanged={(option: IDropdownOption, selectIndex?: number) => this._onChangedFieldMapping(option, index)} /> ); })} {this.props.showOrderBy != false ? <div> <Dropdown label={strings.SPListQueryOrderBy} options={this.state.fields.Select<IDropdownOption>(f => { return { key: f.internalName, text: f.name }; }).ToArray()} selectedKey={this.state.sort.title} onChanged={this._onChangedField} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true} /> <Dropdown label={strings.SPListQueryArranged} options={this.state.arranged} selectedKey={this.state.sort.direction} onChanged={this._onChangedArranged} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true} /> </div> : ''} {this.props.showMax != false ? <Slider label={strings.SPListQueryMax} min={1} className={styles["slider"]} max={this.props.max == null ? 100 : this.props.max} defaultValue={this.state.max} onChange={this._onChangedMax} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true} /> : ''} {this.state.filters != null && this.state.filters.length > 1 ? <Dropdown label={strings.SPListFilterCompareType} disabled={this.props.disabled} options={[ { key: strings.SPListFilterCompareAll, text: strings.SPListFilterCompareAll, selected: true }, { key: strings.SPListFilterCompareAny, text: strings.SPListFilterCompareAny } ]} selectedKey={this.state.filterType} onChanged={this._onChangedFilterType.bind(this)} /> : ''} {this.state.filters != null && this.state.filters.length > 0 ? this.state.filters.map((value: IFilter, index: number) => { return ( <div> <Label>Filter</Label> <Dropdown label='' disabled={this.props.disabled} options={this.state.fields.Select<IDropdownOption>(f => { return { key: f.internalName, text: f.name }; }).ToArray()} selectedKey={value.field} onChanged={(option: IDropdownOption, selectIndex?: number) => this._onChangedFilterField(option, selectIndex, index)} /> <Dropdown label='' disabled={this.props.disabled} options={this.state.operators} selectedKey={value.operator} onChanged={(option: IDropdownOption, selectIndex?: number) => this._onChangedFilterOperator(option, selectIndex, index)} /> <TextField disabled={this.props.disabled} defaultValue={value.value} onChange={(ev: any, value2: string) => this._onChangedFilterValue(value2, index)} /> <Button disabled={this.props.disabled} buttonType={ButtonType.command} onClick={() => this._onClickRemoveFilter(index)} iconProps={{ iconName: "Delete" }}> {strings.SPListQueryRemove} </Button> </div> ); }) : ''} {this.props.showFilters != false ? <Button buttonType={ButtonType.command} onClick={this._onClickAddFilter} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true} iconProps={{ iconName: "Add" }}> {strings.SPListQueryAdd} </Button> : ''} {this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div style={{ paddingBottom: '8px' }}><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{this.state.errorMessage}</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{this.state.errorMessage}</p> </span> </div> : ''} </div> ); } catch (err) { Logger.write(`${err} - ${this.LOG_SOURCE} (render)`, LogLevel.Error); } } } /** * @interface * Defines a SharePoint list */ interface ISPList { Title: string; Id: string; BaseTemplate: number; } interface ISPField { Title: string; InternalName: string; TypeAsString: string; }
the_stack
import converter from 'json-2-csv'; import { range } from 'd3-array'; import shortid from 'shortid'; // @ts-ignore import { Analyzer, DATA_TYPES as AnalyzerDatatypes } from 'type-analyzer'; import { isEmpty, uniq, get, uniqBy, cloneDeep } from 'lodash'; import { MotifImportError } from '../../../components/ImportErrorMessage'; import { notNullorUndefined } from '../../../utils/data-utils/data-utils'; import { Accessors, Edge, Field, GraphData, GroupEdgeCandidates, GroupEdges, Metadata, Node, } from '../types'; import { duplicateDictionary } from './group-edges'; type RowData = { [key: string]: any; }[]; // Type analyzer adapted from https://github.com/keplergl/kepler.gl/blob/master/src/processors/data-processor.js export const ALL_FIELD_TYPES = { boolean: 'boolean', date: 'date', integer: 'integer', real: 'real', string: 'string', timestamp: 'timestamp', array: 'array', time: 'time', }; export const DATASET_FORMATS = { json: 'json', csv: 'csv', }; export const ACCEPTED_ANALYZER_TYPES = [ AnalyzerDatatypes.DATE, AnalyzerDatatypes.TIME, AnalyzerDatatypes.DATETIME, AnalyzerDatatypes.INT, AnalyzerDatatypes.FLOAT, AnalyzerDatatypes.BOOLEAN, AnalyzerDatatypes.STRING, AnalyzerDatatypes.ARRAY, ]; // if any of these value occurs in csv, parse it to null; // const CSV_NULLS = ['', 'null', 'NULL', 'Null', 'NaN', '/N']; // matches empty string export const CSV_NULLS = /^(null|NULL|Null|NaN|\/N||)$/; export const IGNORE_DATA_TYPES = Object.keys(AnalyzerDatatypes).filter( (type) => !ACCEPTED_ANALYZER_TYPES.includes(type), ); export const PARSE_FIELD_VALUE_FROM_STRING = { [ALL_FIELD_TYPES.boolean]: { valid: (d: any) => typeof d === 'boolean', parse: (d: any) => d === 'true' || d === 'True' || d === '1', }, [ALL_FIELD_TYPES.integer]: { valid: (d: any) => parseInt(d, 10) === d, parse: (d: any) => parseInt(d, 10), }, [ALL_FIELD_TYPES.timestamp]: { valid: (d: any, field: any) => ['x', 'X'].includes(field.format) ? typeof d === 'number' : typeof d === 'string', parse: (d: any, field: any) => ['x', 'X'].includes(field.format) ? Number(d) : d, }, [ALL_FIELD_TYPES.real]: { valid: (d: any) => parseFloat(d) === d, // Note this will result in NaN for some string parse: parseFloat, }, }; /** * Quick check to test whether json has the keys required of GraphData type * * @param {GraphData} json * @return {boolean} */ export const validateMotifJson = (json: GraphData): boolean => { if ( json.nodes && json.edges && json.metadata && json.metadata.fields && json.metadata.fields.nodes && json.metadata.fields.edges && json.metadata.groupEdges && json.metadata.groupEdges.availability && json.metadata.key ) { return true; } return false; }; /** * Process json data, output a promise GraphData object with field information in metadata. * * @param {GraphData} json * @param {boolean} groupEdges * @param {*} [key=shortid.generate()] Either an accessor string or the key itself * @return {*} {Promise<GraphData>} */ export const processJson = async ( json: GraphData, groupEdges: boolean, key: string | number = shortid.generate(), ): Promise<GraphData> => { if (validateMotifJson(json)) { const modJson = cloneDeep(json); Object.assign(modJson.metadata.groupEdges, { toggle: groupEdges }); return modJson; } // nodes or edges not found in the json, the format is invalid. const { nodes, edges } = json; if (!nodes || !edges) { throw new Error('missing-nodes-or-edges'); } try { const nodeCsv = await json2csv(json.nodes); const edgeCsv = await json2csv(json.edges); const { fields: nodeFields, json: nodeJson } = await processCsvData( nodeCsv as string, ); const { fields: edgeFields, json: edgeJson } = await processCsvData( edgeCsv as string, ); // group edge configuration or metadata is not found in the graph data, // apply the group edge based on user input const groupEdgeConfig: GroupEdges = json.metadata?.groupEdges ?? applyGroupEdges(groupEdges, nodeJson as Node[], edgeJson as Edge[]); const graphMetadata = { ...json?.metadata, fields: { nodes: nodeFields, edges: edgeFields }, key: get(json, 'metadata.key', key), groupEdges: groupEdgeConfig, }; return { nodes: nodeJson as Node[], edges: edgeJson as Edge[], metadata: graphMetadata, }; } catch (err: any) { throw new Error(err.message); } }; /** * Process a node and edge csv file, output a promise GraphData object with field information in metadata. * * @param {string[]} nodeCsvs * @param {string[]} edgeCsvs * @param {boolean} groupEdges * @param {Accessors} accessors * @param {*} [key=shortid.generate()] * @return {*} {Promise<Graph.GraphData>} */ export const processNodeEdgeCsv = async ( nodeCsvs: string[], edgeCsvs: string[], groupEdges: boolean, accessors: Accessors, key: string = shortid.generate(), ): Promise<GraphData> => { const combineFieldsAndJson = ( acc: ProcessedCsv, processedNode: ProcessedCsv, ): ProcessedCsv => { return { fields: uniqBy( [...acc.fields, ...processedNode.fields], 'name', ) as Field[], json: [...acc.json, ...processedNode.json] as Node[] | Edge[], }; }; const emptyFieldsWithJson: ProcessedCsv = { fields: [], json: [] }; const nodeDataPromises = nodeCsvs.map((nodeCsv: string) => processCsvData(nodeCsv), ); const edgeDataPromises = edgeCsvs.map((edgeCsv: string) => processCsvData(edgeCsv), ); try { // obtain node json and node fields from batch uploaded node csv const processedNodeDatas: ProcessedCsv[] = await Promise.all( nodeDataPromises, ); const { fields: nodeFields, json: nodeJson } = processedNodeDatas.reduce( combineFieldsAndJson, emptyFieldsWithJson, ); // obtain edge json and edge fields from batch uploaded edge csv const processedEdgeDatas: ProcessedCsv[] = await Promise.all( edgeDataPromises, ); const { fields: edgeFields, json: edgeJson } = processedEdgeDatas.reduce( combineFieldsAndJson, emptyFieldsWithJson, ); // ensure all the source and target in edges are present. verifySourceAndTargetExistence( nodeJson as Node[], edgeJson as Edge[], accessors, ); const groupEdgeConfig: GroupEdges = applyGroupEdges( groupEdges, nodeJson as Node[], edgeJson as Edge[], ); const graphMetadata: Metadata = { fields: { nodes: nodeFields, edges: edgeFields }, key, groupEdges: groupEdgeConfig, }; const graphData: GraphData = { nodes: nodeJson as Node[], edges: edgeJson as Edge[], metadata: graphMetadata, }; return graphData; } catch (err: any) { if (err instanceof MotifImportError) { const { name, message } = err; throw new MotifImportError(name as any, message); } throw new Error(err.message); } }; /** * Process an edge list csv file, output a promise GraphData object with field information in metadata. * * @param {string} edgeCsv * @param {string} [edgeSourceAccessor='source'] * @param {string} [edgeTargetAccessor='target'] * @param {boolean} groupEdges * @param {*} [key=shortid.generate()] * @return {*} {Promise<Graph.GraphData>} */ export const processEdgeListCsv = async ( edgeCsv: string, edgeSourceAccessor = 'source', edgeTargetAccessor = 'target', groupEdges: boolean, key = shortid.generate(), ): Promise<GraphData> => { const { fields: edgeFields, json: edgeJson } = await processCsvData(edgeCsv); const edgeIds: string[] = []; (edgeJson as Edge[]).forEach((edge: Edge) => { edgeIds.push(edge[edgeSourceAccessor] as string); edgeIds.push(edge[edgeTargetAccessor] as string); }); const uniqueNodes = [...new Set(edgeIds)]; const nodeJson = uniqueNodes.map((node) => { if (!node) { return { id: node }; } return { id: node.toString() }; }); const groupEdgeConfig: GroupEdges = applyGroupEdges( groupEdges, nodeJson as Node[], edgeJson as Edge[], ); const graphMetadata: Metadata = { fields: { nodes: [], edges: edgeFields }, key, groupEdges: groupEdgeConfig, }; return { nodes: nodeJson, edges: edgeJson as Edge[], metadata: graphMetadata, }; }; /** * Converts a json object to csv and returns a promise. * Nested documents will have a '.' appended between the keys. * Arrays of objects will not not be expanded. * * @param {*} json * @return {*} */ export const json2csv = async (json: any): Promise<string | void> => { const csv = converter .json2csvAsync(json) .then() .catch(() => { throw new Error('invalid-json-format'); }); return csv; }; /** * Converts a csv object to json and returns a promise. * Column names with '.' will be treated as a nested object * * @param {string} csv * @return {Promise<void | any[]>} */ export const csv2json = async (csv: string): Promise<void | any[]> => { const json = converter .csv2jsonAsync(csv) .then() .catch(() => { throw new Error('invalid-csv-format'); }); return json; }; /** * Clean up falsy null values and string like arrays * Recursively loop through json object and cast `'', 'null', 'NULL', 'Null', 'NaN'` to `null`, * so that type-analyzer won't detect it as string * Convert arrays like '[a,b,c]' to an actual array [a,b,c] * * @param {*} obj value to parse and clean */ export const cleanUpValue = (obj: any) => { const nullRe = new RegExp(CSV_NULLS, 'g'); const arrayRe = new RegExp(/^\[.*]$/, 'g'); // '[a,b,c]' for (const k in obj) { if ( typeof obj[k] === 'object' && !Array.isArray(obj[k]) && obj[k] !== null ) { cleanUpValue(obj[k]); } else if (typeof obj[k] === 'string' && obj[k].match(arrayRe)) { const cleanArray: any[] = []; const temp = obj[k].slice(1, -1).split(','); temp.forEach((j: any) => cleanArray.push(j)); obj[k] = cleanArray; } else if (typeof obj[k] === 'string' && obj[k].match(nullRe)) { obj[k] = null; } } }; /** * Flatten nested object, excludes arrays * Keys of the new object are dot seperated corresponding to the previous location * * @param {*} obj * @param {string} [history=""] * @return {*} */ export const flattenObject = (obj: any, history = '') => { const result = {}; for (const i in obj) { if ( typeof obj[i] === 'object' && !Array.isArray(obj[i]) && obj[i] !== null ) { Object.assign(result, flattenObject(obj[i], `${history}.${i}`)); } else { result[`${history}.${i}`.replace(/^\./, '')] = obj[i]; } } return result; }; export type ProcessedCsv = { fields: Field[] | []; json: Node[] | Edge[]; }; /** * Process csv data (node / edge csv or edge list), output a promise data object containing the parse fields and graph data. * * @param {string} rawCsv raw csv string * @return {*} {Promise<ProcessedCsv>} */ export const processCsvData = async (rawCsv: string): Promise<ProcessedCsv> => { let parsedJson; if (typeof rawCsv === 'string') { parsedJson = await csv2json(rawCsv); } let headerRow = rawCsv.replace(/\r/g, '').split('\n')[0].split(','); // remove double quotes if they are first and last character of the string // https://stackoverflow.com/a/19156525 headerRow = headerRow.map((row: string) => row.replace(/^"(.*)"$/, '$1')); if (!parsedJson || !headerRow) { throw new Error('invalid-csv-format'); } // assume the csv file that uploaded csv will have first row // header names seperated by a dot indexed to the json position cleanUpValue(parsedJson); // here we get a list of none null values to run analyze on const sample = getSampleForTypeAnalyze(headerRow, parsedJson); // TODO: might want to add validation on id, source, target and style fields. const fields = getFieldsFromData(sample, headerRow); const cleanedJson = parseJsonByFields(parsedJson, fields); return { fields, json: cleanedJson }; }; /** * Parse rows of csv by analyzed field types. So that `'1'` -> `1`, `'True'` -> `true` * @param json * @param {Array<Object>} fields */ export const parseJsonByFields = (json: any[], fields: Field[]) => { // Edit rows in place fields.forEach((field) => { const parser = PARSE_FIELD_VALUE_FROM_STRING[field.type]; if (parser) { // Loop through objects in json and parse field based on accessor and type // check first not null value of it's already parsed const firstValue = get(json[0], field.name); if (!notNullorUndefined(firstValue) || parser.valid(firstValue, field)) { return; } json.forEach((obj) => { // parse string value based on field type const value = get(obj, field.name); if (value !== null) { obj[field.name] = parser.parse(value, field); } }); } }); return json; }; /** * Get sample data for analyzing field type. * * @param {string[]} fields accessor field string that correspond to the location of the data field in allData * @param {any[]} allData object to access * @param {number} [sampleCount=50] number of samples */ export const getSampleForTypeAnalyze = ( fields: string[], allData: any[], sampleCount = 50, ) => { const total = Math.min(sampleCount, allData.length); const sample = range(0, total, 1).map(() => ({})); // collect sample data for each field fields.forEach((field) => { // data counter let i = 0; // sample counter let j = 0; while (j < total) { if (i >= allData.length) { // if depleted data pool sample[j][field] = null; j++; } else if (notNullorUndefined(get(allData[i], field))) { sample[j][field] = get(allData[i], field); j++; i++; } else { i++; } } }); return sample; }; /** * Analyze field types from data in `string` format, e.g. uploaded csv. * Assign `type`, and `format` (timestamp only) to each field * Exclude restricted fields (in, source, target) * * @param data array of row object * @param fieldOrder array of field names as string * @returns formatted fields * @example * * import {getFieldsFromData} from 'kepler.gl/processors'; * const data = [{ * time: '2016-09-17 00:09:55', * value: '4', * surge: '1.2', * isTrip: 'true', * zeroOnes: '0' * }, { * time: '2016-09-17 00:30:08', * value: '3', * surge: null, * isTrip: 'false', * zeroOnes: '1' * }, { * time: null, * value: '2', * surge: '1.3', * isTrip: null, * zeroOnes: '1' * }]; * * const fieldOrder = ['time', 'value', 'surge', 'isTrip', 'zeroOnes']; * const fields = getFieldsFromData(data, fieldOrder); * // fields = [ * // {name: 'time', format: 'YYYY-M-D H:m:s', type: 'timestamp'}, * // {name: 'value', format: '', type: 'integer'}, * // {name: 'surge', format: '', type: 'real'}, * // {name: 'isTrip', format: '', type: 'boolean'}, * // {name: 'zeroOnes', format: '', type: 'integer'}]; * */ export const getFieldsFromData = ( data: RowData, fieldOrder: string[], ): Field[] => { // add a check for epoch timestamp const metadata = Analyzer.computeColMeta( data, [{ regex: /^\[.*]$/g, dataType: 'ARRAY' }], { ignoredDataTypes: IGNORE_DATA_TYPES }, ); const { fieldByIndex } = renameDuplicateFields(fieldOrder); const result: Field[] = []; fieldOrder.forEach((field, index) => { const name = fieldByIndex[index]; const fieldMeta = metadata.find((m: any) => m.key === field); // Excludes undefined type, restricted fields and style / defaultStyle fields if ( typeof fieldMeta !== 'undefined' && !name.includes('style.') && !name.includes('defaultStyle.') ) { const { type, format } = fieldMeta || {}; const fieldType = analyzerTypeToFieldType(type); if (fieldType === 'array') { // Check first value of the array const arrayMetadata = Analyzer.computeColMeta( data.map((x) => { // when the array value is null, we will assign an empty array to prevent errors. // https://github.com/cylynx/motif.gl/issues/133 if (x[name] === null || x[name].length === 0) { return { arrayValue: null }; } return { arrayValue: x[name][0] }; }), [], { ignoredDataTypes: IGNORE_DATA_TYPES }, ); // Only push if array is non-empty if (arrayMetadata.length > 0) { result.push({ name, format, type: `array<${analyzerTypeToFieldType(arrayMetadata[0].type)}>`, analyzerType: type, }); } } // (x|X) is a timestamp format and convert analyzerType to DATETIME else if ( fieldType === ALL_FIELD_TYPES.time && (format === 'x' || format === 'X') ) { result.push({ name, format, type: ALL_FIELD_TYPES.timestamp, analyzerType: AnalyzerDatatypes.DATETIME, }); } else { result.push({ name, format, type: fieldType, analyzerType: type, }); } } }); return result; }; /** * pass in an array of field names, rename duplicated one * and return a map from old field index to new name * * @param {Array} fieldOrder * @returns {Object} new field name by index */ export const renameDuplicateFields = (fieldOrder: string[]) => { return fieldOrder.reduce( (accu, field, i) => { const { allNames } = accu; let fieldName = field; // add a counter to duplicated names if (allNames.includes(field)) { let counter = 0; while (allNames.includes(`${field}-${counter}`)) { counter++; } fieldName = `${field}-${counter}`; } accu.fieldByIndex[i] = fieldName; accu.allNames.push(fieldName); return accu; }, { allNames: [], fieldByIndex: {} }, ); }; /** * Convert type-analyzer output to field types * * @param aType * @returns corresponding type in `ALL_FIELD_TYPES` */ /* eslint-disable complexity */ export const analyzerTypeToFieldType = (aType: string): string => { const { DATE, TIME, DATETIME, NUMBER, INT, FLOAT, BOOLEAN, STRING, GEOMETRY, GEOMETRY_FROM_STRING, PAIR_GEOMETRY_FROM_STRING, ZIPCODE, ARRAY, OBJECT, } = AnalyzerDatatypes; // unrecognized types // CURRENCY PERCENT NONE switch (aType) { case DATE: return ALL_FIELD_TYPES.date; case TIME: return ALL_FIELD_TYPES.time; case DATETIME: return ALL_FIELD_TYPES.timestamp; case FLOAT: return ALL_FIELD_TYPES.real; case INT: return ALL_FIELD_TYPES.integer; case BOOLEAN: return ALL_FIELD_TYPES.boolean; case ARRAY: return ALL_FIELD_TYPES.array; case GEOMETRY: case GEOMETRY_FROM_STRING: case PAIR_GEOMETRY_FROM_STRING: case OBJECT: // return ALL_FIELD_TYPES.geojson; case NUMBER: case STRING: case ZIPCODE: return ALL_FIELD_TYPES.string; default: // eslint-disable-next-line no-console console.warn(`Unsupported analyzer type: ${aType}`); return ALL_FIELD_TYPES.string; } }; /** * Applies group edge onto metadata on every single imports. * * @param toggle * @param nodeJson * @param edgeJson * @return {void} */ export const applyGroupEdges = ( toggle: boolean, nodeJson: Node[], edgeJson: Edge[], ): GroupEdges => { // identify whether graph edges contain duplicate connectivity. const graphData: GraphData = { nodes: nodeJson, edges: edgeJson }; const duplicateConnectivity: GroupEdgeCandidates = duplicateDictionary(graphData); const isDatasetCanGroupEdge = !isEmpty(duplicateConnectivity); if (isDatasetCanGroupEdge === false) { return { toggle: false, availability: false, }; } const groupEdgeConfig: GroupEdges = { toggle, availability: true, }; if (toggle) { groupEdgeConfig.type = 'all'; } return groupEdgeConfig; }; /** * Verify the source and target existence of an edge. * * @param nodes * @param edges * @param accessors * @return {void} */ export const verifySourceAndTargetExistence = ( nodes: Node[], edges: Edge[], accessors: Accessors, ) => { const { nodeID, edgeSource, edgeTarget } = accessors; const nodeIDAccessor = nodeID === 'auto-generate' ? 'id' : nodeID; const nodeIds: string[] = nodes.map((node: Node) => { const nodeIdProperty: string = get(node, nodeIDAccessor, ''); if (typeof nodeIdProperty !== 'string') { return (nodeIdProperty as any).toString(); } return nodeIdProperty.trim(); }); const uniqueNodeIds: string[] = uniq(nodeIds as string[]); edges.forEach((edge: Edge) => { const source: string = get(edge, edgeSource, '').toString().trim(); const target: string = get(edge, edgeTarget, '').toString().trim(); const isPossessSource = uniqueNodeIds.includes(source); if (!isPossessSource) { throw new MotifImportError('edge-source-not-exist', source); } const isPossessTarget = uniqueNodeIds.includes(target); if (!isPossessTarget) { throw new MotifImportError('edge-target-not-exist', target); } }); };
the_stack
import type {HelperManager} from "./HelperManager"; import type {Options} from "./index"; import type NameManager from "./NameManager"; import {isDeclaration} from "./parser/tokenizer"; import {ContextualKeyword} from "./parser/tokenizer/keywords"; import {TokenType as tt} from "./parser/tokenizer/types"; import type TokenProcessor from "./TokenProcessor"; import {getNonTypeIdentifiers} from "./util/getNonTypeIdentifiers"; interface NamedImport { importedName: string; localName: string; } interface ImportInfo { defaultNames: Array<string>; wildcardNames: Array<string>; namedImports: Array<NamedImport>; namedExports: Array<NamedImport>; hasBareImport: boolean; exportStarNames: Array<string>; hasStarExport: boolean; } /** * Class responsible for preprocessing and bookkeeping import and export declarations within the * file. * * TypeScript uses a simpler mechanism that does not use functions like interopRequireDefault and * interopRequireWildcard, so we also allow that mode for compatibility. */ export default class CJSImportProcessor { private nonTypeIdentifiers: Set<string> = new Set(); private importInfoByPath: Map<string, ImportInfo> = new Map(); private importsToReplace: Map<string, string> = new Map(); private identifierReplacements: Map<string, string> = new Map(); private exportBindingsByLocalName: Map<string, Array<string>> = new Map(); constructor( readonly nameManager: NameManager, readonly tokens: TokenProcessor, readonly enableLegacyTypeScriptModuleInterop: boolean, readonly options: Options, readonly isTypeScriptTransformEnabled: boolean, readonly helperManager: HelperManager, ) {} preprocessTokens(): void { for (let i = 0; i < this.tokens.tokens.length; i++) { if ( this.tokens.matches1AtIndex(i, tt._import) && !this.tokens.matches3AtIndex(i, tt._import, tt.name, tt.eq) ) { this.preprocessImportAtIndex(i); } if ( this.tokens.matches1AtIndex(i, tt._export) && !this.tokens.matches2AtIndex(i, tt._export, tt.eq) ) { this.preprocessExportAtIndex(i); } } this.generateImportReplacements(); } /** * In TypeScript, import statements that only import types should be removed. This does not count * bare imports. */ pruneTypeOnlyImports(): void { this.nonTypeIdentifiers = getNonTypeIdentifiers(this.tokens, this.options); for (const [path, importInfo] of this.importInfoByPath.entries()) { if ( importInfo.hasBareImport || importInfo.hasStarExport || importInfo.exportStarNames.length > 0 || importInfo.namedExports.length > 0 ) { continue; } const names = [ ...importInfo.defaultNames, ...importInfo.wildcardNames, ...importInfo.namedImports.map(({localName}) => localName), ]; if (names.every((name) => this.isTypeName(name))) { this.importsToReplace.set(path, ""); } } } isTypeName(name: string): boolean { return this.isTypeScriptTransformEnabled && !this.nonTypeIdentifiers.has(name); } private generateImportReplacements(): void { for (const [path, importInfo] of this.importInfoByPath.entries()) { const { defaultNames, wildcardNames, namedImports, namedExports, exportStarNames, hasStarExport, } = importInfo; if ( defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0 && namedExports.length === 0 && exportStarNames.length === 0 && !hasStarExport ) { // Import is never used, so don't even assign a name. this.importsToReplace.set(path, `require('${path}');`); continue; } const primaryImportName = this.getFreeIdentifierForPath(path); let secondaryImportName; if (this.enableLegacyTypeScriptModuleInterop) { secondaryImportName = primaryImportName; } else { secondaryImportName = wildcardNames.length > 0 ? wildcardNames[0] : this.getFreeIdentifierForPath(path); } let requireCode = `var ${primaryImportName} = require('${path}');`; if (wildcardNames.length > 0) { for (const wildcardName of wildcardNames) { const moduleExpr = this.enableLegacyTypeScriptModuleInterop ? primaryImportName : `${this.helperManager.getHelperName("interopRequireWildcard")}(${primaryImportName})`; requireCode += ` var ${wildcardName} = ${moduleExpr};`; } } else if (exportStarNames.length > 0 && secondaryImportName !== primaryImportName) { requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName( "interopRequireWildcard", )}(${primaryImportName});`; } else if (defaultNames.length > 0 && secondaryImportName !== primaryImportName) { requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName( "interopRequireDefault", )}(${primaryImportName});`; } for (const {importedName, localName} of namedExports) { requireCode += ` ${this.helperManager.getHelperName( "createNamedExportFrom", )}(${primaryImportName}, '${localName}', '${importedName}');`; } for (const exportStarName of exportStarNames) { requireCode += ` exports.${exportStarName} = ${secondaryImportName};`; } if (hasStarExport) { requireCode += ` ${this.helperManager.getHelperName( "createStarExport", )}(${primaryImportName});`; } this.importsToReplace.set(path, requireCode); for (const defaultName of defaultNames) { this.identifierReplacements.set(defaultName, `${secondaryImportName}.default`); } for (const {importedName, localName} of namedImports) { this.identifierReplacements.set(localName, `${primaryImportName}.${importedName}`); } } } private getFreeIdentifierForPath(path: string): string { const components = path.split("/"); const lastComponent = components[components.length - 1]; const baseName = lastComponent.replace(/\W/g, ""); return this.nameManager.claimFreeName(`_${baseName}`); } private preprocessImportAtIndex(index: number): void { const defaultNames: Array<string> = []; const wildcardNames: Array<string> = []; const namedImports: Array<NamedImport> = []; index++; if ( (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._type) || this.tokens.matches1AtIndex(index, tt._typeof)) && !this.tokens.matches1AtIndex(index + 1, tt.comma) && !this.tokens.matchesContextualAtIndex(index + 1, ContextualKeyword._from) ) { // import type declaration, so no need to process anything. return; } if (this.tokens.matches1AtIndex(index, tt.parenL)) { // Dynamic import, so nothing to do return; } if (this.tokens.matches1AtIndex(index, tt.name)) { defaultNames.push(this.tokens.identifierNameAtIndex(index)); index++; if (this.tokens.matches1AtIndex(index, tt.comma)) { index++; } } if (this.tokens.matches1AtIndex(index, tt.star)) { // * as index += 2; wildcardNames.push(this.tokens.identifierNameAtIndex(index)); index++; } if (this.tokens.matches1AtIndex(index, tt.braceL)) { const result = this.getNamedImports(index + 1); index = result.newIndex; for (const namedImport of result.namedImports) { // Treat {default as X} as a default import to ensure usage of require interop helper if (namedImport.importedName === "default") { defaultNames.push(namedImport.localName); } else { namedImports.push(namedImport); } } } if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._from)) { index++; } if (!this.tokens.matches1AtIndex(index, tt.string)) { throw new Error("Expected string token at the end of import statement."); } const path = this.tokens.stringValueAtIndex(index); const importInfo = this.getImportInfo(path); importInfo.defaultNames.push(...defaultNames); importInfo.wildcardNames.push(...wildcardNames); importInfo.namedImports.push(...namedImports); if (defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0) { importInfo.hasBareImport = true; } } private preprocessExportAtIndex(index: number): void { if ( this.tokens.matches2AtIndex(index, tt._export, tt._var) || this.tokens.matches2AtIndex(index, tt._export, tt._let) || this.tokens.matches2AtIndex(index, tt._export, tt._const) ) { this.preprocessVarExportAtIndex(index); } else if ( this.tokens.matches2AtIndex(index, tt._export, tt._function) || this.tokens.matches2AtIndex(index, tt._export, tt._class) ) { const exportName = this.tokens.identifierNameAtIndex(index + 2); this.addExportBinding(exportName, exportName); } else if (this.tokens.matches3AtIndex(index, tt._export, tt.name, tt._function)) { const exportName = this.tokens.identifierNameAtIndex(index + 3); this.addExportBinding(exportName, exportName); } else if (this.tokens.matches2AtIndex(index, tt._export, tt.braceL)) { this.preprocessNamedExportAtIndex(index); } else if (this.tokens.matches2AtIndex(index, tt._export, tt.star)) { this.preprocessExportStarAtIndex(index); } } private preprocessVarExportAtIndex(index: number): void { let depth = 0; // Handle cases like `export let {x} = y;`, starting at the open-brace in that case. for (let i = index + 2; ; i++) { if ( this.tokens.matches1AtIndex(i, tt.braceL) || this.tokens.matches1AtIndex(i, tt.dollarBraceL) || this.tokens.matches1AtIndex(i, tt.bracketL) ) { depth++; } else if ( this.tokens.matches1AtIndex(i, tt.braceR) || this.tokens.matches1AtIndex(i, tt.bracketR) ) { depth--; } else if (depth === 0 && !this.tokens.matches1AtIndex(i, tt.name)) { break; } else if (this.tokens.matches1AtIndex(1, tt.eq)) { const endIndex = this.tokens.currentToken().rhsEndIndex; if (endIndex == null) { throw new Error("Expected = token with an end index."); } i = endIndex - 1; } else { const token = this.tokens.tokens[i]; if (isDeclaration(token)) { const exportName = this.tokens.identifierNameAtIndex(i); this.identifierReplacements.set(exportName, `exports.${exportName}`); } } } } /** * Walk this export statement just in case it's an export...from statement. * If it is, combine it into the import info for that path. Otherwise, just * bail out; it'll be handled later. */ private preprocessNamedExportAtIndex(index: number): void { // export { index += 2; const {newIndex, namedImports} = this.getNamedImports(index); index = newIndex; if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._from)) { index++; } else { // Reinterpret "a as b" to be local/exported rather than imported/local. for (const {importedName: localName, localName: exportedName} of namedImports) { this.addExportBinding(localName, exportedName); } return; } if (!this.tokens.matches1AtIndex(index, tt.string)) { throw new Error("Expected string token at the end of import statement."); } const path = this.tokens.stringValueAtIndex(index); const importInfo = this.getImportInfo(path); importInfo.namedExports.push(...namedImports); } private preprocessExportStarAtIndex(index: number): void { let exportedName = null; if (this.tokens.matches3AtIndex(index, tt._export, tt.star, tt._as)) { // export * as index += 3; exportedName = this.tokens.identifierNameAtIndex(index); // foo from index += 2; } else { // export * from index += 3; } if (!this.tokens.matches1AtIndex(index, tt.string)) { throw new Error("Expected string token at the end of star export statement."); } const path = this.tokens.stringValueAtIndex(index); const importInfo = this.getImportInfo(path); if (exportedName !== null) { importInfo.exportStarNames.push(exportedName); } else { importInfo.hasStarExport = true; } } private getNamedImports(index: number): {newIndex: number; namedImports: Array<NamedImport>} { const namedImports = []; while (true) { if (this.tokens.matches1AtIndex(index, tt.braceR)) { index++; break; } // Flow type imports should just be ignored. let isTypeImport = false; if ( (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._type) || this.tokens.matches1AtIndex(index, tt._typeof)) && this.tokens.matches1AtIndex(index + 1, tt.name) && !this.tokens.matchesContextualAtIndex(index + 1, ContextualKeyword._as) ) { isTypeImport = true; index++; } const importedName = this.tokens.identifierNameAtIndex(index); let localName; index++; if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._as)) { index++; localName = this.tokens.identifierNameAtIndex(index); index++; } else { localName = importedName; } if (!isTypeImport) { namedImports.push({importedName, localName}); } if (this.tokens.matches2AtIndex(index, tt.comma, tt.braceR)) { index += 2; break; } else if (this.tokens.matches1AtIndex(index, tt.braceR)) { index++; break; } else if (this.tokens.matches1AtIndex(index, tt.comma)) { index++; } else { throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.tokens[index])}`); } } return {newIndex: index, namedImports}; } /** * Get a mutable import info object for this path, creating one if it doesn't * exist yet. */ private getImportInfo(path: string): ImportInfo { const existingInfo = this.importInfoByPath.get(path); if (existingInfo) { return existingInfo; } const newInfo = { defaultNames: [], wildcardNames: [], namedImports: [], namedExports: [], hasBareImport: false, exportStarNames: [], hasStarExport: false, }; this.importInfoByPath.set(path, newInfo); return newInfo; } private addExportBinding(localName: string, exportedName: string): void { if (!this.exportBindingsByLocalName.has(localName)) { this.exportBindingsByLocalName.set(localName, []); } this.exportBindingsByLocalName.get(localName)!.push(exportedName); } /** * Return the code to use for the import for this path, or the empty string if * the code has already been "claimed" by a previous import. */ claimImportCode(importPath: string): string { const result = this.importsToReplace.get(importPath); this.importsToReplace.set(importPath, ""); return result || ""; } getIdentifierReplacement(identifierName: string): string | null { return this.identifierReplacements.get(identifierName) || null; } /** * Return a string like `exports.foo = exports.bar`. */ resolveExportBinding(assignedName: string): string | null { const exportedNames = this.exportBindingsByLocalName.get(assignedName); if (!exportedNames || exportedNames.length === 0) { return null; } return exportedNames.map((exportedName) => `exports.${exportedName}`).join(" = "); } /** * Return all imported/exported names where we might be interested in whether usages of those * names are shadowed. */ getGlobalNames(): Set<string> { return new Set([ ...this.identifierReplacements.keys(), ...this.exportBindingsByLocalName.keys(), ]); } }
the_stack
import {GoogleAuthOptions, Metadata, Service} from '@google-cloud/common'; import {paginator} from '@google-cloud/paginator'; import {promisifyAll} from '@google-cloud/promisify'; import arrify = require('arrify'); import {Stream} from 'stream'; import {Zone} from './zone'; export {Record, RecordMetadata} from './record'; export interface GetZonesRequest { autoPaginate?: boolean; maxApiCalls?: number; maxResults?: number; pageToken?: string; } export interface DNSConfig extends GoogleAuthOptions { autoRetry?: boolean; maxRetries?: number; } export interface GetZonesCallback { ( err: Error | null, zones: Zone[] | null, nextQuery?: GetZonesRequest | null, apiResponse?: Metadata ): void; } export type GetZonesResponse = [Zone[], GetZonesRequest | null, Metadata]; export interface GetZoneCallback { (err: Error | null, zone?: Zone | null, apiResponse?: Metadata): void; } export interface CreateZoneRequest { dnsName: string; description?: string; name?: string; dnssecConfig?: ManagedZoneDnsSecConfig; } export interface ManagedZoneDnsSecConfig { /** * Specifies parameters for generating initial DnsKeys for this ManagedZone. Can only be changed while the state is OFF. */ defaultKeySpecs?: DnsKeySpec[]; kind?: string | null; /** * Specifies the mechanism for authenticated denial-of-existence responses. Can only be changed while the state is OFF. */ nonExistence?: string | null; /** * Specifies whether DNSSEC is enabled, and what mode it is in. */ state?: 'on' | 'off' | null; } export interface DnsKeySpec { /** * String mnemonic specifying the DNSSEC algorithm of this key. */ algorithm?: string | null; /** * Length of the keys in bits. */ keyLength?: number | null; /** * Specifies whether this is a key signing key (KSK) or a zone signing key (ZSK). Key signing keys have the Secure Entry Point flag set and, when active, will only be used to sign resource record sets of type DNSKEY. Zone signing keys do not have the Secure Entry Point flag set and will be used to sign all other types of resource record sets. */ keyType?: string | null; kind?: string | null; } export type CreateZoneResponse = [Zone, Metadata]; export type CreateZoneCallback = GetZoneCallback; export interface DNSOptions extends GoogleAuthOptions { /** * The API endpoint of the service used to make requests. * Defaults to `dns.googleapis.com`. */ apiEndpoint?: string; } /** * @typedef {object} ClientConfig * @property {string} [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://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application * Application Default Credentials}, your project ID will be detected * automatically. * @property {string} [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 above is not necessary. NOTE: .pem and * .p12 require you to specify the `email` option as well. * @property {string} [email] Account email address. Required when using a .pem * or .p12 keyFilename. * @property {object} [credentials] Credentials object. * @property {string} [credentials.client_email] * @property {string} [credentials.private_key] * @property {boolean} [autoRetry=true] Automatically retry requests if the * response is related to rate limits or certain intermittent server errors. * We will exponentially backoff subsequent requests by default. * @property {number} [maxRetries=3] Maximum number of automatic retries * attempted before returning the error. * @property {Constructor} [promise] Custom promise module to use instead of * native Promises. */ /** * [Cloud DNS](https://cloud.google.com/dns/what-is-cloud-dns) is a * high-performance, resilient, global DNS service that provides a * cost-effective way to make your applications and services available to your * users. This programmable, authoritative DNS service can be used to easily * publish and manage DNS records using the same infrastructure relied upon by * Google. * * @class * * @see [What is Cloud DNS?]{@link https://cloud.google.com/dns/what-is-cloud-dns} * * @param {ClientConfig} [options] Configuration options. * * @example <caption>Import the client library</caption> * const {DNS} = require('@google-cloud/dns'); * * @example <caption>Create a client that uses <a * href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application * Default Credentials (ADC)</a>:</caption> const dns = new DNS(); * * @example <caption>Create a client with <a * href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit * credentials</a>:</caption> const dns = new DNS({ projectId: * 'your-project-id', keyFilename: '/path/to/keyfile.json' * }); * * @example <caption>include:samples/quickstart.js</caption> * region_tag:dns_quickstart * Full quickstart example: */ class DNS extends Service { getZonesStream: (query: GetZonesRequest) => Stream; constructor(options: DNSOptions = {}) { options.apiEndpoint = options.apiEndpoint || 'dns.googleapis.com'; const config = { apiEndpoint: options.apiEndpoint, baseUrl: `https://${options.apiEndpoint}/dns/v1`, scopes: [ 'https://www.googleapis.com/auth/ndev.clouddns.readwrite', 'https://www.googleapis.com/auth/cloud-platform', ], packageJson: require('../../package.json'), }; super(config, options); /** * Get {@link Zone} objects for all of the zones in your project as * a readable object stream. * * @method DNS#getZonesStream * @param {GetZonesRequest} [query] Query object for listing zones. * @returns {ReadableStream} A readable stream that emits {@link Zone} instances. * * @example * const {DNS} = require('@google-cloud/dns'); * const dns = new DNS(); * * dns.getZonesStream() * .on('error', console.error) * .on('data', function(zone) { * // zone is a Zone object. * }) * .on('end', () => { * // All zones retrieved. * }); * * //- * // If you anticipate many results, you can end a stream early to prevent * // unnecessary processing and API requests. * //- * dns.getZonesStream() * .on('data', function(zone) { * this.end(); * }); */ this.getZonesStream = paginator.streamify('getZones'); } createZone( name: string, config: CreateZoneRequest ): Promise<CreateZoneResponse>; createZone( name: string, config: CreateZoneRequest, callback: GetZoneCallback ): void; /** * Config to set for the zone. * * @typedef {object} CreateZoneRequest * @property {string} dnsName DNS name for the zone. E.g. "example.com." * @property {string} [description] Description text for the zone. */ /** * @typedef {array} CreateZoneResponse * @property {Zone} 0 The new {@link Zone}. * @property {object} 1 The full API response. */ /** * @callback CreateZoneCallback * @param {?Error} err Request error, if any. * @param {Zone} zone The new {@link Zone}. * @param {object} apiResponse The full API response. */ /** * Create a managed zone. * * @method DNS#createZone * @see [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} * * @throws {error} If a zone name is not provided. * @throws {error} If a zone dnsName is not provided. * * @param {string} name Name of the zone to create, e.g. "my-zone". * @param {CreateZoneRequest} config Config to set for the zone. * @param {CreateZoneCallback} [callback] Callback function. * @returns {Promise<CreateZoneResponse>} * @throws {Error} If a name is not provided. * @see Zone#create * * @example * const {DNS} = require('@google-cloud/dns'); * const dns = new DNS(); * * const config = { * dnsName: 'example.com.', // note the period at the end of the domain. * description: 'This zone is awesome!' * }; * * dns.createZone('my-awesome-zone', config, (err, zone, apiResponse) => { * if (!err) { * // The zone was created successfully. * } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dns.createZone('my-awesome-zone', config).then((data) => { * const zone = data[0]; * const apiResponse = data[1]; * }); */ createZone( name: string, config: CreateZoneRequest, callback?: GetZoneCallback ): void | Promise<CreateZoneResponse> { if (!name) { throw new Error('A zone name is required.'); } if (!config || !config.dnsName) { throw new Error('A zone dnsName is required.'); } config.name = name; // Required by the API. config.description = config.description || ''; this.request( { method: 'POST', uri: '/managedZones', json: config, }, (err, resp) => { if (err) { callback!(err, null, resp); return; } const zone = this.zone(resp.name); zone.metadata = resp; callback!(null, zone, resp); } ); } getZones(query?: GetZonesRequest): Promise<GetZonesResponse>; getZones(callback: GetZonesCallback): void; getZones(query: GetZonesRequest, callback: GetZonesCallback): void; /** * Query object for listing zones. * * @typedef {object} GetZonesRequest * @property {boolean} [autoPaginate=true] Have pagination handled * automatically. * @property {number} [maxApiCalls] Maximum number of API calls to make. * @property {number} [maxResults] Maximum number of items plus prefixes to * return. * @property {string} [pageToken] A previously-returned page token * representing part of the larger set of results to view. */ /** * @typedef {array} GetZonesResponse * @property {Zone[]} 0 Array of {@link Zone} instances. * @property {object} 1 The full API response. */ /** * @callback GetZonesCallback * @param {?Error} err Request error, if any. * @param {Zone[]} zones Array of {@link Zone} instances. * @param {object} apiResponse The full API response. */ /** * Gets a list of managed zones for the project. * * @method DNS#getZones * @see [ManagedZones: list API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/list} * * @param {GetZonesRequest} [query] Query object for listing zones. * @param {GetZonesCallback} [callback] Callback function. * @returns {Promise<GetZonesResponse>} * * @example * const {DNS} = require('@google-cloud/dns'); * const dns = new DNS(); * * dns.getZones((err, zones, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dns.getZones().then(data => { * const zones = data[0]; * }); */ getZones( queryOrCallback?: GetZonesRequest | GetZonesCallback, callback?: GetZonesCallback ): void | Promise<GetZonesResponse> { const query = typeof queryOrCallback === 'object' ? queryOrCallback : {}; callback = typeof queryOrCallback === 'function' ? queryOrCallback : callback; this.request( { uri: '/managedZones', qs: query, }, (err, resp) => { if (err) { callback!(err, null, null, resp); return; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const zones = arrify(resp.managedZones).map((zone: any) => { const zoneInstance = this.zone(zone.name); zoneInstance.metadata = zone; return zoneInstance; }); let nextQuery: GetZonesRequest | null = null; if (resp.nextPageToken) { nextQuery = Object.assign({}, query, { pageToken: resp.nextPageToken, }); } callback!(null, zones, nextQuery, resp); } ); } /** * Get a reference to a Zone. * * @param {string} name The unique name of the zone. * @returns {Zone} * @see Zone * * @throws {error} If a zone name is not provided. * * @example * const {DNS} = require('@google-cloud/dns'); * const dns = new DNS(); * * const zone = dns.zone('my-zone'); */ zone(name: string) { if (!name) { throw new Error('A zone name is required.'); } return new Zone(this, name); } } /*! Developer Documentation * * These methods can be auto-paginated. */ paginator.extend(DNS, 'getZones'); /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ promisifyAll(DNS, { exclude: ['zone'], }); /** * {@link Zone} class. * * @name DNS.Zone * @see Zone * @type {Constructor} */ export {Zone}; /** * The default export of the `@google-cloud/dns` package is the {@link DNS} * class. * * See {@link DNS} and {@link ClientConfig} for client methods and * configuration options. * * @module {DNS} @google-cloud/dns * @alias nodejs-dns * * @example <caption>Install the client library with <a * href="https://www.npmjs.com/">npm</a>:</caption> npm install --save * @google-cloud/dns * * @example <caption>Import the client library</caption> * const {DNS} = require('@google-cloud/dns'); * * @example <caption>Create a client that uses <a * href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application * Default Credentials (ADC)</a>:</caption> const dns = new DNS(); * * @example <caption>Create a client with <a * href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit * credentials</a>:</caption> const dns = new DNS({ projectId: * 'your-project-id', keyFilename: '/path/to/keyfile.json' * }); * * @example <caption>include:samples/quickstart.js</caption> * region_tag:dns_quickstart * Full quickstart example: */ export {DNS};
the_stack
import { TextDocument } from 'vscode-languageserver-types'; import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di'; import { URI, Emitter, Event, FileUri, DisposableCollection, IDisposable, BinaryBuffer, parseGlob, ParsedPattern, Deferred, Uri, FilesChangeEvent, ExtensionActivateEvent, AppConfig, } from '@opensumi/ide-core-browser'; import { CorePreferences } from '@opensumi/ide-core-browser/lib/core-preferences'; import { FileSystemProviderCapabilities, IEventBus, Schemes } from '@opensumi/ide-core-common'; import { IElectronMainUIService } from '@opensumi/ide-core-common/lib/electron'; import { Iterable } from '@opensumi/monaco-editor-core/esm/vs/base/common/iterator'; import { FileStat, FileDeleteOptions, FileMoveOptions, IBrowserFileSystemRegistry, IFileSystemProvider, FileSystemProvider, FileSystemError, FileAccess, IDiskFileProvider, containsExtraFileMethod, IFileSystemProviderRegistrationEvent, IFileSystemProviderCapabilitiesChangeEvent, } from '../common'; import { FileChangeEvent, DidFilesChangedParams, FileChange, IFileServiceClient, FileSetContentOptions, FileCreateOptions, FileCopyOptions, IFileServiceWatcher, TextDocumentContentChangeEvent, } from '../common'; import { FileSystemWatcher } from './watcher'; @Injectable() export class BrowserFileSystemRegistryImpl implements IBrowserFileSystemRegistry { public readonly providers = new Map<string, IFileSystemProvider>(); registerFileSystemProvider(provider: IFileSystemProvider) { const scheme = provider.scheme; this.providers.set(scheme, provider); return { dispose: () => { this.providers.delete(scheme); }, }; } } @Injectable() export class FileServiceClient implements IFileServiceClient { protected readonly watcherWithSchemaMap = new Map<string, number[]>(); protected readonly watcherDisposerMap = new Map<number, IDisposable>(); protected readonly onFileChangedEmitter = new Emitter<FileChangeEvent>(); protected readonly onFileProviderChangedEmitter = new Emitter<string[]>(); protected readonly _onFilesChanged = new Emitter<FileChangeEvent>(); readonly onFilesChanged: Event<FileChangeEvent> = this._onFilesChanged.event; protected readonly _onFileProviderChanged = new Emitter<string[]>(); readonly onFileProviderChanged: Event<string[]> = this._onFileProviderChanged.event; protected readonly _onDidChangeFileSystemProviderRegistrations = new Emitter<IFileSystemProviderRegistrationEvent>(); readonly onDidChangeFileSystemProviderRegistrations = this._onDidChangeFileSystemProviderRegistrations.event; private readonly _onDidChangeFileSystemProviderCapabilities = new Emitter<IFileSystemProviderCapabilitiesChangeEvent>(); readonly onDidChangeFileSystemProviderCapabilities = this._onDidChangeFileSystemProviderCapabilities.event; protected filesExcludesMatcherList: ParsedPattern[] = []; protected watcherId = 0; protected toDisposable = new DisposableCollection(); protected watchFileExcludes: string[] = []; protected watchFileExcludesMatcherList: ParsedPattern[] = []; protected filesExcludes: string[] = []; protected workspaceRoots: string[] = []; // 记录哪些 fsProviders 发生了变更 private _providerChanged: Set<string> = new Set(); @Autowired(IBrowserFileSystemRegistry) private registry: BrowserFileSystemRegistryImpl; private fsProviders: Map<string, FileSystemProvider | IDiskFileProvider> = new Map(); @Autowired(INJECTOR_TOKEN) private injector: Injector; @Autowired(IEventBus) private eventBus: IEventBus; @Autowired(AppConfig) private readonly appConfig: AppConfig; private userHomeDeferred: Deferred<FileStat | undefined> = new Deferred(); public options = { encoding: 'utf8', overwrite: false, recursive: true, moveToTrash: true, }; constructor() { this.toDisposable.push( this.onDidChangeFileSystemProviderRegistrations((e) => { // 只支持 file if (e.added && e.scheme === Schemes.file) { this.doGetCurrentUserHome(); } }), ); } private async doGetCurrentUserHome() { const provider = await this.getProvider(Schemes.file); const userHome = provider.getCurrentUserHome(); this.userHomeDeferred.resolve(userHome); } corePreferences: CorePreferences; handlesScheme(scheme: string) { return this.registry.providers.has(scheme) || this.fsProviders.has(scheme); } public dispose() { this.toDisposable.dispose(); } /** * 直接先读文件,错误在后端抛出 * @deprecated 方法在未来或许有变化 * @param uri URI 地址 */ async resolveContent(uri: string, options?: FileSetContentOptions) { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); const rawContent = await provider.readFile(_uri.codeUri); const data = (rawContent as any).data || rawContent; const buffer = BinaryBuffer.wrap(Uint8Array.from(data)); return { content: buffer.toString(options?.encoding) }; } async readFile(uri: string) { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); const rawContent = await provider.readFile(_uri.codeUri); const data = (rawContent as any).data || rawContent; const buffer = BinaryBuffer.wrap(Uint8Array.from(data)); return { content: buffer }; } async getFileStat(uri: string, withChildren = true) { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); try { const stat = await provider.stat(_uri.codeUri); if (!stat) { throw FileSystemError.FileNotFound(_uri.codeUri.toString(), 'File not found.'); } return this.filterStat(stat, withChildren); } catch (err) { if (FileSystemError.FileNotFound.is(err)) { return undefined; } } } async setContent(file: FileStat, content: string | Uint8Array, options?: FileSetContentOptions) { const _uri = this.convertUri(file.uri); const provider = await this.getProvider(_uri.scheme); const stat = await provider.stat(_uri.codeUri); if (!stat) { throw FileSystemError.FileNotFound(file.uri, 'File not found.'); } if (stat.isDirectory) { throw FileSystemError.FileIsDirectory(file.uri, 'Cannot set the content.'); } if (!(await this.isInSync(file, stat))) { throw this.createOutOfSyncError(file, stat); } await provider.writeFile( _uri.codeUri, typeof content === 'string' ? BinaryBuffer.fromString(content).buffer : content, { create: false, overwrite: true, encoding: options?.encoding }, ); const newStat = await provider.stat(_uri.codeUri); return newStat; } async updateContent( file: FileStat, contentChanges: TextDocumentContentChangeEvent[], options?: FileSetContentOptions, ): Promise<FileStat> { const _uri = this.convertUri(file.uri); const provider = await this.getProvider(_uri.scheme); const stat = await provider.stat(_uri.codeUri); if (!stat) { throw FileSystemError.FileNotFound(file.uri, 'File not found.'); } if (stat.isDirectory) { throw FileSystemError.FileIsDirectory(file.uri, 'Cannot set the content.'); } if (!this.checkInSync(file, stat)) { throw this.createOutOfSyncError(file, stat); } if (contentChanges.length === 0) { return stat; } const content = (await provider.readFile(_uri.codeUri)) as Uint8Array; const newContent = this.applyContentChanges(BinaryBuffer.wrap(content).toString(options?.encoding), contentChanges); await provider.writeFile(_uri.codeUri, BinaryBuffer.fromString(newContent).buffer, { create: false, overwrite: true, encoding: options?.encoding, }); const newStat = await provider.stat(_uri.codeUri); if (!newStat) { throw FileSystemError.FileNotFound(_uri.codeUri.toString(), 'File not found.'); } return newStat; } async createFile(uri: string, options?: FileCreateOptions) { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); const content = BinaryBuffer.fromString(options?.content || '').buffer; let newStat: any = await provider.writeFile(_uri.codeUri, content, { create: true, overwrite: (options && options.overwrite) || false, encoding: options?.encoding, }); newStat = newStat || (await provider.stat(_uri.codeUri)); return newStat; } async createFolder(uri: string): Promise<FileStat> { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); const result = await provider.createDirectory(_uri.codeUri); if (result) { return result; } const stat = await provider.stat(_uri.codeUri); return stat as FileStat; } async move(sourceUri: string, targetUri: string, options?: FileMoveOptions): Promise<FileStat> { const _sourceUri = this.convertUri(sourceUri); const _targetUri = this.convertUri(targetUri); const provider = await this.getProvider(_sourceUri.scheme); const result: any = await provider.rename(_sourceUri.codeUri, _targetUri.codeUri, { overwrite: !!(options && options.overwrite), }); if (result) { return result; } const stat = await provider.stat(_targetUri.codeUri); return stat as FileStat; } async copy(sourceUri: string, targetUri: string, options?: FileCopyOptions): Promise<FileStat> { const _sourceUri = this.convertUri(sourceUri); const _targetUri = this.convertUri(targetUri); const provider = await this.getProvider(_sourceUri.scheme); const overwrite = await this.doGetOverwrite(options); if (!containsExtraFileMethod(provider, 'copy')) { throw this.getErrorProvideNotSupport(_sourceUri.scheme, 'copy'); } const result = await provider.copy(_sourceUri.codeUri, _targetUri.codeUri, { overwrite: !!overwrite, }); if (result) { return result; } const stat = await provider.stat(_targetUri.codeUri); return stat as FileStat; } async getFsPath(uri: string) { if (!uri.startsWith('file:/')) { return undefined; } else { return FileUri.fsPath(uri); } } fireFilesChange(event: DidFilesChangedParams): void { const changes: FileChange[] = event.changes.map( (change) => ({ uri: change.uri, type: change.type, } as FileChange), ); this._onFilesChanged.fire(changes); this.eventBus.fire(new FilesChangeEvent(changes)); } private uriWatcherMap: Map<string, FileSystemWatcher> = new Map(); // 添加监听文件 async watchFileChanges(uri: URI, excludes?: string[]): Promise<IFileServiceWatcher> { const _uri = this.convertUri(uri.toString()); if (this.uriWatcherMap.has(_uri.toString())) { return this.uriWatcherMap.get(_uri.toString())!; } const id = this.watcherId++; const provider = await this.getProvider(_uri.scheme); const schemaWatchIdList = this.watcherWithSchemaMap.get(_uri.scheme) || []; const watcherId = await provider.watch(_uri.codeUri, { recursive: true, excludes: excludes || [], }); this.watcherDisposerMap.set(id, { dispose: () => { provider.unwatch && provider.unwatch(watcherId); this.uriWatcherMap.delete(_uri.toString()); }, }); schemaWatchIdList.push(id); this.watcherWithSchemaMap.set(_uri.scheme, schemaWatchIdList); const watcher = new FileSystemWatcher({ fileServiceClient: this, watchId: id, uri, }); this.uriWatcherMap.set(_uri.toString(), watcher); return watcher; } async setWatchFileExcludes(excludes: string[]) { const provider = await this.getProvider(Schemes.file); return await provider.setWatchFileExcludes(excludes); } async getWatchFileExcludes() { const provider = await this.getProvider(Schemes.file); return await provider.getWatchFileExcludes(); } async setFilesExcludes(excludes: string[], roots?: string[]): Promise<void> { this.filesExcludes = excludes; this.filesExcludesMatcherList = []; if (roots) { this.setWorkspaceRoots(roots); } this.updateExcludeMatcher(); } async setWorkspaceRoots(roots: string[]) { this.workspaceRoots = roots; this.updateExcludeMatcher(); } async unwatchFileChanges(watcherId: number): Promise<void> { const disposable = this.watcherDisposerMap.get(watcherId); if (!disposable || !disposable.dispose) { return; } disposable.dispose(); } async delete(uriString: string, options?: FileDeleteOptions) { if (this.appConfig.isElectronRenderer && options && options.moveToTrash) { const uri = new URI(uriString); if (uri.scheme === Schemes.file) { return (this.injector.get(IElectronMainUIService) as IElectronMainUIService).moveToTrash(uri.codeUri.fsPath); } } const _uri = this.convertUri(uriString); const provider = await this.getProvider(_uri.scheme); await provider.stat(_uri.codeUri); await provider.delete(_uri.codeUri, { recursive: true, moveToTrash: await this.doGetMoveToTrash(options), }); } async getEncoding(uri: string): Promise<string> { // FIXME: 临时修复方案 目前识别率太低,全部返回 UTF8 return 'utf8'; } // capabilities listCapabilities(): Iterable<{ scheme: string; capabilities: FileSystemProviderCapabilities }> { return Iterable.map(this.fsProviders, ([scheme, provider]) => ({ scheme, capabilities: provider.capabilities })); } // capabilities end registerProvider(scheme: string, provider: FileSystemProvider): IDisposable { if (this.fsProviders.has(scheme)) { throw new Error(`'${scheme}' 的文件系统 provider 已存在`); } const disposables: IDisposable[] = []; this.fsProviders.set(scheme, provider); this._onDidChangeFileSystemProviderRegistrations.fire({ added: true, scheme, provider }); disposables.push({ dispose: () => { this._onDidChangeFileSystemProviderRegistrations.fire({ added: false, scheme, provider }); this.fsProviders.delete(scheme); this._providerChanged.add(scheme); }, }); if (provider.onDidChangeFile) { disposables.push(provider.onDidChangeFile((e) => this.fireFilesChange({ changes: e }))); } this.toDisposable.push( provider.onDidChangeCapabilities(() => this._onDidChangeFileSystemProviderCapabilities.fire({ provider, scheme }), ), ); disposables.push({ dispose: () => { (this.watcherWithSchemaMap.get(scheme) || []).forEach((id) => this.unwatchFileChanges(id)); }, }); this._providerChanged.add(scheme); this.onFileProviderChangedEmitter.fire(Array.from(this._providerChanged)); this.toDisposable.pushAll(disposables); /** * 当外部注册了当前 Provider 的时候,暴露出去一个 dispose 供注册方去调用 */ const tempToDisable = new DisposableCollection(); tempToDisable.pushAll(disposables); this._onFileProviderChanged.fire(Array.from(this._providerChanged)); return tempToDisable; } async access(uri: string, mode: number = FileAccess.Constants.F_OK): Promise<boolean> { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); if (!containsExtraFileMethod(provider, 'access')) { throw this.getErrorProvideNotSupport(_uri.scheme, 'access'); } return await provider.access(_uri.codeUri, mode); } // 这里需要 try catch 了 async getFileType(uri: string) { const _uri = this.convertUri(uri); const provider = await this.getProvider(_uri.scheme); if (!containsExtraFileMethod(provider, 'getFileType')) { throw this.getErrorProvideNotSupport(_uri.scheme, 'getFileType'); } return await provider.getFileType(uri); } // FIXME: file scheme only? async getCurrentUserHome() { return this.userHomeDeferred.promise; } private getErrorProvideNotSupport(scheme: string, funName: string): string { return `Scheme ${scheme} not support this function: ${funName}.`; } /** * 提供一个方法让集成方对该方法进行复写。 * 如双容器架构中对 IDE 容器读取不到的研发容器目录进行 scheme 替换,让插件提供提供的 fs-provider 去读取 */ protected convertUri(uri: string | Uri): URI { const _uri = new URI(uri); if (!_uri.scheme) { throw new Error(`没有设置 scheme: ${uri}`); } return _uri; } private updateExcludeMatcher() { this.filesExcludes.forEach((str) => { if (this.workspaceRoots.length > 0) { this.workspaceRoots.forEach((root: string) => { const uri = new URI(root); const pathStrWithExclude = uri.resolve(str).path.toString(); this.filesExcludesMatcherList.push(parseGlob(pathStrWithExclude)); }); } else { this.filesExcludesMatcherList.push(parseGlob(str)); } }); } private async getProvider<T extends string>( scheme: T, ): Promise<T extends 'file' ? IDiskFileProvider : FileSystemProvider>; private async getProvider(scheme: string): Promise<IDiskFileProvider | FileSystemProvider> { if (this._providerChanged.has(scheme)) { // 让相关插件启动完成 (3秒超时), 此处防止每次都发,仅在相关scheme被影响时才尝试激活插件 await this.eventBus.fireAndAwait(new ExtensionActivateEvent({ topic: 'onFileSystem', data: scheme }), { timeout: 3000, }); this._providerChanged.delete(scheme); } const provider = this.fsProviders.get(scheme); if (!provider) { throw new Error(`Not find ${scheme} provider.`); } return provider; } public async isReadonly(uriString: string): Promise<boolean> { try { const uri = new URI(uriString); const provider = await this.getProvider(uri.scheme); const stat = (await provider.stat(this.convertUri(uriString).codeUri)) as FileStat; return !!stat.readonly; } catch (e) { // 考虑到非 readonly 变readonly 的情况,相对于 readonly 变不 readonly 来说更为严重 return false; } } private isExclude(uriString: string) { const uri = new URI(uriString); return this.filesExcludesMatcherList.some((matcher) => matcher(uri.path.toString())); } private filterStat(stat?: FileStat, withChildren = true) { if (!stat) { return; } if (this.isExclude(stat.uri)) { return; } // 这里传了 false 就走不到后面递归逻辑了 if (stat.children && withChildren) { stat.children = this.filterStatChildren(stat.children); } return stat; } private filterStatChildren(children: FileStat[]) { const list: FileStat[] = []; children.forEach((child) => { if (this.isExclude(child.uri)) { return false; } const state = this.filterStat(child); if (state) { list.push(state); } }); return list; } protected applyContentChanges(content: string, contentChanges: TextDocumentContentChangeEvent[]): string { let document = TextDocument.create('', '', 1, content); for (const change of contentChanges) { let newContent = change.text; if (change.range) { const start = document.offsetAt(change.range.start); const end = document.offsetAt(change.range.end); newContent = document.getText().substr(0, start) + change.text + document.getText().substr(end); } document = TextDocument.create(document.uri, document.languageId, document.version, newContent); } return document.getText(); } protected async isInSync(file: FileStat, stat: FileStat): Promise<boolean> { if (this.checkInSync(file, stat)) { return true; } return false; } protected checkInSync(file: FileStat, stat: FileStat): boolean { return stat.lastModification === file.lastModification && stat.size === file.size; } protected createOutOfSyncError(file: FileStat, stat: FileStat): Error { return FileSystemError.FileIsOutOfSync(file, stat); } protected async doGetEncoding(option?: { encoding?: string }): Promise<string> { return option && typeof option.encoding !== 'undefined' ? option.encoding : this.options.encoding; } protected async doGetOverwrite(option?: { overwrite?: boolean }): Promise<boolean | undefined> { return option && typeof option.overwrite !== 'undefined' ? option.overwrite : this.options.overwrite; } protected async doGetRecursive(option?: { recursive?: boolean }): Promise<boolean> { return option && typeof option.recursive !== 'undefined' ? option.recursive : this.options.recursive; } protected async doGetMoveToTrash(option?: { moveToTrash?: boolean }): Promise<boolean> { return option && typeof option.moveToTrash !== 'undefined' ? option.moveToTrash : this.options.moveToTrash; } }
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import { isString, isObject as isObjectLodash, isPlainObject, sortBy } from 'lodash'; import moment, { Moment } from 'moment'; import { parseInterval } from '../../../utils'; import { TimeRangeBounds } from '../../../../../query'; import { calcAutoIntervalLessThan, calcAutoIntervalNear } from './calc_auto_interval'; import { convertDurationToNormalizedOpenSearchInterval, convertIntervalToOpenSearchInterval, OpenSearchInterval, } from './calc_opensearch_interval'; import { autoInterval } from '../../_interval_options'; interface TimeBucketsInterval extends moment.Duration { // TODO double-check whether all of these are needed description: string; opensearchValue: OpenSearchInterval['value']; opensearchUnit: OpenSearchInterval['unit']; expression: OpenSearchInterval['expression']; preScaled?: TimeBucketsInterval; scale?: number; scaled?: boolean; } function isObject(o: any): o is Record<string, any> { return isObjectLodash(o); } function isValidMoment(m: any): boolean { return m && 'isValid' in m && m.isValid(); } export interface TimeBucketsConfig extends Record<string, any> { 'histogram:maxBars': number; 'histogram:barTarget': number; dateFormat: string; 'dateFormat:scaled': string[][]; } /** * Helper class for wrapping the concept of an "Interval", * which describes a timespan that will separate moments. * * @param {state} object - one of "" * @param {[type]} display [description] */ export class TimeBuckets { private _timeBucketConfig: TimeBucketsConfig; private _lb: TimeRangeBounds['min']; private _ub: TimeRangeBounds['max']; private _originalInterval: string | null = null; private _i?: moment.Duration | 'auto'; // because other parts of OpenSearch Dashboards arbitrarily add properties [key: string]: any; constructor(timeBucketConfig: TimeBucketsConfig) { this._timeBucketConfig = timeBucketConfig; } /** * Get a moment duration object representing * the distance between the bounds, if the bounds * are set. * * @return {moment.duration|undefined} */ private getDuration(): moment.Duration | undefined { if (this._ub === undefined || this._lb === undefined || !this.hasBounds()) { return; } const difference = this._ub.valueOf() - this._lb.valueOf(); return moment.duration(difference, 'ms'); } /** * Set the bounds that these buckets are expected to cover. * This is required to support interval "auto" as well * as interval scaling. * * @param {object} input - an object with properties min and max, * representing the edges for the time span * we should cover * * @returns {undefined} */ setBounds(input?: TimeRangeBounds | TimeRangeBounds[]) { if (!input) return this.clearBounds(); let bounds; if (isPlainObject(input) && !Array.isArray(input)) { // accept the response from timefilter.getActiveBounds() bounds = [input.min, input.max]; } else { bounds = Array.isArray(input) ? input : []; } const moments: Moment[] = sortBy(bounds, Number) as Moment[]; const valid = moments.length === 2 && moments.every(isValidMoment); if (!valid) { this.clearBounds(); throw new Error('invalid bounds set: ' + input); } this._lb = moments.shift() as any; this._ub = moments.pop() as any; const duration = this.getDuration(); if (!duration || duration.asSeconds() < 0) { throw new TypeError('Intervals must be positive'); } } /** * Clear the stored bounds * * @return {undefined} */ clearBounds() { this._lb = this._ub = undefined; } /** * Check to see if we have received bounds yet * * @return {Boolean} */ hasBounds(): boolean { return isValidMoment(this._ub) && isValidMoment(this._lb); } /** * Return the current bounds, if we have any. * * THIS DOES NOT CLONE THE BOUNDS, so editing them * may have unexpected side-effects. Always * call bounds.min.clone() before editing * * @return {object|undefined} - If bounds are not defined, this * returns undefined, else it returns the bounds * for these buckets. This object has two props, * min and max. Each property will be a moment() * object * */ getBounds(): TimeRangeBounds | undefined { if (!this.hasBounds()) return; return { min: this._lb, max: this._ub, }; } /** * Update the interval at which buckets should be * generated. * * Input can be one of the following: * - Any object from src/legacy/ui/agg_types.js * - "auto" * - Pass a valid moment unit * * @param {object|string|moment.duration} input - see desc */ setInterval(input: null | string | Record<string, any>) { let interval = input; // selection object -> val if (isObject(input) && !moment.isDuration(input)) { interval = input.val; } if (!interval || interval === autoInterval) { this._i = autoInterval; return; } if (isString(interval)) { input = interval; // Preserve the original units because they're lost when the interval is converted to a // moment duration object. this._originalInterval = input; interval = parseInterval(interval); if (interval === null || +interval === 0) { interval = null; } } // if the value wasn't converted to a duration, and isn't // already a duration, we have a problem if (!moment.isDuration(interval)) { throw new TypeError('"' + input + '" is not a valid interval.'); } this._i = interval; } /** * Get the interval for the buckets. If the * number of buckets created by the interval set * is larger than config:histogram:maxBars then the * interval will be scaled up. If the number of buckets * created is less than one, the interval is scaled back. * * The interval object returned is a moment.duration * object that has been decorated with the following * properties. * * interval.description: a text description of the interval. * designed to be used list "field per {{ desc }}". * - "minute" * - "10 days" * - "3 years" * * interval.expression: the OpenSearch expression that creates this * interval. If the interval does not properly form an OpenSearch * expression it will be forced into one. * * interval.scaled: the interval was adjusted to * accommodate the maxBars setting. * * interval.scale: the number that y-values should be * multiplied by */ getInterval(useNormalizedOpenSearchInterval = true): TimeBucketsInterval { const duration = this.getDuration(); // either pull the interval from state or calculate the auto-interval const readInterval = () => { const interval = this._i; if (moment.isDuration(interval)) return interval; return calcAutoIntervalNear(this._timeBucketConfig['histogram:barTarget'], Number(duration)); }; const parsedInterval = readInterval(); // check to see if the interval should be scaled, and scale it if so const maybeScaleInterval = (interval: moment.Duration) => { if (!this.hasBounds() || !duration) { return interval; } const maxLength: number = this._timeBucketConfig['histogram:maxBars']; const approxLen = Number(duration) / Number(interval); let scaled; if (approxLen > maxLength) { scaled = calcAutoIntervalLessThan(maxLength, Number(duration)); } else { return interval; } if (+scaled === +interval) return interval; interval = decorateInterval(interval); return Object.assign(scaled, { preScaled: interval, scale: Number(interval) / Number(scaled), scaled: true, }); }; // append some TimeBuckets specific props to the interval const decorateInterval = (interval: moment.Duration): TimeBucketsInterval => { const opensearchInterval = useNormalizedOpenSearchInterval ? convertDurationToNormalizedOpenSearchInterval(interval) : convertIntervalToOpenSearchInterval(String(this._originalInterval)); const prettyUnits = moment.normalizeUnits(opensearchInterval.unit); return Object.assign(interval, { description: opensearchInterval.value === 1 ? prettyUnits : opensearchInterval.value + ' ' + prettyUnits + 's', opensearchValue: opensearchInterval.value, opensearchUnit: opensearchInterval.unit, expression: opensearchInterval.expression, }); }; if (useNormalizedOpenSearchInterval) { return decorateInterval(maybeScaleInterval(parsedInterval)); } else { return decorateInterval(parsedInterval); } } /** * Get a date format string that will represent dates that * progress at our interval. * * Since our interval can be as small as 1ms, the default * date format is usually way too much. with `dateFormat:scaled` * users can modify how dates are formatted within series * produced by TimeBuckets * * @return {string} */ getScaledDateFormat() { const interval = this.getInterval(); const rules = this._timeBucketConfig['dateFormat:scaled']; for (let i = rules.length - 1; i >= 0; i--) { const rule = rules[i]; if (!rule[0] || (interval && interval >= moment.duration(rule[0]))) { return rule[1]; } } return this._timeBucketConfig.dateFormat; } }
the_stack
import { Signal, ISignal } from '@lumino/signaling'; import { URLExt } from '@jupyterlab/coreutils'; import { DocumentRegistry } from '@jupyterlab/docregistry'; import { Contents, ServerConnection } from '@jupyterlab/services'; import * as base64js from 'base64-js'; /** * A Contents.IDrive implementation for s3-api-compatible object storage. */ export class S3Drive implements Contents.IDrive { /** * Construct a new drive object. * * @param options - The options used to initialize the object. */ constructor(registry: DocumentRegistry) { // this._serverSettings = ServerConnection.makeSettings(); this._registry = registry; } public _registry: DocumentRegistry; /** * The name of the drive. */ get name(): 'S3' { return 'S3'; } /** * Settings for the notebook server. */ readonly serverSettings: ServerConnection.ISettings; /** * A signal emitted when a file operation takes place. */ get fileChanged(): ISignal<this, Contents.IChangedArgs> { return this._fileChanged; } /** * Test whether the manager has been disposed. */ get isDisposed(): boolean { return this._isDisposed; } /** * Dispose of the resources held by the manager. */ dispose(): void { if (this.isDisposed) { return; } this._isDisposed = true; Signal.clearData(this); } /** * Get a file or directory. * * @param path: The path to the file. * * @param options: The options used to fetch the file. * * @returns A promise which resolves with the file content. */ get( path: string, options?: Contents.IFetchOptions ): Promise<Contents.IModel> { return this.pathToJupyterContents(path); } /** * Get an encoded download url given a file path. * * @param path - An absolute POSIX file path on the server. * * #### Notes * It is expected that the path contains no relative paths, * use [[ContentsManager.getAbsolutePath]] to get an absolute * path if necessary. */ getDownloadUrl(path: string): Promise<string> { console.log('not yet implemented'); return Promise.reject('Not yet implemented'); } /** * Create a new untitled file or directory in the specified directory path. * * @param options: The options used to create the file. * * @returns A promise which resolves with the created file content when the * file is created. */ newUntitled(options: Contents.ICreateOptions = {}): Promise<Contents.IModel> { return Promise.reject('Not yet implemented'); } /** * Delete a file. * * @param path - The path to the file. * * @returns A promise which resolves when the file is deleted. */ delete(path: string): Promise<void> { // if this is a file return Promise.reject('Not yet implemented'); } /** * Rename a file or directory. * * @param path - The original file path. * * @param newPath - The new file path. * * @returns A promise which resolves with the new file contents model when * the file is renamed. */ rename(path: string, newPath: string): Promise<Contents.IModel> { return Promise.reject('Not yet implemented'); } /** * Save a file. * * @param path - The desired file path. * * @param options - Optional overrides to the model. * * @returns A promise which resolves with the file content model when the * file is saved. */ save( path: string, options: Partial<Contents.IModel> ): Promise<Contents.IModel> { return Promise.reject('Not yet implemented'); } /** * Copy a file into a given directory. * * @param path - The original file path. * * @param toDir - The destination directory path. * * @returns A promise which resolves with the new contents model when the * file is copied. */ copy(fromFile: string, toDir: string): Promise<Contents.IModel> { return Promise.reject('Not yet implemented'); } /** * Create a checkpoint for a file. * * @param path - The path of the file. * * @returns A promise which resolves with the new checkpoint model when the * checkpoint is created. */ createCheckpoint(path: string): Promise<Contents.ICheckpointModel> { return Promise.reject('Not yet implemented'); } /** * List available checkpoints for a file. * * @param path - The path of the file. * * @returns A promise which resolves with a list of checkpoint models for * the file. */ listCheckpoints(path: string): Promise<Contents.ICheckpointModel[]> { return Promise.resolve([]); } /** * Restore a file to a known checkpoint state. * * @param path - The path of the file. * * @param checkpointID - The id of the checkpoint to restore. * * @returns A promise which resolves when the checkpoint is restored. */ restoreCheckpoint(path: string, checkpointID: string): Promise<void> { return Promise.reject('Not yet implemented'); } /** * Delete a checkpoint for a file. * * @param path - The path of the file. * * @param checkpointID - The id of the checkpoint to delete. * * @returns A promise which resolves when the checkpoint is deleted. */ deleteCheckpoint(path: string, checkpointID: string): Promise<void> { return Promise.reject('Read only'); } private _isDisposed = false; private _fileChanged = new Signal<this, Contents.IChangedArgs>(this); jupyterPathToS3Path(path: string, isDir: boolean): string { if (path === '') { path = '/'; } else if (isDir) { path += '/'; } return path; } s3ToJupyterContents(s3Content: any): Contents.IModel { const result = { name: s3Content.name, path: s3Content.path, format: 'json', // this._registry.getFileType('text').fileFormat, type: s3Content.type, created: '', writable: false, last_modified: '', mimetype: s3Content.mimetype, content: s3Content.content } as Contents.IModel; return result; } pathToJupyterContents(path: string): Promise<Contents.IModel> { if ( path !== Private.currentPath && // if we're changing paths... Private.availableContentTypes[path] !== 'file' // it's not a file ) { if (Private.showingError) { Private.hideErrorMessage(); } Private.showDirectoryLoadingSpinner(); } let s3path: string; if (Private.availableContentTypes[path] !== 'file') { Private.currentPath = path; s3path = this.jupyterPathToS3Path(path, true); } else { s3path = this.jupyterPathToS3Path(path, false); } return new Promise((resolve, reject) => { const settings = ServerConnection.makeSettings(); // can be stored as class var // s3path = s3path.substring(1, s3path.length) ServerConnection.makeRequest( URLExt.join(settings.baseUrl, 'jupyterlab_s3_browser/files', s3path), {}, settings ).then(response => { response .json() .then((content: any) => { if (content.error) { const errorMessage = `Server returned status code ${content.error}. Error message: ${content.message}.`; console.error(errorMessage); Private.showErrorMessage(errorMessage); reject(errorMessage); return []; } if (Array.isArray(content)) { // why is everything's name ''? Private.hideDirectoryLoadingSpinner(); // why was this line here? // Private.availableContentTypes = {}; content.forEach(i => { Private.availableContentTypes[i.path] = i.type; }); resolve({ type: 'directory', path: path.trim(), name: '', format: 'json', content: content.map(c => { return this.s3ToJupyterContents(c); }), created: '', writable: false, last_modified: '', mimetype: '' }); } else { const types = this._registry.getFileTypesForPath(path); const fileType = types.length === 0 ? this._registry.getFileType('text')! : types[0]; const mimetype = fileType.mimeTypes[0]; const format = fileType.fileFormat; let parsedContent; switch (format) { case 'text': parsedContent = Private.b64DecodeUTF8(content.content); break; case 'base64': parsedContent = content.content; break; case 'json': parsedContent = JSON.parse( Private.b64DecodeUTF8(content.content) ); break; default: throw new Error( `Unexpected file format: ${fileType.fileFormat}` ); } resolve({ type: 'file', path, name: '', format, content: parsedContent, created: '', writable: false, last_modified: '', mimetype }); } }) .then((content: any) => { if (Private.currentPath === '') { document.querySelector('#s3-filebrowser')!.classList.add('root'); } else { document .querySelector('#s3-filebrowser')! .classList.remove('root'); } return content; }); }); }); } } /** * Private namespace for utility functions. */ namespace Private { /** * Decoder from bytes to UTF-8. */ const decoder = new TextDecoder('utf8'); /** * Decode a base-64 encoded string into unicode. * * See https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8 */ export function b64DecodeUTF8(str: string): string { const bytes = base64js.toByteArray(str.replace(/\n/g, '')); return decoder.decode(bytes); } export const availableContentTypes: any = {}; export let currentPath: string; export let showingError = false; export function showErrorMessage(message: string): void { Private.hideDirectoryLoadingSpinner(); const filebrowserListing = document.querySelector( '#s3-filebrowser > .jp-DirListing' ) as HTMLElement; if (!filebrowserListing) { return; } filebrowserListing.insertAdjacentHTML( 'afterend', `<div class="s3-error"><p>${message}</p></div>` ); filebrowserListing.style.display = 'none'; Private.showingError = true; } export function hideErrorMessage(): void { const filebrowserListing = document.querySelector( '#s3-filebrowser > .jp-DirListing' ) as HTMLElement; filebrowserListing.style.display = 'block'; if (document.querySelector('.s3-error')) { document.querySelector('.s3-error')!.remove(); } Private.showingError = false; } export function showDirectoryLoadingSpinner(): void { if (document.querySelector('#s3-spinner')) { return; } (document.querySelector('#s3-filebrowser') as HTMLElement).classList.add( 'loading' ); const browserContent = document.querySelector( '#s3-filebrowser .jp-DirListing-content' ); const loadingSpinner = document.createElement('div'); loadingSpinner.classList.add('jp-SpinnerContent'); loadingSpinner.id = 's3-spinner'; (browserContent as HTMLElement).appendChild(loadingSpinner); } export function hideDirectoryLoadingSpinner(): void { const loadingSpinner = document.querySelector('#s3-spinner'); (document.querySelector('#s3-filebrowser') as HTMLElement).classList.remove( 'loading' ); if (loadingSpinner) { try { (loadingSpinner as HTMLElement).remove(); } catch (err) { console.error(err); } } } }
the_stack
import '@aws-cdk/assert-internal/jest'; import * as ec2 from '@aws-cdk/aws-ec2'; import { testDeprecated } from '@aws-cdk/cdk-build-tools'; import * as cdk from '@aws-cdk/core'; import * as elbv2 from '../../lib'; import { FakeSelfRegisteringTarget } from '../helpers'; describe('tests', () => { test('Empty target Group without type still requires a VPC', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); // WHEN new elbv2.ApplicationTargetGroup(stack, 'LB', {}); // THEN expect(() => { app.synth(); }).toThrow(/'vpc' is required for a non-Lambda TargetGroup/); }); test('Lambda target should not have stickiness.enabled set', () => { const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); new elbv2.ApplicationTargetGroup(stack, 'TG', { targetType: elbv2.TargetType.LAMBDA, }); const tg = new elbv2.ApplicationTargetGroup(stack, 'TG2'); tg.addTarget({ attachToApplicationTargetGroup(_targetGroup: elbv2.IApplicationTargetGroup): elbv2.LoadBalancerTargetProps { return { targetType: elbv2.TargetType.LAMBDA, targetJson: { id: 'arn:aws:lambda:eu-west-1:123456789012:function:myFn' }, }; }, }); expect(stack).not.toHaveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', { TargetGroupAttributes: [ { Key: 'stickiness.enabled', }, ], }); }); test('Can add self-registering target to imported TargetGroup', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'Vpc'); // WHEN const tg = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(stack, 'TG', { targetGroupArn: 'arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/myAlbTargetGroup/73e2d6bc24d8a067', }); tg.addTarget(new FakeSelfRegisteringTarget(stack, 'Target', vpc)); }); testDeprecated('Cannot add direct target to imported TargetGroup', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const tg = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(stack, 'TG', { targetGroupArn: 'arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/myAlbTargetGroup/73e2d6bc24d8a067', }); // WHEN expect(() => { tg.addTarget(new elbv2.InstanceTarget('i-1234')); }).toThrow(/Cannot add a non-self registering target to an imported TargetGroup/); }); testDeprecated('HealthCheck fields set if provided', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const alb = new elbv2.ApplicationLoadBalancer(stack, 'ALB', { vpc }); const listener = new elbv2.ApplicationListener(stack, 'Listener', { port: 80, loadBalancer: alb, open: false, }); // WHEN const ipTarget = new elbv2.IpTarget('10.10.12.12'); listener.addTargets('TargetGroup', { targets: [ipTarget], port: 80, healthCheck: { enabled: true, healthyHttpCodes: '255', interval: cdk.Duration.seconds(255), timeout: cdk.Duration.seconds(192), healthyThresholdCount: 29, unhealthyThresholdCount: 27, path: '/arbitrary', }, }); // THEN expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { HealthCheckEnabled: true, HealthCheckIntervalSeconds: 255, HealthCheckPath: '/arbitrary', HealthCheckTimeoutSeconds: 192, HealthyThresholdCount: 29, Matcher: { HttpCode: '255', }, Port: 80, UnhealthyThresholdCount: 27, }); }); test('Load balancer duration cookie stickiness', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { stickinessCookieDuration: cdk.Duration.minutes(5), vpc, }); // THEN expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { TargetGroupAttributes: [ { Key: 'stickiness.enabled', Value: 'true', }, { Key: 'stickiness.type', Value: 'lb_cookie', }, { Key: 'stickiness.lb_cookie.duration_seconds', Value: '300', }, ], }); }); test('Load balancer app cookie stickiness', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { stickinessCookieDuration: cdk.Duration.minutes(5), stickinessCookieName: 'MyDeliciousCookie', vpc, }); // THEN expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { TargetGroupAttributes: [ { Key: 'stickiness.enabled', Value: 'true', }, { Key: 'stickiness.type', Value: 'app_cookie', }, { Key: 'stickiness.app_cookie.cookie_name', Value: 'MyDeliciousCookie', }, { Key: 'stickiness.app_cookie.duration_seconds', Value: '300', }, ], }); }); test('Custom Load balancer algorithm type', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { loadBalancingAlgorithmType: elbv2.TargetGroupLoadBalancingAlgorithmType.LEAST_OUTSTANDING_REQUESTS, vpc, }); // THEN expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { TargetGroupAttributes: [ { Key: 'stickiness.enabled', Value: 'false', }, { Key: 'load_balancing.algorithm.type', Value: 'least_outstanding_requests', }, ], }); }); test('Can set a protocol version', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, protocolVersion: elbv2.ApplicationProtocolVersion.GRPC, healthCheck: { enabled: true, healthyGrpcCodes: '0-99', interval: cdk.Duration.seconds(255), timeout: cdk.Duration.seconds(192), healthyThresholdCount: 29, unhealthyThresholdCount: 27, path: '/arbitrary', }, }); // THEN expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { ProtocolVersion: 'GRPC', HealthCheckEnabled: true, HealthCheckIntervalSeconds: 255, HealthCheckPath: '/arbitrary', HealthCheckTimeoutSeconds: 192, HealthyThresholdCount: 29, Matcher: { GrpcCode: '0-99', }, UnhealthyThresholdCount: 27, }); }); test('Bad stickiness cookie names', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const errMessage = 'App cookie names that start with the following prefixes are not allowed: AWSALB, AWSALBAPP, and AWSALBTG; they\'re reserved for use by the load balancer'; // THEN ['AWSALBCookieName', 'AWSALBstickinessCookieName', 'AWSALBTGCookieName'].forEach((badCookieName, i) => { expect(() => { new elbv2.ApplicationTargetGroup(stack, `TargetGroup${i}`, { stickinessCookieDuration: cdk.Duration.minutes(5), stickinessCookieName: badCookieName, vpc, }); }).toThrow(errMessage); }); }); test('Empty stickiness cookie name', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // THEN expect(() => { new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { stickinessCookieDuration: cdk.Duration.minutes(5), stickinessCookieName: '', vpc, }); }).toThrow(/App cookie name cannot be an empty string./); }); test('Bad stickiness duration value', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // THEN expect(() => { new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { stickinessCookieDuration: cdk.Duration.days(8), vpc, }); }).toThrow(/Stickiness cookie duration value must be between 1 second and 7 days \(604800 seconds\)./); }); test('Bad slow start duration value', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // THEN [cdk.Duration.minutes(16), cdk.Duration.seconds(29)].forEach((badDuration, i) => { expect(() => { new elbv2.ApplicationTargetGroup(stack, `TargetGroup${i}`, { slowStart: badDuration, vpc, }); }).toThrow(/Slow start duration value must be between 30 and 900 seconds./); }); }); test.each([elbv2.Protocol.UDP, elbv2.Protocol.TCP_UDP, elbv2.Protocol.TLS])( 'Throws validation error, when `healthCheck` has `protocol` set to %s', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, healthCheck: { protocol: protocol, }, }); // THEN expect(() => { app.synth(); }).toThrow(`Health check protocol '${protocol}' is not supported. Must be one of [HTTP, HTTPS]`); }); test.each([elbv2.Protocol.UDP, elbv2.Protocol.TCP_UDP, elbv2.Protocol.TLS])( 'Throws validation error, when `configureHealthCheck()` has `protocol` set to %s', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const tg = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, }); // WHEN tg.configureHealthCheck({ protocol: protocol, }); // THEN expect(() => { app.synth(); }).toThrow(`Health check protocol '${protocol}' is not supported. Must be one of [HTTP, HTTPS]`); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Does not throw validation error, when `healthCheck` has `protocol` set to %s', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, healthCheck: { protocol: protocol, }, }); // THEN expect(() => { app.synth(); }).not.toThrowError(); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Does not throw validation error, when `configureHealthCheck()` has `protocol` set to %s', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const tg = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, }); // WHEN tg.configureHealthCheck({ protocol: protocol, }); // THEN expect(() => { app.synth(); }).not.toThrowError(); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Throws validation error, when `healthCheck` has `protocol` set to %s and `interval` is equal to `timeout`', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, healthCheck: { interval: cdk.Duration.seconds(60), timeout: cdk.Duration.seconds(60), protocol: protocol, }, }); // THEN expect(() => { app.synth(); }).toThrow('Healthcheck interval 1 minute must be greater than the timeout 1 minute'); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Throws validation error, when `healthCheck` has `protocol` set to %s and `interval` is smaller than `timeout`', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); // WHEN new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, healthCheck: { interval: cdk.Duration.seconds(60), timeout: cdk.Duration.seconds(120), protocol: protocol, }, }); // THEN expect(() => { app.synth(); }).toThrow('Healthcheck interval 1 minute must be greater than the timeout 2 minutes'); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Throws validation error, when `configureHealthCheck()` has `protocol` set to %s and `interval` is equal to `timeout`', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const tg = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, }); // WHEN tg.configureHealthCheck({ interval: cdk.Duration.seconds(60), timeout: cdk.Duration.seconds(60), protocol: protocol, }); // THEN expect(() => { app.synth(); }).toThrow('Healthcheck interval 1 minute must be greater than the timeout 1 minute'); }); test.each([elbv2.Protocol.HTTP, elbv2.Protocol.HTTPS])( 'Throws validation error, when `configureHealthCheck()` has `protocol` set to %s and `interval` is smaller than `timeout`', (protocol) => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); const vpc = new ec2.Vpc(stack, 'VPC', {}); const tg = new elbv2.ApplicationTargetGroup(stack, 'TargetGroup', { vpc, }); // WHEN tg.configureHealthCheck({ interval: cdk.Duration.seconds(60), timeout: cdk.Duration.seconds(120), protocol: protocol, }); // THEN expect(() => { app.synth(); }).toThrow('Healthcheck interval 1 minute must be greater than the timeout 2 minutes'); }); test('imported targetGroup has targetGroupName', () => { // GIVEN const app = new cdk.App(); const stack = new cdk.Stack(app, 'Stack'); // WHEN const importedTg = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(stack, 'importedTg', { targetGroupArn: 'arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/myAlbTargetGroup/73e2d6bc24d8a067', }); // THEN expect(importedTg.targetGroupName).toEqual('myAlbTargetGroup'); }); });
the_stack
import { EventEmitter } from 'events'; import * as fs from 'fs'; import { ThinkboxEcrProvider } from '../../lib/ecr-provider'; jest.mock('fs'); jest.mock('https'); describe('ThinkboxEcrProvider', () => { /** * Suite of parametrized tests for testing the ECR index schema validation. * * The suite is an array of tests, where each test should fail validation. Each test is represented as an array of two * elements: [name, indexObject] * * - The first element is the name describing what is contained in the value * - The second element is the value that should be JSON encoded and supplied to the ThinkboxEcrProvider */ const INDEX_SCHEMA_VALIDATION_SUITE: Array<[string, any]> = [ [ 'array', [], ], [ 'number', 1, ], [ 'string', 'abc', ], [ 'object missing registry', { products: { deadline: { namespace: 'a', }, }, }, ], [ 'object with registry with wrong type', { registry: 1, products: { deadline: { namespace: 'a', }, }, }, ], [ 'object missing products', { registry: { uri: 'a', }, }, ], [ 'object with products with wrong type', { registry: { uri: 'a', }, products: 1, }, ], [ 'object with registry missing uri', { registry: {}, products: { deadline: { namespace: 'a', }, }, }, ], [ 'object with registry uri with wrong type', { registry: { uri: 1, }, products: { deadline: { namespace: 'a', }, }, }, ], [ 'object with missing products.deadline', { registry: { uri: 1, }, products: {}, }, ], [ 'object with products.deadline with wrong type', { registry: { uri: 1, }, products: { deadline: 1, }, }, ], [ 'object with missing products.deadline.namespace', { registry: { uri: 1, }, products: { deadline: {}, }, }, ], [ 'object with products.deadline.namespace with wrong type', { registry: { uri: 1, }, products: { deadline: { namespace: 1, }, }, }, ], ]; let ecrProvider: ThinkboxEcrProvider; describe('without indexPath', () => { class MockResponse extends EventEmitter { public statusCode: number = 200; } let request: EventEmitter; let response: MockResponse; /** * Mock implementation of a successful HTTPS GET request * * @param _url The URL of the HTTPS request * @param callback The callback to call when a response is available */ function httpGetMockSuccess(_url: string, callback: (_request: any) => void) { if (callback) { callback(response); } return request; } /** * Mock implementation of a failed HTTPS GET request * * @param _url The URL of the HTTPS request * @param _callback The callback to call when a response is available */ function httpGetMockError(_url: string, _callback: (request: any) => void) { return request; } beforeEach(() => { request = new EventEmitter(); response = new MockResponse(); jest.requireMock('https').get.mockImplementation(httpGetMockSuccess); // GIVEN ecrProvider = new ThinkboxEcrProvider(); }); const EXPECTED_URL = 'https://downloads.thinkboxsoftware.com/thinkbox_ecr.json'; test(`gets ${EXPECTED_URL} for global lookup`, async () => { // GIVEN const registryUri = 'registryUri'; const deadlineNamespace = 'namespace'; const mockData = { registry: { uri: registryUri, }, products: { deadline: { namespace: deadlineNamespace, }, }, }; // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); response.emit('data', JSON.stringify(mockData)); response.emit('end'); await promise; // THEN // should make an HTTPS request for the ECR index expect(jest.requireMock('https').get) .toBeCalledWith( EXPECTED_URL, expect.any(Function), ); }); describe('.getGlobalEcrBaseArn()', () => { test('obtains global prefix from index', async () => { // GIVEN const registryUri = 'registryUri'; const deadlineNamespace = 'namespace'; const mockData = { registry: { uri: registryUri, }, products: { deadline: { namespace: deadlineNamespace, }, }, }; const expectedBaseArn = `${registryUri}/${deadlineNamespace}`; // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); response.emit('data', JSON.stringify(mockData)); response.emit('end'); // THEN await expect(promise) .resolves .toEqual(expectedBaseArn); }); test('handles request errors', async () => { // GIVEN const error = new Error('test'); jest.requireMock('https').get.mockImplementation(httpGetMockError); function simulateRequestError() { request.emit('error', error); }; // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); simulateRequestError(); // THEN await expect(promise) .rejects .toThrowError(error); }); test.each([ [404], [401], [500], ])('handles %d response errors', async (statusCode: number) => { // GIVEN response.statusCode = statusCode; // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); response.emit('data', ''); response.emit('end'); // THEN await expect(promise) .rejects .toThrowError(`Expected status code 200, but got ${statusCode}`); }); test('fails on bad JSON', async () => { // GIVEN const responseBody = 'this is not json'; // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); response.emit('data', responseBody); response.emit('end'); // THEN await expect(promise) .rejects .toThrow(/^ECR index file contains invalid JSON: ".*"$/); }); describe('index schema validation', () => { test.each(INDEX_SCHEMA_VALIDATION_SUITE)('fails when fetching %s', async (_name: string, value: any) => { // WHEN const promise = ecrProvider.getGlobalEcrBaseURI(); response.emit('data', JSON.stringify(value)); response.emit('end'); // THEN await expect(promise) .rejects .toThrowError(/^expected .+ to be an? .+ but got .+$/); }); }); }); }); describe('with indexPath', () => { // GIVEN const registryUri = 'registryUri'; const deadlineNamespace = 'deadlineNamespace'; const indexPath = 'somefile'; const mockData = { registry: { uri: registryUri, }, products: { deadline: { namespace: deadlineNamespace, }, }, }; const globalURIPrefix = `${registryUri}/${deadlineNamespace}`; beforeEach(() => { // WHEN const existsSync: jest.Mock = jest.requireMock('fs').existsSync; const readFileSync: jest.Mock = jest.requireMock('fs').readFileSync; // reset tracked calls to mocks existsSync.mockReset(); readFileSync.mockReset(); // set the default mock implementations existsSync.mockReturnValue(true); readFileSync.mockReturnValue(JSON.stringify(mockData)); ecrProvider = new ThinkboxEcrProvider(indexPath); }); describe('.getGlobalEcrBaseURI', () => { let baseURIPromise: Promise<string>; beforeEach(() => { // WHEN baseURIPromise = ecrProvider.getGlobalEcrBaseURI(); }); test('reads file', async () => { // THEN await expect(baseURIPromise) .resolves.toEqual(globalURIPrefix); expect(fs.existsSync).toBeCalledTimes(1); expect(fs.readFileSync).toBeCalledWith(indexPath, 'utf8'); }); test('returns correct prefix', async () => { await expect(baseURIPromise) .resolves .toEqual(globalURIPrefix); }); test.each([ ['existsSync'], ['readFileSync'], ])('fails on fs.%s exception', async (methodName: string) => { // GIVEN const error = new Error('message'); jest.requireMock('fs')[methodName].mockImplementation(() => { throw error; }); ecrProvider = new ThinkboxEcrProvider(indexPath); // WHEN baseURIPromise = ecrProvider.getGlobalEcrBaseURI(); // THEN await expect(baseURIPromise) .rejects .toThrowError(error); }); describe('index schema validation', () => { test.each(INDEX_SCHEMA_VALIDATION_SUITE)('fails when fetching %s', async (_name: string, value: any) => { // GIVEN jest.requireMock('fs').readFileSync.mockReturnValue(JSON.stringify(value)); ecrProvider = new ThinkboxEcrProvider(indexPath); // WHEN baseURIPromise = ecrProvider.getGlobalEcrBaseURI(); // THEN await expect(baseURIPromise) .rejects .toThrowError(/^expected .+ to be an? .+ but got .+$/); }); }); test('fails on non-existent file', async () => { // GIVEN jest.requireMock('fs').existsSync.mockReturnValue(false); ecrProvider = new ThinkboxEcrProvider(indexPath); // WHEN baseURIPromise = ecrProvider.getGlobalEcrBaseURI(); // THEN await expect(baseURIPromise) .rejects .toThrowError(`File "${indexPath}" was not found`); }); test('fails on bad JSON', async () => { // GIVEN jest.requireMock('fs').readFileSync.mockReturnValue('bad json'); ecrProvider = new ThinkboxEcrProvider(indexPath); // WHEN baseURIPromise = ecrProvider.getGlobalEcrBaseURI(); // THEN await expect(baseURIPromise) .rejects .toThrow(/^ECR index file contains invalid JSON: ".*"$/); }); }); }); });
the_stack
// Edits to work with ECMAScript modules by STM/capnmidnight 2020-07-20 // Converted to TypeScript by STM/capnmidnight 2021-01-01 import { arrayClear } from "kudzu/arrays/arrayClear"; function pathTo(node: GridNode): GridNode[] { let curr = node; const path = new Array<GridNode>(); while (curr.parent) { path.unshift(curr); curr = curr.parent; } return path; } export type scoreCallback = (node: GridNode) => number; function getHeap(): BinaryHeap { return new BinaryHeap(function (node: GridNode) { return node.f; }); } export type heuristicCallback = (pos0: GridNode, pos1: GridNode) => number; export interface SearchOptions { /** * Specifies whether to return the path to the closest node if the target is unreachable. **/ closest?: boolean; /** * Heuristic function (see astar.heuristics) **/ heuristic?: heuristicCallback; } /** * Perform an A* Search on a graph given a start and end node. */ export function search(graph: Graph, start: GridNode, end: GridNode, options?: SearchOptions): GridNode[] { graph.cleanDirty(); options = options || {}; const heuristic = options.heuristic || heuristics.manhattan; const closest = options.closest || false; const openHeap = getHeap(); let closestNode = start; // set the start node to be the closest if required start.h = heuristic(start, end); graph.markDirty(start); openHeap.push(start); while (openHeap.size() > 0) { // Grab the lowest f(x) to process next. Heap keeps this sorted for us. const currentNode = openHeap.pop(); // End case -- result has been found, return the traced path. if (currentNode === end) { return pathTo(currentNode); } // Normal case -- move currentNode from open to closed, process each of its neighbors. currentNode.closed = true; // Find all neighbors for the current node. const neighbors = graph.neighbors(currentNode); for (const neighbor of neighbors) { if (neighbor.closed || neighbor.isWall()) { // Not a valid node to process, skip to next neighbor. continue; } // The g score is the shortest distance from start to current node. // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet. const gScore = currentNode.g + neighbor.getCost(currentNode); const beenVisited = neighbor.visited; if (!beenVisited || gScore < neighbor.g) { // Found an optimal (so far) path to this node. Take score for node to see how good it is. neighbor.visited = true; neighbor.parent = currentNode; neighbor.h = neighbor.h || heuristic(neighbor, end); neighbor.g = gScore; neighbor.f = neighbor.g + neighbor.h; graph.markDirty(neighbor); if (closest) { // If the neighbour is closer than the current closestNode or if it's equally close but has // a cheaper path than the current closest node then it becomes the closest node if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) { closestNode = neighbor; } } if (!beenVisited) { // Pushing to heap will put it in proper place based on the 'f' value. openHeap.push(neighbor); } else { // Already seen the node, but since it has been rescored we need to reorder it in the heap openHeap.rescoreElement(neighbor); } } } } if (closest) { return pathTo(closestNode); } // No result was found - empty array signifies failure to find path. return []; } // See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html export const heuristics = { manhattan(pos0: GridNode, pos1: GridNode): number { const d1 = Math.abs(pos1.x - pos0.x); const d2 = Math.abs(pos1.y - pos0.y); return d1 + d2; }, diagonal(pos0: GridNode, pos1: GridNode): number { const D = 1; const D2 = Math.sqrt(2); const d1 = Math.abs(pos1.x - pos0.x); const d2 = Math.abs(pos1.y - pos0.y); return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2)); } }; export function cleanNode(node: GridNode): void { node.f = 0; node.g = 0; node.h = 0; node.visited = false; node.closed = false; node.parent = null; } export interface GraphOptions { /** * Specifies whether diagonal moves are allowed **/ diagonal?: boolean; } /** * A graph memory structure * @param gridIn 2D array of input weights */ export class Graph { nodes: GridNode[]; dirtyNodes = new Array<GridNode>(); grid: GridNode[][] = null; diagonal: boolean = true; constructor(gridIn: number[][], options?: GraphOptions) { if (options) { this.diagonal = options.diagonal !== false; } this.nodes = new Array<GridNode>(); this.grid = new Array<GridNode[]>(); for (let x = 0; x < gridIn.length; x++) { const row = gridIn[x]; this.grid[x] = new Array<GridNode>(row.length); for (let y = 0; y < row.length; y++) { const node = new GridNode(x, y, row[y]); this.grid[x][y] = node; this.nodes.push(node); } } this.init(); } init(): void { arrayClear(this.dirtyNodes); for (let i = 0; i < this.nodes.length; i++) { cleanNode(this.nodes[i]); } } cleanDirty(): void { for (let i = 0; i < this.dirtyNodes.length; i++) { cleanNode(this.dirtyNodes[i]); } arrayClear(this.dirtyNodes); } markDirty(node: GridNode): void { this.dirtyNodes.push(node); } neighbors(node: GridNode): GridNode[] { const ret = []; const x = node.x; const y = node.y; const grid = this.grid; // West if (grid[x - 1] && grid[x - 1][y]) { ret.push(grid[x - 1][y]); } // East if (grid[x + 1] && grid[x + 1][y]) { ret.push(grid[x + 1][y]); } // South if (grid[x] && grid[x][y - 1]) { ret.push(grid[x][y - 1]); } // North if (grid[x] && grid[x][y + 1]) { ret.push(grid[x][y + 1]); } if (this.diagonal) { // Southwest if (grid[x - 1] && grid[x - 1][y - 1]) { ret.push(grid[x - 1][y - 1]); } // Southeast if (grid[x + 1] && grid[x + 1][y - 1]) { ret.push(grid[x + 1][y - 1]); } // Northwest if (grid[x - 1] && grid[x - 1][y + 1]) { ret.push(grid[x - 1][y + 1]); } // Northeast if (grid[x + 1] && grid[x + 1][y + 1]) { ret.push(grid[x + 1][y + 1]); } } return ret; } toString(): string { const graphString = []; const nodes = this.grid; for (let x = 0; x < nodes.length; x++) { const rowDebug = []; const row = nodes[x]; for (let y = 0; y < row.length; y++) { rowDebug.push(row[y].weight); } graphString.push(rowDebug.join(" ")); } return graphString.join("\n"); } } export class GridNode { f = 0; g = 0; h = 0; visited = false; closed = false; parent: GridNode = null; constructor(public x: number, public y: number, public weight: number) { } toString(): string { return `[${this.x} ${this.y}]`; } getCost(fromNeighbor: GridNode): number { // Take diagonal weight into consideration. if (fromNeighbor && fromNeighbor.x != this.x && fromNeighbor.y != this.y) { return this.weight * 1.41421; } return this.weight; } isWall(): boolean { return this.weight === 0; } } class BinaryHeap { private content = new Array<GridNode>(); constructor(private scoreFunction: scoreCallback) { } push(element: GridNode): void { // Add the new element to the end of the array. this.content.push(element); // Allow it to sink down. this.sinkDown(this.content.length - 1); } pop(): GridNode { // Store the first element so we can return it later. const result = this.content[0]; // Get the element at the end of the array. const end = this.content.pop(); // If there are any elements left, put the end element at the // start, and let it bubble up. if (this.content.length > 0) { this.content[0] = end; this.bubbleUp(0); } return result; } remove(node: GridNode): void { const i = this.content.indexOf(node); // When it is found, the process seen in 'pop' is repeated // to fill up the hole. const end = this.content.pop(); if (i !== this.content.length - 1) { this.content[i] = end; if (this.scoreFunction(end) < this.scoreFunction(node)) { this.sinkDown(i); } else { this.bubbleUp(i); } } } size(): number { return this.content.length; } rescoreElement(node: GridNode): void { this.sinkDown(this.content.indexOf(node)); } sinkDown(n: number): void { // Fetch the element that has to be sunk. const element = this.content[n]; // When at 0, an element can not sink any further. while (n > 0) { // Compute the parent element's index, and fetch it. const parentN = ((n + 1) >> 1) - 1; const parent = this.content[parentN]; // Swap the elements if the parent is greater. if (this.scoreFunction(element) < this.scoreFunction(parent)) { this.content[parentN] = element; this.content[n] = parent; // Update 'n' to continue at the new position. n = parentN; } // Found a parent that is less, no need to sink any further. else { break; } } } bubbleUp(n: number): void { // Look up the target element and its score. const length = this.content.length; const element = this.content[n]; const elemScore = this.scoreFunction(element); while (true) { // Compute the indices of the child elements. const child2N = (n + 1) << 1; const child1N = child2N - 1; // This is used to store the new position of the element, if any. let swap: number = null; let child1Score: number; // If the first child exists (is inside the array)... if (child1N < length) { // Look it up and compute its score. const child1 = this.content[child1N]; child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap. if (child1Score < elemScore) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { const child2 = this.content[child2N]; const child2Score = this.scoreFunction(child2); if (child2Score < (swap === null ? elemScore : child1Score)) { swap = child2N; } } // If the element needs to be moved, swap it, and continue. if (swap !== null) { this.content[n] = this.content[swap]; this.content[swap] = element; n = swap; } // Otherwise, we are done. else { break; } } } }
the_stack
import { errors, ObjectFlags, ts, TypeFlags, TypeFormatFlags } from "@ts-morph/common"; import { ProjectContext } from "../../ProjectContext"; import { getNotFoundErrorMessageForNameOrFindFunction, getSymbolByNameOrFindFunction } from "../../utils"; import { Node } from "../ast"; import { Signature, Symbol } from "../symbols"; import { TypeParameter } from "./TypeParameter"; export class Type<TType extends ts.Type = ts.Type> { /** @internal */ readonly _context: ProjectContext; /** @internal */ private readonly _compilerType: TType; /** * Gets the underlying compiler type. */ get compilerType() { return this._compilerType; } /** * Initializes a new instance of Type. * @private * @param context - Project context. * @param type - Compiler type. */ constructor(context: ProjectContext, type: TType) { this._context = context; this._compilerType = type; } /** * Gets the type text. * @param enclosingNode - The enclosing node. * @param typeFormatFlags - Format flags for the type text. */ getText(enclosingNode?: Node, typeFormatFlags?: TypeFormatFlags): string { return this._context.typeChecker.getTypeText(this, enclosingNode, typeFormatFlags); } /** * Gets the alias symbol if it exists. */ getAliasSymbol(): Symbol | undefined { return this.compilerType.aliasSymbol == null ? undefined : this._context.compilerFactory.getSymbol(this.compilerType.aliasSymbol); } /** * Gets the alias symbol if it exists, or throws. */ getAliasSymbolOrThrow(): Symbol { return errors.throwIfNullOrUndefined(this.getAliasSymbol(), "Expected to find an alias symbol."); } /** * Gets the alias type arguments. */ getAliasTypeArguments(): Type[] { const aliasTypeArgs = this.compilerType.aliasTypeArguments || []; return aliasTypeArgs.map(t => this._context.compilerFactory.getType(t)); } /** * Gets the apparent type. */ getApparentType(): Type { return this._context.typeChecker.getApparentType(this); } /** * Gets the array element type or throws if it doesn't exist (ex. for `T[]` it would be `T`). */ getArrayElementTypeOrThrow() { return errors.throwIfNullOrUndefined(this.getArrayElementType(), "Expected to find an array element type."); } /** * Gets the array element type or returns undefined if it doesn't exist (ex. for `T[]` it would be `T`). */ getArrayElementType() { if (!this.isArray()) return undefined; return this.getTypeArguments()[0]; } /** * Gets the base types. */ getBaseTypes() { const baseTypes = this.compilerType.getBaseTypes() || []; return baseTypes.map(t => this._context.compilerFactory.getType(t)); } /** * Gets the base type of a literal type. * * For example, for a number literal type it will return the number type. */ getBaseTypeOfLiteralType() { return this._context.typeChecker.getBaseTypeOfLiteralType(this); } /** * Gets the call signatures. */ getCallSignatures(): Signature[] { return this.compilerType.getCallSignatures().map(s => this._context.compilerFactory.getSignature(s)); } /** * Gets the construct signatures. */ getConstructSignatures(): Signature[] { return this.compilerType.getConstructSignatures().map(s => this._context.compilerFactory.getSignature(s)); } /** * Gets the constraint or throws if it doesn't exist. */ getConstraintOrThrow() { return errors.throwIfNullOrUndefined(this.getConstraint(), "Expected to find a constraint."); } /** * Gets the constraint or returns undefined if it doesn't exist. */ getConstraint() { const constraint = this.compilerType.getConstraint(); return constraint == null ? undefined : this._context.compilerFactory.getType(constraint); } /** * Gets the default type or throws if it doesn't exist. */ getDefaultOrThrow() { return errors.throwIfNullOrUndefined(this.getDefault(), "Expected to find a default type."); } /** * Gets the default type or returns undefined if it doesn't exist. */ getDefault() { const defaultType = this.compilerType.getDefault(); return defaultType == null ? undefined : this._context.compilerFactory.getType(defaultType); } /** * Gets the properties of the type. */ getProperties(): Symbol[] { return this.compilerType.getProperties().map(s => this._context.compilerFactory.getSymbol(s)); } /** * Gets a property or throws if it doesn't exist. * @param name - By a name. */ getPropertyOrThrow(name: string): Symbol; /** * Gets a property or throws if it doesn't exist. * @param findFunction - Function for searching for a property. */ getPropertyOrThrow(findFunction: (declaration: Symbol) => boolean): Symbol; /** @internal */ getPropertyOrThrow(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol; getPropertyOrThrow(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol { return errors.throwIfNullOrUndefined(this.getProperty(nameOrFindFunction), () => getNotFoundErrorMessageForNameOrFindFunction("symbol property", nameOrFindFunction)); } /** * Gets a property or returns undefined if it does not exist. * @param name - By a name. */ getProperty(name: string): Symbol | undefined; /** * Gets a property or returns undefined if it does not exist. * @param findFunction - Function for searching for a property. */ getProperty(findFunction: (declaration: Symbol) => boolean): Symbol | undefined; /** @internal */ getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined; getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined { return getSymbolByNameOrFindFunction(this.getProperties(), nameOrFindFunction); } /** * Gets the apparent properties of the type. */ getApparentProperties(): Symbol[] { return this.compilerType.getApparentProperties().map(s => this._context.compilerFactory.getSymbol(s)); } /** * Gets an apparent property. * @param name - By a name. * @param findFunction - Function for searching for an apparent property. */ getApparentProperty(name: string): Symbol | undefined; getApparentProperty(findFunction: (declaration: Symbol) => boolean): Symbol | undefined; getApparentProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined { return getSymbolByNameOrFindFunction(this.getApparentProperties(), nameOrFindFunction); } /** * Gets if the type is possibly null or undefined. */ isNullable() { return this.getUnionTypes().some(t => t.isNull() || t.isUndefined()); } /** * Gets the non-nullable type. */ getNonNullableType(): Type { return this._context.compilerFactory.getType(this.compilerType.getNonNullableType()); } /** * Gets the number index type. */ getNumberIndexType(): Type | undefined { const numberIndexType = this.compilerType.getNumberIndexType(); return numberIndexType == null ? undefined : this._context.compilerFactory.getType(numberIndexType); } /** * Gets the string index type. */ getStringIndexType(): Type | undefined { const stringIndexType = this.compilerType.getStringIndexType(); return stringIndexType == null ? undefined : this._context.compilerFactory.getType(stringIndexType); } /** * Returns the generic type when the type is a type reference, returns itself when it's * already a generic type, or otherwise returns undefined. * * For example: * * - Given type reference `Promise<string>` returns `Promise<T>`. * - Given generic type `Promise<T>` returns the same `Promise<T>`. * - Given `string` returns `undefined`. */ getTargetType(): Type<ts.GenericType> | undefined { const targetType = (this.compilerType as any as ts.TypeReference).target || undefined; return targetType == null ? undefined : this._context.compilerFactory.getType(targetType); } /** * Returns the generic type when the type is a type reference, returns itself when it's * already a generic type, or otherwise throws an error. * * For example: * * - Given type reference `Promise<string>` returns `Promise<T>`. * - Given generic type `Promise<T>` returns the same `Promise<T>`. * - Given `string` throws an error. */ getTargetTypeOrThrow(): Type<ts.GenericType> { return errors.throwIfNullOrUndefined(this.getTargetType(), "Expected to find the target type."); } /** * Gets type arguments. */ getTypeArguments(): Type[] { return this._context.typeChecker.getTypeArguments(this); } /** * Gets the individual element types of the tuple. */ getTupleElements(): Type[] { return this.isTuple() ? this.getTypeArguments() : []; } /** * Gets the union types (ex. for `T | U` it returns the array `[T, U]`). */ getUnionTypes(): Type[] { if (!this.isUnion()) return []; return (this.compilerType as any as ts.UnionType).types.map(t => this._context.compilerFactory.getType(t)); } /** * Gets the intersection types (ex. for `T & U` it returns the array `[T, U]`). */ getIntersectionTypes(): Type[] { if (!this.isIntersection()) return []; return (this.compilerType as any as ts.IntersectionType).types.map(t => this._context.compilerFactory.getType(t)); } /** * Gets the value of a literal or returns undefined if this is not a literal type. */ getLiteralValue() { return (this.compilerType as any as ts.LiteralType | undefined)?.value; } /** * Gets the value of the literal or throws if this is not a literal type. */ getLiteralValueOrThrow() { return errors.throwIfNullOrUndefined(this.getLiteralValue(), "Type was not a literal type."); } /** * Gets the fresh type of the literal or returns undefined if this is not a literal type. * * Note: I have no idea what this means. Please help contribute to these js docs if you know. */ getLiteralFreshType() { const type = (this.compilerType as any as ts.LiteralType | undefined)?.freshType; return type == null ? undefined : this._context.compilerFactory.getType(type); } /** * Gets the fresh type of the literal or throws if this is not a literal type. * * Note: I have no idea what this means. Please help contribute to these js docs if you know. */ getLiteralFreshTypeOrThrow() { return errors.throwIfNullOrUndefined(this.getLiteralFreshType(), "Type was not a literal type."); } /** * Gets the regular type of the literal or returns undefined if this is not a literal type. * * Note: I have no idea what this means. Please help contribute to these js docs if you know. */ getLiteralRegularType() { const type = (this.compilerType as any as ts.LiteralType | undefined)?.regularType; return type == null ? undefined : this._context.compilerFactory.getType(type); } /** * Gets the regular type of the literal or throws if this is not a literal type. * * Note: I have no idea what this means. Please help contribute to these js docs if you know. */ getLiteralRegularTypeOrThrow() { return errors.throwIfNullOrUndefined(this.getLiteralRegularType(), "Type was not a literal type."); } /** * Gets the symbol of the type. */ getSymbol(): Symbol | undefined { const tsSymbol = this.compilerType.getSymbol(); return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol); } /** * Gets the symbol of the type or throws. */ getSymbolOrThrow(): Symbol { return errors.throwIfNullOrUndefined(this.getSymbol(), "Expected to find a symbol."); } /** * Gets if this is an anonymous type. */ isAnonymous() { return this._hasObjectFlag(ObjectFlags.Anonymous); } /** * Gets if this is an any type. */ isAny() { return this._hasTypeFlag(TypeFlags.Any); } /** * Gets if this is an array type. */ isArray() { const symbol = this.getSymbol(); if (symbol == null) return false; return symbol.getName() === "Array" && this.getTypeArguments().length === 1; } /** * Gets if this is a boolean type. */ isBoolean() { return this._hasTypeFlag(TypeFlags.Boolean); } /** * Gets if this is a string type. */ isString() { return this._hasTypeFlag(TypeFlags.String); } /** * Gets if this is a number type. */ isNumber() { return this._hasTypeFlag(TypeFlags.Number); } /** * Gets if this is a literal type. */ isLiteral() { // todo: remove this when https://github.com/Microsoft/TypeScript/issues/26075 is fixed const isBooleanLiteralForTs3_0 = this.isBooleanLiteral(); return this.compilerType.isLiteral() || isBooleanLiteralForTs3_0; } /** * Gets if this is a boolean literal type. */ isBooleanLiteral() { return this._hasTypeFlag(TypeFlags.BooleanLiteral); } /** * Gets if this is an enum literal type. */ isEnumLiteral() { return this._hasTypeFlag(TypeFlags.EnumLiteral) && !this.isUnion(); } /** * Gets if this is a number literal type. */ isNumberLiteral() { return this._hasTypeFlag(TypeFlags.NumberLiteral); } /** * Gets if this is a string literal type. */ isStringLiteral() { return this.compilerType.isStringLiteral(); } /** * Gets if this is a class type. */ isClass() { return this.compilerType.isClass(); } /** * Gets if this is a class or interface type. */ isClassOrInterface() { return this.compilerType.isClassOrInterface(); } /** * Gets if this is an enum type. */ isEnum() { const hasEnumFlag = this._hasTypeFlag(TypeFlags.Enum); if (hasEnumFlag) return true; if (this.isEnumLiteral() && !this.isUnion()) return false; const symbol = this.getSymbol(); if (symbol == null) return false; const valueDeclaration = symbol.getValueDeclaration(); return valueDeclaration != null && Node.isEnumDeclaration(valueDeclaration); } /** * Gets if this is an interface type. */ isInterface() { return this._hasObjectFlag(ObjectFlags.Interface); } /** * Gets if this is an object type. */ isObject() { return this._hasTypeFlag(TypeFlags.Object); } /** * Gets if this is a type parameter. */ isTypeParameter(): this is TypeParameter { return this.compilerType.isTypeParameter(); } /** * Gets if this is a tuple type. */ isTuple() { const targetType = this.getTargetType(); if (targetType == null) return false; return targetType._hasObjectFlag(ObjectFlags.Tuple); } /** * Gets if this is a union type. */ isUnion() { return this.compilerType.isUnion(); } /** * Gets if this is an intersection type. */ isIntersection() { return this.compilerType.isIntersection(); } /** * Gets if this is a union or intersection type. */ isUnionOrIntersection() { return this.compilerType.isUnionOrIntersection(); } /** * Gets if this is the unknown type. */ isUnknown() { return this._hasTypeFlag(TypeFlags.Unknown); } /** * Gets if this is the null type. */ isNull() { return this._hasTypeFlag(TypeFlags.Null); } /** * Gets if this is the undefined type. */ isUndefined() { return this._hasTypeFlag(TypeFlags.Undefined); } /** * Gets the type flags. */ getFlags(): TypeFlags { return this.compilerType.flags; } /** * Gets the object flags. * @remarks Returns 0 for a non-object type. */ getObjectFlags() { if (!this.isObject()) return 0; return (this.compilerType as any as ts.ObjectType).objectFlags || 0; } /** @internal */ private _hasTypeFlag(flag: TypeFlags) { return (this.compilerType.flags & flag) === flag; } /** @internal */ private _hasObjectFlag(flag: ObjectFlags) { return (this.getObjectFlags() & flag) === flag; } }
the_stack
import { ContentObject, ExampleObject, ExamplesObject, MediaTypeObject, ParameterObject, SchemaObject, } from "openapi3-ts"; import { RequestBodyObject, ResponseObject, } from "openapi3-ts/src/model/OpenApi"; import { z } from "zod"; import { ArrayElement, extractObjectSchema, getExamples, getRoutePathParams, IOSchema, routePathParamsRegex, } from "./common-helpers"; import { InputSources } from "./config-type"; import { AbstractEndpoint } from "./endpoint"; import { OpenAPIError } from "./errors"; import { ZodFile, ZodFileDef } from "./file-schema"; import { Method } from "./method"; import { ZodUpload, ZodUploadDef } from "./upload-schema"; import { omit } from "ramda"; type MediaExamples = Pick<MediaTypeObject, "examples">; type DepictHelper<T extends z.ZodType<any>> = (params: { schema: T; initial?: SchemaObject; isResponse: boolean; }) => SchemaObject; type DepictingRules = Partial< Record< z.ZodFirstPartyTypeKind | ZodFileDef["typeName"] | ZodUploadDef["typeName"], DepictHelper<any> > >; interface ReqResDepictHelperCommonProps { method: Method; path: string; endpoint: AbstractEndpoint; } /* eslint-disable @typescript-eslint/no-use-before-define */ export const reformatParamsInPath = (path: string) => path.replace(routePathParamsRegex, (param) => `{${param.slice(1)}}`); export const depictDefault: DepictHelper<z.ZodDefault<z.ZodTypeAny>> = ({ schema: { _def: { innerType, defaultValue }, }, initial, isResponse, }) => ({ ...initial, ...depictSchema({ schema: innerType, initial, isResponse }), default: defaultValue(), }); export const depictAny: DepictHelper<z.ZodAny> = ({ initial }) => ({ ...initial, format: "any", }); export const depictUpload: DepictHelper<ZodUpload> = ({ initial }) => ({ ...initial, type: "string", format: "binary", }); export const depictFile: DepictHelper<ZodFile> = ({ schema: { isBinary, isBase64 }, initial, }) => ({ ...initial, type: "string", format: isBinary ? "binary" : isBase64 ? "byte" : "file", }); export const depictUnion: DepictHelper< z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]> > = ({ schema: { _def: { options }, }, initial, isResponse, }) => ({ ...initial, oneOf: options.map((option) => depictSchema({ schema: option, isResponse })), }); export const depictIntersection: DepictHelper< z.ZodIntersection<z.ZodTypeAny, z.ZodTypeAny> > = ({ schema: { _def: { left, right }, }, initial, isResponse, }) => ({ ...initial, allOf: [ depictSchema({ schema: left, isResponse }), depictSchema({ schema: right, isResponse }), ], }); export const depictOptionalOrNullable: DepictHelper< z.ZodOptional<any> | z.ZodNullable<any> > = ({ schema, initial, isResponse }) => ({ ...initial, ...depictSchema({ schema: schema.unwrap(), isResponse }), }); export const depictEnum: DepictHelper< z.ZodEnum<any> | z.ZodNativeEnum<any> > = ({ schema: { _def: { values }, }, initial, }) => ({ ...initial, type: typeof Object.values(values)[0] as "string" | "number", enum: Object.values(values), }); export const depictLiteral: DepictHelper<z.ZodLiteral<any>> = ({ schema: { _def: { value }, }, initial, }) => ({ ...initial, type: typeof value as "string" | "number" | "boolean", enum: [value], }); export const depictObject: DepictHelper<z.AnyZodObject> = ({ schema, initial, isResponse, }) => ({ ...initial, type: "object", properties: depictObjectProperties({ schema, isResponse }), required: Object.keys(schema.shape).filter( (key) => !schema.shape[key].isOptional() ), }); /** @see https://swagger.io/docs/specification/data-models/data-types/ */ export const depictNull: DepictHelper<z.ZodNull> = ({ initial }) => ({ ...initial, type: "string", nullable: true, format: "null", }); export const depictDate: DepictHelper<z.ZodDate> = ({ initial }) => ({ ...initial, type: "string", format: "date", }); export const depictBoolean: DepictHelper<z.ZodBoolean> = ({ initial }) => ({ ...initial, type: "boolean", }); export const depictBigInt: DepictHelper<z.ZodBigInt> = ({ initial }) => ({ ...initial, type: "integer", format: "bigint", }); export const depictRecord: DepictHelper<z.ZodRecord<z.ZodTypeAny>> = ({ schema: { _def: def }, initial, isResponse, }) => { if ( def.keyType instanceof z.ZodEnum || def.keyType instanceof z.ZodNativeEnum ) { const keys = Object.values(def.keyType._def.values) as string[]; const shape = keys.reduce( (carry, key) => ({ ...carry, [key]: def.valueType, }), {} as z.ZodRawShape ); return { ...initial, type: "object", properties: depictObjectProperties({ schema: z.object(shape), isResponse, }), required: keys, }; } if (def.keyType instanceof z.ZodLiteral) { return { ...initial, type: "object", properties: depictObjectProperties({ schema: z.object({ [def.keyType._def.value]: def.valueType, }), isResponse, }), required: [def.keyType._def.value], }; } if (def.keyType instanceof z.ZodUnion) { const areOptionsLiteral = def.keyType.options.reduce( (carry: boolean, option: z.ZodTypeAny) => carry && option instanceof z.ZodLiteral, true ); if (areOptionsLiteral) { const shape = def.keyType.options.reduce( (carry: z.ZodRawShape, option: z.ZodLiteral<any>) => ({ ...carry, [option.value]: def.valueType, }), {} as z.ZodRawShape ); return { ...initial, type: "object", properties: depictObjectProperties({ schema: z.object(shape), isResponse, }), required: def.keyType.options.map( (option: z.ZodLiteral<any>) => option.value ), }; } } return { ...initial, type: "object", additionalProperties: depictSchema({ schema: def.valueType, isResponse }), }; }; export const depictArray: DepictHelper<z.ZodArray<z.ZodTypeAny>> = ({ schema: { _def: def }, initial, isResponse, }) => ({ ...initial, type: "array", items: depictSchema({ schema: def.type, isResponse }), ...(def.minLength ? { minItems: def.minLength.value } : {}), ...(def.maxLength ? { maxItems: def.maxLength.value } : {}), }); /** @todo improve it when OpenAPI 3.1.0 will be released */ export const depictTuple: DepictHelper<z.ZodTuple> = ({ schema: { items }, initial, isResponse, }) => { const types = items.map((item) => depictSchema({ schema: item, isResponse })); return { ...initial, type: "array", minItems: types.length, maxItems: types.length, items: { oneOf: types, format: "tuple", ...(types.length === 0 ? {} : { description: types .map((item, index) => `${index}: ${item.type}`) .join(", "), }), }, }; }; export const depictString: DepictHelper<z.ZodString> = ({ schema: { _def: { checks }, }, initial, }) => { const isEmail = checks.find(({ kind }) => kind === "email") !== undefined; const isUrl = checks.find(({ kind }) => kind === "url") !== undefined; const isUUID = checks.find(({ kind }) => kind === "uuid") !== undefined; const isCUID = checks.find(({ kind }) => kind === "cuid") !== undefined; const minLengthCheck = checks.find(({ kind }) => kind === "min") as | Extract<ArrayElement<z.ZodStringDef["checks"]>, { kind: "min" }> | undefined; const maxLengthCheck = checks.find(({ kind }) => kind === "max") as | Extract<ArrayElement<z.ZodStringDef["checks"]>, { kind: "max" }> | undefined; const regexCheck = checks.find(({ kind }) => kind === "regex") as | Extract<ArrayElement<z.ZodStringDef["checks"]>, { kind: "regex" }> | undefined; return { ...initial, type: "string" as const, ...(isEmail ? { format: "email" } : {}), ...(isUrl ? { format: "url" } : {}), ...(isUUID ? { format: "uuid" } : {}), ...(isCUID ? { format: "cuid" } : {}), ...(minLengthCheck ? { minLength: minLengthCheck.value } : {}), ...(maxLengthCheck ? { maxLength: maxLengthCheck.value } : {}), ...(regexCheck ? { pattern: `/${regexCheck.regex.source}/${regexCheck.regex.flags}` } : {}), }; }; export const depictNumber: DepictHelper<z.ZodNumber> = ({ schema, initial, }) => { const minCheck = schema._def.checks.find(({ kind }) => kind === "min") as | Extract<ArrayElement<z.ZodNumberDef["checks"]>, { kind: "min" }> | undefined; const isMinInclusive = minCheck ? minCheck.inclusive : true; const maxCheck = schema._def.checks.find(({ kind }) => kind === "max") as | Extract<ArrayElement<z.ZodNumberDef["checks"]>, { kind: "max" }> | undefined; const isMaxInclusive = maxCheck ? maxCheck.inclusive : true; return { ...initial, type: schema.isInt ? ("integer" as const) : ("number" as const), format: schema.isInt ? ("int64" as const) : ("double" as const), minimum: schema.minValue === null ? schema.isInt ? Number.MIN_SAFE_INTEGER : Number.MIN_VALUE : schema.minValue, exclusiveMinimum: !isMinInclusive, maximum: schema.maxValue === null ? schema.isInt ? Number.MAX_SAFE_INTEGER : Number.MAX_VALUE : schema.maxValue, exclusiveMaximum: !isMaxInclusive, }; }; export const depictObjectProperties = ({ schema: { shape }, isResponse, }: Parameters<DepictHelper<z.AnyZodObject>>[0]) => { return Object.keys(shape).reduce( (carry, key) => ({ ...carry, [key]: depictSchema({ schema: shape[key], isResponse }), }), {} as Record<string, SchemaObject> ); }; export const depictEffect: DepictHelper<z.ZodEffects<z.ZodTypeAny>> = ({ schema, initial, isResponse, }) => { const input = depictSchema({ schema: schema._def.schema, isResponse }); const effect = schema._def.effect; if (isResponse && effect && effect.type === "transform") { let output = "undefined"; try { output = typeof effect.transform( ["integer", "number"].includes(`${input.type}`) ? 0 : "string" === input.type ? "" : "boolean" === input.type ? false : "object" === input.type ? {} : "null" === input.type ? null : "array" === input.type ? [] : undefined ); } catch (e) { /**/ } return { ...initial, ...input, ...(["number", "string", "boolean"].includes(output) ? { type: output as "number" | "string" | "boolean", } : {}), }; } if (!isResponse && effect && effect.type === "preprocess") { const { type: inputType, ...rest } = input; return { ...initial, ...rest, format: `${rest.format || inputType} (preprocessed)`, }; } return { ...initial, ...input }; }; export const depictIOExamples = <T extends IOSchema>( schema: T, isResponse: boolean, omitProps: string[] = [] ): MediaExamples => { const examples = getExamples(schema, isResponse); if (examples.length === 0) { return {}; } return { examples: examples.reduce<ExamplesObject>( (carry, example, index) => ({ ...carry, [`example${index + 1}`]: <ExampleObject>{ value: omit(omitProps, example), }, }), {} ), }; }; export const depictIOParamExamples = <T extends IOSchema>( schema: T, isResponse: boolean, param: string ): MediaExamples => { const examples = getExamples(schema, isResponse); if (examples.length === 0) { return {}; } return { examples: examples.reduce<ExamplesObject>( (carry, example, index) => param in example ? { ...carry, [`example${index + 1}`]: <ExampleObject>{ value: example[param], }, } : carry, {} ), }; }; export const depictRequestParams = ({ path, method, endpoint, inputSources, }: ReqResDepictHelperCommonProps & { inputSources: InputSources[Method]; }): ParameterObject[] => { const schema = endpoint.getInputSchema(); const shape = extractObjectSchema(schema).shape; const pathParams = getRoutePathParams(path); const isQueryEnabled = inputSources.includes("query"); const isParamsEnabled = inputSources.includes("params"); const isPathParam = (name: string) => isParamsEnabled && pathParams.includes(name); return Object.keys(shape) .filter((name) => isQueryEnabled || isPathParam(name)) .map((name) => ({ name, in: isPathParam(name) ? "path" : "query", required: !shape[name].isOptional(), schema: { description: `${method.toUpperCase()} ${path} parameter`, ...depictSchema({ schema: shape[name], isResponse: false }), }, ...depictIOParamExamples(schema, false, name), })); }; const depictHelpers: DepictingRules = { ZodString: depictString, ZodNumber: depictNumber, ZodBigInt: depictBigInt, ZodBoolean: depictBoolean, ZodDate: depictDate, ZodNull: depictNull, ZodArray: depictArray, ZodTuple: depictTuple, ZodRecord: depictRecord, ZodObject: depictObject, ZodLiteral: depictLiteral, ZodIntersection: depictIntersection, ZodUnion: depictUnion, ZodFile: depictFile, ZodUpload: depictUpload, ZodAny: depictAny, ZodDefault: depictDefault, ZodEnum: depictEnum, ZodNativeEnum: depictEnum, ZodEffects: depictEffect, ZodOptional: depictOptionalOrNullable, ZodNullable: depictOptionalOrNullable, }; export const depictSchema: DepictHelper<z.ZodTypeAny> = ({ schema, isResponse, }) => { const initial: SchemaObject = {}; if (schema.isNullable()) { initial.nullable = true; } if (schema.description) { initial.description = `${schema.description}`; } const examples = getExamples(schema, isResponse); if (examples.length > 0) { initial.example = examples[0]; } const nextHelper = "typeName" in schema._def ? depictHelpers[schema._def.typeName as keyof typeof depictHelpers] : null; if (!nextHelper) { throw new OpenAPIError( `Zod type ${schema.constructor.name} is unsupported` ); } return nextHelper({ schema, initial, isResponse }); }; export const excludeParamsFromDepiction = ( depicted: SchemaObject, pathParams: string[] ): SchemaObject => { const properties = depicted.properties ? omit(pathParams, depicted.properties) : undefined; const required = depicted.required ? depicted.required.filter((name) => !pathParams.includes(name)) : undefined; const allOf = depicted.allOf ? depicted.allOf.map((entry) => excludeParamsFromDepiction(entry, pathParams) ) : undefined; const oneOf = depicted.oneOf ? depicted.oneOf.map((entry) => excludeParamsFromDepiction(entry, pathParams) ) : undefined; return omit( Object.entries({ properties, required, allOf, oneOf }) .filter(([{}, value]) => value === undefined) .map(([key]) => key), { ...depicted, properties, required, allOf, oneOf, } ); }; export const excludeExampleFromDepiction = ( depicted: SchemaObject ): SchemaObject => omit(["example"], depicted); export const depictResponse = ({ method, path, description, endpoint, isPositive, }: ReqResDepictHelperCommonProps & { description: string; isPositive: boolean; }): ResponseObject => { const schema = isPositive ? endpoint.getPositiveResponseSchema() : endpoint.getNegativeResponseSchema(); const mimeTypes = isPositive ? endpoint.getPositiveMimeTypes() : endpoint.getNegativeMimeTypes(); const depictedSchema = excludeExampleFromDepiction( depictSchema({ schema, isResponse: true, }) ); const examples = depictIOExamples(schema, true); return { description: `${method.toUpperCase()} ${path} ${description}`, content: mimeTypes.reduce( (carry, mimeType) => ({ ...carry, [mimeType]: { schema: depictedSchema, ...examples, }, }), {} as ContentObject ), }; }; export const depictRequest = ({ method, path, endpoint, }: ReqResDepictHelperCommonProps): RequestBodyObject => { const pathParams = getRoutePathParams(path); const bodyDepiction = excludeExampleFromDepiction( excludeParamsFromDepiction( depictSchema({ schema: endpoint.getInputSchema(), isResponse: false, }), pathParams ) ); const bodyExamples = depictIOExamples( endpoint.getInputSchema(), false, pathParams ); return { content: endpoint.getInputMimeTypes().reduce( (carry, mimeType) => ({ ...carry, [mimeType]: { schema: { description: `${method.toUpperCase()} ${path} request body`, ...bodyDepiction, }, ...bodyExamples, }, }), {} as ContentObject ), }; };
the_stack
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; import * as tab from "./tab"; import { server, cast } from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; import { Types } from "../../../socket/socketContract"; import * as $ from "jquery"; import * as styles from "../../styles/styles"; import * as onresize from "onresize"; import { Clipboard } from "../../components/clipboard"; import * as typestyle from "typestyle"; type FileDependency = Types.FileDependency; let EOL = '\n'; /** * The styles */ require('./dependencyView.less'); export interface Props extends tab.TabProps { } export interface State { cycles: string[][]; } let controlRootStyle = { pointerEvents: 'none', } let controlRightStyle = { width: '200px', padding: '10px', overflow: 'auto', wordBreak: 'break-all', pointerEvents: 'all', } let controlItemClassName = typestyle.style({ pointerEvents: 'auto', padding: '.4rem', transition: 'background .2s', background: 'rgba(200,200,200,.05)', $nest: { '&:hover': { background: 'rgba(200,200,200,.25)', } } }) let cycleHeadingStyle = { fontSize: '1.2rem', } export class DependencyView extends ui.BaseComponent<Props, State> { private graphRenderer: GraphRenderer; constructor(props: Props) { super(props); this.filePath = utils.getFilePathFromUrl(props.url); this.state = { cycles: [] }; } refs: { [string: string]: any; root: HTMLDivElement; graphRoot: HTMLDivElement; controlRoot: HTMLDivElement; } filePath: string; componentDidMount() { this.loadData(); this.disposible.add( cast.activeProjectConfigDetailsUpdated.on(() => { this.loadData(); }) ); const focused = () => { this.props.onFocused(); } this.refs.root.addEventListener('focus', focused); this.disposible.add({ dispose: () => { this.refs.root.removeEventListener('focus', focused); } }) // Listen to tab events const api = this.props.api; this.disposible.add(api.resize.on(this.resize)); this.disposible.add(api.focus.on(this.focus)); this.disposible.add(api.save.on(this.save)); this.disposible.add(api.close.on(this.close)); this.disposible.add(api.gotoPosition.on(this.gotoPosition)); // Listen to search tab events this.disposible.add(api.search.doSearch.on(this.search.doSearch)); this.disposible.add(api.search.hideSearch.on(this.search.hideSearch)); this.disposible.add(api.search.findNext.on(this.search.findNext)); this.disposible.add(api.search.findPrevious.on(this.search.findPrevious)); this.disposible.add(api.search.replaceNext.on(this.search.replaceNext)); this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious)); this.disposible.add(api.search.replaceAll.on(this.search.replaceAll)); } render() { let hasCycles = !!this.state.cycles.length; let cyclesMessages = hasCycles ? this.state.cycles.map((cycle, i) => { let cycleText = cycle.join(' ⬅️ '); return ( <div key={i} className={controlItemClassName}> <div style={cycleHeadingStyle}> {i + 1}) Cycle <Clipboard text={cycleText} /></div> <div> {cycleText} </div> </div> ); }) : <div key={-1} className={controlItemClassName}>No cycles 🌹</div>; return ( <div ref="root" tabIndex={0} className="dependency-view" style={csx.extend(csx.vertical, csx.flex, csx.newLayerParent, styles.someChildWillScroll)} onKeyPress={this.handleKey}> <div ref="graphRoot" style={csx.extend(csx.vertical, csx.flex)}> {/* Graph goes here */} </div> <div ref="controlRoot" className="graph-controls" style={csx.extend(csx.newLayer, csx.horizontal, csx.endJustified, controlRootStyle)}> <div style={csx.extend(csx.vertical, controlRightStyle)}> <div className={`control-zoom ${controlItemClassName}`}> <a className="control-zoom-in" href="#" title="Zoom in" onClick={this.zoomIn} /> <a className="control-zoom-out" href="#" title="Zoom out" onClick={this.zoomOut} /> <a className="control-fit" href="#" title="Fit" onClick={this.zoomFit} /> </div> {cyclesMessages} </div> </div> <div data-comment="Tip" style={csx.extend(styles.Tip.root, csx.content)}> Tap <span style={styles.Tip.keyboardShortCutStyle}>R</span> to refresh </div> </div> ); } handleKey = (e: any) => { let unicode = e.charCode; if (String.fromCharCode(unicode).toLowerCase() === "r") { this.loadData(); } } loadData = () => { this.refs.graphRoot.innerHTML = ''; return server.getDependencies({}).then((res) => { // Create the graph renderer this.graphRenderer = new GraphRenderer({ dependencies: res.links, measureSizeRoot: $(this.refs.root), graphRoot: $(this.refs.graphRoot), display: (node) => { } }); // get the cycles let cycles = this.graphRenderer.d3Graph.cycles(); this.setState({ cycles }); }); } zoomIn = (e: React.SyntheticEvent<any>) => { e.preventDefault(); if (!this.graphRenderer) return; this.graphRenderer.zoomIn(); } zoomOut = (e: React.SyntheticEvent<any>) => { e.preventDefault(); if (!this.graphRenderer) return; this.graphRenderer.zoomOut(); } zoomFit = (e: React.SyntheticEvent<any>) => { e.preventDefault(); if (!this.graphRenderer) return; this.graphRenderer.zoomFit(); } /** * TAB implementation */ resize = () => { this.graphRenderer && this.graphRenderer.resize(); } focus = () => { this.refs.root.focus(); // if its not there its because an XHR is lagging and it will show up when that xhr completes anyways this.graphRenderer && this.graphRenderer.resize(); } save = () => { } close = () => { } gotoPosition = (position: EditorPosition) => { } search = { doSearch: (options: FindOptions) => { this.graphRenderer && this.graphRenderer.applyFilter(options.query); }, hideSearch: () => { this.graphRenderer && this.graphRenderer.clearFilter(); }, findNext: (options: FindOptions) => { }, findPrevious: (options: FindOptions) => { }, replaceNext: ({newText}: { newText: string }) => { }, replacePrevious: ({newText}: { newText: string }) => { }, replaceAll: ({newText}: { newText: string }) => { } } } interface D3LinkNode extends d3.layout.force.Node { name: string } interface D3Link { source: D3LinkNode; target: D3LinkNode; } var prefixes = { circle: 'circle' } class GraphRenderer { graph: d3.Selection<any>; links: d3.Selection<d3.layout.force.Link<d3.layout.force.Node>>; nodes: d3.Selection<d3.layout.force.Node>; text: d3.Selection<d3.layout.force.Node>; zoom: d3.behavior.Zoom<{}>; layout: d3.layout.Force<d3.layout.force.Link<d3.layout.force.Node>, d3.layout.force.Node>; graphWidth = 0; graphHeight = 0; d3Graph: D3Graph; svgRoot: d3.Selection<any>; constructor(public config: { dependencies: FileDependency[], measureSizeRoot: JQuery, graphRoot: JQuery, display: (content: FileDependency) => any }) { var d3Root = d3.select(config.graphRoot[0]); let self = this; // Compute the distinct nodes from the links. var d3NodeLookup: { [name: string]: D3LinkNode } = {}; var d3links: D3Link[] = config.dependencies.map(function(link) { var source = d3NodeLookup[link.sourcePath] || (d3NodeLookup[link.sourcePath] = { name: link.sourcePath }); var target = d3NodeLookup[link.targetPath] || (d3NodeLookup[link.targetPath] = { name: link.targetPath }); return { source, target }; }); // Calculate all the good stuff this.d3Graph = new D3Graph(d3links); // setup weights based on degrees Object.keys(d3NodeLookup).forEach(name => { var node = d3NodeLookup[name]; node.weight = self.d3Graph.avgDeg(node); }) // Setup zoom this.zoom = d3.behavior.zoom() .scale(0.4) .scaleExtent([.1, 6]) .on("zoom", onZoomChanged); this.svgRoot = d3Root.append("svg") .call(this.zoom); this.graph = this.svgRoot .append('svg:g'); this.layout = d3.layout.force() .nodes(d3.values(d3NodeLookup)) .links(d3links) .gravity(.05) .linkDistance(function(link: D3Link) { return (self.d3Graph.difference(link)) * 200; }) .charge(-900) .on("tick", this.tick) .start(); var drag = this.layout.drag() .on("dragstart", dragstart); /** resize initially and setup for resize */ this.resize(); this.centerGraph(); function onZoomChanged() { self.graph.attr("transform", "translate(" + (d3.event as any).translate + ")" + " scale(" + (d3.event as any).scale + ")"); } // Per-type markers, as they don't inherit styles. self.graph.append("defs").selectAll("marker") .data(["regular"]) .enter().append("marker") .attr("id", function(d) { return d; }) .attr("viewBox", "0 -5 10 10") .attr("refX", 15) .attr("refY", -1.5) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("path") .attr("d", "M0,-5L10,0L0,5"); this.links = self.graph.append("g").selectAll("path") .data(this.layout.links()) .enter().append("path") .attr("class", function(d: D3Link) { return "link"; }) .attr("data-target", function(o: D3Link) { return self.htmlName(o.target) }) .attr("data-source", function(o: D3Link) { return self.htmlName(o.source) }) .attr("marker-end", function(d: D3Link) { return "url(#regular)"; }); this.nodes = self.graph.append("g").selectAll("circle") .data(this.layout.nodes()) .enter().append("circle") .attr("class", function(d: D3LinkNode) { return formatClassName(prefixes.circle, d) }) // Store class name for easier later lookup .attr("data-name", function(o: D3LinkNode) { return self.htmlName(o) }) // Store for easier later lookup .attr("r", function(d: D3LinkNode) { return Math.max(d.weight, 3); }) .classed("inonly", function(d: D3LinkNode) { return self.d3Graph.inOnly(d); }) .classed("outonly", function(d: D3LinkNode) { return self.d3Graph.outOnly(d); }) .classed("circular", function(d: D3LinkNode) { return self.d3Graph.isCircular(d); }) .call(drag) .on("dblclick", dblclick) // Unstick .on("mouseover", function(d: D3LinkNode) { onNodeMouseOver(d) }) .on("mouseout", function(d: D3LinkNode) { onNodeMouseOut(d) }) this.text = self.graph.append("g").selectAll("text") .data(this.layout.nodes()) .enter().append("text") .attr("x", 8) .attr("y", ".31em") .attr("data-name", function(o: D3LinkNode) { return self.htmlName(o) }) .text(function(d: D3LinkNode) { return d.name; }); function onNodeMouseOver(d: D3LinkNode) { // Highlight circle var elm = findElementByNode(prefixes.circle, d); elm.classed("hovering", true); updateNodeTransparencies(d, true); } function onNodeMouseOut(d: D3LinkNode) { // Highlight circle var elm = findElementByNode(prefixes.circle, d); elm.classed("hovering", false); updateNodeTransparencies(d, false); } let findElementByNode = (prefix, node) => { var selector = '.' + formatClassName(prefix, node); return self.graph.select(selector); } function updateNodeTransparencies(d: D3LinkNode, fade = true) { // clean self.nodes.classed('not-hovering', false); self.nodes.classed('dimmed', false); if (fade) { self.nodes.each(function(o: D3LinkNode) { if (!self.d3Graph.isConnected(d, o)) { this.classList.add('not-hovering'); this.classList.add('dimmed'); } }); } // Clean self.graph.selectAll('path.link').attr('data-show', '') .classed('outgoing', false) .attr('marker-end', fade ? '' : 'url(#regular)') .classed('incomming', false) .classed('dimmed', fade); self.links.each(function(o: D3Link) { if (o.source.name === d.name) { this.classList.remove('dimmed'); // Highlight target of the link var elmNodes = self.graph.selectAll('.' + formatClassName(prefixes.circle, o.target)); elmNodes.attr('fill-opacity', 1); elmNodes.attr('stroke-opacity', 1); elmNodes.classed('dimmed', false); // Highlight arrows let outgoingLink = self.graph.selectAll('path.link[data-source="' + self.htmlName(o.source) + '"]'); outgoingLink.attr('data-show', 'true'); outgoingLink.attr('marker-end', 'url(#regular)'); outgoingLink.classed('outgoing', true); } else if (o.target.name === d.name) { this.classList.remove('dimmed'); // Highlight arrows let incommingLink = self.graph.selectAll('path.link[data-target="' + self.htmlName(o.target) + '"]'); incommingLink.attr('data-show', 'true'); incommingLink.attr('marker-end', 'url(#regular)'); incommingLink.classed('incomming', true); } }); self.text.classed("dimmed", function(o: D3LinkNode) { if (!fade) return false; if (self.d3Graph.isConnected(d, o)) return false; return true; }); } // Helpers function formatClassName(prefix, object: D3LinkNode) { return prefix + '-' + self.htmlName(object); } function dragstart(d) { d.fixed = true; // http://bl.ocks.org/mbostock/3750558 (d3.event as any).sourceEvent.stopPropagation(); // http://bl.ocks.org/mbostock/6123708 d3.select(this).classed("fixed", true); } function dblclick(d) { d3.select(this).classed("fixed", d.fixed = false); } } // Use elliptical arc path segments to doubly-encode directionality. tick = () => { function transform(d: D3LinkNode) { return "translate(" + d.x + "," + d.y + ")"; } this.links.attr("d", linkArc); this.nodes.attr("transform", transform); this.text.attr("transform", transform); } applyFilter = utils.debounce((val: string) => { if (!val) { this.clearFilter(); return; } else { this.nodes.classed('filtered-out', true); this.links.classed('filtered-out', true); this.text.classed('filtered-out', true); let filteredNodes = this.graph.selectAll(`circle[data-name*="${this.htmlName({ name: val })}"]`); filteredNodes.classed('filtered-out', false); var filteredLinks = this.graph.selectAll(`[data-source*="${this.htmlName({ name: val })}"][data-target*="${this.htmlName({ name: val })}"]`); filteredLinks.classed('filtered-out', false); let filteredText = this.graph.selectAll(`text[data-name*="${this.htmlName({ name: val })}"]`); filteredText.classed('filtered-out', false); } }, 250); clearFilter = () => { this.nodes.classed('filtered-out', false); this.links.classed('filtered-out', false); this.text.classed('filtered-out', false); } /** * Layout */ resize = () => { this.graphWidth = this.config.measureSizeRoot.width(); this.graphHeight = this.config.measureSizeRoot.height(); this.svgRoot.attr("width", this.graphWidth) .attr("height", this.graphHeight); this.layout.size([this.graphWidth, this.graphHeight]) .resume(); } centerGraph = () => { var centerTranslate: [number, number] = [ (this.graphWidth / 4), (this.graphHeight / 4), ]; this.zoom.translate(centerTranslate); // Render transition this.transitionScale(); } zoomIn = () => { this.zoomCenter(1); } zoomOut = () => { this.zoomCenter(-1); } zoomFit = () => { this.zoom.scale(0.4); this.centerGraph(); } /** Modifed from http://bl.ocks.org/linssen/7352810 */ private zoomCenter(direction: number) { var factor = 0.3, target_zoom = 1, center = [this.graphWidth / 2, this.graphHeight / 2], extent = this.zoom.scaleExtent(), translate = this.zoom.translate(), translate0 = [], l = [], view = { x: translate[0], y: translate[1], k: this.zoom.scale() }; target_zoom = this.zoom.scale() * (1 + factor * direction); if (target_zoom < extent[0] || target_zoom > extent[1]) { return false; } translate0 = [(center[0] - view.x) / view.k, (center[1] - view.y) / view.k]; view.k = target_zoom; l = [translate0[0] * view.k + view.x, translate0[1] * view.k + view.y]; view.x += center[0] - l[0]; view.y += center[1] - l[1]; this.zoom.scale(view.k); this.zoom.translate([view.x, view.y]); this.transitionScale(); } /** * Helpers */ private htmlName(object: D3LinkNode) { return object.name.replace(/(\.|\/)/gi, '-'); } private transitionScale() { this.graph.transition() .duration(500) .attr("transform", "translate(" + this.zoom.translate() + ")" + " scale(" + this.zoom.scale() + ")"); } } interface TargetBySourceName { [source: string]: D3LinkNode[] } /** * A class to do analysis on D3 links array * Degree : The number of connections * Bit of a lie about degrees : 0 is changed to 1 intentionally */ class D3Graph { private inDegLookup = {}; private outDegLookup = {}; private linkedByName = {}; private targetsBySourceName: TargetBySourceName = {}; private circularPaths: string[][] = []; constructor(private links: D3Link[]) { links.forEach(l => { if (!this.inDegLookup[l.target.name]) this.inDegLookup[l.target.name] = 2; else this.inDegLookup[l.target.name]++; if (!this.outDegLookup[l.source.name]) this.outDegLookup[l.source.name] = 2; else this.outDegLookup[l.source.name]++; // Build linked lookup for quick connection checks this.linkedByName[l.source.name + "," + l.target.name] = 1; // Build an adjacency list if (!this.targetsBySourceName[l.source.name]) this.targetsBySourceName[l.source.name] = []; this.targetsBySourceName[l.source.name].push(l.target); }); // Taken from madge this.findCircular(); } public inDeg(node: D3LinkNode) { return this.inDegLookup[node.name] ? this.inDegLookup[node.name] : 1; } public outDeg(node: D3LinkNode) { return this.outDegLookup[node.name] ? this.outDegLookup[node.name] : 1; } public avgDeg(node: D3LinkNode) { return (this.inDeg(node) + this.outDeg(node)) / 2; } public isConnected(a: D3LinkNode, b: D3LinkNode) { return this.linkedByName[a.name + "," + b.name] || this.linkedByName[b.name + "," + a.name] || a.name == b.name; } /** how different are the two nodes in the link */ public difference(link: D3Link) { // take file path into account: return utils.relative(link.source.name, link.target.name).split('/').length; } public inOnly(node: D3LinkNode) { return !this.outDegLookup[node.name] && this.inDegLookup[node.name]; } public outOnly(node: D3LinkNode) { return !this.inDegLookup[node.name] && this.outDegLookup[node.name]; } /** * Get path to the circular dependency. */ private getPath(parent: D3LinkNode, unresolved: { [source: string]: boolean }): string[] { var parentVisited = false; return Object.keys(unresolved).filter((module) => { if (module === parent.name) { parentVisited = true; } return parentVisited && unresolved[module]; }); } /** * A circular dependency is occurring when we see a software package * more than once, unless that software package has all its dependencies resolved. */ private resolver(sourceName: string, resolved: { [source: string]: boolean }, unresolved: { [source: string]: boolean }) { unresolved[sourceName] = true; if (this.targetsBySourceName[sourceName]) { this.targetsBySourceName[sourceName].forEach((dependency) => { if (!resolved[dependency.name]) { if (unresolved[dependency.name]) { this.circularPaths.push(this.getPath(dependency, unresolved)); return; } this.resolver(dependency.name, resolved, unresolved); } }); } resolved[sourceName] = true; unresolved[sourceName] = false; } /** * Finds all circular dependencies for the given modules. */ private findCircular() { var resolved: any = {}, unresolved: any = {}; Object.keys(this.targetsBySourceName).forEach((sourceName) => { this.resolver(sourceName, resolved, unresolved); }); }; /** Check if the given module is part of a circular dependency */ public isCircular(node: D3LinkNode) { var cyclic = false; this.circularPaths.some((path) => { if (path.indexOf(node.name) >= 0) { cyclic = true; return true; } return false; }); return cyclic; } public cycles(): string[][] { return this.circularPaths; } } /** modified version of http://stackoverflow.com/a/26616564/390330 Takes weight into account */ function linkArc(d: D3Link) { var targetX = d.target.x; var targetY = d.target.y; var sourceX = d.source.x; var sourceY = d.source.y; var theta = Math.atan((targetX - sourceX) / (targetY - sourceY)); var phi = Math.atan((targetY - sourceY) / (targetX - sourceX)); var sinTheta = d.source.weight / 2 * Math.sin(theta); var cosTheta = d.source.weight / 2 * Math.cos(theta); var sinPhi = (d.target.weight - 6) * Math.sin(phi); var cosPhi = (d.target.weight - 6) * Math.cos(phi); // Set the position of the link's end point at the source node // such that it is on the edge closest to the target node if (d.target.y > d.source.y) { sourceX = sourceX + sinTheta; sourceY = sourceY + cosTheta; } else { sourceX = sourceX - sinTheta; sourceY = sourceY - cosTheta; } // Set the position of the link's end point at the target node // such that it is on the edge closest to the source node if (d.source.x > d.target.x) { targetX = targetX + cosPhi; targetY = targetY + sinPhi; } else { targetX = targetX - cosPhi; targetY = targetY - sinPhi; } // Draw an arc between the two calculated points var dx = targetX - sourceX, dy = targetY - sourceY, dr = Math.sqrt(dx * dx + dy * dy); return "M" + sourceX + "," + sourceY + "A" + dr + "," + dr + " 0 0,1 " + targetX + "," + targetY; }
the_stack
import { registerEventHandler, triggerEvent, removeNode, arrayForEach, options } from '@tko/utils' import { applyBindings } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { computed } from '@tko/computed' import { DataBindProvider } from '@tko/provider.databind' import { bindings as coreBindings } from '../dist' import { bindings as templateBindings } from '@tko/binding.template' import '@tko/utils/helpers/jasmine-13-helper' describe('Binding: Checked', function () { beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new DataBindProvider() options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(templateBindings) }) it('Triggering a click should toggle a checkbox\'s checked state before the event handler fires', function () { // This isn't strictly to do with the checked binding, but if this doesn't work, the rest of the specs aren't meaningful testNode.innerHTML = "<input type='checkbox' />" var clickHandlerFireCount = 0, expectedCheckedStateInHandler registerEventHandler(testNode.childNodes[0], 'click', function () { clickHandlerFireCount++ expect(testNode.childNodes[0].checked).toEqual(expectedCheckedStateInHandler) }) expect(testNode.childNodes[0].checked).toEqual(false) expectedCheckedStateInHandler = true triggerEvent(testNode.childNodes[0], 'click') expect(testNode.childNodes[0].checked).toEqual(true) expect(clickHandlerFireCount).toEqual(1) expectedCheckedStateInHandler = false triggerEvent(testNode.childNodes[0], 'click') expect(testNode.childNodes[0].checked).toEqual(false) expect(clickHandlerFireCount).toEqual(2) }) it('Should be able to control a checkbox\'s checked state', function () { var myobservable = observable(true) testNode.innerHTML = "<input type='checkbox' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) expect(testNode.childNodes[0].checked).toEqual(true) myobservable(false) expect(testNode.childNodes[0].checked).toEqual(false) }) it('Should update observable properties on the underlying model when the checkbox click event fires', function () { var myobservable = observable(false) testNode.innerHTML = "<input type='checkbox' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) triggerEvent(testNode.childNodes[0], 'click') expect(myobservable()).toEqual(true) }) it('Should only notify observable properties on the underlying model *once* even if the checkbox change events fire multiple times', function () { var myobservable = observable() var timesNotified = 0 myobservable.subscribe(function () { timesNotified++ }) testNode.innerHTML = "<input type='checkbox' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) // Multiple events only cause one notification... triggerEvent(testNode.childNodes[0], 'click') triggerEvent(testNode.childNodes[0], 'change') triggerEvent(testNode.childNodes[0], 'change') expect(timesNotified).toEqual(1) // ... until the checkbox value actually changes triggerEvent(testNode.childNodes[0], 'click') triggerEvent(testNode.childNodes[0], 'change') expect(timesNotified).toEqual(2) }) it('Should update non-observable properties on the underlying model when the checkbox click event fires', function () { var model = { someProp: false } testNode.innerHTML = "<input type='checkbox' data-bind='checked:someProp' />" applyBindings(model, testNode) triggerEvent(testNode.childNodes[0], 'click') expect(model.someProp).toEqual(true) }) it('Should make a radio button checked if and only if its value matches the bound model property', function () { var myobservable = observable('another value') testNode.innerHTML = "<input type='radio' value='This Radio Button Value' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) expect(testNode.childNodes[0].checked).toEqual(false) myobservable('This Radio Button Value') expect(testNode.childNodes[0].checked).toEqual(true) }) it('Should set an observable model property to this radio button\'s value when checked', function () { var myobservable = observable('another value') testNode.innerHTML = "<input type='radio' value='this radio button value' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) expect(myobservable()).toEqual('another value') testNode.childNodes[0].click() expect(myobservable()).toEqual('this radio button value') }) it('Should only notify observable properties on the underlying model *once* even if the radio button change/click events fire multiple times', function () { var myobservable = observable('original value') var timesNotified = 0 myobservable.subscribe(function () { timesNotified++ }) testNode.innerHTML = "<input type='radio' value='this radio button value' data-bind='checked:someProp' /><input type='radio' value='different value' data-bind='checked:someProp' />" applyBindings({ someProp: myobservable }, testNode) // Multiple events only cause one notification... triggerEvent(testNode.childNodes[0], 'click') triggerEvent(testNode.childNodes[0], 'change') triggerEvent(testNode.childNodes[0], 'click') triggerEvent(testNode.childNodes[0], 'change') expect(timesNotified).toEqual(1) // ... until you click something with a different value triggerEvent(testNode.childNodes[1], 'click') triggerEvent(testNode.childNodes[1], 'change') expect(timesNotified).toEqual(2) }) it('Should set a non-observable model property to this radio button\'s value when checked', function () { var model = { someProp: 'another value' } testNode.innerHTML = "<input type='radio' value='this radio button value' data-bind='checked:someProp' />" applyBindings(model, testNode) triggerEvent(testNode.childNodes[0], 'click') expect(model.someProp).toEqual('this radio button value') }) it('When a checkbox is bound to an array, the checkbox should control whether its value is in that array', function () { var model = { myArray: ['Existing value', 'Unrelated value'] } testNode.innerHTML = "<input type='checkbox' value='Existing value' data-bind='checked:myArray' />" + "<input type='checkbox' value='New value' data-bind='checked:myArray' />" applyBindings(model, testNode) expect(model.myArray).toEqual(['Existing value', 'Unrelated value']) // Checkbox initial state is determined by whether the value is in the array expect(testNode).toHaveCheckedStates([true, false]) // Checking the checkbox puts it in the array triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([true, true]) expect(model.myArray).toEqual(['Existing value', 'Unrelated value', 'New value']) // Unchecking the checkbox removes it from the array triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([true, false]) expect(model.myArray).toEqual(['Existing value', 'Unrelated value']) }) it('When a checkbox is bound to an observable array, the checkbox checked state responds to changes in the array', function () { var model = { myObservableArray: observableArray(['Unrelated value']) } testNode.innerHTML = "<input type='checkbox' value='My value' data-bind='checked:myObservableArray' />" applyBindings(model, testNode) expect(testNode.childNodes[0].checked).toEqual(false) // Put the value in the array; observe the checkbox reflect this model.myObservableArray.push('My value') expect(testNode.childNodes[0].checked).toEqual(true) // Remove the value from the array; observe the checkbox reflect this model.myObservableArray.remove('My value') expect(testNode.childNodes[0].checked).toEqual(false) }) it('When a checkbox is bound to a computed array, the checkbox and the computed observable should update each other', function () { var myObservable = observable([]), myComputed = computed({ read: function () { return myObservable().slice(0) // return a copy of the array so that we know that writes to the computed are really working }, write: myObservable // just pass writes on to the observable }) testNode.innerHTML = "<input type='checkbox' value='A' data-bind='checked: myComputed' /><input type='checkbox' value='B' data-bind='checked: myComputed' />" applyBindings({ myComputed: myComputed }, testNode) // Binding adds an item to the observable triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([false, true]) expect(myObservable()).toEqual(['B']) // Updating the observable updates the view myObservable(['A']) expect(testNode).toHaveCheckedStates([true, false]) // Binding removes an item from the observable triggerEvent(testNode.childNodes[0], 'click') expect(testNode).toHaveCheckedStates([false, false]) expect(myObservable()).toEqual([]) }) it('When the radio button \'value\' attribute is set via attr binding, should set initial checked state correctly (attr before checked)', function () { var myObservable = observable('this radio button value') testNode.innerHTML = "<input type='radio' data-bind='attr:{value:\"this radio button value\"}, checked:someProp' />" applyBindings({ someProp: myObservable }, testNode) expect(testNode.childNodes[0].checked).toEqual(true) myObservable('another value') expect(testNode.childNodes[0].checked).toEqual(false) }) it('When the radio button \'value\' attribute is set via attr binding, should set initial checked state correctly (checked before attr)', function () { var myobservable = observable('this radio button value') testNode.innerHTML = "<input type='radio' data-bind='checked:someProp, attr:{value:\"this radio button value\"}' />" applyBindings({ someProp: myobservable }, testNode) expect(testNode.childNodes[0].checked).toEqual(true) myobservable('another value') expect(testNode.childNodes[0].checked).toEqual(false) }) it('When the bound observable is updated in a subscription in response to a radio click, view and model should stay in sync', function () { // This test failed when jQuery was included before the changes made in #1191 testNode.innerHTML = '<input type="radio" value="1" name="x" data-bind="checked: choice" />' + '<input type="radio" value="2" name="x" data-bind="checked: choice" />' + '<input type="radio" value="3" name="x" data-bind="checked: choice" />' var choice = observable('1') choice.subscribe(function (newValue) { if (newValue == '3') // don't allow item 3 to be selected; revert to item 1 { choice('1') } }) applyBindings({choice: choice}, testNode) expect(testNode).toHaveCheckedStates([true, false, false]) // Click on item 2; verify it's selected triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([false, true, false]) // Click on item 3; verify item 1 is selected triggerEvent(testNode.childNodes[2], 'click') expect(testNode).toHaveCheckedStates([true, false, false]) }) arrayForEach([ { binding: 'checkedValue', label: "With \'checkedValue\'" }, { binding: 'value', label: 'With \'value\' treated like \'checkedValue\' when used with \'checked\'' } ], function (data) { var binding = data.binding describe(data.label, function () { it('Should use that value as the checkbox value in the array', function () { var model = { myArray: observableArray([1, 3]) } testNode.innerHTML = "<input type='checkbox' data-bind='checked:myArray, " + binding + ":1' />" + "<input value='off' type='checkbox' data-bind='checked:myArray, " + binding + ":2' />" applyBindings(model, testNode) expect(model.myArray()).toEqual([1, 3]) // initial value is unchanged // Checkbox initial state is determined by whether the value is in the array expect(testNode).toHaveCheckedStates([true, false]) // Verify that binding sets element value expect(testNode).toHaveValues(['1', '2']) // Checking the checkbox puts it in the array triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([true, true]) expect(model.myArray()).toEqual([1, 3, 2]) // Unchecking the checkbox removes it from the array triggerEvent(testNode.childNodes[1], 'click') expect(testNode).toHaveCheckedStates([true, false]) expect(model.myArray()).toEqual([1, 3]) // Put the value in the array; observe the checkbox reflect this model.myArray.push(2) expect(testNode).toHaveCheckedStates([true, true]) // Remove the value from the array; observe the checkbox reflect this model.myArray.remove(1) expect(testNode).toHaveCheckedStates([false, true]) }) it('Should be able to use objects as value of checkboxes', function () { var object1 = {x: 1}, object2 = {y: 1}, model = { values: [object1], choices: [object1, object2] } testNode.innerHTML = "<div data-bind='foreach: choices'><input type='checkbox' data-bind='checked:$parent.values, " + binding + ":$data' /></div>" applyBindings(model, testNode) // Checkbox initial state is determined by whether the value is in the array expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Checking the checkbox puts it in the array triggerEvent(testNode.childNodes[0].childNodes[1], 'click') expect(testNode.childNodes[0]).toHaveCheckedStates([true, true]) expect(model.values).toEqual([object1, object2]) // Unchecking the checkbox removes it from the array triggerEvent(testNode.childNodes[0].childNodes[1], 'click') expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) expect(model.values).toEqual([object1]) }) it('Should be able to use observables as value of checkboxes', function () { var object1 = {id: observable(1)}, object2 = {id: observable(2)}, model = { values: observableArray([1]), choices: [object1, object2] } testNode.innerHTML = "<div data-bind='foreach: choices'><input type='checkbox' data-bind='" + binding + ":id, checked:$parent.values' /></div>" applyBindings(model, testNode) expect(model.values()).toEqual([1]) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the checked item; should update the selected values and leave checked values unchanged object1.id(3) expect(model.values()).toEqual([3]) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item; should do nothing object2.id(4) expect(model.values()).toEqual([3]) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item to the current model value; should set to checked object2.id(3) expect(model.values()).toEqual([3]) expect(testNode.childNodes[0]).toHaveCheckedStates([true, true]) // Update the value again; should leave checked and replace item in the selected values (other checkbox should be unchecked) object2.id(4) expect(model.values()).toEqual([4]) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) // Revert to original value; should update value in selected values object2.id(2) expect(model.values()).toEqual([2]) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) }) it('When node is removed, subscription to observable bound to \'' + binding + '\' is disposed', function () { var model = { values: [1], checkedValue: observable(1) } testNode.innerHTML = "<input type='checkbox' data-bind='" + binding + ":checkedValue, checked:values' />" applyBindings(model, testNode) expect(model.values).toEqual([1]) expect(testNode.childNodes[0].checked).toEqual(true) expect(model.checkedValue.getSubscriptionsCount()).toBeGreaterThan(0) removeNode(testNode.childNodes[0]) expect(model.checkedValue.getSubscriptionsCount()).toEqual(0) }) it('Should use that value as the radio button\'s value', function () { var myobservable = observable(false) testNode.innerHTML = "<input type='radio' data-bind='checked:someProp, " + binding + ":true' />" + "<input type='radio' data-bind='checked:someProp, " + binding + ":false' />" applyBindings({ someProp: myobservable }, testNode) expect(myobservable()).toEqual(false) // Check initial state expect(testNode).toHaveCheckedStates([false, true]) // Update observable; verify elements myobservable(true) expect(testNode).toHaveCheckedStates([true, false]) // "Click" a button; verify observable and elements testNode.childNodes[1].click() expect(myobservable()).toEqual(false) expect(testNode).toHaveCheckedStates([false, true]) }) it('Should be able to use observables as value of radio buttons', function () { var object1 = {id: observable(1)}, object2 = {id: observable(2)}, model = { value: observable(1), choices: [object1, object2] } testNode.innerHTML = "<div data-bind='foreach: choices'><input type='radio' data-bind='" + binding + ":id, checked:$parent.value' /></div>" applyBindings(model, testNode) expect(model.value()).toEqual(1) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the checked item; should update the selected value and leave checked values unchanged object1.id(3) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item; should do nothing object2.id(4) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item to the current model value; should set to checked object2.id(3) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, true]) // Update the value again; should leave checked and replace selected value (other button should be unchecked) object2.id(4) expect(model.value()).toEqual(4) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) // Revert to original value; should update selected value object2.id(2) expect(model.value()).toEqual(2) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) }) if (binding === 'checkedValue') { // When bound to a checkbox, the "checkedValue" binding will affect a non-array // "checked" binding, but "value" won't. it('Should use that value as the checkbox\'s value when not bound to an array', function () { var myobservable = observable('random value') testNode.innerHTML = "<input type='checkbox' data-bind='checked:someProp, " + binding + ":true' />" + "<input type='checkbox' data-bind='checked:someProp, " + binding + ":false' />" applyBindings({ someProp: myobservable }, testNode) expect(myobservable()).toEqual('random value') // Check initial state: both are unchecked because neither has a matching value expect(testNode).toHaveCheckedStates([false, false]) // Update observable; verify element states myobservable(false) expect(testNode).toHaveCheckedStates([false, true]) myobservable(true) expect(testNode).toHaveCheckedStates([true, false]) // "check" a box; verify observable and elements testNode.childNodes[1].click() expect(myobservable()).toEqual(false) expect(testNode).toHaveCheckedStates([false, true]) // "uncheck" a box; verify observable and elements testNode.childNodes[1].click() expect(myobservable()).toEqual(undefined) expect(testNode).toHaveCheckedStates([false, false]) }) it('Should be able to use observables as value of checkboxes when not bound to an array', function () { var object1 = {id: observable(1)}, object2 = {id: observable(2)}, model = { value: observable(1), choices: [object1, object2] } testNode.innerHTML = "<div data-bind='foreach: choices'><input type='checkbox' data-bind='" + binding + ":id, checked:$parent.value' /></div>" applyBindings(model, testNode) expect(model.value()).toEqual(1) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the checked item; should update the selected values and leave checked values unchanged object1.id(3) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item; should do nothing object2.id(4) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, false]) // Update the value observable of the unchecked item to the current model value; should set to checked object2.id(3) expect(model.value()).toEqual(3) expect(testNode.childNodes[0]).toHaveCheckedStates([true, true]) // Update the value again; should leave checked and replace selected value (other button should be unchecked) object2.id(4) expect(model.value()).toEqual(4) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) // Revert to original value; should update selected value object2.id(2) expect(model.value()).toEqual(2) expect(testNode.childNodes[0]).toHaveCheckedStates([false, true]) }) } it('Should ignore \'undefined\' value for checkbox', function () { var myobservable = observable(true) testNode.innerHTML = "<input type='checkbox' data-bind='checked: someProp, " + binding + ":undefined' />" applyBindings({ someProp: myobservable }, testNode) // ignores 'undefined' value and treats checkbox value as true/false expect(testNode.childNodes[0].checked).toEqual(true) myobservable(false) expect(testNode.childNodes[0].checked).toEqual(false) triggerEvent(testNode.childNodes[0], 'click') expect(myobservable()).toEqual(true) triggerEvent(testNode.childNodes[0], 'click') expect(myobservable()).toEqual(false) }) }) }) })
the_stack
export type SourceMapUrl = string; export interface StartOfSourceMap { file?: string; sourceRoot?: string; skipValidation?: boolean; } export interface RawSourceMap { version: number; sources: string[]; names: string[]; sourceRoot?: string; sourcesContent?: string[]; mappings: string; file: string; } export interface RawIndexMap extends StartOfSourceMap { version: number; sections: RawSection[]; } export interface RawSection { offset: Position; map: RawSourceMap; } export interface Position { line: number; column: number; } export interface NullablePosition { line: number | null; column: number | null; lastColumn: number | null; } export interface MappedPosition { source: string; line: number; column: number; name?: string; } export interface NullableMappedPosition { source: string | null; line: number | null; column: number | null; name: string | null; } export interface MappingItem { source: string; generatedLine: number; generatedColumn: number; lastGeneratedColumn: number | null; originalLine: number; originalColumn: number; name: string; } export interface Mapping { generated: Position; original: Position; source: string; name?: string; } export interface CodeWithSourceMap { code: string; map: SourceMapGenerator; } export interface SourceMappings { "lib/mappings.wasm": SourceMapUrl | ArrayBuffer; } export interface SourceMapConsumer { /** * When using SourceMapConsumer outside of node.js, for example on the Web, it * needs to know from what URL to load lib/mappings.wasm. You must inform it * by calling initialize before constructing any SourceMapConsumers. * * @param mappings an object with the following property: * - "lib/mappings.wasm": A String containing the URL of the * lib/mappings.wasm file, or an ArrayBuffer with the contents of * lib/mappings.wasm. */ initialize(mappings: SourceMappings): void; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ computeColumnSpans(): void; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[]; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ hasContentsOfAllSources(): boolean; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param callback * The function that is called with each mapping. * @param context * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param order * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; /** * Free this source map consumer's associated wasm data that is manually-managed. * Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy. */ destroy(): void; } export interface SourceMapConsumerConstructor { prototype: SourceMapConsumer; GENERATED_ORDER: number; ORIGINAL_ORDER: number; GREATEST_LOWER_BOUND: number; LEAST_UPPER_BOUND: number; new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>; new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise<IndexedSourceMapConsumer>; new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise< BasicSourceMapConsumer | IndexedSourceMapConsumer >; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param sourceMap * The source map that will be consumed. */ fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>; /** * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait * for `f` to complete, call `destroy` on the consumer, and return `f`'s return * value. * * You must not use the consumer after `f` completes! * * By using `with`, you do not have to remember to manually call `destroy` on * the consumer, since it will be called automatically once `f` completes. * * ```js * const xSquared = await SourceMapConsumer.with( * myRawSourceMap, * null, * async function (consumer) { * // Use `consumer` inside here and don't worry about remembering * // to call `destroy`. * * const x = await whatever(consumer); * return x * x; * } * ); * * // You may not use that `consumer` anymore out here; it has * // been destroyed. But you can use `xSquared`. * console.log(xSquared); * ``` */ with<T>( rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise<T> | T ): Promise<T>; } export const SourceMapConsumer: SourceMapConsumerConstructor; export interface BasicSourceMapConsumer extends SourceMapConsumer { file: string; sourceRoot: string; sources: string[]; sourcesContent: string[]; } export interface BasicSourceMapConsumerConstructor { prototype: BasicSourceMapConsumer; new (rawSourceMap: RawSourceMap | string): Promise<BasicSourceMapConsumer>; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param sourceMap * The source map that will be consumed. */ fromSourceMap(sourceMap: SourceMapGenerator): Promise<BasicSourceMapConsumer>; } export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor; export interface IndexedSourceMapConsumer extends SourceMapConsumer { sources: string[]; } export interface IndexedSourceMapConsumerConstructor { prototype: IndexedSourceMapConsumer; new (rawSourceMap: RawIndexMap | string): Promise<IndexedSourceMapConsumer>; } export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor; export class SourceMapGenerator { constructor(startOfSourceMap?: StartOfSourceMap); /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param sourceMapConsumer The SourceMap. */ static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ addMapping(mapping: Mapping): void; /** * Set the source content for a source file. */ setSourceContent(sourceFile: string, sourceContent: string): void; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param sourceMapConsumer The source map to be applied. * @param sourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param sourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; toString(): string; toJSON(): RawSourceMap; } export class SourceNode { children: SourceNode[]; sourceContents: any; line: number; column: number; source: string; name: string; constructor(); constructor( line: number | null, column: number | null, source: string | null, chunks?: Array<string | SourceNode> | SourceNode | string, name?: string ); static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; add(chunk: Array<string | SourceNode> | SourceNode | string): SourceNode; prepend(chunk: Array<string | SourceNode> | SourceNode | string): SourceNode; setSourceContent(sourceFile: string, sourceContent: string): void; walk(fn: (chunk: string, mapping: MappedPosition) => void): void; walkSourceContents(fn: (file: string, content: string) => void): void; join(sep: string): SourceNode; replaceRight(pattern: string, replacement: string): SourceNode; toString(): string; toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; }
the_stack
import { OtokenInstance, MockERC20Instance, MockAddressBookInstance } from '../../build/types/truffle-types' import { createTokenAmount } from '../utils' const { expectRevert } = require('@openzeppelin/test-helpers') const Otoken = artifacts.require('Otoken.sol') const MockERC20 = artifacts.require('MockERC20.sol') const MockAddressBook = artifacts.require('MockAddressBook') contract('Otoken', ([deployer, controller, user1, user2, random]) => { let addressBook: MockAddressBookInstance let otoken: OtokenInstance let usdc: MockERC20Instance let weth: MockERC20Instance let addressBookAddr: string // let expiry: number; const strikePrice = createTokenAmount(200) const expiry = 1601020800 // 2020/09/25 0800 UTC const isPut = true before('Deployment', async () => { // Need another mock contract for addressbook when we add ERC20 operations. addressBook = await MockAddressBook.new() addressBookAddr = addressBook.address await addressBook.setController(controller) // deploy oToken with addressbook otoken = await Otoken.new() usdc = await MockERC20.new('USDC', 'USDC', 6) weth = await MockERC20.new('WETH', 'WETH', 18) }) describe('Otoken Initialization', () => { it('should be able to initialize with put parameter correctly', async () => { await otoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, isPut, { from: deployer, }) assert.equal(await otoken.underlyingAsset(), weth.address) assert.equal(await otoken.strikeAsset(), usdc.address) assert.equal(await otoken.collateralAsset(), usdc.address) assert.equal((await otoken.strikePrice()).toString(), strikePrice.toString()) assert.equal(await otoken.isPut(), isPut) assert.equal((await otoken.expiryTimestamp()).toNumber(), expiry) }) it('should initilized the put option with valid name / symbol', async () => { assert.equal(await otoken.name(), `WETHUSDC 25-September-2020 200Put USDC Collateral`) assert.equal(await otoken.symbol(), `oWETHUSDC/USDC-25SEP20-200P`) assert.equal((await otoken.decimals()).toNumber(), 8) }) it('should get correct otoken details', async () => { const otokenDetails = await otoken.getOtokenDetails() assert.equal(otokenDetails[0], usdc.address, 'getOtokenDetails collateral asset mismatch') assert.equal(otokenDetails[1], weth.address, 'getOtokenDetails underlying asset mismatch') assert.equal(otokenDetails[2], usdc.address, 'getOtokenDetails strike asset mismatch') assert.equal(otokenDetails[3].toString(), strikePrice.toString(), 'getOtokenDetails strike price mismatch') assert.equal(otokenDetails[4].toNumber(), expiry, 'getOtokenDetails expiry mismatch') assert.equal(otokenDetails[5], isPut, 'getOtokenDetails isPut mismatch') }) it('should revert when init is called again with the same parameters', async () => { await expectRevert( otoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, isPut), 'Contract instance has already been initialized', ) }) it('should revert when init is called again with different parameters', async () => { await expectRevert( otoken.init(addressBookAddr, usdc.address, weth.address, weth.address, strikePrice, expiry, false), 'Contract instance has already been initialized', ) }) it('should set the right name for calls', async () => { const callOption = await Otoken.new() await callOption.init(addressBookAddr, weth.address, usdc.address, weth.address, strikePrice, expiry, false, { from: deployer, }) assert.equal(await callOption.name(), `WETHUSDC 25-September-2020 200Call WETH Collateral`) assert.equal(await callOption.symbol(), `oWETHUSDC/WETH-25SEP20-200C`) }) it('should set the right name and symbol for option with strikePrice < 1', async () => { // strike price with lots of ending zeros const strikePrice = createTokenAmount(0.5) const o1 = await Otoken.new() await o1.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, true, { from: deployer, }) assert.equal(await o1.name(), `WETHUSDC 25-September-2020 0.5Put USDC Collateral`) assert.equal(await o1.symbol(), `oWETHUSDC/USDC-25SEP20-0.5P`) }) it('should set the right name and symbol for option with strikePrice < 1, with 8 decimals', async () => { // strike price with 8 decimals const strikePrice2 = createTokenAmount(0.00010052) const o2 = await Otoken.new() await o2.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice2, expiry, true, { from: deployer, }) assert.equal(await o2.name(), `WETHUSDC 25-September-2020 0.00010052Put USDC Collateral`) assert.equal(await o2.symbol(), `oWETHUSDC/USDC-25SEP20-0.00010052P`) }) it('should set the right name and symbol for option with strikePrice < 1, with starting and trailing zeroes.', async () => { const strikePrice3 = createTokenAmount(0.0729) const o3 = await Otoken.new() await o3.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice3, expiry, true, { from: deployer, }) assert.equal(await o3.name(), `WETHUSDC 25-September-2020 0.0729Put USDC Collateral`) assert.equal(await o3.symbol(), `oWETHUSDC/USDC-25SEP20-0.0729P`) }) it('should set the right name for option with strikePrice 0', async () => { const strikePrice = '0' const oToken = await Otoken.new() await oToken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, true, { from: deployer, }) assert.equal(await oToken.name(), `WETHUSDC 25-September-2020 0Put USDC Collateral`) assert.equal(await oToken.symbol(), `oWETHUSDC/USDC-25SEP20-0P`) }) it('should set the right name for non-eth options', async () => { const weth = await MockERC20.new('WETH', 'WETH', 18) const putOption = await Otoken.new() await putOption.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, isPut, { from: deployer, }) assert.equal(await putOption.name(), `WETHUSDC 25-September-2020 200Put USDC Collateral`) assert.equal(await putOption.symbol(), `oWETHUSDC/USDC-25SEP20-200P`) }) it('should revert when init asset with non-erc20 address', async () => { /* This behavior should've been banned by factory) */ const put = await Otoken.new() await expectRevert( put.init(addressBookAddr, random, usdc.address, usdc.address, strikePrice, expiry, isPut, { from: deployer, }), 'revert', ) }) it('should set the right name for options with 0 expiry (should be banned by factory)', async () => { /* This behavior should've been banned by factory) */ const otoken = await Otoken.new() await otoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 0, isPut, { from: deployer, }) assert.equal(await otoken.name(), `WETHUSDC 01-January-1970 200Put USDC Collateral`) assert.equal(await otoken.symbol(), `oWETHUSDC/USDC-01JAN70-200P`) }) it('should set the right name for options expiry on 2345/12/31', async () => { /** This is the largest timestamp that the factoy will allow (the largest bokkypoobah covers) **/ const otoken = await Otoken.new() const _expiry = '11865394800' // Mon, 31 Dec 2345 await otoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, _expiry, isPut, { from: deployer, }) assert.equal(await otoken.name(), `WETHUSDC 31-December-2345 200Put USDC Collateral`) assert.equal(await otoken.symbol(), `oWETHUSDC/USDC-31DEC45-200P`) }) it('should set the right symbol for year 220x ', async () => { const expiry = 7560230400 // 2209-07-29 const otoken = await Otoken.new() await otoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, expiry, true, { from: deployer, }) assert.equal(await otoken.symbol(), 'oWETHUSDC/USDC-29JUL09-200P') assert.equal(await otoken.name(), 'WETHUSDC 29-July-2209 200Put USDC Collateral') }) it('should set the right name and symbol for expiry on each month', async () => { // We need to go through all decision branches in _getMonth() to make a 100% test coverage. const January = await Otoken.new() await January.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1893456000, isPut, { from: deployer, }) assert.equal(await January.name(), 'WETHUSDC 01-January-2030 200Put USDC Collateral') assert.equal(await January.symbol(), 'oWETHUSDC/USDC-01JAN30-200P') const February = await Otoken.new() await February.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1896134400, isPut, { from: deployer, }) assert.equal(await February.name(), 'WETHUSDC 01-February-2030 200Put USDC Collateral') assert.equal(await February.symbol(), 'oWETHUSDC/USDC-01FEB30-200P') const March = await Otoken.new() await March.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1898553600, isPut, { from: deployer, }) assert.equal(await March.name(), 'WETHUSDC 01-March-2030 200Put USDC Collateral') assert.equal(await March.symbol(), 'oWETHUSDC/USDC-01MAR30-200P') const April = await Otoken.new() await April.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1901232000, isPut, { from: deployer, }) assert.equal(await April.name(), 'WETHUSDC 01-April-2030 200Put USDC Collateral') assert.equal(await April.symbol(), 'oWETHUSDC/USDC-01APR30-200P') const May = await Otoken.new() await May.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1903824000, isPut, { from: deployer, }) assert.equal(await May.name(), 'WETHUSDC 01-May-2030 200Put USDC Collateral') assert.equal(await May.symbol(), 'oWETHUSDC/USDC-01MAY30-200P') const June = await Otoken.new() await June.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1906502400, isPut, { from: deployer, }) assert.equal(await June.name(), 'WETHUSDC 01-June-2030 200Put USDC Collateral') assert.equal(await June.symbol(), 'oWETHUSDC/USDC-01JUN30-200P') const July = await Otoken.new() await July.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1909094400, isPut, { from: deployer, }) assert.equal(await July.name(), 'WETHUSDC 01-July-2030 200Put USDC Collateral') assert.equal(await July.symbol(), 'oWETHUSDC/USDC-01JUL30-200P') const August = await Otoken.new() await August.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1911772800, isPut, { from: deployer, }) assert.equal(await August.name(), 'WETHUSDC 01-August-2030 200Put USDC Collateral') assert.equal(await August.symbol(), 'oWETHUSDC/USDC-01AUG30-200P') const September = await Otoken.new() await September.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1914451200, isPut, { from: deployer, }) assert.equal(await September.name(), 'WETHUSDC 01-September-2030 200Put USDC Collateral') assert.equal(await September.symbol(), 'oWETHUSDC/USDC-01SEP30-200P') const October = await Otoken.new() await October.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1917043200, isPut, { from: deployer, }) assert.equal(await October.name(), 'WETHUSDC 01-October-2030 200Put USDC Collateral') assert.equal(await October.symbol(), 'oWETHUSDC/USDC-01OCT30-200P') const November = await Otoken.new() await November.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1919721600, isPut, { from: deployer, }) assert.equal(await November.name(), 'WETHUSDC 01-November-2030 200Put USDC Collateral') assert.equal(await November.symbol(), 'oWETHUSDC/USDC-01NOV30-200P') const December = await Otoken.new() await December.init(addressBookAddr, weth.address, usdc.address, usdc.address, strikePrice, 1922313600, isPut, { from: deployer, }) assert.equal(await December.name(), 'WETHUSDC 01-December-2030 200Put USDC Collateral') assert.equal(await December.symbol(), 'oWETHUSDC/USDC-01DEC30-200P') }) it('should display strikePrice as $0 in name and symbol when strikePrice < 10^18', async () => { const testOtoken = await Otoken.new() await testOtoken.init(addressBookAddr, weth.address, usdc.address, usdc.address, 0, expiry, isPut, { from: deployer, }) assert.equal(await testOtoken.name(), `WETHUSDC 25-September-2020 0Put USDC Collateral`) assert.equal(await testOtoken.symbol(), `oWETHUSDC/USDC-25SEP20-0P`) }) }) describe('Token operations: Mint', () => { const amountToMint = createTokenAmount(10) it('should be able to mint tokens from controller address', async () => { await otoken.mintOtoken(user1, amountToMint, { from: controller }) const balance = await otoken.balanceOf(user1) assert.equal(balance.toString(), amountToMint.toString()) }) it('should revert when minting from random address', async () => { await expectRevert( otoken.mintOtoken(user1, amountToMint, { from: random }), 'Otoken: Only Controller can mint Otokens', ) }) it('should revert when someone try to mint for himself.', async () => { await expectRevert( otoken.mintOtoken(user1, amountToMint, { from: user1 }), 'Otoken: Only Controller can mint Otokens', ) }) }) describe('Token operations: Transfer', () => { const amountToMint = createTokenAmount(10) it('should be able to transfer tokens from user 1 to user 2', async () => { await otoken.transfer(user2, amountToMint, { from: user1 }) const balance = await otoken.balanceOf(user2) assert.equal(balance.toString(), amountToMint.toString()) }) it('should revert when calling transferFrom with no allownace', async () => { await expectRevert( otoken.transferFrom(user2, user1, amountToMint, { from: random }), 'ERC20: transfer amount exceeds allowance', ) }) it('should revert when controller call transferFrom with no allownace', async () => { await expectRevert( otoken.transferFrom(user2, user1, amountToMint, { from: controller }), 'ERC20: transfer amount exceeds allowance', ) }) it('should be able to use transferFrom to transfer token from user2 to user1.', async () => { await otoken.approve(random, amountToMint, { from: user2 }) await otoken.transferFrom(user2, user1, amountToMint, { from: random }) const user2Remaining = await otoken.balanceOf(user2) assert.equal(user2Remaining.toString(), '0') }) }) describe('Token operations: Burn', () => { const amountToMint = createTokenAmount(10) it('should revert when burning from random address', async () => { await expectRevert( otoken.burnOtoken(user1, amountToMint, { from: random }), 'Otoken: Only Controller can burn Otokens', ) }) it('should revert when someone trys to burn for himeself', async () => { await expectRevert( otoken.burnOtoken(user1, amountToMint, { from: user1 }), 'Otoken: Only Controller can burn Otokens', ) }) it('should be able to burn tokens from controller address', async () => { await otoken.burnOtoken(user1, amountToMint, { from: controller }) const balance = await otoken.balanceOf(user1) assert.equal(balance.toString(), '0') }) }) })
the_stack
import { FormItem, InfoShellLayout } from 'components/dataView'; import { DesForm } from 'components/decorators'; import { WtmEditor, WtmDatePicker, WtmRangePicker, WtmSelect, WtmCheckbox, WtmRadio, WtmTransfer } from 'components/form'; import Request from 'utils/Request'; import * as React from 'react'; import lodash from 'lodash'; import { Button, Divider } from 'antd'; export default class extends React.Component<any, any> { render() { return ( <div> <Divider>级联选择</Divider> <Select /> <Divider>Checkbox</Divider> <Checkbox /> <Divider>Radio</Divider> <Radio /> <Divider>Transfer</Divider> <Transfer /> </div> ); } } @DesForm class Select extends React.Component<any, any> { models: WTM.FormItem = { "province": { label: "province", rules: [], formItem: <WtmSelect dataSource={Request.cache({ url: "/mock/select" })} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['city', 'county']) }} /> }, "city": { label: "city", rules: [], formItem: <WtmSelect // 级联模型 配合 dataSource 函数 返回使用 linkage={['province']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); if (province) { return Request.cache({ url: "/mock/select?one=" + province }) } }} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['county']) }} /> }, "county": { label: "county", rules: [], formItem: <WtmSelect mode="multiple" // 级联模型 配合 dataSource 函数 返回使用 linkage={['province', 'city']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); const city = lodash.get(linkage, 'city'); if (province && city) { return Request.cache({ url: `/mock/select?one=${province}&two=${city}` }) } }} /> }, } onSubmit() { this.props.form.validateFields((err, values) => { console.log("TCL: App -> onSubmit -> values", values) }); } render() { const props = { ...this.props, models: this.models, } return ( <div> <div> <Button onClick={this.onSubmit.bind(this)}>打印数据(控制台)</Button> </div> <InfoShellLayout> <FormItem fieId="province" {...props} /> <FormItem fieId="city" {...props} /> <FormItem fieId="county" {...props} /> </InfoShellLayout> </div> ); } } @DesForm class Radio extends React.Component<any, any> { models: WTM.FormItem = { "province": { label: "province", rules: [], formItem: <WtmRadio dataSource={Request.cache({ url: "/mock/select" })} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['city', 'county']) }} /> }, "city": { label: "city", rules: [], formItem: <WtmRadio // 级联模型 配合 dataSource 函数 返回使用 linkage={['province']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); if (province) { return Request.cache({ url: "/mock/select?one=" + province }) } }} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['county']) }} /> }, "county": { label: "county", rules: [], formItem: <WtmRadio // 级联模型 配合 dataSource 函数 返回使用 linkage={['province', 'city']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); const city = lodash.get(linkage, 'city'); if (province && city) { return Request.cache({ url: `/mock/select?one=${province}&two=${city}` }) } }} /> }, } onSubmit() { this.props.form.validateFields((err, values) => { console.log("TCL: App -> onSubmit -> values", values) }); } render() { const props = { ...this.props, models: this.models, } return ( <div> <div> <Button onClick={this.onSubmit.bind(this)}>打印数据(控制台)</Button> </div> <InfoShellLayout> <FormItem fieId="province" {...props} layout="row" /> <FormItem fieId="city" {...props} layout="row" /> <FormItem fieId="county" {...props} layout="row" /> </InfoShellLayout> </div> ); } } @DesForm class Checkbox extends React.Component<any, any> { models: WTM.FormItem = { "province": { label: "province", rules: [], formItem: <WtmCheckbox dataSource={Request.cache({ url: "/mock/select" })} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['city', 'county']) }} /> }, "city": { label: "city", rules: [], formItem: <WtmCheckbox // 级联模型 配合 dataSource 函数 返回使用 linkage={['province']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); if (province) { return Request.cache({ url: "/mock/select?one=" + province }) } }} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['county']) }} /> }, "county": { label: "county", rules: [], formItem: <WtmCheckbox // 级联模型 配合 dataSource 函数 返回使用 linkage={['province', 'city']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); const city = lodash.get(linkage, 'city'); if (province && city) { return Request.cache({ url: `/mock/select?one=${province}&two=${city}` }) } }} /> }, } onSubmit() { this.props.form.validateFields((err, values) => { console.log("TCL: App -> onSubmit -> values", values) }); } render() { const props = { ...this.props, models: this.models, } return ( <div> <div> <Button onClick={this.onSubmit.bind(this)}>打印数据(控制台)</Button> </div> <InfoShellLayout> <FormItem fieId="province" {...props} layout="row" /> <FormItem fieId="city" {...props} layout="row" /> <FormItem fieId="county" {...props} layout="row" /> </InfoShellLayout> </div> ); } } @DesForm class Transfer extends React.Component<any, any> { models: WTM.FormItem = { "province": { label: "province", rules: [], formItem: <WtmTransfer listStyle={undefined} dataSource={Request.cache({ url: "/mock/select" })} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['city', 'county']) }} /> }, "city": { label: "city", rules: [], formItem: <WtmTransfer listStyle={undefined} // 级联模型 配合 dataSource 函数 返回使用 linkage={['province']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); if (province) { return Request.cache({ url: "/mock/select?one=" + province }) } }} // 重置 子数据 使用 setFieldsValue 或者 resetFields onChange={event => { const { resetFields } = this.props.form; resetFields(['county']) }} /> }, "county": { label: "county", rules: [], formItem: <WtmTransfer listStyle={undefined} // 级联模型 配合 dataSource 函数 返回使用 linkage={['province', 'city']} dataSource={(linkage) => { const province = lodash.get(linkage, 'province'); const city = lodash.get(linkage, 'city'); if (province && city) { return Request.cache({ url: `/mock/select?one=${province}&two=${city}` }) } }} /> }, } onSubmit() { this.props.form.validateFields((err, values) => { console.log("TCL: App -> onSubmit -> values", values) }); } render() { const props = { ...this.props, models: this.models, } return ( <div> <div> <Button onClick={this.onSubmit.bind(this)}>打印数据(控制台)</Button> </div> <InfoShellLayout> <FormItem fieId="province" {...props} layout="row" /> <FormItem fieId="city" {...props} layout="row" /> <FormItem fieId="county" {...props} layout="row" /> </InfoShellLayout> </div> ); } }
the_stack
import { autobind } from "core-decorators"; import * as _ from "lodash"; import * as MobileDetect from "mobile-detect"; import { inject, observer } from "mobx-react"; import * as React from "react"; import { Link } from "react-router-dom"; import { Button, Container, Divider, Grid, Header, Icon, Image, Popup, Segment } from "semantic-ui-react"; import { IEpisode } from "../../../lib/interfaces"; import { colors, globalStyles } from "../../../lib/styles"; import { RootState } from "../../../state/RootState"; import RSSImportForm, { IRSSImportFields } from "../forms/RSSImportForm"; import PublishPodcastModal, { IPublishPodcastFields } from "../generic/PublishPodcastModal"; import ContentHeader from "../generic/ContentHeader"; import Episode from "../generic/Episode"; import Footer from "../generic/Footer"; import LoadingContainer from "../generic/LoadingContainer"; import Sidebar from "../generic/Sidebar"; import UnsupportedBrowser from "../generic/UnsupportedBrowser"; interface IPodcastHomeScreenProps { rootState?: RootState; } interface IPodcastHomeScreenState { filter: "all" | "published" | "drafts" | "scheduled"; episodes?: IEpisode[]; message?: string; error?: string; } function browserSwitch(component) { const md = new MobileDetect(window.navigator.userAgent); if (md.mobile()) { return <UnsupportedBrowser />; } return component; } @inject("rootState") @observer export default class PodcastHomeScreen extends React.Component<IPodcastHomeScreenProps, IPodcastHomeScreenState> { constructor(props: IPodcastHomeScreenProps) { super(); this.state = { filter: "all" }; } public render() { if (this.props.rootState.isAuthenticated) { return browserSwitch( <LoadingContainer loading={!!this.props.rootState.loadingCount} restrictAccess="authOnly" isAuthenticated={this.props.rootState.isAuthenticated} podcastRequired={this.props.rootState.podcast} > <div style={globalStyles.contentWrapper} > <Sidebar currentPodcast={this.props.rootState.podcast} /> <main style={globalStyles.workspaceContent}> <ContentHeader clearMessages={() => this.clearMessages()} message={this.state.message} /> <div style={{ display: "flex", flexDirection: "row", width: "75%" }}> <Header as="h2" style={globalStyles.title}>Episodes</Header> <RSSImportForm onSubmit={this.onSubmitFeed} /> <PublishPodcastModal onSubmit={this.onSubmitPodcast}/> </div> <div style={style.headWrapper}> {this.renderEpisodesMenu()} </div> <br /> {this.renderGetStartedMessage()} <Grid> <Grid.Column style={{ width: "75%" }}> {this.renderEpisodes()} </Grid.Column> </Grid> </main> </div> </LoadingContainer>, ); } else { return ( <div style={globalStyles.contentWrapper} > <main style={style.content}> <Grid doubling stackable style={style.gridContainer}> <Grid.Row style={{ paddingBottom: 0 }}> <Grid.Column style={style.platformMessageContainer} width={12}> <div style={{ maxWidth: 500, height: 150, marginBottom: 30 }}> <h1 style={style.mainMessage}> Podsheets is an open source platform to host and monetize your podcast </h1> </div> <div style={{ height: 125 }}> <Button onClick={() => window.location.href = "/#/sign_up"} size="large" floated={"left"} style={style.getStarted}> Get Started </Button> </div> <div style={{ maxWidth: 350 }}> <h4 style={style.secondaryMessage}> </h4> </div> </Grid.Column> <Grid.Column mobile={4} width={8}> <div style={style.someImagesContainer}> <div style={style.someImagesBox}> <img style={style.someImage} src="assets/audio-reviews-hd.png" /> </div> </div> </Grid.Column> </Grid.Row> </Grid> <Grid style={{ padding: 20, paddingBottom: 0, paddingTop: 15 }} doubling stackable centered> <Grid.Row textAlign="center" style={{ marginTop: 40 }}> <Grid.Column columns={1} width={7}> <h1 style={style.creatorText}> What We Offer </h1> </Grid.Column> </Grid.Row> <Grid.Row textAlign="center" style={{ marginTop: 40 }}> <Grid.Column width={3}> <Grid.Row textAlign="center"> <h3 style={{ ...style.podsheetsOptionsText, marginBottom: 5 }}> Open Source </h3> </Grid.Row> <Grid.Row centered textAlign="center" style={{ marginTop: 30, marginBottom: 30 }}> <Grid.Column width={4}> <Image width={100 as 10} src="assets/opensource.svg" centered /> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainDark, marginTop: 5, fontSize: "140%", }} centered textAlign="center"> Open source platform for managing your podcast </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Column width={3}> <Grid.Row textAlign="center"> <h3 style={{ ...style.podsheetsOptionsText, marginBottom: 5 }}> Hosting </h3> </Grid.Row> <Grid.Row centered textAlign="center" style={{ marginTop: 30, marginBottom: 30 }}> <Grid.Column width={4}> <Image width={100 as 10} src="assets/headphones.svg" centered /> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainDark, marginTop: 5, fontSize: "140%", }} centered textAlign="center"> One click publishing across all podcast players </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Column width={3}> <Grid.Row textAlign="center"> <h3 style={{ ...style.podsheetsOptionsText, marginBottom: 5 }}> Analytics </h3> </Grid.Row> <Grid.Row centered textAlign="center" style={{ marginTop: 30, marginBottom: 30 }}> <Grid.Column width={4}> <Image width={100 as 10} src="assets/analytics.svg" centered /> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainDark, marginTop: 10, fontSize: "140%", }} centered textAlign="center"> Detailed analytics on downloads & episode popularity </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Column width={3}> <Grid.Row textAlign="center"> <h3 style={{ ...style.podsheetsOptionsText, marginBottom: 5 }}> Community </h3> </Grid.Row> <Grid.Row centered textAlign="center" style={{ marginTop: 30, marginBottom: 30 }}> <Grid.Column width={4}> <Image width={100 as 10} src="assets/community.svg" centered /> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 10, paddingBottom: "40px" }} textAlign="center"> <Grid.Row style={{ color: colors.mainDark, marginTop: 5, fontSize: "140%", }} centered textAlign="center"> Connect with a community of experienced podcasters </Grid.Row> </Grid.Row> </Grid.Column> </Grid.Row> <Grid.Row textAlign="center" style={{ marginTop: 40 }}> <Grid.Column columns={1} width={7}> <h1 style={style.creatorText}> The Platform </h1> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 80 }}> <Grid.Column width={5}> <Grid.Row > <h3 style={{textAlign: "left", color: colors.mainDark, marginBottom: 5 , marginTop: "2vw", fontWeight: 600 as 600, fontSize: "150%"}}> Intuitive and fast </h3> <Grid.Row textAlign="left" style={{ color: colors.mainDark}}> <div style={{textAlign: "left", paddingTop: "20px", fontSize: "130%", lineHeight: "25px"}}> With just a podcast title, cover image, and an audio file, publish your podcast to iTunes, Google Play and all other players <br/><br/> Migrate your podcasts from other hosting providers with one click RSS imports </div> </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Column width={1}></Grid.Column> <Grid.Column width={6}> <img style={style.productImage} src="assets/podcast-episodes.png" /> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 80 }}> <Grid.Column width={6}> <img style={style.productImage} src="assets/audio-reviews.png" /> </Grid.Column> <Grid.Column width={1}></Grid.Column> <Grid.Column width={5}> <Grid.Row> <h3 style={{ textAlign: "left", color: colors.mainDark, marginBottom: 5 , marginTop: "2vw", fontWeight: 600 as 600, fontSize: "150%"}}> Your podcast on the web </h3> <Grid.Row textAlign="left" style={{ color: colors.mainDark}}> <div style={{textAlign: "left", paddingTop: "20px", fontSize: "130%", lineHeight: "25px"}}> Forget fumbling to create a separate website for your podcast.<br/><br/> Customize a simple website, your home on the web, where your episodes will be posted automatically.<br/><br/> Invite your team to collaborate. </div> </Grid.Row> </Grid.Row> </Grid.Column> </Grid.Row> <Grid.Row textAlign="center" style={{ marginTop: 90 }}> <Grid.Column columns={1} width={7}> <h1 style={style.creatorText}> From the creators of </h1> </Grid.Column> </Grid.Row> <Grid.Row textAlign="center" style={{ marginTop: 20}}> <Grid.Column width={4}> <a href="https://softwareengineeringdaily.com/"> <Image style={{ marginLeft: "auto", marginRight: "auto" }} src="assets/software-engineering-daily.png" /> </a> </Grid.Column> <Grid.Column width={4}> <a href="https://thewomenintechshow.com/"> <Image style={{ marginLeft: "auto", marginRight: "auto" }} src="assets/the-women-in-tech-show.png" /> </a> </Grid.Column> </Grid.Row> <Grid.Row style={{ marginTop: 100, marginBottom: 80, }} width={12}></Grid.Row> {/*TO-DO: uncomment payment information <Grid.Row style={{ marginTop: 100, marginBottom: 80, }} width={12}> <Grid.Column floated="left" style={{ marginTop: 15, backgroundColor: "#F2E7FA", padding: "50px 30px 50px 30px", marginRight: 20, }} width={4}> <Grid.Row textAlign="center"> <h1 style={{ ...style.positiveText, marginBottom: 20 }}> Free for 10 episodes </h1> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 5, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> Create a podcast website </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> View your podcast stats </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> 10 episodes free </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Row only="mobile"> <div style={{ height: 10, width: 10 }}> </div> </Grid.Row> <Grid.Column style={{ marginTop: "15", backgroundColor: "#F2E7FA", padding: "50px 30px 50px 30px", marginLeft: 20, marginRight: 20, }} width={4}> <Grid.Row textAlign="center"> <h1 style={{ ...style.positiveText, marginBottom: 20 }}> $5 monthly </h1> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 5, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> Create a podcast website </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> View your podcast stats </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> Ideal for 30 min weekly shows </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> 200 MB of storage per month </Grid.Row> </Grid.Row> </Grid.Column> <Grid.Row only="mobile"> <div style={{ height: 10, width: 10 }}> </div> </Grid.Row> <Grid.Column style={{ marginTop: "15", backgroundColor: "#F2E7FA", padding: "50px 30px 50px 30px", marginLeft: 20, }} width={4}> <Grid.Row textAlign="center"> <h1 style={{ ...style.positiveText, marginBottom: 20 }}> $20 monthly </h1> </Grid.Row> <Grid.Row style={{ marginTop: 10 }} textAlign="center"> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 5, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> Create a podcast website </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> View your podcast stats </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> Ideal for 60 min weekly shows </Grid.Row> <Grid.Row style={{ color: colors.mainLVibrant, marginTop: 10, fontSize: "140%", fontWeight: 100, }} centered textAlign="center"> 500 MB of storage per month </Grid.Row> </Grid.Row> </Grid.Column> </Grid.Row>*/} </Grid> <Footer /> </main> </div> ); } } protected clearMessages() { this.setState({ error: null, message: null }); } @autobind protected async onSubmitFeed(form: IRSSImportFields) { try { return await this.props.rootState.uploadRssFeed(form.feedUrl, form.publish); } catch (e) { console.error("ERROR IMPORTING FEED"); } } @autobind protected async onSubmitPodcast(form: IPublishPodcastFields) { try { // Get the data of the podcast: rss link, podcast id // Send an email with the details of the podcast to be submitted const response = await this.props.rootState.submitPodcast(); if (response.status === 200) { this.setState({message: response.message}); } return response; } catch (e) { console.error("ERROR SUBMITTING PODCAST"); this.setState({error: "Your podcast could not be submitted for publishing."}); } } @autobind protected chanfeFilter(filter: "all" | "published" | "drafts" | "scheduled") { return (e: React.MouseEvent<HTMLButtonElement>) => { if (filter === "all") { this.setState({ filter: "all", episodes: this.props.rootState.episodes, }); } else if (filter === "published") { this.setState({ filter: "published", episodes: this.props.rootState.publishedEpisodes, }); } else if (filter === "drafts") { this.setState({ filter: "drafts", episodes: this.props.rootState.draftEpisodes, }); } else if (filter === "scheduled") { this.setState({ filter: "scheduled", episodes: this.props.rootState.scheduledEpisodes, }); } }; } protected renderEpisodesMenu() { const episodes = (this.state.episodes && this.state.episodes.length > 0) ? this.state.episodes : this.props.rootState.episodes; if (!episodes || episodes.length === 0) { return (null); } return (<Grid style={{ display: "flex", flex: 1 }}> <Grid.Row centered> <Button.Group centered> <Button basic style={{ backgroundColor: "transparent", borderRight: "1px solid #EEE", }} onClick={this.chanfeFilter("all")}> <span style={this.state.filter === "all" ? style.activeSectionButton : style.sectionButton }>All</span> </Button> <Button basic style={{ backgroundColor: "transparent", borderRight: "1px solid #EEE", }} onClick={this.chanfeFilter("published")}> <span style={this.state.filter === "published" ? style.activeSectionButton : style.sectionButton }>Published</span> </Button> <Button basic style={{ backgroundColor: "transparent", borderRight: "1px solid #EEE", }} onClick={this.chanfeFilter("drafts")}> <span style={this.state.filter === "drafts" ? style.activeSectionButton : style.sectionButton }>Drafts</span> </Button> <Button basic style={{ backgroundColor: "transparent" }} onClick={this.chanfeFilter("scheduled")}> <span style={this.state.filter === "scheduled" ? style.activeSectionButton : style.sectionButton }>Scheduled</span> </Button> </Button.Group> </Grid.Row> </Grid>); } protected renderRSSLink() { if (!this.props.rootState.podcast) { return null; } return ( <Popup trigger={ <Button as="a" href={`/p/${this.props.rootState.podcast.slug}/rss.xml`} target="_blank" floated="left" style={{ marginTop: 5, padding: 2, backgroundColor: "#EDAA44", marginRight: 15, }} > <Icon style={{ margin: 0, marginTop: 4, fontSize: "140%", }} name="rss" inverted /> </Button> } style={{ ...globalStyles.tooltip, margin: 0, marginBottom: -10, marginLeft: 15, }} basic size="tiny" content="RSS feed" /> ); } protected uploadProgress(publicFileUrl: string) { const currentProgress = _.find(this.props.rootState.uploadProgress, { publicFileUrl }); const progressEvent = _.get(currentProgress, "progress", { loaded: false, total: 0, }); if (publicFileUrl && progressEvent && progressEvent.loaded && progressEvent.total) { return Math.ceil((+progressEvent.loaded / progressEvent.total) * 100); } else { return 0; } } protected uploadError(publicFileUrl: string) { const currentProgress = _.find(this.props.rootState.uploadProgress, { publicFileUrl }); return _.get(currentProgress, "error", ""); } protected renderGetStartedMessage() { const episodes = (this.state.episodes && this.state.episodes.length > 0) ? this.state.episodes : this.props.rootState.episodes; if (!episodes || episodes.length === 0) { return (<p style={globalStyles.workspaceContentText}>To get started create a new episode.</p>); } } protected renderEpisodes() { const episodes = this.state.episodes || this.props.rootState.episodes; if (!episodes) { return (null); } return episodes.map(e => { return (<Episode key={`ep-${e._id}`} item={e} progress={this.uploadProgress(e.uploadUrl)} uploadError={this.uploadError(e.uploadUrl)} editItemHandler={this.props.rootState.getEpisodeById} deleteItemHandler={this.props.rootState.deleteEpisode} publishItemHandler={this.props.rootState.publishEpisode} unpublishItemHandler={this.props.rootState.unpublishEpisode} />); }); } protected async componentDidMount() { await this.props.rootState.getPodcastWithEpisodes(); } } const style = { content: { ...globalStyles.content, padding: 0, }, headWrapper: { display: "flex", width: "75%", }, buttonGroup: { float: "center", backgroundColor: "green", display: "flex", flex: 1, justifyContent: "center", }, sectionButton: { color: colors.mainULight, fontSize: "130%", }, activeSectionButton: { color: colors.mainDark, fontSize: "130%", }, newEpisode: { color: "white", fontSize: "120%", backgroundColor: "limegreen", }, platformMessageContainer: { display: "flex", flex: 1, flexDirection: "column", marginTop: "2em", }, mainMessage: { color: "white", textAlign: "left", fontSize: "250%", fontWeight: 200 as 200, }, secondaryMessage: { color: "white", textAlign: "left", fontSize: "145%", marginTop: 0, fontWeight: 100 as 100, }, gridContainer: { marginTop: 0, minHeight: "60vh", padding: "10vw", paddingTop: "10vh", paddingBottom: "0vh", background: "linear-gradient(to right, #2740a8 0%,#c190d9 79%)", }, getStarted: { backgroundColor: "#5FC67A", color: "white", fontSize: "1.25em", }, someImagesContainer: { display: "flex", flex: 1, justifyContent: "center" as "center", }, someImagesBox: { display: "flex", flex: 1, justifyContent: "center" as "center", paddingTop: 15, }, someImage: { width: "100%", height: "auto", position: "absolute", bottom: 0, } as React.CSSProperties, productImage: { width: "100%", height: "auto", border: "none", boxShadow: "2px 3px 10px 3px #e6e6e6", }, creatorText: { aligSelf: "center", color: colors.mainLVibrant, fontWeight: 900 as 900, }, podsheetText: { marginTop: "2vw", color: colors.mainLVibrant, fontWeight: 900 as 900, fontSize: "220%", }, podsheetsOptionsText: { marginTop: "2vw", marginBottom: "2vw", color: colors.mainDark, fontWeight: 600 as 600, fontSize: "190%", }, positiveText: { color: "limegreen", fontSize: "190%", }, };
the_stack
import * as assert from 'assert'; import { getValidator, TransformSchema } from './'; describe('Transforms Schema', () => { const validator = getValidator(TransformSchema); const validate = (params) => { const res = validator(params); return res.errors.length === 0 ? true : false; }; const assertFail = (res) => assert.ok(!res); it('should load json schema', () => { // console.log(schema); }); describe('Watermark', () => { it('should validate correct params', () => { assert.ok(validate({ watermark: { file: 'testfilehandle', size: 300, position: 'top', }, })); }); it('should validate correct params (position array)', () => { assert.ok(validate({ watermark: { file: 'testfilehandle', size: 300, position: ['top', 'left'], }, })); }); it('should fail on wrong position params [top, bottom]', () => { assertFail(validate({ watermark: { file: 'testfilehandle', size: 300, position: ['top', 'bottom'], }, })); }); }); describe('Partial Blur', () => { it('should validate correct params', () => { assert.ok(validate({ partial_blur: { objects: [ [1, 1, 2, 2], [1, 1, 32, 15], ], amount: 18.2, blur: 12, type: 'rect', }, })); }); it('should fail on wrong params (amount, blur, type)', () => { assertFail(validate({ partial_blur: { objects: [ [1, 1, 2, 2], [1, 1, 32, 15], ], amount: -10, blur: 300, type: 'wrong_type', }, })); }); it('should fail on wrong params (objects)', () => { assertFail(validate({ partial_blur: { objects: [ [1, 1, 2], [1, 1, 32, 15, 32], ], amount: 10, blur: 20, }, })); }); }); describe('Partial Pixelate', () => { it('should validate correct params', () => { assert.ok(validate({ partial_pixelate: { objects: [ [1, 1, 2, 2], [1, 1, 32, 15], ], amount: 100, blur: 12.2, type: 'oval', }, })); }); it('should fail on wrong params (amount, blur, type)', () => { assertFail(validate({ partial_pixelate: { objects: [ [1, 1, 2, 2], [1, 1, 32, 15], ], amount: -10, blur: 300, type: 'wrong_type', }, })); }); it('should fail on wrong params (objects)', () => { assertFail(validate({ partial_pixelate: { objects: [ [1, 1, 2], [1, 1, 32, 15, 32], ], amount: 10, blur: 20, }, })); }); }); describe('Crop', () => { it('should validate correct params', () => { assert.ok(validate({ crop: { dim: [1, 1, 2, 2], }, })); }); it('should fail on empty dim params', () => { assertFail(validate({ crop: { dim: [], }, })); }); it('should fail on wrong params (minimum value for 2 first items)', () => { assertFail(validate({ crop: { dim: [2, 1, 0, 2], }, })); }); it('should fail on wrong params (5 items in array)', () => { assertFail(validate({ crop: { dim: [1, 1, 2, 2, 4], }, })); }); }); describe('Resize', () => { it('should validate correct params', () => { assert.ok(validate({ resize: { width: 10, height: 20, fit: 'crop', align: ['top', 'left'], }, })); }); it('should validate correct when only one width or height is provided', () => { assert.ok(validate({ resize: { width: 10, fit: 'crop', align: 'left', }, })); assert.ok(validate({ resize: { height: 10, fit: 'crop', align: 'left', }, })); }); it('should fail on wrong params (missing width and height)', () => { assertFail(validate({ resize: { fit: 'crop', align: 'left', }, })); }); }); describe('Resize', () => { it('should validate correct params', () => { assert.ok(validate({ rotate: { deg: 'exif', exif: false, background: 'fff', }, })); }); it('should validate correct params', () => { assert.ok(validate({ rotate: { deg: 200, exif: true, background: 'ffffff', }, })); }); it('should fail on wrong params (wrong exif rotation)', () => { assertFail(validate({ rotate: { deg: 123, exif: 'true', background: 'ffffff', }, })); }); }); describe('Pdfinfo', () => { it('should validate correct params with bool value', () => { assert.ok(validate({ pdfinfo: true, })); }); it('should validate correct params with color info', () => { assert.ok(validate({ pdfinfo: { colorinfo: true, }, })); }); }); describe('Pdfconvert', () => { describe('Pages', () => { [[1,2], ['1-', 3], ['-2']].forEach((val) => { it(`should validate on correct page "${val}"`, () => { assert.ok(validate({ pdfconvert: { pages: val, }, })); }); }); it('should return error on fail page "1a"', () => { assertFail(validate({ pdfconvert: { pages: '1a', }, })); }); }); describe('Page orientation', () => { it('should pass on correct orientation "landscape"', () => { assert.ok(validate({ pdfconvert: { pageorientation: 'landscape', }, })); }); it('should pass on correct orientation "portrait"', () => { assert.ok(validate({ pdfconvert: { pageorientation: 'portrait', }, })); }); it('should fail on wrong orientation "landscape1"', () => { assertFail(validate({ pdfconvert: { pageorientation: 'landscape1', }, })); }); }); describe('Page format', () => { ['a2', 'a3', 'a4', 'a5', 'b4', 'b5', 'letter', 'legal', 'tabloid'].forEach((val) => { it(`should when correct page format is provided ${val}`, () => { assert.ok(validate({ pdfconvert: { pages: [1,2], pageformat: val, }, })); }); }); it('should fail on wrong page format ie a22', () => { assertFail(validate({ pdfconvert: { pageformat: 'a22', }, })); }); }); }); }); // import * as assert from 'assert'; // import { getValidator, TransformSchema } from './'; // describe('Transforms Schema', () => { // const validate = getValidator(TransformSchema); // const assertFail = (val) => assert.ok(!val); // it('should load json schema', () => { // // console.log(schema); // }); // describe('Watermark', () => { // it('should validate correct params', () => { // assert.ok(validate({ // watermark: { // file: 'testfilehandle', // size: 300, // position: 'top', // }, // })); // }); // it('should validate correct params (position array)', () => { // assert.ok(validate({ // watermark: { // file: 'testfilehandle', // size: 300, // position: ['top', 'left'], // }, // })); // }); // it('should fail on wrong position params [top, bottom]', () => { // assertFail(validate({ // watermark: { // file: 'testfilehandle', // size: 300, // position: ['top', 'bottom'], // }, // })); // }); // }); // describe('Partial Blur', () => { // it('should validate correct params', () => { // assert.ok(validate({ // partial_blur: { // objects: [ // [1, 1, 2, 2], // [1, 1, 32, 15], // ], // amount: 18.2, // blur: 12, // type: 'rect', // }, // })); // }); // it('should fail on wrong params (amount, blur, type)', () => { // assertFail(validate({ // partial_blur: { // objects: [ // [1, 1, 2, 2], // [1, 1, 32, 15], // ], // amount: -10, // blur: 300, // type: 'wrong_type', // }, // })); // }); // it('should fail on wrong params (objects)', () => { // assertFail(validate({ // partial_blur: { // objects: [ // [1, 1, 2], // [1, 1, 32, 15, 32], // ], // amount: 10, // blur: 20, // }, // })); // }); // }); // describe('Partial Pixelate', () => { // it('should validate correct params', () => { // assert.ok(validate({ // partial_pixelate: { // objects: [ // [1, 1, 2, 2], // [1, 1, 32, 15], // ], // amount: 100, // blur: 12.2, // type: 'oval', // }, // })); // }); // it('should fail on wrong params (amount, blur, type)', () => { // assertFail(validate({ // partial_pixelate: { // objects: [ // [1, 1, 2, 2], // [1, 1, 32, 15], // ], // amount: -10, // blur: 300, // type: 'wrong_type', // }, // })); // }); // it('should fail on wrong params (objects)', () => { // assertFail(validate({ // partial_pixelate: { // objects: [ // [1, 1, 2], // [1, 1, 32, 15, 32], // ], // amount: 10, // blur: 20, // }, // })); // }); // }); // describe('Crop', () => { // it('should validate correct params', () => { // assert.ok(validate({ // crop: { // dim: [1, 1, 2, 2], // }, // })); // }); // it('should fail on empty dim params', () => { // assertFail(validate({ // crop: { // dim: [], // }, // })); // }); // it('should fail on wrong params (minimum value for 2 first items)', () => { // assertFail(validate({ // crop: { // dim: [2, 1, 0, 2], // }, // })); // }); // it('should fail on wrong params (5 items in array)', () => { // assertFail(validate({ // crop: { // dim: [1, 1, 2, 2, 4], // }, // })); // }); // }); // describe('Resize', () => { // it('should validate correct params', () => { // assert.ok(validate({ // resize: { // width: 10, // height: 20, // fit: 'crop', // align: ['top', 'left'], // }, // })); // }); // it('should validate correct when only one width or height is provided', () => { // assert.ok(validate({ // resize: { // width: 10, // fit: 'crop', // align: 'left', // }, // })); // assert.ok(validate({ // resize: { // height: 10, // fit: 'crop', // align: 'left', // }, // })); // }); // it('should fail on wrong params (missing width and height)', () => { // assertFail(validate({ // resize: { // fit: 'crop', // align: 'left', // }, // })); // }); // }); // describe('Resize', () => { // it('should validate correct params', () => { // assert.ok(validate({ // rotate: { // deg: 'exif', // exif: false, // background: 'fff', // }, // })); // }); // it('should validate correct params', () => { // assert.ok(validate({ // rotate: { // deg: 200, // exif: true, // background: 'ffffff', // }, // })); // }); // it('should fail on wrong params (wrong exif rotation)', () => { // assertFail(validate({ // rotate: { // deg: 123, // exif: 'true', // background: 'ffffff', // }, // })); // }); // }); // describe('Pdfinfo', () => { // it('should validate correct params with bool value', () => { // assert.ok(validate({ // pdfinfo: true, // })); // }); // it('should validate correct params with color info', () => { // assert.ok(validate({ // pdfinfo: { // colorinfo: true, // }, // })); // }); // }); // describe('Pdfconvert', () => { // describe('Pages', () => { // [[1,2], ['1-', 3], ['-2']].forEach((val) => { // it(`should validate on correct page "${val}"`, () => { // assert.ok(validate({ // pdfconvert: { // pages: val, // }, // })); // }); // }); // it('should return error on fail page "1a"', () => { // assertFail(validate({ // pdfconvert: { // pages: '1a', // }, // })); // }); // }); // describe('Page orientation', () => { // it('should pass on correct orientation "landscape"', () => { // assert.ok(validate({ // pdfconvert: { // pageorientation: 'landscape', // }, // })); // }); // it('should pass on correct orientation "portrait"', () => { // assert.ok(validate({ // pdfconvert: { // pageorientation: 'portrait', // }, // })); // }); // it('should fail on wrong orientation "landscape1"', () => { // assertFail(validate({ // pdfconvert: { // pageorientation: 'landscape1', // }, // })); // }); // }); // describe('Page format', () => { // ['a2', 'a3', 'a4', 'a5', 'b4', 'b5', 'letter', 'legal', 'tabloid'].forEach((val) => { // it(`should when correct page format is provided ${val}`, () => { // assert.ok(validate({ // pdfconvert: { // pages: [1,2], // pageformat: val, // }, // })); // }); // }); // it('should fail on wrong page format ie a22', () => { // assertFail(validate({ // pdfconvert: { // pageformat: 'a22', // }, // })); // }); // }); // }); // });
the_stack
declare module 'aurelia-http-client' { import 'core-js'; import { join, buildQueryString } from 'aurelia-path'; import { PLATFORM, DOM } from 'aurelia-pal'; /** * Creates an XHR implementation. */ export interface XHRConstructor { } // new():XHR; /** * Represents an XHR. */ export interface XHR { /** * The status code of the response. */ status: number; /** * The status text. */ statusText: string; /** * The raw response. */ response: any; /** * The raw response text. */ responseText: string; /** * The load callback. */ onload: Function; /** * The timeout callback. */ ontimeout: Function; /** * The error callback. */ onerror: Function; /** * The abort callback. */ onabort: Function; /** * Aborts the request. */ abort(): void; /** * Opens the XHR channel. */ open(method: string, url: string, isAsync: boolean, user?: string, password?: string): void; /** * Sends the request. */ send(content?: any): void; } /** * Represents an XHR transformer. */ export interface XHRTransformer { } /** * Intercepts requests, responses and errors. */ export interface Interceptor { /** * Intercepts the response. */ response?: Function; /** * Intercepts a response error. */ responseError?: Function; /** * Intercepts the request. */ request?: Function; /** * Intercepts a request error. */ requestError?: Function; } /** * Transforms a request. */ export interface RequestTransformer { } /** * Represents http request/response headers. */ export class Headers { /** * Creates an instance of the headers class. * @param headers A set of key/values to initialize the headers with. */ constructor(headers?: Object); /** * Adds a header. * @param key The header key. * @param value The header value. */ add(key: string, value: string): void; /** * Gets a header value. * @param key The header key. * @return The header value. */ get(key: string): string; /** * Clears the headers. */ clear(): void; /** * Determines whether or not the indicated header exists in the collection. * @param key The header key to check. * @return True if it exists, false otherwise. */ has(header: string): boolean; /** * Configures an XMR object with the headers. * @param xhr The XHRT instance to configure. */ configureXHR(xhr: XHR): void; /** * XmlHttpRequest's getAllResponseHeaders() method returns a string of response * headers according to the format described here: * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method * This method parses that string into a user-friendly key/value pair object. * @param headerStr The string from the XHR. * @return A Headers instance containing the parsed headers. */ static parse(headerStr: string): Headers; } /** * Represents a request message. */ export class RequestMessage { /** * The HTTP method. */ method: string; /** * The url to submit the request to. */ url: string; /** * The content of the request. */ content: any; /** * The headers to send along with the request. */ headers: Headers; /** * The base url that the request url is joined with. */ baseUrl: string; /** * Creates an instance of RequestMessage. * @param method The HTTP method. * @param url The url to submit the request to. * @param content The content of the request. * @param headers The headers to send along with the request. */ constructor(method: string, url: string, content: any, headers?: Headers); /** * Builds the url to make the request from. * @return The constructed url. */ buildFullUrl(): string; } /** * Represents a responce message from an HTTP or JSONP request. */ export class HttpResponseMessage { /** * The request message that resulted in this response. */ requestMessage: RequestMessage; /** * The status code of the response. */ statusCode: string; /** * The raw response. */ response: any; /** * The success status of the request based on status code. */ isSuccess: boolean; /** * The status text. */ statusText: string; /** * A reviver function to use in transforming the content. */ reviver: ((key: string, value: any) => any); /** * The mime type of the response. */ mimeType: string; /** * Creates an instance of HttpResponseMessage. * @param requestMessage The request message that resulted in this response. * @param xhr The XHR instance that made the request. * @param responseType The type of the response. * @param reviver A reviver function to use in transforming the content. */ constructor(requestMessage: RequestMessage, xhr: XHR, responseType: string, reviver: ((key: string, value: any) => any)); /** * Gets the content of the response. * @return the response content. */ content: any; } /** * MimeTypes mapped to responseTypes * * @type {Object} */ export let mimeTypes: any; /** * Processes request messages. */ export class RequestMessageProcessor { /** * Creates an instance of RequestMessageProcessor. */ constructor(xhrType: XHRConstructor, xhrTransformers: XHRTransformer[]); /** * Aborts the request. */ abort(): void; /** * Processes the request. * @param client The HttpClient making the request. * @param requestMessage The message to process. * @return A promise for an HttpResponseMessage. */ process(client: HttpClient, requestMessage: RequestMessage): Promise<HttpResponseMessage>; } /** * Adds a timeout to the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function timeoutTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Adds a callback parameter name to the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function callbackParameterNameTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Sets withCredentials on the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function credentialsTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Adds an onprogress callback to the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function progressTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Adds a response type transformer to the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function responseTypeTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Adds headers to the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function headerTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Transforms the content of the request. * @param client The http client. * @param processor The request message processor. * @param message The request message. * @param xhr The xhr instance. */ export function contentTransformer(client: HttpClient, processor: RequestMessageProcessor, message: RequestMessage, xhr: XHR): any; /** * Represents an JSONP request message. */ export class JSONPRequestMessage extends RequestMessage { /** * Creates an instance of JSONPRequestMessage. * @param url The url to submit the request to. * @param callbackParameterName The name of the callback parameter that the api expects. */ constructor(url: string, callbackParameterName: string); } class JSONPXHR { open(method: string, url: string): void; send(): void; abort(): void; setRequestHeader(): any; } /** * Creates a RequestMessageProcessor for handling JSONP request messages. * @return A processor instance for JSONP request messages. */ export function createJSONPRequestMessageProcessor(): RequestMessageProcessor; /** * Represents an HTTP request message. */ export class HttpRequestMessage extends RequestMessage { /** * Creates an instance of HttpRequestMessage. * @param method The http method. * @param url The url to submit the request to. * @param content The content of the request. * @param headers The headers to send along with the request. */ constructor(method: string, url: string, content: any, headers?: Headers); } // text, arraybuffer, blob, document /** * Creates a RequestMessageProcessor for handling HTTP request messages. * @return A processor instance for HTTP request messages. */ export function createHttpRequestMessageProcessor(): RequestMessageProcessor; /** * A builder class allowing fluent composition of HTTP requests. */ export class RequestBuilder { /** * Creates an instance of RequestBuilder * @param client An instance of HttpClient */ constructor(client: HttpClient); /** * Makes the request a DELETE request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asDelete(): RequestBuilder; /** * Makes the request a GET request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asGet(): RequestBuilder; /** * Makes the request a HEAD request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asHead(): RequestBuilder; /** * Makes the request a OPTIONS request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asOptions(): RequestBuilder; /** * Makes the request a PATCH request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asPatch(): RequestBuilder; /** * Makes the request a POST request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asPost(): RequestBuilder; /** * Makes the request a PUT request. * @return The chainable RequestBuilder to use in further configuration of the request. */ asPut(): RequestBuilder; /** * Makes the request a JSONP request. * @param callbackParameterName The name of the callback to use. * @return The chainable RequestBuilder to use in further configuration of the request. */ asJsonp(callbackParameterName: string): RequestBuilder; /** * Sets the request url. * @param url The url to use. * @return The chainable RequestBuilder to use in further configuration of the request. */ withUrl(url: string): RequestBuilder; /** * Sets the request content. * @param The content to send. * @return The chainable RequestBuilder to use in further configuration of the request. */ withContent(content: any): RequestBuilder; /** * Sets the base url that will be prepended to the url. * @param baseUrl The base url to use. * @return The chainable RequestBuilder to use in further configuration of the request. */ withBaseUrl(baseUrl: string): RequestBuilder; /** * Sets params that will be added to the request url as a query string. * @param params The key/value pairs to use to build the query string. * @return The chainable RequestBuilder to use in further configuration of the request. */ withParams(params: Object): RequestBuilder; /** * Sets the response type. * @param responseType The response type to expect. * @return The chainable RequestBuilder to use in further configuration of the request. */ withResponseType(responseType: string): RequestBuilder; /** * Sets a timeout for the request. * @param timeout The timeout for the request. * @return The chainable RequestBuilder to use in further configuration of the request. */ withTimeout(timeout: number): RequestBuilder; /** * Sets a header on the request. * @param key The header key to add. * @param value The header value to add. * @return The chainable RequestBuilder to use in further configuration of the request. */ withHeader(key: string, value: string): RequestBuilder; /** * Sets the withCredentials flag on the request. * @param value The value of the withCredentials flag to set. * @return The chainable RequestBuilder to use in further configuration of the request. */ withCredentials(value: boolean): RequestBuilder; /** * Sets the user and password to use in opening the request. * @param user The username to send. * @param password The password to send. * @return The chainable RequestBuilder to use in further configuration of the request. */ withLogin(user: string, password: string): RequestBuilder; /** * Sets a reviver to transform the response content. * @param reviver The reviver to use in processing the response. * @return The chainable RequestBuilder to use in further configuration of the request. */ withReviver(reviver: ((key: string, value: any) => any)): RequestBuilder; /** * Sets a replacer to transform the request content. * @param replacer The replacer to use in preparing the request. * @return The chainable RequestBuilder to use in further configuration of the request. */ withReplacer(replacer: ((key: string, value: any) => any)): RequestBuilder; /** * Sets an upload progress callback. * @param progressCallback The progress callback function. * @return The chainable RequestBuilder to use in further configuration of the request. */ withProgressCallback(progressCallback: Function): RequestBuilder; /** * Sets a callback parameter name for JSONP. * @param callbackParameterName The name of the callback parameter that the JSONP request requires. * @return The chainable RequestBuilder to use in further configuration of the request. */ withCallbackParameterName(callbackParameterName: string): RequestBuilder; /** * Adds an interceptor to the request. * @param interceptor The interceptor to add. * @return The chainable RequestBuilder to use in further configuration of the request. */ withInterceptor(interceptor: Interceptor): RequestBuilder; /** * Skips the request content processing transform. * @return The chainable RequestBuilder to use in further configuration of the request. */ skipContentProcessing(): RequestBuilder; /** * Adds a user-defined request transformer to the RequestBuilder. * @param name The name of the helper to add. * @param fn The helper function. */ static addHelper(name: string, fn: (() => RequestTransformer)): void; /** * Sends the request. * @return {Promise} A cancellable promise object. */ send(): Promise<HttpResponseMessage>; } /** * The main HTTP client object. */ export class HttpClient { /** * Creates an instance of HttpClient. */ constructor(); /** * Configure this HttpClient with default settings to be used by all requests. * @param fn A function that takes a RequestBuilder as an argument. */ configure(fn: ((builder: RequestBuilder) => void)): HttpClient; /** * Returns a new RequestBuilder for this HttpClient instance that can be used to build and send HTTP requests. * @param url The target URL. */ createRequest(url: string): RequestBuilder; /** * Sends a message using the underlying networking stack. * @param message A configured HttpRequestMessage or JSONPRequestMessage. * @param transformers A collection of transformers to apply to the HTTP request. * @return A cancellable promise object. */ send(requestMessage: RequestMessage, transformers: Array<RequestTransformer>): Promise<HttpResponseMessage>; /** * Sends an HTTP DELETE request. * @param url The target URL. * @return A cancellable promise object. */ delete(url: string): Promise<HttpResponseMessage>; /** * Sends an HTTP GET request. * @param url The target URL. * @return {Promise} A cancellable promise object. */ get(url: string): Promise<HttpResponseMessage>; /** * Sends an HTTP HEAD request. * @param url The target URL. * @return A cancellable promise object. */ head(url: string): Promise<HttpResponseMessage>; /** * Sends a JSONP request. * @param url The target URL. * @return A cancellable promise object. */ jsonp(url: string, callbackParameterName?: string): Promise<HttpResponseMessage>; /** * Sends an HTTP OPTIONS request. * @param url The target URL. * @return A cancellable promise object. */ options(url: string): Promise<HttpResponseMessage>; /** * Sends an HTTP PUT request. * @param url The target URL. * @param content The request payload. * @return A cancellable promise object. */ put(url: string, content: any): Promise<HttpResponseMessage>; /** * Sends an HTTP PATCH request. * @param url The target URL. * @param content The request payload. * @return A cancellable promise object. */ patch(url: string, content: any): Promise<HttpResponseMessage>; /** * Sends an HTTP POST request. * @param url The target URL. * @param content The request payload. * @return A cancellable promise object. */ post(url: string, content: any): Promise<HttpResponseMessage>; } }
the_stack
import { Component, Optional, OnInit, OnDestroy, ViewChild, AfterViewInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { IonContent } from '@ionic/angular'; import { ModalOptions } from '@ionic/core'; import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component'; import { AddonModForum, AddonModForumData, AddonModForumProvider, AddonModForumSortOrder, AddonModForumDiscussion, AddonModForumNewDiscussionData, AddonModForumReplyDiscussionData, } from '@addons/mod/forum/services/forum'; import { AddonModForumOffline, AddonModForumOfflineDiscussion } from '@addons/mod/forum/services/forum-offline'; import { Translate } from '@singletons'; import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; import { AddonModForumHelper } from '@addons/mod/forum/services/forum-helper'; import { CoreGroups, CoreGroupsProvider } from '@services/groups'; import { CoreEvents, CoreEventObserver } from '@singletons/events'; import { AddonModForumAutoSyncData, AddonModForumManualSyncData, AddonModForumSyncProvider, AddonModForumSyncResult, } from '@addons/mod/forum/services/forum-sync'; import { CoreSites } from '@services/sites'; import { CoreUser } from '@features/user/services/user'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { CoreCourse } from '@features/course/services/course'; import { CorePageItemsListManager } from '@classes/page-items-list-manager'; import { CoreSplitViewComponent } from '@components/split-view/split-view'; import { AddonModForumDiscussionOptionsMenuComponent } from '../discussion-options-menu/discussion-options-menu'; import { AddonModForumSortOrderSelectorComponent } from '../sort-order-selector/sort-order-selector'; import { CoreScreen } from '@services/screen'; import { CoreArray } from '@singletons/array'; import { AddonModForumPrefetchHandler } from '../../services/handlers/prefetch'; import { AddonModForumModuleHandlerService } from '../../services/handlers/module'; import { CoreRatingProvider } from '@features/rating/services/rating'; import { CoreRatingSyncProvider } from '@features/rating/services/rating-sync'; import { CoreRatingOffline } from '@features/rating/services/rating-offline'; import { ContextLevel } from '@/core/constants'; /** * Component that displays a forum entry page. */ @Component({ selector: 'addon-mod-forum-index', templateUrl: 'index.html', styleUrls: ['index.scss'], }) export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild(CoreSplitViewComponent) splitView!: CoreSplitViewComponent; component = AddonModForumProvider.COMPONENT; moduleName = 'forum'; descriptionNote?: string; forum?: AddonModForumData; discussions: AddonModForumDiscussionsManager; canAddDiscussion = false; addDiscussionText!: string; availabilityMessage: string | null = null; sortingAvailable!: boolean; sortOrders: AddonModForumSortOrder[] = []; selectedSortOrder: AddonModForumSortOrder | null = null; canPin = false; trackPosts = false; hasOfflineRatings = false; sortOrderSelectorModalOptions: ModalOptions = { component: AddonModForumSortOrderSelectorComponent, }; protected syncEventName = AddonModForumSyncProvider.AUTO_SYNCED; protected page = 0; protected usesGroups = false; protected syncManualObserver?: CoreEventObserver; // It will observe the sync manual event. protected replyObserver?: CoreEventObserver; protected newDiscObserver?: CoreEventObserver; protected viewDiscObserver?: CoreEventObserver; protected changeDiscObserver?: CoreEventObserver; protected ratingOfflineObserver?: CoreEventObserver; protected ratingSyncObserver?: CoreEventObserver; constructor( route: ActivatedRoute, @Optional() protected content?: IonContent, @Optional() courseContentsPage?: CoreCourseContentsPage, ) { super('AddonModForumIndexComponent', content, courseContentsPage); this.discussions = new AddonModForumDiscussionsManager( route.component, this, courseContentsPage ? `${AddonModForumModuleHandlerService.PAGE_NAME}/` : '', ); } /** * Component being initialized. */ async ngOnInit(): Promise<void> { this.addDiscussionText = Translate.instant('addon.mod_forum.addanewdiscussion'); this.sortingAvailable = AddonModForum.isDiscussionListSortingAvailable(); this.sortOrders = AddonModForum.getAvailableSortOrders(); this.sortOrderSelectorModalOptions.componentProps = { sortOrders: this.sortOrders, }; await super.ngOnInit(); // Refresh data if this forum discussion is synchronized from discussions list. this.syncManualObserver = CoreEvents.on(AddonModForumSyncProvider.MANUAL_SYNCED, (data) => { this.autoSyncEventReceived(data); }, this.siteId); // Listen for discussions added. When a discussion is added, we reload the data. this.newDiscObserver = CoreEvents.on( AddonModForumProvider.NEW_DISCUSSION_EVENT, this.eventReceived.bind(this, true), ); this.replyObserver = CoreEvents.on( AddonModForumProvider.REPLY_DISCUSSION_EVENT, this.eventReceived.bind(this, false), ); this.changeDiscObserver = CoreEvents.on(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data => { if ((this.forum && this.forum.id === data.forumId) || data.cmId === this.module.id) { AddonModForum.invalidateDiscussionsList(this.forum!.id).finally(() => { if (data.discussionId) { // Discussion changed, search it in the list of discussions. const discussion = this.discussions.items.find( (disc) => this.discussions.isOnlineDiscussion(disc) && data.discussionId == disc.discussion, ) as AddonModForumDiscussion; if (discussion) { if (typeof data.locked != 'undefined') { discussion.locked = data.locked; } if (typeof data.pinned != 'undefined') { discussion.pinned = data.pinned; } if (typeof data.starred != 'undefined') { discussion.starred = data.starred; } this.showLoadingAndRefresh(false); } } if (typeof data.deleted != 'undefined' && data.deleted) { if (data.post?.parentid == 0 && CoreScreen.isTablet && !this.discussions.empty) { // Discussion deleted, clear details page. this.discussions.select(this.discussions[0]); } this.showLoadingAndRefresh(false); } }); } }); // Listen for offline ratings saved and synced. this.ratingOfflineObserver = CoreEvents.on(CoreRatingProvider.RATING_SAVED_EVENT, (data) => { if (this.forum && data.component == 'mod_forum' && data.ratingArea == 'post' && data.contextLevel == ContextLevel.MODULE && data.instanceId == this.forum.cmid) { this.hasOfflineRatings = true; } }); this.ratingSyncObserver = CoreEvents.on(CoreRatingSyncProvider.SYNCED_EVENT, async (data) => { if (this.forum && data.component == 'mod_forum' && data.ratingArea == 'post' && data.contextLevel == ContextLevel.MODULE && data.instanceId == this.forum.cmid) { this.hasOfflineRatings = await CoreRatingOffline.hasRatings('mod_forum', 'post', ContextLevel.MODULE, this.forum.cmid); } }); } async ngAfterViewInit(): Promise<void> { await this.loadContent(false, true); if (!this.forum) { return; } CoreUtils.ignoreErrors( AddonModForum.instance .logView(this.forum.id, this.forum.name) .then(async () => { CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); return; }), ); this.discussions.start(this.splitView); } /** * Component being destroyed. */ ngOnDestroy(): void { super.ngOnDestroy(); this.syncManualObserver && this.syncManualObserver.off(); this.newDiscObserver && this.newDiscObserver.off(); this.replyObserver && this.replyObserver.off(); this.viewDiscObserver && this.viewDiscObserver.off(); this.changeDiscObserver && this.changeDiscObserver.off(); this.ratingOfflineObserver && this.ratingOfflineObserver.off(); this.ratingSyncObserver && this.ratingSyncObserver.off(); } /** * Download the component contents. * * @param refresh Whether we're refreshing data. * @param sync If the refresh needs syncing. * @param showErrors Wether to show errors to the user or hide them. */ protected async fetchContent(refresh: boolean = false, sync: boolean = false, showErrors: boolean = false): Promise<void> { this.discussions.fetchFailed = false; const promises: Promise<void>[] = []; promises.push(this.fetchForum(sync, showErrors)); promises.push(this.fetchSortOrderPreference()); try { await Promise.all(promises); await Promise.all([ this.fetchOfflineDiscussions(), this.fetchDiscussions(refresh), CoreRatingOffline.hasRatings('mod_forum', 'post', ContextLevel.MODULE, this.forum!.cmid).then((hasRatings) => { this.hasOfflineRatings = hasRatings; return; }), ]); } catch (error) { if (refresh) { CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); this.discussions.fetchFailed = true; // Set to prevent infinite calls with infinite-loading. } else { // Get forum failed, retry without using cache since it might be a new activity. await this.refreshContent(sync); } } this.fillContextMenu(refresh); } private async fetchForum(sync: boolean = false, showErrors: boolean = false): Promise<void> { if (!this.courseId || !this.module) { return; } const forum = await AddonModForum.getForum(this.courseId, this.module.id); this.forum = forum; this.description = forum.intro || this.description; this.availabilityMessage = AddonModForumHelper.getAvailabilityMessage(forum); this.descriptionNote = Translate.instant('addon.mod_forum.numdiscussions', { numdiscussions: forum.numdiscussions, }); if (typeof forum.istracked != 'undefined') { this.trackPosts = forum.istracked; } this.dataRetrieved.emit(forum); switch (forum.type) { case 'news': case 'blog': this.addDiscussionText = Translate.instant('addon.mod_forum.addanewtopic'); break; case 'qanda': this.addDiscussionText = Translate.instant('addon.mod_forum.addanewquestion'); break; default: this.addDiscussionText = Translate.instant('addon.mod_forum.addanewdiscussion'); } if (sync) { // Try to synchronize the forum. const updated = await this.syncActivity(showErrors); if (updated) { // Sync successful, send event. CoreEvents.trigger(AddonModForumSyncProvider.MANUAL_SYNCED, { forumId: forum.id, userId: CoreSites.getCurrentSiteUserId(), source: 'index', }, CoreSites.getCurrentSiteId()); } } const promises: Promise<void>[] = []; // Check if the activity uses groups. promises.push( CoreGroups.instance .getActivityGroupMode(this.forum.cmid) .then(async mode => { this.usesGroups = mode === CoreGroupsProvider.SEPARATEGROUPS || mode === CoreGroupsProvider.VISIBLEGROUPS; return; }), ); promises.push( AddonModForum.instance .getAccessInformation(this.forum.id, { cmId: this.module.id }) .then(async accessInfo => { // Disallow adding discussions if cut-off date is reached and the user has not the // capability to override it. // Just in case the forum was fetched from WS when the cut-off date was not reached but it is now. const cutoffDateReached = AddonModForumHelper.isCutoffDateReached(this.forum!) && !accessInfo.cancanoverridecutoff; this.canAddDiscussion = !!this.forum?.cancreatediscussions && !cutoffDateReached; return; }), ); if (AddonModForum.isSetPinStateAvailableForSite()) { // Use the canAddDiscussion WS to check if the user can pin discussions. promises.push( AddonModForum.instance .canAddDiscussionToAll(this.forum.id, { cmId: this.module.id }) .then(async response => { this.canPin = !!response.canpindiscussions; return; }) .catch(async () => { this.canPin = false; return; }), ); } else { this.canPin = false; } await Promise.all(promises); } /** * Convenience function to fetch offline discussions. * * @return Promise resolved when done. */ protected async fetchOfflineDiscussions(): Promise<void> { const forum = this.forum!; let offlineDiscussions = await AddonModForumOffline.getNewDiscussions(forum.id); this.hasOffline = !!offlineDiscussions.length; if (!this.hasOffline) { this.discussions.setOfflineDiscussions([]); return; } if (this.usesGroups) { offlineDiscussions = await AddonModForum.formatDiscussionsGroups(forum.cmid, offlineDiscussions); } // Fill user data for Offline discussions (should be already cached). const promises = offlineDiscussions.map(async (offlineDiscussion) => { const discussion = offlineDiscussion as unknown as AddonModForumDiscussion; if (discussion.parent === 0 || forum.type === 'single') { // Do not show author for first post and type single. return; } try { const user = await CoreUser.getProfile(discussion.userid, this.courseId, true); discussion.userfullname = user.fullname; discussion.userpictureurl = user.profileimageurl; } catch (error) { // Ignore errors. } }); await Promise.all(promises); // Sort discussion by time (newer first). offlineDiscussions.sort((a, b) => b.timecreated - a.timecreated); this.discussions.setOfflineDiscussions(offlineDiscussions); } /** * Convenience function to get forum discussions. * * @param refresh Whether we're refreshing data. * @return Promise resolved when done. */ protected async fetchDiscussions(refresh: boolean): Promise<void> { const forum = this.forum!; this.discussions.fetchFailed = false; if (refresh) { this.page = 0; } const response = await AddonModForum.getDiscussions(forum.id, { cmId: forum.cmid, sortOrder: this.selectedSortOrder!.value, page: this.page, }); let discussions = response.discussions; if (this.usesGroups) { discussions = await AddonModForum.formatDiscussionsGroups(forum.cmid, discussions); } // Hide author for first post and type single. if (forum.type === 'single') { for (const discussion of discussions) { if (discussion.userfullname && discussion.parent === 0) { discussion.userfullname = false; break; } } } // If any discussion has unread posts, the whole forum is being tracked. if (typeof forum.istracked === 'undefined' && !this.trackPosts) { for (const discussion of discussions) { if (discussion.numunread > 0) { this.trackPosts = true; break; } } } if (this.page === 0) { this.discussions.setOnlineDiscussions(discussions, response.canLoadMore); } else { this.discussions.setItems(this.discussions.items.concat(discussions), response.canLoadMore); } this.page++; // Check if there are replies for discussions stored in offline. const hasOffline = await AddonModForumOffline.hasForumReplies(forum.id); this.hasOffline = this.hasOffline || hasOffline; if (hasOffline) { // Only update new fetched discussions. const promises = discussions.map(async (discussion) => { // Get offline discussions. const replies = await AddonModForumOffline.getDiscussionReplies(discussion.discussion); discussion.numreplies = Number(discussion.numreplies) + replies.length; }); await Promise.all(promises); } } /** * Convenience function to load more forum discussions. * * @param infiniteComplete Infinite scroll complete function. Only used from core-infinite-loading. * @return Promise resolved when done. */ async fetchMoreDiscussions(complete: () => void): Promise<void> { try { await this.fetchDiscussions(false); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); this.discussions.fetchFailed = true; } finally { complete(); } } /** * Convenience function to fetch the sort order preference. * * @return Promise resolved when done. */ protected async fetchSortOrderPreference(): Promise<void> { const getSortOrder = async () => { if (!this.sortingAvailable) { return null; } const value = await CoreUtils.ignoreErrors( CoreUser.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER), ); return value ? parseInt(value, 10) : null; }; const value = await getSortOrder(); this.selectedSortOrder = this.sortOrders.find(sortOrder => sortOrder.value === value) || this.sortOrders[0]; this.sortOrderSelectorModalOptions.componentProps!.selected = this.selectedSortOrder.value; } /** * Perform the invalidate content function. * * @return Resolved when done. */ protected async invalidateContent(): Promise<void> { const promises: Promise<void>[] = []; promises.push(AddonModForum.invalidateForumData(this.courseId)); if (this.forum) { promises.push(AddonModForum.invalidateDiscussionsList(this.forum.id)); promises.push(CoreGroups.invalidateActivityGroupMode(this.forum.cmid)); promises.push(AddonModForum.invalidateAccessInformation(this.forum.id)); } if (this.sortingAvailable) { promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); } await Promise.all(promises); } /** * Performs the sync of the activity. * * @return Promise resolved when done. */ protected sync(): Promise<AddonModForumSyncResult> { return AddonModForumPrefetchHandler.sync(this.module, this.courseId); } /** * Checks if sync has succeed from result sync data. * * @param result Data returned on the sync function. * @return Whether it succeed or not. */ protected hasSyncSucceed(result: AddonModForumSyncResult): boolean { return result.updated; } /** * Compares sync event data with current data to check if refresh content is needed. * * @param syncEventData Data receiven on sync observer. * @return True if refresh is needed, false otherwise. */ protected isRefreshSyncNeeded(syncEventData: AddonModForumAutoSyncData | AddonModForumManualSyncData): boolean { return !!this.forum && (!('source' in syncEventData) || syncEventData.source != 'index') && syncEventData.forumId == this.forum.id && syncEventData.userId == CoreSites.getCurrentSiteUserId(); } /** * Function called when we receive an event of new discussion or reply to discussion. * * @param isNewDiscussion Whether it's a new discussion event. * @param data Event data. */ protected eventReceived( isNewDiscussion: boolean, data: AddonModForumNewDiscussionData | AddonModForumReplyDiscussionData, ): void { if ((this.forum && this.forum.id === data.forumId) || data.cmId === this.module.id) { this.showLoadingAndRefresh(false).finally(() => { // If it's a new discussion in tablet mode, try to open it. if (isNewDiscussion && CoreScreen.isTablet) { const newDiscussionData = data as AddonModForumNewDiscussionData; const discussion = this.discussions.items.find(disc => { if (this.discussions.isOfflineDiscussion(disc)) { return disc.timecreated === newDiscussionData.discTimecreated; } if (this.discussions.isOnlineDiscussion(disc)) { return CoreArray.contains(newDiscussionData.discussionIds ?? [], disc.discussion); } return false; }); if (discussion || !this.discussions.empty) { this.discussions.select(discussion ?? this.discussions.items[0]); } } }); // Check completion since it could be configured to complete once the user adds a new discussion or replies. CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); } } /** * Opens the new discussion form. * * @param timeCreated Creation time of the offline discussion. */ openNewDiscussion(): void { this.discussions.select({ newDiscussion: true }); } /** * Changes the sort order. * * @param sortOrder Sort order new data. */ async setSortOrder(sortOrder: AddonModForumSortOrder): Promise<void> { if (sortOrder.value != this.selectedSortOrder?.value) { this.selectedSortOrder = sortOrder; this.sortOrderSelectorModalOptions.componentProps!.selected = this.selectedSortOrder.value; this.page = 0; try { await CoreUser.setUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, sortOrder.value.toFixed(0)); await this.showLoadingAndFetch(); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error updating preference.'); } } } /** * Display the sort order selector modal. */ async showSortOrderSelector(): Promise<void> { const modalData = await CoreDomUtils.openModal<AddonModForumSortOrder>(this.sortOrderSelectorModalOptions); if (modalData) { this.setSortOrder(modalData); } } /** * Show the context menu. * * @param event Click Event. * @param discussion Discussion. */ async showOptionsMenu(event: Event, discussion: AddonModForumDiscussion): Promise<void> { event.preventDefault(); event.stopPropagation(); const popoverData = await CoreDomUtils.openPopover<{ action?: string; value: boolean }>({ component: AddonModForumDiscussionOptionsMenuComponent, componentProps: { discussion, forumId: this.forum!.id, cmId: this.module.id, }, event, }); if (popoverData && popoverData.action) { switch (popoverData.action) { case 'lock': discussion.locked = popoverData.value; break; case 'pin': discussion.pinned = popoverData.value; break; case 'star': discussion.starred = popoverData.value; break; default: break; } } } } /** * Type to select the new discussion form. */ type NewDiscussionForm = { newDiscussion: true }; /** * Type of items that can be held by the discussions manager. */ type DiscussionItem = AddonModForumDiscussion | AddonModForumOfflineDiscussion | NewDiscussionForm; /** * Discussions manager. */ class AddonModForumDiscussionsManager extends CorePageItemsListManager<DiscussionItem> { onlineLoaded = false; fetchFailed = false; private discussionsPathPrefix: string; private component: AddonModForumIndexComponent; constructor(pageComponent: unknown, component: AddonModForumIndexComponent, discussionsPathPrefix: string) { super(pageComponent); this.component = component; this.discussionsPathPrefix = discussionsPathPrefix; } get loaded(): boolean { return super.loaded && (this.onlineLoaded || this.fetchFailed); } get onlineDiscussions(): AddonModForumDiscussion[] { return this.items.filter(discussion => this.isOnlineDiscussion(discussion)) as AddonModForumDiscussion[]; } /** * @inheritdoc */ getItemQueryParams(discussion: DiscussionItem): Params { return { courseId: this.component.courseId, cmId: this.component.module.id, forumId: this.component.forum!.id, ...(this.isOnlineDiscussion(discussion) ? { discussion, trackPosts: this.component.trackPosts } : {}), }; } /** * Type guard to infer NewDiscussionForm objects. * * @param discussion Item to check. * @return Whether the item is a new discussion form. */ isNewDiscussionForm(discussion: DiscussionItem): discussion is NewDiscussionForm { return 'newDiscussion' in discussion; } /** * Type guard to infer AddonModForumDiscussion objects. * * @param discussion Item to check. * @return Whether the item is an online discussion. */ isOfflineDiscussion(discussion: DiscussionItem): discussion is AddonModForumOfflineDiscussion { return !this.isNewDiscussionForm(discussion) && !this.isOnlineDiscussion(discussion); } /** * Type guard to infer AddonModForumDiscussion objects. * * @param discussion Item to check. * @return Whether the item is an online discussion. */ isOnlineDiscussion(discussion: DiscussionItem): discussion is AddonModForumDiscussion { return 'id' in discussion; } /** * Update online discussion items. * * @param onlineDiscussions Online discussions */ setOnlineDiscussions(onlineDiscussions: AddonModForumDiscussion[], hasMoreItems: boolean = false): void { const otherDiscussions = this.items.filter(discussion => !this.isOnlineDiscussion(discussion)); this.setItems(otherDiscussions.concat(onlineDiscussions), hasMoreItems); this.onlineLoaded = true; } /** * Update offline discussion items. * * @param offlineDiscussions Offline discussions */ setOfflineDiscussions(offlineDiscussions: AddonModForumOfflineDiscussion[]): void { const otherDiscussions = this.items.filter(discussion => !this.isOfflineDiscussion(discussion)); this.setItems((offlineDiscussions as DiscussionItem[]).concat(otherDiscussions), this.hasMoreItems); } /** * @inheritdoc */ protected getItemPath(discussion: DiscussionItem): string { const getRelativePath = () => { if (this.isOnlineDiscussion(discussion)) { return discussion.discussion; } if (this.isOfflineDiscussion(discussion)) { return `new/${discussion.timecreated}`; } return 'new/0'; }; return this.discussionsPathPrefix + getRelativePath(); } }
the_stack
import { errors, statuses } from '@tanker/core'; import type { Tanker, b64string, OutputOptions } from '@tanker/core'; import { encryptionV4, tcrypto, utils } from '@tanker/crypto'; import { Data, getConstructorName, getDataLength } from '@tanker/types'; import { getPublicIdentity, createProvisionalIdentity } from '@tanker/identity'; import { expect, sinon, uuid } from '@tanker/test-utils'; import type { TestArgs, AppHelper, AppProvisionalUser, TestResourceSize } from './helpers'; import { expectProgressReport, expectType, expectSameType, expectDeepEqual, expectDecrypt } from './helpers'; const { READY } = statuses; export const generateEncryptionTests = (args: TestArgs) => { const clearText: string = 'Rivest Shamir Adleman'; describe('text resource encryption and sharing - no session', () => { let bobLaptop: Tanker; before(() => { bobLaptop = args.makeTanker(); }); it('throws when using a session in an invalid state', async () => { await expect(bobLaptop.encrypt(clearText)).to.be.rejectedWith(errors.PreconditionFailed); }); it('throws when decrypting using a session in an invalid state', async () => { await expect(bobLaptop.decrypt(utils.fromString('test'))).to.be.rejectedWith(errors.PreconditionFailed); }); }); describe('text resource encryption and sharing', () => { let aliceLaptop: Tanker; let aliceIdentity: b64string; let alicePublicIdentity: b64string; let bobLaptop: Tanker; let bobIdentity: b64string; let bobPublicIdentity: b64string; let charlieLaptop: Tanker; let charlieIdentity: b64string; let charliePublicIdentity: b64string; let appHelper: AppHelper; before(async () => { ({ appHelper } = args); aliceIdentity = await appHelper.generateIdentity(); alicePublicIdentity = await getPublicIdentity(aliceIdentity); bobIdentity = await appHelper.generateIdentity(); bobPublicIdentity = await getPublicIdentity(bobIdentity); charlieIdentity = await appHelper.generateIdentity(); charliePublicIdentity = await getPublicIdentity(charlieIdentity); aliceLaptop = args.makeTanker(); bobLaptop = args.makeTanker(); charlieLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await charlieLaptop.start(charlieIdentity); await charlieLaptop.registerIdentity({ passphrase: 'passphrase' }); }); after(async () => { await Promise.all([ aliceLaptop.stop(), bobLaptop.stop(), charlieLaptop.stop(), ]); }); describe('encrypt and decrypt a text resource', () => { it('throws when calling encrypt of undefined', async () => { // @ts-expect-error Testing invalid argument await expect(bobLaptop.encrypt()).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when decrypting an invalid type', async () => { const notUint8ArrayTypes = [undefined, null, 0, {}, [], 'str']; for (let i = 0; i < notUint8ArrayTypes.length; i++) { // @ts-expect-error Testing invalid types await expect(bobLaptop.decrypt(notUint8ArrayTypes[i]), `bad decryption #${i}`).to.be.rejectedWith(errors.InvalidArgument); } }); it('throws when decrypting data with an unknow encryption format', async () => { const invalidEncrypted = new Uint8Array([127]); await expect(bobLaptop.decrypt(invalidEncrypted)).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when decrypting data with an invalid encryption format', async () => { const invalidEncrypted = new Uint8Array([255]); // not a varint await expect(bobLaptop.decrypt(invalidEncrypted)).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when decrypting truncated encrypted resource', async () => { const encrypted = await bobLaptop.encrypt(clearText); // shorter than version + resource id: should not even try to decrypt const invalidEncrypted = encrypted.subarray(0, tcrypto.MAC_SIZE - 4); await expect(bobLaptop.decrypt(invalidEncrypted)).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when calling decrypt with a corrupted buffer (resource id)', async () => { const encrypted = await bobLaptop.encrypt(clearText); const corruptPos = encrypted.length - 4; encrypted[corruptPos] = (encrypted[corruptPos]! + 1) % 256; await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when calling decrypt with a corrupted buffer (data)', async () => { const encrypted = await bobLaptop.encrypt(clearText); const corruptPos = 4; encrypted[corruptPos] = (encrypted[corruptPos]! + 1) % 256; await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.DecryptionFailed); }); it('can encrypt and decrypt a text resource', async () => { const encrypted = await bobLaptop.encrypt(clearText); await expectDecrypt([bobLaptop], clearText, encrypted); }); it('can report progress when encrypting and decrypting', async () => { const onProgress = sinon.fake(); const encrypted = await bobLaptop.encrypt(clearText, { onProgress }); expectProgressReport(onProgress, encrypted.length); onProgress.resetHistory(); const decrypted = await bobLaptop.decrypt(encrypted, { onProgress }); expectProgressReport(onProgress, decrypted.length, encryptionV4.defaultMaxEncryptedChunkSize - encryptionV4.overhead); }); it('encrypt should ignore resource id argument', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); const encrypted2 = await bobLaptop.encrypt(clearText, ({ resourceId } as any)); const resourceId2 = await bobLaptop.getResourceId(encrypted2); expect(resourceId2).to.not.equal(resourceId); }); }); describe('share at encryption time', () => { it('encrypts and shares with a permanent identity', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [alicePublicIdentity] }); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('encrypts and shares with two permanent identities', async () => { const encrypted = await charlieLaptop.encrypt(clearText, { shareWithUsers: [alicePublicIdentity, bobPublicIdentity] }); await expectDecrypt([aliceLaptop, bobLaptop], clearText, encrypted); }); it('encrypts and shares with a permanent identity and not self', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [alicePublicIdentity], shareWithSelf: false }); await expect(bobLaptop.decrypt(encrypted)).to.be.rejectedWith(errors.InvalidArgument); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('fails to encrypt and not share with anybody', async () => { await expect(bobLaptop.encrypt(clearText, { shareWithSelf: false })).to.be.rejectedWith(errors.InvalidArgument, 'not share with anybody'); }); it('throws when trying to share with more than 100 recipients', async () => { const identities = new Array(101).fill(alicePublicIdentity); await expect(bobLaptop.encrypt(clearText, { shareWithUsers: identities })).to.be.rejectedWith(errors.InvalidArgument, 'more than 100 recipients'); const encryptedData = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encryptedData); await expect(bobLaptop.share([resourceId], { shareWithUsers: identities })).to.be.rejectedWith(errors.InvalidArgument, 'more than 100 recipients'); }); it('throws when sharing with secret identities', async () => { await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [aliceIdentity] })).to.be.rejectedWith(errors.InvalidArgument, 'unexpected secret identity'); const provisional = await appHelper.generateEmailProvisionalIdentity(); await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.identity] })).to.be.rejectedWith(errors.InvalidArgument, 'unexpected secret identity'); }); it('throws when sharing with a permanent identity that is not registered', async () => { const evePublicIdentity = await getPublicIdentity(await appHelper.generateIdentity('eve')); await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [evePublicIdentity] })).to.be.rejectedWith(errors.InvalidArgument, evePublicIdentity); }); it('shares even when the recipient is not connected', async () => { await aliceLaptop.stop(); const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [alicePublicIdentity] }); await aliceLaptop.start(aliceIdentity); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('shares with a device created after sharing', async () => { const encrypted = await aliceLaptop.encrypt(clearText, { shareWithUsers: [bobPublicIdentity] }); const bobPhone = args.makeTanker(); await bobPhone.start(bobIdentity); await bobPhone.verifyIdentity({ passphrase: 'passphrase' }); await expectDecrypt([bobPhone], clearText, encrypted); await bobPhone.stop(); }); }); describe('share after encryption (reshare)', () => { it('throws when sharing an invalid resource id', async () => { // @ts-expect-error await expect(bobLaptop.share(null, { shareWithUsers: [alicePublicIdentity] })).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when sharing with an invalid recipient list', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); // @ts-expect-error await expect(bobLaptop.share([resourceId])).to.be.rejectedWith(errors.InvalidArgument); }); it('throws when sharing a resource that doesn\'t exist', async () => { const badResourceId = 'AAAAAAAAAAAAAAAAAAAAAA=='; await expect(bobLaptop.share([badResourceId], { shareWithUsers: [alicePublicIdentity] })).to.be.rejectedWith(errors.InvalidArgument, badResourceId); }); it('throws when sharing with a permanent identity that is not registered', async () => { const edata = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(edata); const evePublicIdentity = await getPublicIdentity(await appHelper.generateIdentity('eve')); await expect(bobLaptop.share([resourceId], { shareWithUsers: [evePublicIdentity] })) .to.be.rejectedWith(errors.InvalidArgument, evePublicIdentity); }); it('throws when sharing with a provisional identity from another trustchain', async () => { const otherTrustchain = { id: 'gOhJDFYKK/GNScGOoaZ1vLAwxkuqZCY36IwEo4jcnDE=', sk: 'D9jiQt7nB2IlRjilNwUVVTPsYkfbCX0PelMzx5AAXIaVokZ71iUduWCvJ9Akzojca6lvV8u1rnDVEdh7yO6JAQ==', }; const invalidProvisionalIdentity = await createProvisionalIdentity(otherTrustchain.id, 'email', 'doe@john.com'); const invalidPublicIdentity = await getPublicIdentity(invalidProvisionalIdentity); const edata = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(edata); await expect(bobLaptop.share([resourceId], { shareWithUsers: [invalidPublicIdentity] })) .to.be.rejectedWith(errors.InvalidArgument, 'Invalid appId for identities'); }); it('is a noop to share an empty resource array', async () => { await expect(bobLaptop.share([], { shareWithUsers: [alicePublicIdentity] })).to.be.fulfilled; }); it('shares an existing resource with a permanent identity', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); await bobLaptop.share([resourceId], { shareWithUsers: [alicePublicIdentity] }); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('shares a not-cached resource with a permanent identity', async () => { const encrypted = await aliceLaptop.encrypt(clearText); const resourceId = await aliceLaptop.getResourceId(encrypted); await aliceLaptop.share([resourceId], { shareWithUsers: [bobPublicIdentity] }); await bobLaptop.share([resourceId], { shareWithUsers: [charliePublicIdentity] }); await expectDecrypt([charlieLaptop], clearText, encrypted); }); it('shares multiple resources with multiple permanent identities', async () => { const encrypted = await aliceLaptop.encrypt(clearText); const resourceId = await aliceLaptop.getResourceId(encrypted); const encrypted2 = await aliceLaptop.encrypt(clearText); const resourceId2 = await aliceLaptop.getResourceId(encrypted2); await aliceLaptop.share([resourceId, resourceId2], { shareWithUsers: [bobPublicIdentity, charliePublicIdentity] }); await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted); await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted2); }); it('shares the same resourceId twice', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); await bobLaptop.share([resourceId, resourceId], { shareWithUsers: [alicePublicIdentity] }); await expectDecrypt([aliceLaptop], clearText, encrypted); }); }); describe('decrypt resources shared with email (+phone) provisional identities', () => { let provisional: AppProvisionalUser; let provisional2: AppProvisionalUser; beforeEach(async () => { provisional = await appHelper.generateEmailProvisionalIdentity(); provisional2 = await appHelper.generatePhoneNumberProvisionalIdentity(); }); it('does not throw if nothing to claim', async () => { await expect(appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional)).to.be.fulfilled; }); it('throws if verifying a provisional identity before attaching it', async () => { const verificationCode = await appHelper.getEmailVerificationCode(provisional.value); await expect(bobLaptop.verifyProvisionalIdentity({ email: provisional.value, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed, 'without having called attachProvisionalIdentity'); }); it('throws if claiming an already attached provisional', async () => { await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await expect(appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional)).to.be.rejectedWith(errors.IdentityAlreadyAttached); }); it('does not throw if nothing to claim and same email registered as verification method', async () => { const verificationCode = await appHelper.getEmailVerificationCode(provisional.value); await aliceLaptop.setVerificationMethod({ email: provisional.value, verificationCode }); const attachResult = await aliceLaptop.attachProvisionalIdentity(provisional.identity); expect(attachResult).to.deep.equal({ status: READY }); }); it('decrypts data encrypted-and-shared with an attached provisional identity', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('decrypts data shared with two attached provisional identities', async () => { const encrypted = await aliceLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity, provisional2.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(charlieLaptop, provisional2); await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted); }); it('shares an existing resource with an email provisional identity', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); await expect(bobLaptop.share([resourceId], { shareWithUsers: [provisional.publicIdentity] })).to.be.fulfilled; await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('shares an existing resource with a phone number provisional identity', async () => { const encrypted = await bobLaptop.encrypt(clearText); const resourceId = await bobLaptop.getResourceId(encrypted); await expect(bobLaptop.share([resourceId], { shareWithUsers: [provisional2.publicIdentity] })).to.be.fulfilled; await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional2); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('shares an existing resource with two provisional identities', async () => { const encrypted = await aliceLaptop.encrypt(clearText); const resourceId = await aliceLaptop.getResourceId(encrypted); await expect(aliceLaptop.share([resourceId], { shareWithUsers: [provisional.publicIdentity, provisional2.publicIdentity] })).to.be.fulfilled; await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(charlieLaptop, provisional2); await expectDecrypt([bobLaptop, charlieLaptop], clearText, encrypted); }); it('decrypt data shared with an attached provisional identity after session restart', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await aliceLaptop.stop(); await aliceLaptop.start(aliceIdentity); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('throws when sharing with already claimed identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] })).to.be.rejectedWith(errors.IdentityAlreadyAttached); }); it('gracefully accept an already attached provisional identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); const attachResult = await aliceLaptop.attachProvisionalIdentity(provisional.identity); expect(attachResult).to.deep.equal({ status: READY }); }); it('attach without another verification if email already verified and claimed', async () => { const verificationCode = await appHelper.getEmailVerificationCode(provisional.value); await aliceLaptop.setVerificationMethod({ email: provisional.value, verificationCode }); const attachResult = await aliceLaptop.attachProvisionalIdentity(provisional.identity); expect(attachResult).to.deep.equal({ status: READY }); }); it('throws when verifying provisional identity with wrong verification code', async () => { await aliceLaptop.attachProvisionalIdentity(provisional.identity); await expect(aliceLaptop.verifyProvisionalIdentity({ email: provisional.value, verificationCode: 'wrongCode' })).to.be.rejectedWith(errors.InvalidVerification); }); it('throws when verifying an email that does not match the provisional identity', async () => { await aliceLaptop.attachProvisionalIdentity(provisional.identity); const anotherEmail = `${uuid.v4()}@tanker.io`; const verificationCode = await appHelper.getEmailVerificationCode(anotherEmail); await expect(aliceLaptop.verifyProvisionalIdentity({ email: anotherEmail, verificationCode })).to.be.rejectedWith(errors.InvalidArgument, 'does not match provisional identity'); }); it('throws when two users attach the same provisional identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); await expect(appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional)).to.be.rejectedWith(errors.IdentityAlreadyAttached, 'one or more provisional identities are already attached'); }); it('can attach a provisional identity after a revocation', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); const bobPhone = args.makeTanker(); await bobPhone.start(bobIdentity); await bobPhone.verifyIdentity({ passphrase: 'passphrase' }); const deviceID = bobPhone.deviceId; await bobPhone.revokeDevice(deviceID); await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisional); await bobPhone.stop(); }); it('decrypt resource on a new device', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyEmailProvisionalIdentity(aliceLaptop, provisional); const alicePhone = args.makeTanker(); await alicePhone.start(aliceIdentity); await alicePhone.verifyIdentity({ passphrase: 'passphrase' }); await expectDecrypt([alicePhone], clearText, encrypted); await alicePhone.stop(); }); }); describe('decrypt resources shared with phone_number provisional identities', () => { let provisional: AppProvisionalUser; beforeEach(async () => { provisional = await appHelper.generatePhoneNumberProvisionalIdentity(); }); it('throws if claiming an already attached provisional', async () => { await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); await expect(appHelper.attachVerifyPhoneNumberProvisionalIdentity(bobLaptop, provisional)).to.be.rejectedWith(errors.IdentityAlreadyAttached); }); it('decrypts data encrypted-and-shared with an attached provisional identity', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('decrypt data shared with an attached provisional identity after session restart', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); await aliceLaptop.stop(); await aliceLaptop.start(aliceIdentity); await expectDecrypt([aliceLaptop], clearText, encrypted); }); it('throws when sharing with already claimed identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); await expect(bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] })).to.be.rejectedWith(errors.IdentityAlreadyAttached); }); it('gracefully accept an already attached provisional identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); const attachResult = await aliceLaptop.attachProvisionalIdentity(provisional.identity); expect(attachResult).to.deep.equal({ status: READY }); }); it('attach without another verification if phone number already verified and claimed', async () => { const verificationCode = await appHelper.getSMSVerificationCode(provisional.value); await aliceLaptop.setVerificationMethod({ phoneNumber: provisional.value, verificationCode }); const attachResult = await aliceLaptop.attachProvisionalIdentity(provisional.identity); expect(attachResult).to.deep.equal({ status: READY }); }); it('throws when verifying provisional identity with wrong verification code', async () => { await aliceLaptop.attachProvisionalIdentity(provisional.identity); await expect(aliceLaptop.verifyProvisionalIdentity({ phoneNumber: provisional.value, verificationCode: 'wrongCode' })).to.be.rejectedWith(errors.InvalidVerification); }); it('throws when verifying a phone number that does not match the provisional identity', async () => { await aliceLaptop.attachProvisionalIdentity(provisional.identity); const anotherPhone = (await appHelper.generatePhoneNumberProvisionalIdentity()).value; const verificationCode = await appHelper.getSMSVerificationCode(anotherPhone); await expect(aliceLaptop.verifyProvisionalIdentity({ phoneNumber: anotherPhone, verificationCode })).to.be.rejectedWith(errors.InvalidArgument); }); it('throw when two users attach the same provisional identity', async () => { await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); await expect(appHelper.attachVerifyPhoneNumberProvisionalIdentity(bobLaptop, provisional)).to.be.rejectedWith(errors.IdentityAlreadyAttached, 'one or more provisional identities are already attached'); }); it('decrypt resource on a new device', async () => { const encrypted = await bobLaptop.encrypt(clearText, { shareWithUsers: [provisional.publicIdentity] }); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(aliceLaptop, provisional); const alicePhone = args.makeTanker(); await alicePhone.start(aliceIdentity); await alicePhone.verifyIdentity({ passphrase: 'passphrase' }); await expectDecrypt([alicePhone], clearText, encrypted); await alicePhone.stop(); }); }); }); describe('text resource encryption and sharing with multiple devices', () => { let appHelper: AppHelper; let aliceLaptop: Tanker; let aliceIdentity: b64string; let bobLaptop: Tanker; let bobPhone: Tanker; let bobIdentity: b64string; before(() => { ({ appHelper } = args); }); beforeEach(async () => { aliceIdentity = await appHelper.generateIdentity(); bobIdentity = await appHelper.generateIdentity(); aliceLaptop = args.makeTanker(); bobLaptop = args.makeTanker(); bobPhone = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobPhone.start(bobIdentity); await bobPhone.verifyIdentity({ passphrase: 'passphrase' }); }); afterEach(async () => { await Promise.all([ bobPhone.stop(), bobLaptop.stop(), aliceLaptop.stop(), ]); }); it('can decrypt a resource encrypted from another device', async () => { const encrypted = await bobLaptop.encrypt(clearText); await expectDecrypt([bobPhone], clearText, encrypted); }); it('can access a resource encrypted and shared from a device that was then revoked', async () => { const encrypted = await bobLaptop.encrypt(clearText); // revoke bobLaptop await bobPhone.revokeDevice(bobLaptop.deviceId); await expectDecrypt([bobPhone], clearText, encrypted); }); }); // Some sizes may not be tested on some platforms (e.g. 'big' on Safari) const forEachSize = (sizes: Array<TestResourceSize>, fun: (size: TestResourceSize) => void) => { const availableSizes = Object.keys(args.resources); return sizes.filter(size => availableSizes.includes(size)).forEach(fun); }; describe('binary resource encryption', () => { let aliceLaptop: Tanker; let aliceIdentity: b64string; before(async () => { aliceIdentity = await args.appHelper.generateIdentity(); aliceLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ passphrase: 'passphrase' }); }); after(async () => { await aliceLaptop.stop(); }); forEachSize(['empty', 'small', 'medium', 'big'], size => { args.resources[size]!.forEach(({ type, resource: clear }) => { it(`can encrypt and decrypt a ${size} ${getConstructorName(type)}`, async () => { const onProgress = sinon.fake(); const encrypted = await aliceLaptop.encryptData(clear, { onProgress }); expectSameType(encrypted, clear); expectProgressReport(onProgress, getDataLength(encrypted)); onProgress.resetHistory(); const decrypted = await aliceLaptop.decryptData(encrypted, { onProgress }); expectSameType(decrypted, clear); expectDeepEqual(decrypted, clear); expectProgressReport(onProgress, getDataLength(decrypted), encryptionV4.defaultMaxEncryptedChunkSize - encryptionV4.overhead); }); }); }); // Medium and big resources use the same encryption format, so no need to test on big resources forEachSize(['small', 'medium'], size => { args.resources[size]!.forEach(({ type: originalType, resource: clear }) => { args.resources[size]!.forEach(({ type: transientType }) => { it(`can encrypt a ${size} ${getConstructorName(originalType)} into a ${getConstructorName(transientType)} and decrypt back a ${getConstructorName(originalType)}`, async () => { const encrypted = await aliceLaptop.encryptData(clear, { type: transientType }); expectType(encrypted, transientType); const outputOptions: Partial<OutputOptions<Data>> = {}; outputOptions.type = originalType; if (global.Blob && outputOptions.type === Blob) { outputOptions.mime = (clear as Blob).type; } if (global.File && outputOptions.type === File) { const file = clear as File; outputOptions.mime = file.type; outputOptions.name = file.name; outputOptions.lastModified = file.lastModified; } const decrypted = await aliceLaptop.decryptData(encrypted, outputOptions); expectType(decrypted, originalType); expectDeepEqual(decrypted, clear); }); }); }); }); }); };
the_stack
import { formatVideoTime, isTouch } from 'shared/utils/utils' import { Options, playerParameters, configEvent } from 'shared/assets/interfaces/interfaces' import ControlBar from '../../components/control-bar/assets/scripts/control-bar' /** * Vlitejs Player * @module Vlitejs/Player */ export default class Player { Vlitejs: any type: string media: HTMLAudioElement | HTMLVideoElement options: Options isFullScreen: Boolean isMuted: Boolean isPaused: null | Boolean controlBar: any playerEvents: Array<configEvent> isTouch: Boolean plugins: { [key: string]: any } elements: { container: HTMLElement bigPlay: HTMLElement | null poster: HTMLElement | null controlBar: HTMLElement | null playPause: HTMLElement | null progressBar: HTMLInputElement | null currentTime: HTMLElement | null duration: HTMLElement | null volume: HTMLElement | null fullscreen: HTMLElement | null } /** * @constructor * @param {Object} options * @param {Class} options.Vlitejs Vlitejs instance * @param {HTMLElement} options.type Player type (video|audio) */ constructor({ Vlitejs, type }: playerParameters) { this.Vlitejs = Vlitejs this.type = type this.plugins = {} this.media = Vlitejs.media this.options = Vlitejs.options this.elements = { container: Vlitejs.container, bigPlay: Vlitejs.container.querySelector('.v-bigPlay'), poster: Vlitejs.container.querySelector('.v-poster'), controlBar: null, playPause: null, progressBar: null, currentTime: null, duration: null, volume: null, fullscreen: null } this.isFullScreen = false this.isMuted = this.options.muted this.isPaused = null this.playerEvents = [] this.isTouch = isTouch() this.controlBar = new ControlBar({ player: this, type }) } /** * Build the player */ build() { this.options.controls && this.controlBar.init() this.init() } /** * init * Extends by the provider */ init() { throw new Error('You have to implement the function "init".') } /** * waitUntilVideoIsReady * Extends by the provider */ waitUntilVideoIsReady() { throw new Error('You have to implement the function "waitUntilVideoIsReady".') } /** * getInstance * Extends by the provider */ getInstance() { throw new Error('You have to implement the function "getInstance".') } /** * getCurrentTime * Extends by the provider */ getCurrentTime(): Promise<number> { throw new Error('You have to implement the function "getCurrentTime".') } /** * methodSeekTo * Extends by the provider */ methodSeekTo(newTime: number) { throw new Error('You have to implement the function "methodSeekTo".') } /** * getDuration * Extends by the provider */ getDuration(): Promise<number> { throw new Error('You have to implement the function "getDuration".') } /** * methodPlay * Extends by the provider */ methodPlay() { throw new Error('You have to implement the function "methodPlay".') } /** * methodPause * Extends by the provider */ methodPause() { throw new Error('You have to implement the function "methodPause".') } /** * methodSetVolume * Extends by the provider */ methodSetVolume(newVolume: number) { throw new Error('You have to implement the function "methodSetVolume".') } /** * methodGetVolume * Extends by the provider */ methodGetVolume(): Promise<number> { throw new Error('You have to implement the function "methodGetVolume".') } /** * methodMute * Extends by the provider */ methodMute() { throw new Error('You have to implement the function "methodMute".') } /** * methodUnMute * Extends by the provider */ methodUnMute() { throw new Error('You have to implement the function "methodUnMute".') } /** * On the player is ready */ onReady() { this.options.muted && this.mute() // The iframe needs to be ignored by the focus this.media.setAttribute('tabindex', '-1') // If player has autoplay option, play now if (this.options.autoplay) { // Autoplay on video is authorize only when the media element is muted !this.media.muted && this.mute() this.play() } // Call the onReady functions of components this.options.controls && this.controlBar.onReady() Object.keys(this.plugins).forEach((id) => { this.plugins[id].onReady instanceof Function && this.plugins[id].onReady() }) this.loading(false) this.Vlitejs.onReady instanceof Function && this.Vlitejs.onReady.call(this, this) } /** * Add media action listeners on the container * @param {String} type Event type * @param {EventListener} listener Event listener */ on(type: string, listener: EventListener) { if (listener instanceof Function) { this.playerEvents.push({ type, listener }) this.elements.container.addEventListener(type, listener) } } /** * Dispatch custom event on the container * @param {String} type Event type */ dispatchEvent(type: string) { this.elements.container.dispatchEvent(new Event(type)) } /** * Update the loader status * @param {Boolean} state Status of the loader */ loading(state: Boolean) { this.elements.container.classList[state ? 'add' : 'remove']('v-loading') this.dispatchEvent('progress') } /** * On time update * Update current time displaying in the control bar * Udpdate the progress bar */ onTimeUpdate() { if (this.options.time) { Promise.all([this.getCurrentTime(), this.getDuration()]).then( ([seconds, duration]: [number, number]) => { const currentTime = Math.round(seconds) if (this.elements.progressBar) { const width = (currentTime * 100) / duration this.elements.progressBar.value = `${width}` this.elements.progressBar.style.setProperty('--value', `${width}%`) this.elements.progressBar.setAttribute( 'aria-valuenow', `${Math.round(seconds)}` ) } if (this.elements.currentTime) { this.elements.currentTime.innerHTML = formatVideoTime(currentTime) } this.dispatchEvent('timeupdate') } ) } } /** * On media ended */ onMediaEnded() { if (this.options.loop) { this.play() } else { this.elements.container.classList.replace('v-playing', 'v-paused') this.elements.container.classList.add('v-firstStart') } if (this.elements.poster) { this.elements.poster.classList.add('v-active') } if (this.elements.progressBar) { this.elements.progressBar.value = '0' this.elements.progressBar.style.setProperty('--value', '0%') this.elements.progressBar.removeAttribute('aria-valuenow') } if (this.elements.currentTime) { this.elements.currentTime.innerHTML = '00:00' } this.dispatchEvent('ended') } /** * Play the media element */ play() { if (this.elements.container.classList.contains('v-firstStart')) { this.elements.container.classList.remove('v-firstStart') if (this.type === 'video' && this.elements.poster) { this.elements.poster.classList.remove('v-active') } } this.methodPlay() this.isPaused = false this.elements.container.classList.replace('v-paused', 'v-playing') if (this.elements.playPause) { this.elements.playPause.setAttribute('aria-label', 'Pause') this.elements.playPause.classList.add('v-controlPressed') } if (this.type === 'video' && this.elements.bigPlay) { this.elements.bigPlay.setAttribute('aria-label', 'Pause') } this.afterPlayPause() this.dispatchEvent('play') } /** * Pause the media element */ pause() { this.methodPause() this.isPaused = true this.elements.container.classList.replace('v-playing', 'v-paused') if (this.elements.playPause) { this.elements.playPause.setAttribute('aria-label', 'Play') this.elements.playPause.classList.remove('v-controlPressed') } if (this.type === 'video' && this.elements.bigPlay) { this.elements.bigPlay.setAttribute('aria-label', 'Play') } this.afterPlayPause() this.dispatchEvent('pause') } /** * Callback function after the play|pause */ afterPlayPause() { if (this.Vlitejs.autoHideGranted) { this.Vlitejs.stopAutoHideTimer() !this.isPaused && this.Vlitejs.startAutoHideTimer() } } /** * Set player volume * @param {Number} volume New volume */ setVolume(volume: number) { if (volume > 1) { volume = 1 } else if (volume <= 0) { volume = 0 this.isMuted = true if (this.elements.volume) { this.elements.volume.classList.add('v-controlPressed') } } else { this.isMuted = false if (this.elements.volume) { this.elements.volume.classList.remove('v-controlPressed') } } this.methodSetVolume(volume) this.dispatchEvent('volumechange') } /** * Get player volume * @returns {Promise<Number>} Player volume */ getVolume(): Promise<number> { return new window.Promise((resolve) => { this.methodGetVolume().then((volume: number) => { resolve(volume) }) }) } /** * Mute the volume on the media element */ mute() { this.methodMute() this.isMuted = true if (this.elements.volume) { this.elements.volume.classList.add('v-controlPressed') this.elements.volume.setAttribute('aria-label', 'Unmute') } this.dispatchEvent('volumechange') } /** * Unmute the volume on the media element */ unMute() { this.methodUnMute() this.isMuted = false if (this.elements.volume) { this.elements.volume.classList.remove('v-controlPressed') this.elements.volume.setAttribute('aria-label', 'Mute') } this.dispatchEvent('volumechange') } /** * Update the current time of the media element * @param {Number} newTime New current time of the media element */ seekTo(newTime: number) { this.methodSeekTo(newTime) } /** * Request the fullscreen */ requestFullscreen() { const { requestFn } = this.Vlitejs.supportFullScreen // @ts-ignore: Object is possibly 'null'. if (this.media[requestFn]) { // Request fullscreen on parentNode player, to display custom controls // @ts-ignore: Object is possibly 'null'. this.elements.container[requestFn]() this.isFullScreen = true this.elements.container.classList.add('v-fullscreenButton-display') if (this.elements.fullscreen) { this.elements.fullscreen.classList.add('v-controlPressed') this.elements.fullscreen.setAttribute('aria-label', 'Exit fullscreen') } this.dispatchEvent('enterfullscreen') } } /** * Exit the fullscreen * @param {Object} options * @param {Boolean} options.escKey The exit is trigger by the esk key */ exitFullscreen({ escKey = false }: { escKey?: Boolean } = {}) { const { cancelFn } = this.Vlitejs.supportFullScreen if (document[cancelFn]) { // @ts-ignore: Object is possibly 'null'. !escKey && document[cancelFn]() this.isFullScreen = false this.elements.container.classList.remove('v-fullscreenButton-display') if (this.elements.fullscreen) { this.elements.fullscreen.classList.remove('v-controlPressed') this.elements.fullscreen.setAttribute('aria-label', 'Enter fullscreen') } this.dispatchEvent('exitfullscreen') } } /** * Destroy the player * Remove event listeners, player instance and HTML */ destroy() { this.controlBar && this.controlBar.destroy() // Call the destroy function on each plugins Object.keys(this.plugins).forEach((id) => { this.plugins[id].destroy instanceof Function && this.plugins[id].destroy() }) this.playerEvents.forEach((event) => { this.elements.container.removeEventListener(event.type, event.listener) }) this.elements.container.remove() } }
the_stack
import * as path from 'path'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; import * as ecs from '@aws-cdk/aws-ecs'; import * as events from '@aws-cdk/aws-events'; import * as events_targets from '@aws-cdk/aws-events-targets'; import * as iam from '@aws-cdk/aws-iam'; import * as lambda from '@aws-cdk/aws-lambda'; import * as logs from '@aws-cdk/aws-logs'; import * as sns from '@aws-cdk/aws-sns'; import * as subscription from '@aws-cdk/aws-sns-subscriptions'; import * as sqs from '@aws-cdk/aws-sqs'; import * as cdk from '@aws-cdk/core'; import { Construct } from 'constructs'; import { Service } from '../../service'; import { Container } from '../container'; import { ContainerMutatingHook, ServiceExtension } from '../extension-interfaces'; /** * An interface that will be implemented by all the resources that can be subscribed to. */ export interface ISubscribable { /** * The `SubscriptionQueue` object for the `ISubscribable` object. * * @default none */ readonly subscriptionQueue?: SubscriptionQueue; /** * All classes implementing this interface must also implement the `subscribe()` method */ subscribe(extension: QueueExtension): sqs.IQueue; } /** * The settings for the Queue extension. */ export interface QueueExtensionProps { /** * The list of subscriptions for this service. * * @default none */ readonly subscriptions?: ISubscribable[]; /** * The user-provided default queue for this service. * If the `eventsQueue` is not provided, a default SQS Queue is created for the service. * * @default none */ readonly eventsQueue?: sqs.IQueue; /** * The user-provided queue delay fields to configure auto scaling for the default queue. * * @default none */ readonly scaleOnLatency?: QueueAutoScalingOptions; } /** * The topic-specific settings for creating the queue subscriptions. */ export interface TopicSubscriptionProps { /** * The SNS Topic to subscribe to. */ readonly topic: sns.ITopic; /** * The user-provided queue to subscribe to the given topic. * * @default none * @deprecated use `topicSubscriptionQueue` */ readonly queue?: sqs.IQueue; /** * The object representing topic-specific queue and corresponding queue delay fields to configure auto scaling. * If not provided, the default `eventsQueue` will subscribe to the given topic. * * @default none */ readonly topicSubscriptionQueue?: SubscriptionQueue; } /** * `SubscriptionQueue` represents the subscription queue object which includes the topic-specific queue and its * corresponding auto scaling fields. */ interface SubscriptionQueue { /** * The user-provided queue to subscribe to the given topic. */ readonly queue: sqs.IQueue; /** * The user-provided queue delay fields to configure auto scaling for the topic-specific queue. * * @default none */ readonly scaleOnLatency?: QueueAutoScalingOptions; } /** * Options for configuring SQS Queue auto scaling. */ interface QueueAutoScalingOptions { /** * Average amount of time for processing a single message in the queue. */ readonly messageProcessingTime: cdk.Duration; /** * Acceptable amount of time a message can sit in the queue (including the time required to process it). */ readonly acceptableLatency: cdk.Duration; } /** * The `TopicSubscription` class represents an SNS Topic resource that can be subscribed to by the service queues. */ export class TopicSubscription implements ISubscribable { public readonly topic: sns.ITopic; /** * The queue that subscribes to the given topic. * * @default none * @deprecated use `subscriptionQueue` */ public readonly queue?: sqs.IQueue; /** * The subscription queue object for this subscription. * * @default none */ public readonly subscriptionQueue?: SubscriptionQueue; constructor(props: TopicSubscriptionProps) { this.topic = props.topic; if (props.topicSubscriptionQueue && props.queue) { throw Error('Either provide the `subscriptionQueue` or the `queue` (deprecated) for the topic subscription, but not both.'); } this.subscriptionQueue = props.topicSubscriptionQueue; this.queue = props.queue ?? props.topicSubscriptionQueue?.queue; } /** * This method sets up SNS Topic subscriptions for the SQS queue provided by the user. If a `queue` is not provided, * the default `eventsQueue` subscribes to the given topic. * * @param extension `QueueExtension` added to the service * @returns the queue subscribed to the given topic */ public subscribe(extension: QueueExtension) : sqs.IQueue { const queue = this.subscriptionQueue?.queue ?? this.queue ?? extension.eventsQueue; this.topic.addSubscription(new subscription.SqsSubscription(queue)); return queue; } } /** * Settings for the hook which mutates the application container * to add the events queue URI to its environment. */ interface ContainerMutatingProps { /** * The events queue name and URI to be added to the container environment. */ readonly environment: { [key: string]: string }; } /** * This hook modifies the application container's environment to * add the queue URL for the events queue of the service. */ class QueueExtensionMutatingHook extends ContainerMutatingHook { private environment: { [key: string]: string }; constructor(props: ContainerMutatingProps) { super(); this.environment = props.environment; } public mutateContainerDefinition(props: ecs.ContainerDefinitionOptions): ecs.ContainerDefinitionOptions { return { ...props, environment: { ...(props.environment || {}), ...this.environment }, } as ecs.ContainerDefinitionOptions; } } /** * This extension creates a default `eventsQueue` for the service (if not provided) and accepts a list of objects of * type `ISubscribable` that the `eventsQueue` subscribes to. It creates the subscriptions and sets up permissions * for the service to consume messages from the SQS Queues. * * It also configures a target tracking scaling policy for the service to maintain an acceptable queue latency by tracking * the backlog per task. For more information, please refer: https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-using-sqs-queue.html . * * The default queue for this service can be accessed using the getter `<extension>.eventsQueue`. */ export class QueueExtension extends ServiceExtension { private _eventsQueue!: sqs.IQueue; private _autoscalingOptions?: QueueAutoScalingOptions; private subscriptionQueues = new Set<SubscriptionQueue>(); private environment: { [key: string]: string } = {}; private props?: QueueExtensionProps; /** * The log group created by the extension where the AWS Lambda function logs are stored. */ public logGroup?: logs.ILogGroup; constructor(props?: QueueExtensionProps) { super('queue'); this.props = props; } /** * This hook creates (if required) and sets the default queue `eventsQueue`. It also sets up the subscriptions for * the provided `ISubscribable` objects. * * @param service The parent service which this extension has been added to * @param scope The scope that this extension should create resources in */ public prehook(service: Service, scope: Construct) { this.parentService = service; this.scope = scope; let eventsQueue = this.props?.eventsQueue; if (!eventsQueue) { const deadLetterQueue = new sqs.Queue(this.scope, 'EventsDeadLetterQueue', { retentionPeriod: cdk.Duration.days(14), }); eventsQueue = new sqs.Queue(this.scope, 'EventsQueue', { deadLetterQueue: { queue: deadLetterQueue, maxReceiveCount: 3, }, }); } this._eventsQueue = eventsQueue; this._autoscalingOptions = this.props?.scaleOnLatency; this.environment[`${this.parentService.id.toUpperCase()}_QUEUE_URI`] = this._eventsQueue.queueUrl; if (this.props?.subscriptions) { for (const subs of this.props.subscriptions) { const subsQueue = subs.subscribe(this); if (subsQueue !== this._eventsQueue) { if (subs.subscriptionQueue?.scaleOnLatency && !this._autoscalingOptions) { throw Error(`Autoscaling for a topic-specific queue cannot be configured as autoscaling based on SQS Queues hasn’t been set up for the service '${this.parentService.id}'. If you want to enable autoscaling for this service, please also specify 'scaleOnLatency' in the 'QueueExtension'.`); } const subscriptionQueue = subs.subscriptionQueue ?? { queue: subsQueue, } as SubscriptionQueue; this.subscriptionQueues.add(subscriptionQueue); } } } } /** * Add hooks to the main application extension so that it is modified to * add the events queue URL to the container environment. */ public addHooks() { const container = this.parentService.serviceDescription.get('service-container') as Container; if (!container) { throw new Error('Queue Extension requires an application extension'); } container.addContainerMutatingHook(new QueueExtensionMutatingHook({ environment: this.environment, })); } /** * After the task definition has been created, this hook grants SQS permissions to the task role. * * @param taskDefinition The created task definition */ public useTaskDefinition(taskDefinition: ecs.TaskDefinition) { this._eventsQueue.grantConsumeMessages(taskDefinition.taskRole); for (const subsQueue of this.subscriptionQueues) { subsQueue.queue.grantConsumeMessages(taskDefinition.taskRole); } } /** * When this hook is implemented by extension, it allows the extension * to use the service which has been created. It is used to add target tracking * scaling policies for the SQS Queues of the service. It also creates an AWS Lambda * Function for calculating the backlog per task metric. * * @param service - The generated service. */ public useService(service: ecs.Ec2Service | ecs.FargateService) { if (!this._autoscalingOptions) { return; } if (!this.parentService.scalableTaskCount) { throw Error(`Auto scaling target for the service '${this.parentService.id}' hasn't been configured. Please use Service construct to configure 'minTaskCount' and 'maxTaskCount'.`); } this.addQueueScalingPolicy(this._eventsQueue, this._autoscalingOptions); for (const subsQueue of this.subscriptionQueues) { const autoscalingOpts = subsQueue.scaleOnLatency ?? this._autoscalingOptions; this.addQueueScalingPolicy(subsQueue.queue, autoscalingOpts!); } this.parentService.enableAutoScalingPolicy(); this.createLambdaFunction(service); } /** * This method adds a target tracking policy based on the backlog per task custom metric * to the auto scaling target configured for this service. * * @param queue The queue for which backlog per task metric is being configured * @param queueDelay The auto scaling options for the queue */ private addQueueScalingPolicy(queue: sqs.IQueue, queueDelay: QueueAutoScalingOptions) { const messageProcessingTime = queueDelay.messageProcessingTime.toSeconds(); const acceptableLatency = queueDelay.acceptableLatency.toSeconds(); if (messageProcessingTime > acceptableLatency) { throw Error(`Message processing time (${messageProcessingTime}s) for the queue cannot be greater acceptable queue latency (${acceptableLatency}s).`); } const acceptableBacklog = acceptableLatency/messageProcessingTime; this.parentService.scalableTaskCount?.scaleToTrackCustomMetric(`${queue.node.id}-autoscaling-policy`, { metric: new cloudwatch.Metric({ namespace: `${this.parentService.environment.id}-${this.parentService.id}`, metricName: 'BacklogPerTask', dimensionsMap: { QueueName: queue.queueName }, unit: cloudwatch.Unit.COUNT, }), targetValue: acceptableBacklog, }); } /** * This method is used to create the AWS Lambda Function for calculating backlog * per task metric and a Cloudwatch event trigger for this function. * * @param service - The generated service. */ private createLambdaFunction(service: ecs.Ec2Service | ecs.FargateService) { const queueNames = [this._eventsQueue.queueName]; this.subscriptionQueues.forEach(subs => queueNames.push(subs.queue.queueName)); const backLogPerTaskCalculator = new lambda.Function(this.scope, 'BackLogPerTaskCalculatorFunction', { runtime: lambda.Runtime.PYTHON_3_9, code: lambda.Code.fromAsset(path.join(__dirname, 'lambda')), handler: 'index.queue_handler', environment: { CLUSTER_NAME: this.parentService.cluster.clusterName, SERVICE_NAME: service.serviceName, NAMESPACE: `${this.parentService.environment.id}-${this.parentService.id}`, QUEUE_NAMES: queueNames.join(','), }, initialPolicy: [new iam.PolicyStatement({ actions: ['ecs:DescribeServices'], resources: [`${service.serviceArn}`], conditions: { ArnEquals: { 'ecs:cluster': this.parentService.cluster.clusterArn, }, }, })], }); const queueArns = [this._eventsQueue.queueArn]; this.subscriptionQueues.forEach(subs => queueArns.push(subs.queue.queueArn)); backLogPerTaskCalculator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ actions: [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', ], resources: queueArns, })); new events.Rule(this.scope, 'BacklogPerTaskScheduledRule', { schedule: events.Schedule.rate(cdk.Duration.seconds(60)), targets: [new events_targets.LambdaFunction(backLogPerTaskCalculator)], }); this.logGroup = new logs.LogGroup(this.scope, `${this.parentService.id}-BackLogPerTaskCalculatorLogs`, { logGroupName: `/aws/lambda/${backLogPerTaskCalculator.functionName}`, removalPolicy: cdk.RemovalPolicy.DESTROY, retention: logs.RetentionDays.THREE_DAYS, }); } public get eventsQueue() : sqs.IQueue { return this._eventsQueue; } public get autoscalingOptions() : QueueAutoScalingOptions | undefined { return this._autoscalingOptions; } }
the_stack
import assert = require('assert'); import { atob } from './base/stringutil'; import agile_keychain_crypto = require('./agile_keychain_crypto'); import crypto = require('./base/crypto'); import err_util = require('./base/err_util'); import event_stream = require('./base/event_stream'); var AES_128_KEY_LEN = 32; // 16 byte key + 16 byte IV /** Specifies supported algorithms that key agents can use * to encrypt/decrypt data. */ export enum CryptoAlgorithm { /** The algorithm used in the Agile Keychain format to encrypt item * data. * * Data is encrypted using AES-128 with a random salt and encryption key/IV derived * using onepass_crypto.openSSLKey(). * See onepass_crypto.encryptAgileKeychainItemData() */ AES128_OpenSSLKey, } export class CryptoParams { algo: CryptoAlgorithm; constructor(algo: CryptoAlgorithm) { this.algo = algo; } } export enum KeyFormat { /** Encryption key format used in the 1Password Agile Keychain format. * * Keys in this format are encrypted using AES-CBC-128 using a key * derived from a master password using PBKDF2. */ AgileKeychainKey, } export interface Key { /** Format of the encrypted key. This specifies the * storage format of the encrypted key, the algorithm used * for password derivation. */ format: KeyFormat; /** Unique ID for this encryption key */ identifier: string; /** Encrypted key */ data: string; /** Number of iterations of the password stretching function used * for this key. */ iterations: number; /** Data used to validate an encrypted key. */ validation: string; } export interface EncryptedKey { /** The master key for the vault, encrypted with a key derived from the user's * master password. */ key: string; /** A copy of the master key encrypted with itself. This can be used to verify * successful decryption of the key when it is next decrypted. */ validation: string; } export interface DecryptedKey { id: string; key: string; } export class DecryptionError extends err_util.BaseError { constructor(message: string) { super(message); } } /** Decrypt a set of keys using a password. */ export function decryptKeys( keys: Key[], password: string ): Promise<DecryptedKey[]> { let decryptedKeys: Promise<DecryptedKey>[] = []; keys.forEach(key => { assert.equal(key.format, KeyFormat.AgileKeychainKey); var saltCipher = agile_keychain_crypto.extractSaltAndCipherText( atob(key.data) ); let decryptedKey = keyFromPassword( password, saltCipher.salt, key.iterations ) .then(derivedKey => { return decryptKey( derivedKey, saltCipher.cipherText, atob(key.validation) ); }) .then(decryptedKey => ({ id: key.identifier, key: decryptedKey, })); decryptedKeys.push(decryptedKey); }); return Promise.all(decryptedKeys); } /** Interface for agent which handles storage of decryption * keys and provides methods to encrypt and decrypt data * using the stored keys. */ export interface KeyAgent { /** Register a key with the agent for future use when decrypting items. */ addKey(id: string, key: string): Promise<void>; /** Returns the IDs of stored keys. */ listKeys(): Promise<string[]>; /** Clear all stored keys. */ forgetKeys(): Promise<void>; /** Decrypt data for an item using the given key ID and crypto * parameters. * * Returns a promise for the decrypted plaintext. */ decrypt( id: string, cipherText: string, params: CryptoParams ): Promise<string>; /** Encrypt data for an item using the given key ID and crypto * parameters. * * Returns a promise for the encrypted text. */ encrypt( id: string, plainText: string, params: CryptoParams ): Promise<string>; /** Optional event stream which emits events when forgetKeys() is * called. Some key agents may not support this. */ onLock?(): event_stream.EventStream<void>; /** Reset the timeout for auto-locking this key agent. * This should be called when the user interacts with the app * in some way to prevent auto-locking whilst the user is * interacting with the app. */ resetAutoLock(): void; } /** A simple key agent which just stores keys in memory */ export class SimpleKeyAgent implements KeyAgent { private autoLockTimeout: number; private crypto: agile_keychain_crypto.Crypto; private keys: { [id: string]: string }; private lockEvents: event_stream.EventStream<void>; // in Node, setTimeout() returns a Timer, in the browser // it returns a number private lockTimeout: any; keyCount(): number { return Object.keys(this.keys).length; } constructor(cryptoImpl?: agile_keychain_crypto.Crypto) { this.crypto = cryptoImpl || agile_keychain_crypto.defaultCrypto; this.keys = {}; this.lockEvents = new event_stream.EventStream<void>(); this.autoLockTimeout = 0; } /** Reset the auto-lock timer. */ public resetAutoLock() { if (!this.autoLockTimeout) { return; } if (this.lockTimeout) { clearTimeout(this.lockTimeout); this.lockTimeout = null; } this.lockTimeout = setTimeout(() => { this.forgetKeys(); }, this.autoLockTimeout); } /** Set a timeout after which the agent will automatically discard * its keys, thereby locking the vault. * * If timeout is zero or null, auto-lock is disabled. * Auto-lock is disabled by default in SimpleKeyAgent */ setAutoLockTimeout(timeout: number) { this.autoLockTimeout = timeout; if (this.lockTimeout) { this.resetAutoLock(); } } addKey(id: string, key: string): Promise<void> { this.keys[id] = key; this.resetAutoLock(); return Promise.resolve<void>(null); } listKeys(): Promise<string[]> { return Promise.resolve(Object.keys(this.keys)); } forgetKeys(): Promise<void> { if (this.lockTimeout) { clearTimeout(this.lockTimeout); this.lockTimeout = null; } this.keys = {}; this.lockEvents.publish(null); return Promise.resolve<void>(null); } decrypt( id: string, cipherText: string, params: CryptoParams ): Promise<string> { if (!this.keys.hasOwnProperty(id)) { return Promise.reject<string>( new DecryptionError('No such key: ' + id) ); } switch (params.algo) { case CryptoAlgorithm.AES128_OpenSSLKey: return agile_keychain_crypto.decryptAgileKeychainItemData( this.crypto, this.keys[id], cipherText ); default: return Promise.reject<string>( new Error('Unknown encryption algorithm') ); } } encrypt( id: string, plainText: string, params: CryptoParams ): Promise<string> { if (!this.keys.hasOwnProperty(id)) { return Promise.reject<string>(new Error('No such key: ' + id)); } switch (params.algo) { case CryptoAlgorithm.AES128_OpenSSLKey: return agile_keychain_crypto.encryptAgileKeychainItemData( this.crypto, this.keys[id], plainText ); default: return Promise.reject<string>( new Error('Unknown encryption algorithm') ); } } onLock(): event_stream.EventStream<void> { return this.lockEvents; } } /** Decrypt the master key for a vault. * * @param derivedKey The encryption key that was used to encrypt @p encryptedKey, this is * derived from a password using keyFromPassword() * @param encryptedKey The encryption key, encrypted with @p derivedKey * @param validation Validation data used to verify whether decryption was successful. * This is a copy of the decrypted version of @p encryptedKey, encrypted with itself. */ export async function decryptKey( derivedKey: string, encryptedKey: string, validation: string ): Promise<string> { try { let aesKey = derivedKey.substring(0, 16); let iv = derivedKey.substring(16, 32); let decryptedKey = await agile_keychain_crypto.defaultCrypto.aesCbcDecrypt( aesKey, encryptedKey, iv ); let validationSaltCipher = agile_keychain_crypto.extractSaltAndCipherText( validation ); let keyParams = await agile_keychain_crypto.openSSLKey( agile_keychain_crypto.defaultCrypto, decryptedKey, validationSaltCipher.salt ); let decryptedValidation = await agile_keychain_crypto.defaultCrypto.aesCbcDecrypt( keyParams.key, validationSaltCipher.cipherText, keyParams.iv ); if (decryptedValidation !== decryptedKey) { throw new DecryptionError('Incorrect password'); } return decryptedKey; } catch (err) { throw new DecryptionError('Incorrect password'); } } /** Derive an encryption key from a password for use with decryptKey(). * This version is synchronous and will block the UI if @p iterCount * is high. */ export async function keyFromPasswordSync( pass: string, salt: string, iterCount: number ) { return agile_keychain_crypto.defaultCrypto.pbkdf2( pass, salt, iterCount, AES_128_KEY_LEN ); } /** Derive an encryption key from a password for use with decryptKey() * This version is asynchronous and will not block the UI. */ export function keyFromPassword( pass: string, salt: string, iterCount: number ): Promise<string> { return agile_keychain_crypto.defaultCrypto.pbkdf2( pass, salt, iterCount, AES_128_KEY_LEN ); } /** Encrypt the master key for a vault. * @param derivedKey An encryption key for the master key, derived from a password using keyFromPassword() * @param decryptedKey The master key for the vault to be encrypted. */ export async function encryptKey( derivedKey: string, decryptedKey: string ): Promise<EncryptedKey> { let aesKey = derivedKey.substring(0, 16); let iv = derivedKey.substring(16, 32); let encryptedKey = agile_keychain_crypto.defaultCrypto.aesCbcEncrypt( aesKey, decryptedKey, iv ); let validationSalt = crypto.randomBytes(8); let keyParams = await agile_keychain_crypto.openSSLKey( agile_keychain_crypto.defaultCrypto, decryptedKey, validationSalt ); let validation = agile_keychain_crypto.defaultCrypto.aesCbcEncrypt( keyParams.key, decryptedKey, keyParams.iv ); return Promise.all([encryptedKey, validation]).then( (result: [string, string]) => { let encryptedKey = result[0]; let validation = 'Salted__' + validationSalt + result[1]; return { key: encryptedKey, validation: validation }; } ); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * The Eventarc Trigger resource * * ## Example Usage * ### Basic * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const _default = new gcp.cloudrun.Service("default", { * location: "europe-west1", * metadata: { * namespace: "my-project-name", * }, * template: { * spec: { * containers: [{ * image: "gcr.io/cloudrun/hello", * args: ["arrgs"], * }], * containerConcurrency: 50, * }, * }, * traffics: [{ * percent: 100, * latestRevision: true, * }], * }); * const primary = new gcp.eventarc.Trigger("primary", { * location: "europe-west1", * matchingCriterias: [{ * attribute: "type", * value: "google.cloud.pubsub.topic.v1.messagePublished", * }], * destination: { * cloudRunService: { * service: _default.name, * region: "europe-west1", * }, * }, * labels: { * foo: "bar", * }, * }); * const foo = new gcp.pubsub.Topic("foo", {}); * ``` * * ## Import * * Trigger can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:eventarc/trigger:Trigger default projects/{{project}}/locations/{{location}}/triggers/{{name}} * ``` * * ```sh * $ pulumi import gcp:eventarc/trigger:Trigger default {{project}}/{{location}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:eventarc/trigger:Trigger default {{location}}/{{name}} * ``` */ export class Trigger extends pulumi.CustomResource { /** * Get an existing Trigger 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?: TriggerState, opts?: pulumi.CustomResourceOptions): Trigger { return new Trigger(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:eventarc/trigger:Trigger'; /** * Returns true if the given object is an instance of Trigger. 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 Trigger { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Trigger.__pulumiType; } /** * Output only. The creation time. */ public /*out*/ readonly createTime!: pulumi.Output<string>; /** * Required. Destination specifies where the events should be sent to. */ public readonly destination!: pulumi.Output<outputs.eventarc.TriggerDestination>; /** * Output only. This checksum is computed by the server based on the value of other fields, and may be sent only on create * requests to ensure the client has an up-to-date value before proceeding. */ public /*out*/ readonly etag!: pulumi.Output<string>; /** * Optional. User labels attached to the triggers that can be used to group resources. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The location for the resource */ public readonly location!: pulumi.Output<string>; /** * Required. null The list of filters that applies to event attributes. Only events that match all the provided filters will be sent to the destination. */ public readonly matchingCriterias!: pulumi.Output<outputs.eventarc.TriggerMatchingCriteria[]>; /** * Required. The resource name of the trigger. Must be unique within the location on the project and must be in `projects/{project}/locations/{location}/triggers/{trigger}` format. */ public readonly name!: pulumi.Output<string>; /** * The project for the resource */ public readonly project!: pulumi.Output<string>; /** * Optional. The IAM service account email associated with the trigger. The service account represents the identity of the trigger. The principal who calls this API must have `iam.serviceAccounts.actAs` permission in the service account. See https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common for more information. For Cloud Run destinations, this service account is used to generate identity tokens when invoking the service. See https://cloud.google.com/run/docs/triggering/pubsub-push#create-service-account for information on how to invoke authenticated Cloud Run services. In order to create Audit Log triggers, the service account should also have `roles/eventarc.eventReceiver` IAM role. */ public readonly serviceAccount!: pulumi.Output<string | undefined>; /** * Optional. In order to deliver messages, Eventarc may use other GCP products as transport intermediary. This field contains a reference to that transport intermediary. This information can be used for debugging purposes. */ public readonly transports!: pulumi.Output<outputs.eventarc.TriggerTransport[]>; /** * Output only. Server assigned unique identifier for the trigger. The value is a UUID4 string and guaranteed to remain * unchanged until the resource is deleted. */ public /*out*/ readonly uid!: pulumi.Output<string>; /** * Output only. The last-modified time. */ public /*out*/ readonly updateTime!: pulumi.Output<string>; /** * Create a Trigger 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: TriggerArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: TriggerArgs | TriggerState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as TriggerState | undefined; inputs["createTime"] = state ? state.createTime : undefined; inputs["destination"] = state ? state.destination : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["location"] = state ? state.location : undefined; inputs["matchingCriterias"] = state ? state.matchingCriterias : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["serviceAccount"] = state ? state.serviceAccount : undefined; inputs["transports"] = state ? state.transports : undefined; inputs["uid"] = state ? state.uid : undefined; inputs["updateTime"] = state ? state.updateTime : undefined; } else { const args = argsOrState as TriggerArgs | undefined; if ((!args || args.destination === undefined) && !opts.urn) { throw new Error("Missing required property 'destination'"); } if ((!args || args.location === undefined) && !opts.urn) { throw new Error("Missing required property 'location'"); } if ((!args || args.matchingCriterias === undefined) && !opts.urn) { throw new Error("Missing required property 'matchingCriterias'"); } inputs["destination"] = args ? args.destination : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["location"] = args ? args.location : undefined; inputs["matchingCriterias"] = args ? args.matchingCriterias : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["serviceAccount"] = args ? args.serviceAccount : undefined; inputs["transports"] = args ? args.transports : undefined; inputs["createTime"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["uid"] = undefined /*out*/; inputs["updateTime"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Trigger.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Trigger resources. */ export interface TriggerState { /** * Output only. The creation time. */ createTime?: pulumi.Input<string>; /** * Required. Destination specifies where the events should be sent to. */ destination?: pulumi.Input<inputs.eventarc.TriggerDestination>; /** * Output only. This checksum is computed by the server based on the value of other fields, and may be sent only on create * requests to ensure the client has an up-to-date value before proceeding. */ etag?: pulumi.Input<string>; /** * Optional. User labels attached to the triggers that can be used to group resources. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The location for the resource */ location?: pulumi.Input<string>; /** * Required. null The list of filters that applies to event attributes. Only events that match all the provided filters will be sent to the destination. */ matchingCriterias?: pulumi.Input<pulumi.Input<inputs.eventarc.TriggerMatchingCriteria>[]>; /** * Required. The resource name of the trigger. Must be unique within the location on the project and must be in `projects/{project}/locations/{location}/triggers/{trigger}` format. */ name?: pulumi.Input<string>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Optional. The IAM service account email associated with the trigger. The service account represents the identity of the trigger. The principal who calls this API must have `iam.serviceAccounts.actAs` permission in the service account. See https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common for more information. For Cloud Run destinations, this service account is used to generate identity tokens when invoking the service. See https://cloud.google.com/run/docs/triggering/pubsub-push#create-service-account for information on how to invoke authenticated Cloud Run services. In order to create Audit Log triggers, the service account should also have `roles/eventarc.eventReceiver` IAM role. */ serviceAccount?: pulumi.Input<string>; /** * Optional. In order to deliver messages, Eventarc may use other GCP products as transport intermediary. This field contains a reference to that transport intermediary. This information can be used for debugging purposes. */ transports?: pulumi.Input<pulumi.Input<inputs.eventarc.TriggerTransport>[]>; /** * Output only. Server assigned unique identifier for the trigger. The value is a UUID4 string and guaranteed to remain * unchanged until the resource is deleted. */ uid?: pulumi.Input<string>; /** * Output only. The last-modified time. */ updateTime?: pulumi.Input<string>; } /** * The set of arguments for constructing a Trigger resource. */ export interface TriggerArgs { /** * Required. Destination specifies where the events should be sent to. */ destination: pulumi.Input<inputs.eventarc.TriggerDestination>; /** * Optional. User labels attached to the triggers that can be used to group resources. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The location for the resource */ location: pulumi.Input<string>; /** * Required. null The list of filters that applies to event attributes. Only events that match all the provided filters will be sent to the destination. */ matchingCriterias: pulumi.Input<pulumi.Input<inputs.eventarc.TriggerMatchingCriteria>[]>; /** * Required. The resource name of the trigger. Must be unique within the location on the project and must be in `projects/{project}/locations/{location}/triggers/{trigger}` format. */ name?: pulumi.Input<string>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Optional. The IAM service account email associated with the trigger. The service account represents the identity of the trigger. The principal who calls this API must have `iam.serviceAccounts.actAs` permission in the service account. See https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common for more information. For Cloud Run destinations, this service account is used to generate identity tokens when invoking the service. See https://cloud.google.com/run/docs/triggering/pubsub-push#create-service-account for information on how to invoke authenticated Cloud Run services. In order to create Audit Log triggers, the service account should also have `roles/eventarc.eventReceiver` IAM role. */ serviceAccount?: pulumi.Input<string>; /** * Optional. In order to deliver messages, Eventarc may use other GCP products as transport intermediary. This field contains a reference to that transport intermediary. This information can be used for debugging purposes. */ transports?: pulumi.Input<pulumi.Input<inputs.eventarc.TriggerTransport>[]>; }
the_stack
import IChannelsDatabase from './storage/IChannelsDatabase' import PaymentManager from './PaymentManager' import ChannelContract from './ChannelContract' import { TransactionResult } from 'truffle-contract' import Mutex from './Mutex' import Payment from './payment' import MachinomyOptions from './MachinomyOptions' import IChannelManager from './IChannelManager' import * as BigNumber from 'bignumber.js' import ChannelId from './ChannelId' import { EventEmitter } from 'events' import * as Web3 from 'web3' import IPaymentsDatabase from './storage/IPaymentsDatabase' import ITokensDatabase from './storage/ITokensDatabase' import Logger from '@machinomy/logger' import { PaymentChannel } from './PaymentChannel' import ChannelInflator from './ChannelInflator' import * as uuid from 'uuid' import { PaymentNotValidError, InvalidChannelError } from './Exceptions' import { RemoteChannelInfo } from './RemoteChannelInfo' import { recoverPersonalSignature } from 'eth-sig-util' import pify from './util/pify' const LOG = new Logger('channel-manager') const DAY_IN_SECONDS = 86400 const NEW_BLOCK_TIME_IN_SECONDS = 15 export default class ChannelManager extends EventEmitter implements IChannelManager { /** Default settlement period for a payment channel */ static DEFAULT_SETTLEMENT_PERIOD = 2 * DAY_IN_SECONDS / NEW_BLOCK_TIME_IN_SECONDS private account: string private web3: Web3 private channelsDao: IChannelsDatabase private paymentsDao: IPaymentsDatabase private tokensDao: ITokensDatabase private channelContract: ChannelContract private paymentManager: PaymentManager private mutex: Mutex = new Mutex() private machinomyOptions: MachinomyOptions constructor (account: string, web3: Web3, channelsDao: IChannelsDatabase, paymentsDao: IPaymentsDatabase, tokensDao: ITokensDatabase, channelContract: ChannelContract, paymentManager: PaymentManager, machinomyOptions: MachinomyOptions) { super() this.account = account this.web3 = web3 this.channelsDao = channelsDao this.paymentsDao = paymentsDao this.tokensDao = tokensDao this.channelContract = channelContract this.paymentManager = paymentManager this.machinomyOptions = machinomyOptions } openChannel (sender: string, receiver: string, amount: BigNumber.BigNumber, minDepositAmount?: BigNumber.BigNumber, channelId?: ChannelId | string, tokenContract?: string): Promise<PaymentChannel> { return this.mutex.synchronize(async () => { return this.internalOpenChannel(sender, receiver, amount, minDepositAmount, channelId, tokenContract) }) } closeChannel (channelId: string | ChannelId): Promise<TransactionResult> { return this.mutex.synchronizeOn(channelId.toString(), () => this.internalCloseChannel(channelId)) } deposit (channelId: string, value: BigNumber.BigNumber): Promise<TransactionResult> { return this.mutex.synchronizeOn(channelId, async () => { const channel = await this.channelById(channelId) if (!channel) { throw new Error('No payment channel found.') } const res = await this.channelContract.deposit(this.account, channelId, value, channel.tokenContract) await this.channelsDao.deposit(channelId, value) return res }) } nextPayment (channelId: string | ChannelId, amount: BigNumber.BigNumber, meta: string): Promise<Payment> { return this.mutex.synchronizeOn(channelId.toString(), async () => { const channel = await this.channelById(channelId) if (!channel) { throw new Error(`Channel with id ${channelId.toString()} not found.`) } const toSpend = channel.spent.add(amount) if (toSpend.greaterThan(channel.value)) { throw new Error(`Total spend ${toSpend.toString()} is larger than channel value ${channel.value.toString()}`) } return this.paymentManager.buildPaymentForChannel(channel, amount, toSpend, meta) }) } async spendChannel (payment: Payment, token?: string): Promise<Payment> { const chan = PaymentChannel.fromPayment(payment) await this.channelsDao.saveOrUpdate(chan) let _token = token || payment.token || uuid.v4().replace(/-/g, '') await this.paymentsDao.save(_token, payment) return payment } async acceptPayment (payment: Payment): Promise<string> { const isPaymentInTokens = ChannelInflator.isTokenContractDefined(payment.tokenContract) if (isPaymentInTokens) { LOG.info(`Queueing payment of ${payment.price.toString()} token(s) to channel with ID ${payment.channelId}.`) } else { LOG.info(`Queueing payment of ${payment.price.toString()} Wei to channel with ID ${payment.channelId}.`) } return this.mutex.synchronizeOn(payment.channelId, async () => { const channel = await this.findChannel(payment) if (isPaymentInTokens) { LOG.info(`Adding ${payment.price.toString()} token(s) to channel with ID ${channel.channelId.toString()}.`) } else { LOG.info(`Adding ${payment.price.toString()} Wei to channel with ID ${channel.channelId.toString()}.`) } const valid = await this.paymentManager.isValid(payment, channel) if (valid) { channel.spent = payment.value const token = this.web3.sha3(JSON.stringify(payment) + (new Date()).toString()).toString() await Promise.all([ this.channelsDao.saveOrUpdate(channel), this.tokensDao.save(token, payment.channelId), this.paymentsDao.save(token, payment) ]) return token } if (this.machinomyOptions.closeOnInvalidPayment) { LOG.info(`Received invalid payment from ${payment.sender}!`) const existingChannel = await this.channelsDao.findBySenderReceiverChannelId(payment.sender, payment.receiver, payment.channelId) if (existingChannel) { LOG.info(`Found existing channel with id ${payment.channelId} between ${payment.sender} and ${payment.receiver}.`) LOG.info('Closing channel due to malfeasance.') await this.internalCloseChannel(channel.channelId) } } throw new PaymentNotValidError() }) } requireOpenChannel (sender: string, receiver: string, amount: BigNumber.BigNumber, minDepositAmount?: BigNumber.BigNumber, tokenContract?: string): Promise<PaymentChannel> { return this.mutex.synchronize(async () => { if (!minDepositAmount && this.machinomyOptions && this.machinomyOptions.minimumChannelAmount) { minDepositAmount = new BigNumber.BigNumber(this.machinomyOptions.minimumChannelAmount) } let channel = await this.channelsDao.findUsable(sender, receiver, amount) return channel || this.internalOpenChannel(sender, receiver, amount, minDepositAmount, undefined, tokenContract) }) } channels (): Promise<PaymentChannel[]> { return this.channelsDao.all() } openChannels (): Promise<PaymentChannel[]> { return this.channelsDao.allOpen() } settlingChannels (): Promise<PaymentChannel[]> { return this.channelsDao.allSettling() } async channelById (channelId: ChannelId | string): Promise<PaymentChannel | null> { let channel = await this.channelsDao.firstById(channelId) let channelC = await this.channelContract.channelById(channelId.toString()) if (channel && channelC) { channel.value = channelC[2] return channel } else { return this.handleUnknownChannel(channelId) } } verifyToken (token: string): Promise<boolean> { return this.tokensDao.isPresent(token) } /** * DO NOT USE THIS. * @param sender * @param receiver * @param remoteChannels */ async syncChannels (sender: string, receiver: string, remoteChannels: RemoteChannelInfo[]): Promise<void> { const channels = await this.openChannels() const recChannels = channels.filter(chan => chan.receiver === receiver) const promises = remoteChannels.map(async remoteChan => { const localChan = recChannels.find(chan => chan.channelId === remoteChan.channelId) if (localChan) { // all is ok if (localChan.spent >= remoteChan.spent) { return } } else { await this.nextPayment(remoteChan.channelId, new BigNumber.BigNumber(0), '') } const digest = await this.channelContract.paymentDigest(remoteChan.channelId, remoteChan.spent) const restored = recoverPersonalSignature({ data: digest, sig: remoteChan.sign.toString() }) if (restored !== sender) { throw new InvalidChannelError('signature') } const payment = await this.nextPayment(remoteChan.channelId, remoteChan.spent, '') let chan = await this.findChannel(payment) chan.spent = remoteChan.spent await this.channelsDao.saveOrUpdate(chan) }) await Promise.all(promises) } async lastPayment (channelId: string | ChannelId): Promise<Payment | null> { channelId = channelId.toString() return this.paymentsDao.firstMaximum(channelId) } private async internalOpenChannel (sender: string, receiver: string, amount: BigNumber.BigNumber, minDepositAmount: BigNumber.BigNumber = new BigNumber.BigNumber(0), channelId?: ChannelId | string, tokenContract?: string): Promise<PaymentChannel > { let depositAmount = amount.times(10) if (minDepositAmount.greaterThan(0) && minDepositAmount.greaterThan(depositAmount)) { depositAmount = minDepositAmount } this.emit('willOpenChannel', sender, receiver, depositAmount) let settlementPeriod = this.machinomyOptions.settlementPeriod || ChannelManager.DEFAULT_SETTLEMENT_PERIOD let paymentChannel = await this.buildChannel(sender, receiver, depositAmount, settlementPeriod, undefined, channelId, tokenContract) await this.channelsDao.save(paymentChannel) this.emit('didOpenChannel', paymentChannel) return paymentChannel } private async internalCloseChannel (channelId: ChannelId | string) { let channel = await this.channelById(channelId) || await this.handleUnknownChannel(channelId) if (!channel) { throw new Error(`Channel ${channelId} not found.`) } this.emit('willCloseChannel', channel) let res: Promise<TransactionResult> if (channel.sender === this.account) { res = this.settle(channel) } else { res = this.claim(channel) } const txn = await res this.emit('didCloseChannel', channel) return txn } private settle (channel: PaymentChannel): Promise<TransactionResult> { return this.channelContract.getState(channel.channelId).then(async (state: number) => { if (state === 2) { throw new Error(`Channel ${channel.channelId.toString()} is already settled.`) } switch (state) { case 0: { const block: any = await pify((cb: (error: Error, block: any) => void) => { this.web3.eth.getBlock('latest', cb) }) const settlingUntil = new BigNumber.BigNumber(block.number).plus(channel.settlementPeriod) const res = await this.channelContract.startSettle(this.account, channel.channelId) await this.channelsDao.updateState(channel.channelId, 1) await this.channelsDao.updateSettlingUntil(channel.channelId, settlingUntil) return res } case 1: return this.channelContract.finishSettle(this.account, channel.channelId) .then((res: TransactionResult) => this.channelsDao.updateState(channel.channelId, 2).then(() => res)) default: throw new Error(`Unknown state: ${state}`) } }) } private async claim (channel: PaymentChannel): Promise<TransactionResult> { let payment = await this.lastPayment(channel.channelId) if (payment) { let result = await this.channelContract.claim(channel.receiver, channel.channelId, payment.value, payment.signature) await this.channelsDao.updateState(channel.channelId, 2) return result } else { throw new Error('Can not claim unknown channnel') } } private async buildChannel (sender: string, receiver: string, price: BigNumber.BigNumber, settlementPeriod: number, settlingUntil: BigNumber.BigNumber | undefined, channelId?: ChannelId | string, tokenContract?: string): Promise<PaymentChannel> { const res = await this.channelContract.open(sender, receiver, price, settlementPeriod, channelId, tokenContract) const _channelId = res.logs[0].args.channelId return new PaymentChannel(sender, receiver, _channelId, price, new BigNumber.BigNumber(0), 0, tokenContract, settlementPeriod, settlingUntil) } private async handleUnknownChannel (channelId: ChannelId | string): Promise<PaymentChannel | null> { channelId = channelId.toString() const channel = await this.channelContract.channelById(channelId) if (!channel) return null const sender = channel[0] const receiver = channel[1] const value = channel[2] const settlingUntil = channel[4] if (sender !== this.account && receiver !== this.account) { return null } const chan = new PaymentChannel(sender, receiver, channelId, value, new BigNumber.BigNumber(0), settlingUntil.eq(0) ? 0 : 1, '', undefined, settlingUntil) await this.channelsDao.save(chan) return chan } private async findChannel (payment: Payment): Promise<PaymentChannel> { let chan = await this.channelsDao.findBySenderReceiverChannelId(payment.sender, payment.receiver, payment.channelId) if (chan) { return chan } chan = PaymentChannel.fromPayment(payment) chan.spent = new BigNumber.BigNumber(0) return chan } }
the_stack
import { db } from "./firebase"; // DEFINITIONS export interface Collection { id: string; name: string; type: CollectionType; nftName: string; supply: number; sellerFeeBasisPoints: number; symbol: string; url: string; userGroupId: string; } export enum CollectionType { Generative = 0, Prerendered, Tilemapped, } export interface Conflict { id: string; traitSetId: string | null; trait1Id: string; trait2Id: string; trait1ValueId: string | null; trait2ValueId: string | null; resolutionType: ConflictResolutionType; } export enum ConflictResolutionType { Trait2None = 0, Trait1None, Trait2Random, Trait1Random, } export interface ImageComposite { id: string; externalURL: string | null; traits: TraitValuePair[]; traitsHash: string; additionalMetadataEntries: { [attributeTitle: string]: string }; } export interface ImageCompositeGroup { id: string; timestamp: number; indexes: number[]; } export interface ImageLayer { id: string; bucketFilename: string; url: string; name: string; bytes: number; traitSetId: string | null; traitId: string | null; traitValueId: string | null; companionLayerId: string | null; companionLayerZIndex: number | null; } export interface OrderedImageLayer { imageLayer: ImageLayer; zIndex: number; } export interface Project { id: string; name: string; description: string; domain: string | undefined; url: string; } // GENERIC INTERFACES export interface RarityValue { id: string; rarity: number; } export interface Trait { id: string; name: string; zIndex: number; traitSetIds: string[]; isMetadataOnly: boolean; isArtworkOnly: boolean; isAlwaysUnique: boolean; excludeFromDuplicateDetection: boolean; } export interface TraitSet { id: string; name: string; supply: number; metadataEntries: { [attributeTitle: string]: string }; } export interface TraitValue { id: string; name: string; rarity: number; } export interface TraitValuePair { trait: Trait; traitValue: TraitValue | null; imageLayer: ImageLayer | null; } export interface User { id: string; address: string; name: string; email: string; avatarURL: string | null; share: number; } // NAMESPACES export namespace Collections { export async function withId( collectionId: string, projectId: string ): Promise<Collection> { const collectionDoc = await db .doc("/projects/" + projectId + "/collections/" + collectionId) .get(); const collection = collectionDoc.data() as Collection; collection.id = collectionDoc.id; return collection; } } export namespace Conflicts { export async function all( projectId: string, collectionId: string, traitSetId: string | null ): Promise<Conflict[]> { const path = "/projects/" + projectId + "/collections/" + collectionId + "/conflicts"; let conflictsQuery; if (traitSetId) { conflictsQuery = await db .collection(path) .where("traitSetId", "==", traitSetId) .orderBy("trait1Id", "asc") .get(); } else { conflictsQuery = await db .collection(path) .orderBy("trait1Id", "asc") .get(); } let conflicts = conflictsQuery.docs.map((conflictsDoc) => { let conflict = conflictsDoc.data() as Conflict; conflict.id = conflictsDoc.id; return conflict; }); return conflicts; } } export namespace ImageComposites { export async function all( projectId: string, collectionId: string, compositeGroupId: string ): Promise<ImageComposite[]> { const compositesQuery = db .collection( "/projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + compositeGroupId + "/composites" ) .get(); const composites = (await compositesQuery).docs.map((compositeDoc) => { const composite = compositeDoc.data() as ImageComposite; composite.id = compositeDoc.id; return composite; }); return composites; } export async function create( imageComposite: ImageComposite, projectId: string, collectionId: string, compositeGroupId: string ): Promise<ImageComposite> { const docQuery = db.collection( "/projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + compositeGroupId + "/composites" ); await docQuery.add(imageComposite); return { ...imageComposite, } as ImageComposite; } export async function isUniqueTraitsHash( hash: string, projectId: string, collectionId: string, compositeGroupId: string ): Promise<boolean> { const compositesQuery = db .collection( "/projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + compositeGroupId + "/composites" ) .where("traitsHash", "==", hash) .limit(1); const querySnapshot = await compositesQuery.get(); const isUnique = querySnapshot.docs.length == 0; return isUnique; } export const traitsHash = (traitValuePairs: TraitValuePair[]): string => { return traitValuePairs .sort((a, b) => { const zIndexA = a.trait.zIndex; const zIndexB = b.trait.zIndex; return zIndexA < zIndexB ? -1 : zIndexA == zIndexB ? 0 : 1; }) .reduce(function (result, traitPair) { if ( traitPair.trait.excludeFromDuplicateDetection || traitPair.traitValue == null ) { return result; } return result + (traitPair.traitValue.id ?? ""); }, ""); }; } export namespace ImageCompositeGroups { export async function withId( groupId: string, projectId: string, collectionId: string ): Promise<ImageCompositeGroup> { const groupDoc = await db .doc( "projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + groupId ) .get(); const compositeGroup = groupDoc.data() as ImageCompositeGroup; compositeGroup.id = groupDoc.id; return compositeGroup; } } export namespace ImageLayers { export async function all( projectId: string, collectionId: string, traitSetId: string | null ): Promise<ImageLayer[]> { const path = "/projects/" + projectId + "/collections/" + collectionId + "/imagelayers"; let imageLayerQuery: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>; if (traitSetId) { imageLayerQuery = await db .collection(path) .where("traitSetId", "==", traitSetId) .orderBy("name", "asc") .get(); } else { imageLayerQuery = await db.collection(path).orderBy("name", "asc").get(); } let imageLayers = imageLayerQuery.docs.map((imageLayerDoc) => { let imageLayer = imageLayerDoc.data() as ImageLayer; imageLayer.id = imageLayerDoc.id; return imageLayer; }); return imageLayers; } } export namespace Projects { export async function withId(projectId: string): Promise<Project> { const projectDoc = await db.doc("projects/" + projectId).get(); const project = projectDoc.data() as Project; project.id = projectDoc.id; return project; } } export namespace Traits { export async function all( projectId: string, collectionId: string, traitSetId: string | null ): Promise<Trait[]> { const path = "/projects/" + projectId + "/collections/" + collectionId + "/traits"; let traitsQuery: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>; if (traitSetId) { traitsQuery = await db .collection(path) .where("traitSetIds", "array-contains", traitSetId) .orderBy("zIndex", "asc") .get(); } else { traitsQuery = await db.collection(path).orderBy("zIndex", "asc").get(); } const traits = traitsQuery.docs.map((traitDoc) => { const trait = traitDoc.data() as Trait; trait.id = traitDoc.id; return trait; }); return traits; } } export namespace TraitSets { export async function withId( traitSetId: string, projectId: string, collectionId: string ): Promise<TraitSet> { const traitSetDoc = await db .doc( "projects/" + projectId + "/collections/" + collectionId + "/traitSets/" + traitSetId ) .get(); const traitSet = traitSetDoc.data() as TraitSet; traitSet.id = traitSetDoc.id; return traitSet; } } export namespace TraitValues { /** * fetch all trait values for a given trait * * @param traitId the id of the trait * @param isAlwaysUnique whether the trait should be uniqued for every NFT * @param validTraitValueIds trait value ids that are valid for the current traitSet (if they have images) * @returns an array of TraitValue for the given trait */ export async function all( projectId: string, collectionId: string, compositeGroupId: string, trait: Trait, validTraitValueIds: string[] ): Promise<TraitValue[]> { const traitValuesQuery = await db .collection( "/projects/" + projectId + "/collections/" + collectionId + "/traits/" + trait.id + "/traitValues" ) .get(); const traitValues = traitValuesQuery.docs.map((traitValueDoc) => { const traitValue = traitValueDoc.data() as TraitValue; traitValue.id = traitValueDoc.id; return traitValue; }); if (trait.isAlwaysUnique) { console.log( "loading metadata only: /projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + compositeGroupId + "/composites" ); const existingCompositesQuery = await db .collection( "/projects/" + projectId + "/collections/" + collectionId + "/compositeGroups/" + compositeGroupId + "/composites" ) .get(); const existingComposites: ImageComposite[] = existingCompositesQuery.docs.map((existingCompositeDoc) => { const existingComposite = existingCompositeDoc.data() as ImageComposite; return existingComposite; }); const existingValueIds: string[] = existingComposites.reduce(function ( result, composite ) { const traitPair = composite.traits.find((traitPair) => { traitPair.trait.id == trait.id; }); const valueId = traitPair?.traitValue?.id; if (valueId) { result.push(valueId); } return result; }, Array<string>()); return traitValues.filter((traitValue: TraitValue) => { return existingValueIds.find((id) => id == traitValue.id) == undefined; }); } return traitValues.filter((traitValue: TraitValue) => { return trait.isMetadataOnly || validTraitValueIds.includes(traitValue.id); }); } } export namespace Users { export async function all(userGroupId: string): Promise<User[]> { const usersQuery = await db .collection("/userGroups/" + userGroupId + "/users") .get(); let users = usersQuery.docs.map((userDoc) => { let user = userDoc.data() as User; user.id = userDoc.id; return user; }); return users; } }
the_stack
import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import EventEmitter from 'events'; import { envUtils } from '@growi/core'; import detectIndent from 'detect-indent'; import { throttle, debounce } from 'throttle-debounce'; import AppContainer from '~/client/services/AppContainer'; import EditorContainer from '~/client/services/EditorContainer'; import PageContainer from '~/client/services/PageContainer'; import { apiGet, apiPostForm } from '~/client/util/apiv1-client'; import { getOptionsToSave } from '~/client/util/editor'; import { useIsEditable, useIsIndentSizeForced, useCurrentPagePath } from '~/stores/context'; import { useCurrentIndentSize, useSWRxSlackChannels, useIsSlackEnabled, useIsTextlintEnabled, } from '~/stores/editor'; import { EditorMode, useEditorMode, useIsMobile, useSelectedGrant, useSelectedGrantGroupId, useSelectedGrantGroupName, } from '~/stores/ui'; import loggerFactory from '~/utils/logger'; import { ConflictDiffModal } from './PageEditor/ConflictDiffModal'; import Editor from './PageEditor/Editor'; import Preview from './PageEditor/Preview'; import scrollSyncHelper from './PageEditor/ScrollSyncHelper'; import { withUnstatedContainers } from './UnstatedUtils'; // TODO: remove this when omitting unstated is completed const logger = loggerFactory('growi:PageEditor'); declare const globalEmitter: EventEmitter; type EditorRef = { setValue: (markdown: string) => void, setCaretLine: (line: number) => void, insertText: (text: string) => void, forceToFocus: () => void, terminateUploadingState: () => void, } type Props = { appContainer: AppContainer, pageContainer: PageContainer, editorContainer: EditorContainer, isEditable: boolean, editorMode: string, isSlackEnabled: boolean, slackChannels: string, isMobile?: boolean, grant: number, grantGroupId?: string, grantGroupName?: string, mutateGrant: (grant: number) => void, isTextlintEnabled?: boolean, isIndentSizeForced?: boolean, indentSize?: number, mutateCurrentIndentSize: (indent: number) => void, }; // for scrolling let lastScrolledDateWithCursor: Date | null = null; let isOriginOfScrollSyncEditor = false; let isOriginOfScrollSyncPreview = false; const PageEditor = (props: Props): JSX.Element => { const { appContainer, pageContainer, editorContainer, } = props; const { data: isEditable } = useIsEditable(); const { data: editorMode } = useEditorMode(); const { data: isMobile } = useIsMobile(); const { data: isSlackEnabled } = useIsSlackEnabled(); const { data: currentPagePath } = useCurrentPagePath(); const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath); const { data: grant, mutate: mutateGrant } = useSelectedGrant(); const { data: grantGroupId } = useSelectedGrantGroupId(); const { data: grantGroupName } = useSelectedGrantGroupName(); const { data: isTextlintEnabled } = useIsTextlintEnabled(); const { data: isIndentSizeForced } = useIsIndentSizeForced(); const { data: indentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const [markdown, setMarkdown] = useState<string>(pageContainer.state.markdown!); const editorRef = useRef<EditorRef>(null); const previewRef = useRef<HTMLDivElement>(null); const setMarkdownWithDebounce = useMemo(() => debounce(50, throttle(100, value => setMarkdown(value))), []); const saveDraftWithDebounce = useMemo(() => debounce(800, () => { editorContainer.saveDraft(pageContainer.state.path, markdown); }), [editorContainer, markdown, pageContainer.state.path]); const markdownChangedHandler = useCallback((value: string): void => { setMarkdownWithDebounce(value); // only when the first time to edit if (!pageContainer.state.revisionId) { saveDraftWithDebounce(); } }, [pageContainer.state.revisionId, saveDraftWithDebounce, setMarkdownWithDebounce]); const saveWithShortcut = useCallback(async() => { if (grant == null) { return; } const slackChannels = slackChannelsData ? slackChannelsData.toString() : ''; const optionsToSave = getOptionsToSave(isSlackEnabled ?? false, slackChannels, grant, grantGroupId, grantGroupName, editorContainer); try { // disable unsaved warning editorContainer.disableUnsavedWarning(); // eslint-disable-next-line no-unused-vars const { tags } = await pageContainer.save(markdown, editorMode, optionsToSave); logger.debug('success to save'); pageContainer.showSuccessToastr(); // update state of EditorContainer editorContainer.setState({ tags }); } catch (error) { logger.error('failed to save', error); pageContainer.showErrorToastr(error); } }, [editorContainer, editorMode, grant, grantGroupId, grantGroupName, isSlackEnabled, slackChannelsData, markdown, pageContainer]); /** * the upload event handler * @param {any} file */ const uploadHandler = useCallback(async(file) => { if (editorRef.current == null) { return; } try { // eslint-disable-next-line @typescript-eslint/no-explicit-any let res: any = await apiGet('/attachments.limit', { fileSize: file.size, }); if (!res.isUploadable) { throw new Error(res.errorMessage); } const formData = new FormData(); const { pageId, path } = pageContainer.state; formData.append('file', file); if (path != null) { formData.append('path', path); } if (pageId != null) { formData.append('page_id', pageId); } res = await apiPostForm('/attachments.add', formData); const attachment = res.attachment; const fileName = attachment.originalName; let insertText = `[${fileName}](${attachment.filePathProxied})`; // when image if (attachment.fileFormat.startsWith('image/')) { // modify to "![fileName](url)" syntax insertText = `!${insertText}`; } editorRef.current.insertText(insertText); // when if created newly if (res.pageCreated) { logger.info('Page is created', res.page._id); pageContainer.updateStateAfterSave(res.page, res.tags, res.revision, editorMode); mutateGrant(res.page.grant); } } catch (e) { logger.error('failed to upload', e); pageContainer.showErrorToastr(e); } finally { editorRef.current.terminateUploadingState(); } }, [editorMode, mutateGrant, pageContainer]); const scrollPreviewByEditorLine = useCallback((line: number) => { if (previewRef.current == null) { return; } // prevent circular invocation if (isOriginOfScrollSyncPreview) { isOriginOfScrollSyncPreview = false; // turn off the flag return; } // turn on the flag isOriginOfScrollSyncEditor = true; scrollSyncHelper.scrollPreview(previewRef.current, line); }, []); const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]); /** * the scroll event handler from codemirror * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position, * the size of the scrollable area, and the size of the visible area (minus scrollbars). * And data.line is also available that is added by Editor component * @see https://codemirror.net/doc/manual.html#events */ const editorScrolledHandler = useCallback(({ line }: { line: number }) => { // prevent scrolling // if the elapsed time from last scroll with cursor is shorter than 40ms const now = new Date(); if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) { return; } scrollPreviewByEditorLineWithThrottle(line); }, [scrollPreviewByEditorLineWithThrottle]); /** * scroll Preview element by cursor moving * @param {number} line */ const scrollPreviewByCursorMoving = useCallback((line: number) => { if (previewRef.current == null) { return; } // prevent circular invocation if (isOriginOfScrollSyncPreview) { isOriginOfScrollSyncPreview = false; // turn off the flag return; } // turn on the flag isOriginOfScrollSyncEditor = true; scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line); }, []); const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]); /** * the scroll event handler from codemirror * @param {number} line * @see https://codemirror.net/doc/manual.html#events */ const editorScrollCursorIntoViewHandler = useCallback((line: number) => { // record date lastScrolledDateWithCursor = new Date(); scrollPreviewByCursorMovingWithThrottle(line); }, [scrollPreviewByCursorMovingWithThrottle]); /** * scroll Editor component by scroll event of Preview component * @param {number} offset */ const scrollEditorByPreviewScroll = useCallback((offset: number) => { if (editorRef.current == null || previewRef.current == null) { return; } // prevent circular invocation if (isOriginOfScrollSyncEditor) { isOriginOfScrollSyncEditor = false; // turn off the flag return; } // turn on the flag // eslint-disable-next-line @typescript-eslint/no-unused-vars isOriginOfScrollSyncPreview = true; scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset); }, []); const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]); // register dummy instance to get markdown useEffect(() => { const pageEditorInstance = { getMarkdown: () => { return markdown; }, }; appContainer.registerComponentInstance('PageEditor', pageEditorInstance); }, [appContainer, markdown]); // initial caret line useEffect(() => { if (editorRef.current != null) { editorRef.current.setCaretLine(0); } }, []); // set handler to set caret line useEffect(() => { const handler = (line) => { if (editorRef.current != null) { editorRef.current.setCaretLine(line); } if (previewRef.current != null) { scrollSyncHelper.scrollPreview(previewRef.current, line); } }; globalEmitter.on('setCaretLine', handler); return function cleanup() { globalEmitter.removeListener('setCaretLine', handler); }; }, []); // set handler to focus useEffect(() => { if (editorRef.current != null && editorMode === EditorMode.Editor) { editorRef.current.forceToFocus(); } }, [editorMode]); // set handler to update editor value useEffect(() => { const handler = (markdown) => { if (editorRef.current != null) { editorRef.current.setValue(markdown); } }; globalEmitter.on('updateEditorValue', handler); return function cleanup() { globalEmitter.removeListener('updateEditorValue', handler); }; }, []); // Displays an alert if there is a difference with pageContainer's markdown useEffect(() => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (pageContainer.state.markdown! !== markdown) { editorContainer.enableUnsavedWarning(); } }, [editorContainer, markdown, pageContainer.state.markdown]); // Detect indent size from contents (only when users are allowed to change it) useEffect(() => { const currentPageMarkdown = pageContainer.state.markdown; if (!isIndentSizeForced && currentPageMarkdown != null) { const detectedIndent = detectIndent(currentPageMarkdown); if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) { mutateCurrentIndentSize(detectedIndent.amount); } } }, [isIndentSizeForced, mutateCurrentIndentSize, pageContainer.state.markdown]); if (!isEditable) { return <></>; } const config = props.appContainer.getConfig(); const isUploadable = config.upload.image || config.upload.file; const isUploadableFile = config.upload.file; const isMathJaxEnabled = !!config.env.MATHJAX; const noCdn = envUtils.toBoolean(config.env.NO_CDN); // TODO: omit no-explicit-any -- 2022.06.02 Yuki Takei // It is impossible to avoid the error // "Property '...' does not exist on type 'IntrinsicAttributes & RefAttributes<any>'" // because Editor is a class component and must be wrapped with React.forwardRef // eslint-disable-next-line @typescript-eslint/no-explicit-any const EditorAny = Editor as any; return ( <div className="d-flex flex-wrap"> <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0"> <EditorAny ref={editorRef} value={markdown} noCdn={noCdn} isMobile={isMobile} isUploadable={isUploadable} isUploadableFile={isUploadableFile} isTextlintEnabled={isTextlintEnabled} indentSize={indentSize} onScroll={editorScrolledHandler} onScrollCursorIntoView={editorScrollCursorIntoViewHandler} onChange={markdownChangedHandler} onUpload={uploadHandler} onSave={() => saveWithShortcut()} /> </div> <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0"> <Preview markdown={markdown} // eslint-disable-next-line no-return-assign inputRef={previewRef} isMathJaxEnabled={isMathJaxEnabled} renderMathJaxOnInit={false} onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)} /> </div> <ConflictDiffModal isOpen={pageContainer.state.isConflictDiffModalOpen} onClose={() => pageContainer.setState({ isConflictDiffModalOpen: false })} pageContainer={pageContainer} markdownOnEdit={markdown} /> </div> ); }; /** * Wrapper component for using unstated */ const PageEditorWrapper = withUnstatedContainers(PageEditor, [AppContainer, PageContainer, EditorContainer]); export default PageEditorWrapper;
the_stack
import { BurnAndReleaseParams, DepositCommon, LockAndMintParams, LockChain, Logger, LogLevel, MintChain, RenNetwork, RenNetworkDetails, RenNetworkString, SimpleLogger, } from "@renproject/interfaces"; import { AbstractRenVMProvider, CombinedProvider } from "@renproject/rpc"; import { RenVMProvider } from "@renproject/rpc/build/main/v2"; import { fromSmallestUnit, randomNonce, toSmallestUnit, } from "@renproject/utils"; import BigNumber from "bignumber.js"; import { BurnAndRelease } from "./burnAndRelease"; import { RenJSConfig } from "./config"; import { defaultDepositHandler } from "./defaultDepositHandler"; import { LockAndMint, DepositStatus, LockAndMintDeposit } from "./lockAndMint"; export { BurnAndRelease } from "./burnAndRelease"; export { LockAndMint, DepositStatus, LockAndMintDeposit } from "./lockAndMint"; /** * This is the main exported class from `@renproject/ren`. * * ```typescript * import RenJS from "@renproject/ren"; * ``` * * By default, RenJS will connect to the RenVM mainnet network. To connect * to `testnet` or to configure a custom connection, RenJS takes an optional * provider object. See the [[constructor]] for more details. * * ```typescript * new RenJS(); // Same as `new RenJS("mainnet");` * new RenJS("testnet"); * new RenJS(custom provider object); * ``` * * It then exposes two main functions: * 1. [[lockAndMint]] - for transferring assets to Ethereum. * 2. [[burnAndRelease]] - for transferring assets out of Ethereum. * * Also see: * 1. [[getFees]] - for estimating the fees that will be incurred by minting or * burning. * 2. [[defaultDepositHandler]] * */ export default class RenJS { // /** // * [STATIC] `Tokens` exposes the tokens that can be passed in to the lockAndMint and // * burnAndRelease methods. // */ // public static Tokens = Tokens; /** * `Networks` exposes the network options that can be passed in to the RenJS * constructor. `Networks.Mainnet` resolves to the string `"mainnet"`. */ public static Networks = RenNetwork; /** * A collection of helper functions. [[utils.randomNonce]] can be be used to * generate a nonce when calling [[RenJS.lockAndMint]]. */ public static utils = { randomNonce, toSmallestUnit, fromSmallestUnit, fromAscii: (str: string) => Buffer.from(str), }; /** * `RenJS.defaultDepositHandler` can be passed as a deposit callback when * minting. It will handle submitting to RenVM and then to the mint-chain, * as long as a valid provider for the mint-chain is given. * * This is not recommended for front-ends, since it may trigger a wallet * pop-up unexpectedly when the mint is ready to be submitted. * * ```ts * lockAndMint.on("deposit", RenJS.defaultDepositHandler); * ``` */ public static defaultDepositHandler = defaultDepositHandler; /** * @hidden */ public readonly utils = RenJS.utils; /** * RenVM provider exposing `sendMessage` and other helper functions for * interacting with RenVM. See [[AbstractRenVMProvider]]. * * ```ts * renJS.renVM.sendMessage("ren_queryNumPeers", {}); * ``` */ public readonly renVM: AbstractRenVMProvider; private readonly _logger: Logger; private readonly _config: RenJSConfig; /** * Accepts the name of a network, or a network object. * * @param network Provide the name of a network - `"mainnet"` or `"testnet"` - or a network object. * @param providerOrConfig Provide a custom RPC provider, or provide RenJS configuration settings. */ constructor( providerOrNetwork?: | RenNetwork | RenNetworkString | RenNetworkDetails | AbstractRenVMProvider | null | undefined, config?: RenJSConfig, ) { // const provider: string | Provider | undefined; // let config: RenJSConfig | undefined; // if ( // providerOrConfig && // (typeof providerOrConfig === "string" || // (providerOrConfig as Provider).sendMessage) // ) { // provider = providerOrConfig as string | Provider; // } else if (providerOrConfig) { // config = providerOrConfig as RenJSConfig; // } this._config = config || {}; this._logger = (config && config.logger) || new SimpleLogger((config && config.logLevel) || LogLevel.Error); this._config.logger = this._logger; const defaultProvider = () => config && config.useV2TransactionFormat ? new RenVMProvider( // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion (providerOrNetwork || RenNetwork.Mainnet) as | RenNetwork | RenNetworkString | RenNetworkDetails, undefined, this._logger, ) : new CombinedProvider( // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion (providerOrNetwork || RenNetwork.Mainnet) as | RenNetwork | RenNetworkString | RenNetworkDetails, this._logger, ); // Use provided provider, provider URL or default lightnode URL. this.renVM = providerOrNetwork && typeof providerOrNetwork !== "string" && (providerOrNetwork as AbstractRenVMProvider).sendMessage ? (providerOrNetwork as AbstractRenVMProvider) : defaultProvider(); } public getFees = async ({ asset, from, to, }: { asset: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any from: LockChain<any, any, any> | MintChain<any, any>; // eslint-disable-next-line @typescript-eslint/no-explicit-any to: LockChain<any, any, any> | MintChain<any, any>; }): Promise<{ lock?: BigNumber; release?: BigNumber; mint: number; burn: number; }> => { if (!(await from.assetIsSupported(asset))) { throw new Error(`Asset not supported by chain ${from.name}.`); } if (!(await to.assetIsSupported(asset))) { throw new Error(`Asset not supported by chain ${to.name}.`); } if (await from.assetIsNative(asset)) { // LockAndMint return await this.renVM.estimateTransactionFee(asset, from, to); } else if (await to.assetIsNative(asset)) { // BurnAndRelease return await this.renVM.estimateTransactionFee(asset, to, from); } else { // BurnAndMint return await this.renVM.estimateTransactionFee(asset, from, to); } }; /** * `lockAndMint` initiates the process of bridging an asset from its native * chain to a host chain. * * See [[LockAndMintParams]] for all the options that can be set. * * Returns a [[LockAndMint]] object. * * Example initialization: * * ```js * const lockAndMint = renJS.lockAndMint({ * asset: "BTC", * from: Bitcoin(), * to: Ethereum(web3Provider).Account({ * address: "0x...", * }), * }); * ``` * * @param params See [[LockAndMintParams]]. */ public readonly lockAndMint = async < // eslint-disable-next-line @typescript-eslint/no-explicit-any Transaction = any, Deposit extends DepositCommon<Transaction> = DepositCommon<Transaction>, // eslint-disable-next-line @typescript-eslint/no-explicit-any Address extends string | { address: string } = any, >( params: LockAndMintParams<Transaction, Deposit, Address>, config?: RenJSConfig, ): Promise<LockAndMint<Transaction, Deposit, Address>> => new LockAndMint<Transaction, Deposit, Address>(this.renVM, params, { ...this._config, ...config, })._initialize(); /** * `burnAndRelease` submits a burn log to RenVM. * Returns a [[BurnAndRelease]] object. */ public readonly burnAndRelease = async < // eslint-disable-next-line @typescript-eslint/no-explicit-any Transaction = any, Deposit extends DepositCommon<Transaction> = DepositCommon<Transaction>, // eslint-disable-next-line @typescript-eslint/no-explicit-any Address extends string | { address: string } = any, >( params: BurnAndReleaseParams<Transaction, Deposit, Address>, config?: RenJSConfig, ): Promise<BurnAndRelease<Transaction, Deposit, Address>> => new BurnAndRelease<Transaction, Deposit, Address>(this.renVM, params, { ...this._config, ...config, })._initialize(); } // ////////////////////////////////////////////////////////////////////////// // // EXPORTS // // Based on https://github.com/MikeMcl/bignumber.js/blob/master/bignumber.js // // ////////////////////////////////////////////////////////////////////////// // /* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-explicit-any */ (RenJS as any).default = (RenJS as any).RenJS = RenJS; (RenJS as any).LockAndMint = LockAndMint; (RenJS as any).BurnAndRelease = BurnAndRelease; (RenJS as any).DepositStatus = DepositStatus; (RenJS as any).LockAndMintDeposit = LockAndMintDeposit; // AMD try { // @ts-ignore if (typeof define === "function" && define.amd) { // @ts-ignore define(() => RenJS); } } catch (error) { /* ignore */ } // Node.js and other environments that support module.exports. try { // @ts-ignore if (typeof module !== "undefined" && module.exports) { module.exports = RenJS; } } catch (error) { /* ignore */ } // Browser. try { // @ts-ignore if (typeof window !== "undefined" && window) { (window as any).RenJS = RenJS; } } catch (error) { /* ignore */ }
the_stack
import { dialog, shell } from "electron"; import * as fs from "fs"; import { injectable } from "inversify"; import * as path from "path"; import { acceptedExtensionObject } from "readium-desktop/common/extension"; import { File } from "readium-desktop/common/models/file"; import { PublicationView } from "readium-desktop/common/views/publication"; import { ContentType } from "readium-desktop/utils/contentType"; import { getFileSize, rmDirSync } from "readium-desktop/utils/fs"; import slugify from "slugify"; import { PublicationParsePromise } from "@r2-shared-js/parser/publication-parser"; import { streamToBufferPromise } from "@r2-utils-js/_utils/stream/BufferUtils"; import { IZip } from "@r2-utils-js/_utils/zip/zip.d"; import * as debug_ from "debug"; const debug = debug_("readium-desktop:main/storage/pub-storage"); // Store pubs in a repository on filesystem // Each file of publication is stored in a directory whose name is the // publication uuid // repository // |- <publication 1 uuid> // |- epub file // |- cover file // |- <publication 2 uuid> @injectable() export class PublicationStorage { private rootPath: string; public constructor(rootPath: string) { this.rootPath = rootPath; } public getRootPath() { return this.rootPath; } /** * Store a publication in a repository * * @param identifier Identifier of publication * @param srcPath Path of epub/audiobook to import * @return List of all stored files */ public async storePublication( identifier: string, srcPath: string, ): Promise<File[]> { // Create a directory whose name is equals to publication identifier const pubDirPath = this.buildPublicationPath(identifier); fs.mkdirSync(pubDirPath); const files: File[] = []; const bookFile = await this.storePublicationBook( identifier, srcPath); files.push(bookFile); const coverFile = await this.storePublicationCover( identifier, srcPath); if (coverFile) { files.push(coverFile); } return files; } public removePublication(identifier: string, preservePublicationOnFileSystem?: string) { const p = this.buildPublicationPath(identifier); try { if (preservePublicationOnFileSystem) { const log = path.join(p, "error.txt"); fs.writeFileSync(log, preservePublicationOnFileSystem, { encoding: "utf-8" }); shell.showItemInFolder(log); // const parent = path.dirname(p) + "_REMOVED"; // if (!fs.existsSync(parent)) { // fs.mkdirSync(parent); // } // setTimeout(async () => { // await shell.openPath(parent); // }, 0); // shell.showItemInFolder(parent); // const f = path.basename(p); // const n = path.join(parent, f); // shell.showItemInFolder(n); return; } rmDirSync(p); } catch (e) { debug(e); debug(preservePublicationOnFileSystem); debug(`removePublication error (ignore) ${identifier} ${p}`); } } // TODO: fs.existsSync() is really costly, // TODO : A disaster ! :) // and getPublicationEpubPath() is called many times! public getPublicationEpubPath(identifier: string): string { const root = this.buildPublicationPath(identifier); // -- const pathEpub = path.join( root, `book${acceptedExtensionObject.epub}`, ); if (fs.existsSync(pathEpub)) { return pathEpub; } // -- const pathWebpub = path.join( root, `book${acceptedExtensionObject.webpub}`, ); if (fs.existsSync(pathWebpub)) { return pathWebpub; } // -- const pathAudioBook = path.join( root, `book${acceptedExtensionObject.audiobook}`, ); if (fs.existsSync(pathAudioBook)) { return pathAudioBook; } // -- const pathAudioBookLcp = path.join( root, `book${acceptedExtensionObject.audiobookLcp}`, ); if (fs.existsSync(pathAudioBookLcp)) { return pathAudioBookLcp; } // -- const pathAudioBookLcpAlt = path.join( root, `book${acceptedExtensionObject.audiobookLcpAlt}`, ); if (fs.existsSync(pathAudioBookLcpAlt)) { return pathAudioBookLcpAlt; } // -- const pathDivina = path.join( root, `book${acceptedExtensionObject.divina}`, ); if (fs.existsSync(pathDivina)) { return pathDivina; } // -- const pathLcpPdf = path.join( root, `book${acceptedExtensionObject.pdfLcp}`, ); if (fs.existsSync(pathLcpPdf)) { return pathLcpPdf; } // -- const pathEpub3 = path.join( root, `book${acceptedExtensionObject.epub3}`, ); if (fs.existsSync(pathEpub3)) { return pathEpub3; } // -- const pathDaisy = path.join( root, `book${acceptedExtensionObject.daisy}`, ); if (fs.existsSync(pathDaisy)) { return pathDaisy; } // -- throw new Error(`getPublicationEpubPath() FAIL ${identifier} (cannot find book.epub|audiobook|etc.)`); } public copyPublicationToPath(publicationView: PublicationView, destinationPath: string) { const publicationPath = this.getPublicationEpubPath(publicationView.identifier); const extension = path.extname(publicationPath); const newFilePath = `${destinationPath}/${slugify(publicationView.title)}${extension}`; fs.copyFile(publicationPath, newFilePath, async (err) => { if (err) { await dialog.showMessageBox({ type: "error", message: err.message, title: err.name, buttons: ["OK"], }); } }); } public buildPublicationPath(identifier: string): string { return path.join(this.rootPath, identifier); } private async storePublicationBook( identifier: string, srcPath: string, ): Promise<File> { const extension = path.extname(srcPath); const isAudioBook = new RegExp(`\\${acceptedExtensionObject.audiobook}$`).test(extension); const isAudioBookLcp = new RegExp(`\\${acceptedExtensionObject.audiobookLcp}$`).test(extension); const isAudioBookLcpAlt = new RegExp(`\\${acceptedExtensionObject.audiobookLcpAlt}$`).test(extension); const isWebpub = new RegExp(`\\${acceptedExtensionObject.webpub}$`).test(extension); const isDivina = new RegExp(`\\${acceptedExtensionObject.divina}$`).test(extension); const isLcpPdf = new RegExp(`\\${acceptedExtensionObject.pdfLcp}$`).test(extension); const isDaisy = new RegExp(`\\${acceptedExtensionObject.daisy}$`).test(extension); const ext = isAudioBook ? acceptedExtensionObject.audiobook : ( isAudioBookLcp ? acceptedExtensionObject.audiobookLcp : ( isAudioBookLcpAlt ? acceptedExtensionObject.audiobookLcpAlt : ( isDivina ? acceptedExtensionObject.divina : ( isWebpub ? acceptedExtensionObject.webpub : ( isLcpPdf ? acceptedExtensionObject.pdfLcp : ( isDaisy ? acceptedExtensionObject.daisy : acceptedExtensionObject.epub ) ) ) ) ) ); const filename = `book${ext}`; const dstPath = path.join( this.buildPublicationPath(identifier), filename, ); return new Promise<File>((resolve, _reject) => { const writeStream = fs.createWriteStream(dstPath); const fileResolve = () => { resolve({ url: `store://${identifier}/${filename}`, ext, contentType: isAudioBook ? ContentType.AudioBookPacked : ( (isAudioBookLcp || isAudioBookLcpAlt) ? ContentType.AudioBookPackedLcp : isDivina ? ContentType.DivinaPacked : isWebpub ? ContentType.webpubPacked : isLcpPdf ? ContentType.lcppdf : ContentType.Epub ), size: getFileSize(dstPath), }); }; writeStream.on("finish", fileResolve); fs.createReadStream(srcPath).pipe(writeStream); }); } // Extract the image cover buffer then create a file on the publication folder private async storePublicationCover( identifier: string, srcPath: string, ): Promise<File> { let r2Publication; try { r2Publication = await PublicationParsePromise(srcPath); } catch (err) { console.log(err); return null; } // private Internal is very hacky! :( const zipInternal = (r2Publication as any).Internal.find((i: any) => { if (i.Name === "zip") { return true; } return false; }); const zip = zipInternal.Value as IZip; const coverLink = r2Publication.GetCover(); if (!coverLink) { // after PublicationParsePromise, cleanup zip handler r2Publication.freeDestroy(); return null; } const coverType: string = coverLink.TypeLink; const zipStream = await zip.entryStreamPromise(coverLink.Href); const zipBuffer = await streamToBufferPromise(zipStream.stream); // after PublicationParsePromise, cleanup zip handler r2Publication.freeDestroy(); // Remove start dot in extensoion const coverExt = path.extname(coverLink.Href).slice(1); const coverFilename = "cover." + coverExt; const coverDstPath = path.join( this.buildPublicationPath(identifier), coverFilename, ); // Write cover to fs fs.writeFileSync(coverDstPath, zipBuffer); // Return cover file information return { url: `store://${identifier}/${coverFilename}`, ext: coverExt, contentType: coverType, size: getFileSize(coverDstPath), }; } }
the_stack
import {Constants} from "../constants"; import {PromiseUtils} from "../promiseUtils"; import {Settings} from "../settings"; import {StringUtils} from "../stringUtils"; import {UserInfo} from "../userInfo"; import {Clipper} from "../clipperUI/frontEndGlobals"; import {ClipperStorageKeys} from "../storage/clipperStorageKeys"; import * as Log from "../logging/log"; import {OneNoteApiWithLogging} from "./oneNoteApiWithLogging"; import {OneNoteApiWithRetries} from "./oneNoteApiWithRetries"; import {OneNoteSaveable} from "./oneNoteSaveable"; import * as _ from "lodash"; export interface SaveToOneNoteOptions { page: OneNoteSaveable; saveLocation?: string; progressCallback?: (num: number, denom: number) => void; } /** * Solely responsible for saving the user's OneNote pages */ export class SaveToOneNote { private static timeBeforeFirstPatch = 1000; private static timeBetweenPatchRequests = 7000; private static timeBeforeFirstBatch = 1000; private static timeBetweenBatchRequests = 7000; private static timeBeforeFirstPost = 1000; private static timeBetweenPostRequests = 0; private accessToken: string; constructor(accessToken: string) { this.accessToken = accessToken; } /** * Saves a page (and if necessary, appends PATCHES) to OneNote */ public save(options: SaveToOneNoteOptions): Promise<OneNoteApi.ResponsePackage<any>> { if (options.page.getNumPages() > 1) { return this.saveMultiplePagesSynchronously(options); } else { if (options.page.getNumPatches() > 0) { return this.rejectIfNoPatchPermissions(options.saveLocation).then(() => { return this.saveWithoutCheckingPatchPermissions(options); }); } else { return this.saveWithoutCheckingPatchPermissions(options); } } } private saveMultiplePagesSynchronously(options: SaveToOneNoteOptions) { let progressCallback = options.progressCallback ? options.progressCallback : () => { }; progressCallback(0, options.page.getNumPages()); return options.page.getPage().then((page) => { return this.getApi().createPage(page, options.saveLocation).then((responsePackage) => { return this.synchronouslyCreateMultiplePages(options, progressCallback).then(() => { return Promise.resolve(responsePackage); }); }); }); } private synchronouslyCreateMultiplePages(options: SaveToOneNoteOptions, progressCallback: (completed: number, total: number) => void = () => {}): Promise<any> { const saveable = options.page; const end = saveable.getNumPages(); // We start the range at 1 since we have already included the first page return _.range(1, end).reduce((chainedPromise, i) => { return chainedPromise = chainedPromise.then(() => { return new Promise((resolve, reject) => { // Parallelize the POST request intervals with the fetching of current dataUrl let getPagePromise = this.getPageWithLogging(saveable, i); let timeoutPromise = PromiseUtils.wait(SaveToOneNote.timeBetweenPostRequests); Promise.all([getPagePromise, timeoutPromise]).then((values) => { let page = values[0] as OneNoteApi.OneNotePage; this.getApi().createPage(page, options.saveLocation).then(() => { progressCallback(i, end); resolve(); }).catch((error) => { reject(error); }); }); }); }); }, Promise.resolve()); } private rejectIfNoPatchPermissions(saveLocation: string): Promise<void> { return new Promise<void>((resolve, reject) => { Clipper.getStoredValue(ClipperStorageKeys.hasPatchPermissions, (hasPermissions) => { // We have checked their permissions successfully in the past, or the user signed in on this device (with the latest scope) if (hasPermissions) { resolve(); } else { // As of v3.2.9, we have added a new scope for MSA to allow for PATCHing, however currently-logged-in users will not have // this scope, so this call is a workaround to check for permissions, but is very unperformant. We need to investigate a // quicker way of doing this ... perhaps exposing an endpoint that we can use for this sole purpose. this.getApi().getPages({ top: 1, sectionId: saveLocation }).then(() => { Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); resolve(); }).catch((error) => { reject(error); }); } }); }); } private saveWithoutCheckingPatchPermissions(options: SaveToOneNoteOptions): Promise<OneNoteApi.ResponsePackage<any>> { // options.page is a misnomer, as its the saveable, not a specific page return options.page.getPage().then((page) => { return this.getApi().createPage(page, options.saveLocation).then((responsePackage) => { if (options.page.getNumPatches() > 0) { let pageId = responsePackage.parsedResponse.id; return this.patch(pageId, options.page).then(() => { return Promise.resolve(responsePackage); }); } else if (options.page.getNumBatches() > 0) { return this.batch(options.page).then(() => { return Promise.resolve(responsePackage); }); } else { return Promise.resolve(responsePackage); } }); }); } private batch(saveable: OneNoteSaveable): Promise<any> { let timeBetweenBatchRequests = SaveToOneNote.timeBeforeFirstBatch; return _.range(saveable.getNumBatches()).reduce((chainedPromise, i) => { return chainedPromise = chainedPromise.then(() => { return new Promise((resolve, reject) => { // Parallelize the BATCH request intervals with the fetching of the next set of dataUrls let getRevisionsPromise = this.getBatchWithLogging(saveable, i); let timeoutPromise = PromiseUtils.wait(timeBetweenBatchRequests); Promise.all([getRevisionsPromise, timeoutPromise]).then((values) => { let batchRequest = values[0] as OneNoteApi.BatchRequest; this.getApi().sendBatchRequest(batchRequest).then(() => { resolve(); }).catch((error) => { reject(error); }); }); }); }); }, Promise.resolve()); } private patch(pageId: string, saveable: OneNoteSaveable): Promise<any> { // As of 10/27/16, the page is not always ready when the 200 is returned, so we wait a bit, and then getPageContent with retries // When the getPageContent returns a 200, we start PATCHing the page. let timeBetweenPatchRequests = SaveToOneNote.timeBeforeFirstPatch; return Promise.all([ _.range(saveable.getNumPatches()).reduce((chainedPromise, i) => { return chainedPromise = chainedPromise.then(() => { return new Promise((resolve, reject) => { // OneNote API returns 204 on a PATCH request when it receives it, but we have no way of telling when it actually // completes processing, so we add an artificial timeout before the next PATCH to try and ensure that they get // processed in the order that they were sent. // Parallelize the PATCH request intervals with the fetching of the next set of dataUrls let getRevisionsPromise = this.getPatchWithLogging(saveable, i); let timeoutPromise = PromiseUtils.wait(timeBetweenPatchRequests); Promise.all([getRevisionsPromise, timeoutPromise]).then((values) => { let revisions = values[0] as OneNoteApi.Revision[]; let thenCb = () => { timeBetweenPatchRequests = SaveToOneNote.timeBetweenPatchRequests; resolve(); }; let catchCb = (error: OneNoteApi.RequestError) => { if (error.statusCode === 401) { // The clip has taken a really long time and the user token has expired Clipper.getExtensionCommunicator().callRemoteFunction(Constants.FunctionKeys.ensureFreshUserBeforeClip, { callback: (updatedUser: UserInfo) => { if (updatedUser.user.accessToken) { // Try again with the new token this.accessToken = updatedUser.user.accessToken; this.updatePage(pageId, revisions, thenCb, catchCb); } else { reject(error); } } }); } else { reject(error); } }; this.updatePage(pageId, revisions, thenCb, catchCb); }); }); }); }, this.getApi().getPageContent(pageId)) // Check if page exists with retries ]); } private updatePage(pageId: string, revisions: OneNoteApi.Revision[], thenCb: () => void, catchCb: (error: OneNoteApi.RequestError) => void) { this.getApi().updatePage(pageId, revisions) .then(thenCb) .catch(catchCb); } // We try not and put logging logic in this class, but since we lazy-load images, this has to be an exception private getPatchWithLogging(saveable: OneNoteSaveable, index: number): Promise<OneNoteApi.Revision[]> { let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls); return saveable.getPatch(index).then((revisions: OneNoteApi.Revision[]) => { event.stopTimer(); let numPages = revisions.length; event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages); if (revisions.length > 0) { // There's some html in the content itself, but it's negligible compared to the length of the actual dataUrls let lengthOfDataUrls = _.sumBy(revisions, (revision) => { return revision.content.length; }); event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls); event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages); event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages); } Clipper.logger.logEvent(event); return Promise.resolve(revisions); }); } private getPageWithLogging(saveable: OneNoteSaveable, index: number) { let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls); return saveable.getPage(index).then((page: OneNoteApi.OneNotePage) => { event.stopTimer(); const numPages = 1; event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages); let lengthOfDataUrls = page.getEntireOnml().length; event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls); event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages); event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages); Clipper.logger.logEvent(event); return Promise.resolve(page); }); } private getBatchWithLogging(saveable: OneNoteSaveable, index: number): Promise<OneNoteApi.BatchRequest> { let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls); return saveable.getBatch(index).then((batchRequest: OneNoteApi.BatchRequest) => { event.stopTimer(); let numPages = batchRequest.getNumOperations(); event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages); if (numPages > 0) { // There's some html in the content itself, but it's negligible compared to the length of the actual dataUrls const batchRequestOperations = _.range(numPages).map((pageNumber) => { return batchRequest.getOperation(pageNumber); }); const lengthOfDataUrls = _.sumBy(batchRequestOperations, (op) => { return op.content.length; }); event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls); event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages); event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages); } Clipper.logger.logEvent(event); return Promise.resolve(batchRequest); }); } /** * We set the correlation id each time this gets called. When using this, make sure you are not reusing * the same object unless it's your intention to have their API calls use the same correlation id. */ private getApi(): OneNoteApi.IOneNoteApi { let headers: { [key: string]: string } = {}; headers[Constants.HeaderValues.appIdKey] = Settings.getSetting("App_Id"); headers[Constants.HeaderValues.userSessionIdKey] = Clipper.getUserSessionId(); let api = new OneNoteApi.OneNoteApi(this.accessToken, undefined /* timeout */, headers); let apiWithRetries = new OneNoteApiWithRetries(api); return new OneNoteApiWithLogging(apiWithRetries); } }
the_stack
import {CategoryControlProvider, CategoryControlProviderLogLevel} from "../api/CategoryControlProvider"; import {LogId, LogLevel, util} from "typescript-logging"; import {CATEGORY_PATH_SEPARATOR, CategoryProviderImpl} from "./CategoryProviderImpl"; import {Category} from "../api/Category"; /** * Implementation of the CategoryControlProvider. */ export class CategoryControlProviderImpl implements CategoryControlProvider { private readonly _provider: CategoryProviderImpl; private readonly _messageChannel: (msg: string) => void; /** Tracks the original log levels for all categories when they were created, updated only in reset() */ private _originalLogLevels: Map<LogId, LogLevel>; public constructor(provider: CategoryProviderImpl, messageChannel: (msg: string) => void) { this._provider = provider; this._messageChannel = messageChannel; this._originalLogLevels = CategoryControlProviderImpl.loadCurrentGroupLogLevels(provider); } public get name() { return this._provider.name; } /** * Shows current settings. */ public showSettings(): void { /* We create this kind of output: Available categories (CategoryProvider 'test'): [0, root level=Error] [1, - child1 level=Warn ] [2, - my awesome child level=Error] [3, - another child level=Error] [4, anotherRoot level=Error] [5, - child x level=Error] */ let result = `Available categories (CategoryProvider '${this._provider.name}'):\n`; const categories = this.createCategoryInfoHierarchy(); const maxWidthIndex = categories.size.toString().length; /* Note depth means on how deeply nested a child is, each depth is multiplied by 1 spaces (length) */ const maxWidthIdentifier = util.maxLengthStringValueInArray([...categories.values()].map(value => value.category.name + " ".repeat(value.depth))); const providerLines = [...categories.values()] .map((category, idx) => CategoryControlProviderImpl.createSettingLineCategory(category, idx, maxWidthIndex, maxWidthIdentifier)); result += providerLines.join("\n") + (providerLines.length > 0 ? "\n" : ""); this._messageChannel(result); } public help(): void { const msg = `You can use the following commands (CategoryProvider ${this._provider.name}):\n` + " showSettings()\n" + " Shows the current configuration settings.\n" + " update(level: CategoryControlProviderLogLevel, categoryId?: number | string, noRecurse?: boolean)\n" + " Change the log level for a category (by default recursively).\n" + " @param level The log level to set - must be one of 'trace', 'debug', 'info', 'warn', 'error' or 'fatal'\n" + " @param categoryId The category id or path of a category (e.g. root#child1) to update. Use showSettings() for id and/or name.\n" + " When omitted, it applies the level to all categories recursively.\n" + " reset()\n" + " Resets the log levels of the config groups back to when this control provider was created.\n" + " save()\n" + " Saves the current log levels for all categories of this provider. Use restore() to load last saved state.\n" + " restore()\n" + " Restore stored saved state, if any. Log levels will be set according to the saved state.\n" + " help()\n" + " Shows this help.\n"; this._messageChannel(msg); } public reset(): void { const currentCategories = new Map<LogId, Category>(this._provider.getRegisteredCategories().map(cat => [cat.id, cat])); /* * For all stored categories, update them if we can still find them and remove them from "currentCategories". */ this._originalLogLevels.forEach((value, key) => { const category = currentCategories.get(key); if (category !== undefined) { this._provider.updateRuntimeSettingsCategory(category, {level: value, disableRecursion: true}); } currentCategories.delete(key); }); /* * For any remaining categories (these are new compared to when originals were loaded), set their parent levels. * * This is just a best effort, we had no previous log levels available for them after all. */ currentCategories.forEach(category => { if (category.parent !== undefined) { this._provider.updateRuntimeSettingsCategory(category, {level: category.parent.logLevel, disableRecursion: true}); } }); /* Update the levels so we're up-to-date again */ this._originalLogLevels = CategoryControlProviderImpl.loadCurrentGroupLogLevels(this._provider); this._messageChannel("Successfully reset log levels back to original state (from when this CategoryControlProvider was created)."); } public save(): void { if (!localStorage) { this._messageChannel("Cannot save state, localStorage is not available."); return; } const saveDataForAllRootCategories = this._provider.getRegisteredCategories() .filter(cat => cat.parent === undefined) .map(rootCategory => CategoryControlProviderImpl.createCategorySaveData(rootCategory)); const saveData: SaveData = { name: this._provider.name, rootCategories: saveDataForAllRootCategories, }; localStorage.setItem(this.createKey(), JSON.stringify(saveData)); this._messageChannel(`Successfully saved state for CategoryControlProvider '${this._provider.name}'.`); } public restore(logRestoreFailures: boolean | undefined): void { const finalLogRestoreFailures = logRestoreFailures !== undefined ? logRestoreFailures : true; if (!localStorage) { if (finalLogRestoreFailures) { this._messageChannel(`Will not attempt to restore state for CategoryControlProvider '${this._provider.name}', localStorage is not available.`); } return; } const key = this.createKey(); const value = localStorage.getItem(key); if (value === null) { if (finalLogRestoreFailures) { this._messageChannel(`Cannot restore state for CategoryControlProvider '${this._provider.name}', no data available.`); } return; } try { const savedData: SaveData = JSON.parse(value); if (this._provider.name !== savedData.name) { if (finalLogRestoreFailures) { this._messageChannel(`Cannot restore state for CategoryControlProvider '${this._provider.name}', data is not for provider - found name '${savedData.name}'.`); } return; } this.restoreBySaveData(savedData, finalLogRestoreFailures); this._messageChannel(`Successfully restored state for CategoryControlProvider '${this._provider.name}'`); this._originalLogLevels = CategoryControlProviderImpl.loadCurrentGroupLogLevels(this._provider); } catch (e) { localStorage.removeItem(key); this._messageChannel(`Cannot restore state for CategoryControlProvider '${this._provider.name}', data is not valid. Invalid data removed from localStorage.`); } } public update(level: CategoryControlProviderLogLevel, categoryId?: number | string, noRecurse?: boolean): void { if (typeof categoryId === "undefined") { this.updateAll(level); } else if (typeof categoryId === "number") { this.updateByIndex(level, categoryId, noRecurse !== undefined ? noRecurse : false); } else { this.updateByPath(level, categoryId, noRecurse !== undefined ? noRecurse : false); } } private updateAll(level: CategoryControlProviderLogLevel) { const logLevel = LogLevel.toLogLevel(level); this._provider.getRegisteredCategories() .filter(cat => cat.parent === undefined) .forEach(cat => this._provider.updateRuntimeSettingsCategory(cat, {level: logLevel})); this._messageChannel(`Updated all categories to use log level '${level.toLowerCase()}'`); } private updateByPath(level: CategoryControlProviderLogLevel, path: string, noRecurse: boolean) { const category = this._provider.getCategoryByPath(path); if (category === undefined) { this._messageChannel(`Failed to find a provider by path '${path}', please make sure to separate the parts by a ${CATEGORY_PATH_SEPARATOR}.`); return; } this._provider.updateRuntimeSettingsCategory(category, {level: LogLevel.toLogLevel(level), disableRecursion: noRecurse}); this._messageChannel(`Successfully updated category '${category.name}' with path '${path}' to log level '${level.toLowerCase()}'${noRecurse ? "" : " and recursively applied to children (if any)"}.`); } private updateByIndex(level: CategoryControlProviderLogLevel, index: number, noRecurse: boolean) { if (index < 0) { this._messageChannel(`Cannot update category by index '${index}', it is negative.`); return; } const categories = this.createCategoryInfoHierarchy(); if (index >= categories.size) { this._messageChannel(`Cannot update category by index '${index}', it is outside of the range of available categories, use showSettings() to see the indices.`); return; } const category = [...categories.values()][index].category; this._provider.updateRuntimeSettingsCategory(category, {level: LogLevel.toLogLevel(level), disableRecursion: noRecurse}); this._messageChannel(`Successfully updated category '${category.name}' by index '${index}' to log level '${level.toLowerCase()}'${noRecurse ? "" : " and recursively applied to children (if any)"}.`); } private restoreBySaveData(saveData: SaveData, logCannotRestore: boolean) { const restoreCategory = (categorySaveData: CategorySaveData, currentPath: string) => { const newPath = currentPath.length > 0 ? (currentPath + CATEGORY_PATH_SEPARATOR + categorySaveData.name) : categorySaveData.name; const category = this._provider.getCategoryByPath(newPath); if (category !== undefined) { const newLevel = LogLevel.toLogLevel(categorySaveData.level); if (newLevel !== undefined) { this._provider.updateRuntimeSettingsCategory(category, {level: newLevel, disableRecursion: true}); } else if (logCannotRestore) { this._messageChannel(`CategoryControlProvider '${this._provider.name}' - cannot restore log level for category path '${newPath}', log level is invalid.`); } for (const childSaveData of categorySaveData.children) { restoreCategory(childSaveData, newPath); } } else if (logCannotRestore) { this._messageChannel(`CategoryControlProvider '${this._provider.name}' - failed to find a Category by path '${newPath}', will not restore category (and children)`); } }; for (const rootSaveData of saveData.rootCategories) { restoreCategory(rootSaveData, ""); } } private createKey(): string { return `CategoryProvider-${this._provider.name}`; } private createCategoryInfoHierarchy(): Map<LogId, CategoryInfo> { const result = new Map<LogId, CategoryInfo>(); const rootCategories = this._provider.getRegisteredCategories().filter(cat => cat.parent === undefined); rootCategories.forEach(category => CategoryControlProviderImpl.addCategoryInfoHierarchy(category, 0, result)); return result; } private static createCategorySaveData(category: Category): CategorySaveData { return { name: category.name, level: LogLevel[category.logLevel], children: category.children.map(child => this.createCategorySaveData(child)), }; } private static loadCurrentGroupLogLevels(provider: CategoryProviderImpl): Map<LogId, LogLevel> { return new Map<LogId, LogLevel>(provider.getRegisteredCategories().map(category => [category.id, category.logLevel])); } private static createSettingLineCategory(categoryInfo: CategoryInfo, index: number, maxWidthIndex: number, maxWidthIdentifier: number): string { const prefix = " ".repeat(categoryInfo.depth); const catName = prefix + categoryInfo.category.name; return ` [${util.padStart(index.toString(), maxWidthIndex)}, ${util.padEnd(catName, maxWidthIdentifier)} (level=${util.padEnd(categoryInfo.logLevel, 5)})]`; } private static addCategoryInfoHierarchy(category: Category, currentDepth: number, result: Map<LogId, CategoryInfo>) { result.set(category.id, { category, logLevel: LogLevel[category.logLevel], depth: currentDepth, }); category.children.forEach(child => this.addCategoryInfoHierarchy(child, currentDepth + 1, result)); } } interface CategoryInfo { category: Category; depth: number; logLevel: string; } interface SaveData { /** * Name of the provider. */ name: string; rootCategories: CategorySaveData[]; } interface CategorySaveData { /** * Category name. */ name: string; level: string; children: CategorySaveData[]; }
the_stack
import lerp from 'lerp' //export { WebGLMultisampleRenderTarget } from 'three/src/renderers/WebGLMultisampleRenderTarget.js'; //export { WebGLCubeRenderTarget } from 'three/src/renderers/WebGLCubeRenderTarget.js'; export { WebGLRenderTarget } from 'three/src/renderers/WebGLRenderTarget.js' export { WebGLRenderer } from 'three/src/renderers/WebGLRenderer.js' export { WebGL1Renderer } from 'three/src/renderers/WebGL1Renderer.js' export { ShaderLib } from 'three/src/renderers/shaders/ShaderLib.js' export { UniformsLib } from 'three/src/renderers/shaders/UniformsLib.js' export { UniformsUtils } from 'three/src/renderers/shaders/UniformsUtils.js' export { ShaderChunk } from 'three/src/renderers/shaders/ShaderChunk.js' //export { FogExp2 } from 'three/src/scenes/FogExp2.js'; //export { Fog } from 'three/src/scenes/Fog.js'; export { Scene } from 'three/src/scenes/Scene.js' //export { Sprite } from 'three/src/objects/Sprite.js'; //export { LOD } from 'three/src/objects/LOD.js'; //export { SkinnedMesh } from 'three/src/objects/SkinnedMesh.js'; export class SkinnedMesh {} //export { Skeleton } from 'three/src/objects/Skeleton.js'; export class Skeleton {} //export { Bone } from 'three/src/objects/Bone.js'; export class Bone {} export { Mesh } from 'three/src/objects/Mesh.js' //export { InstancedMesh } from 'three/src/objects/InstancedMesh.js'; //export { LineSegments } from 'three/src/objects/LineSegments.js'; export class LineSegments {} //export { LineLoop } from 'three/src/objects/LineLoop.js'; export class LineLoop {} export { Line } from 'three/src/objects/Line.js' //export { Points } from 'three/src/objects/Points.js'; export class Points {} export { Group } from 'three/src/objects/Group.js' //export { VideoTexture } from 'three/src/textures/VideoTexture.js'; export { DataTexture } from 'three/src/textures/DataTexture.js' //export { DataTexture2DArray } from 'three/src/textures/DataTexture2DArray.js'; //export { DataTexture3D } from 'three/src/textures/DataTexture3D.js'; //export { CompressedTexture } from 'three/src/textures/CompressedTexture.js'; //export { CubeTexture } from 'three/src/textures/CubeTexture.js'; export { CanvasTexture } from 'three/src/textures/CanvasTexture.js' //export { DepthTexture } from 'three/src/textures/DepthTexture.js'; export { Texture } from 'three/src/textures/Texture.js' //export * from 'three/src/geometries/Geometries.js' export { PlaneBufferGeometry } from 'three/src/geometries/PlaneGeometry' export { WireframeGeometry } from 'three/src/geometries/WireframeGeometry' //export * from 'three/src/materials/Materials.js' export { Material } from 'three/src/materials/Material.js' export { MeshStandardMaterial } from 'three/src/materials/MeshStandardMaterial.js' export { MeshPhysicalMaterial } from 'three/src/materials/MeshPhysicalMaterial.js' export { MeshBasicMaterial } from 'three/src/materials/MeshBasicMaterial.js' export { LineBasicMaterial } from 'three/src/materials/LineBasicMaterial.js' export { ShaderMaterial } from 'three/src/materials/ShaderMaterial.js' export class PointsMaterial {} //export { AnimationLoader } from 'three/src/loaders/AnimationLoader.js' //export { CompressedTextureLoader } from 'three/src/loaders/CompressedTextureLoader.js' //export { CubeTextureLoader } from 'three/src/loaders/CubeTextureLoader.js' //export { DataTextureLoader } from 'three/src/loaders/DataTextureLoader.js' export { TextureLoader } from 'three/src/loaders/TextureLoader.js' //export { ObjectLoader } from 'three/src/loaders/ObjectLoader.js' //export { MaterialLoader } from 'three/src/loaders/MaterialLoader.js' //export { BufferGeometryLoader } from 'three/src/loaders/BufferGeometryLoader.js' export { DefaultLoadingManager, LoadingManager } from 'three/src/loaders/LoadingManager.js' export { ImageLoader } from 'three/src/loaders/ImageLoader.js' export { ImageBitmapLoader } from 'three/src/loaders/ImageBitmapLoader.js' //export class ImageBitmapLoader {} //export { FontLoader } from 'three/src/loaders/FontLoader.js' export { FileLoader } from 'three/src/loaders/FileLoader.js' export { Loader } from 'three/src/loaders/Loader.js' export { LoaderUtils } from 'three/src/loaders/LoaderUtils.js' //export { Cache } from 'three/src/loaders/Cache.js' //export { AudioLoader } from 'three/src/loaders/AudioLoader.js' export { SpotLight } from 'three/src/lights/SpotLight.js' export { PointLight } from 'three/src/lights/PointLight.js' //export { RectAreaLight } from 'three/src/lights/RectAreaLight.js' //export { HemisphereLight } from 'three/src/lights/HemisphereLight.js' //export { HemisphereLightProbe } from 'three/src/lights/HemisphereLightProbe.js' //export { DirectionalLight } from 'three/src/lights/DirectionalLight.js' export class DirectionalLight {} export { AmbientLight } from 'three/src/lights/AmbientLight.js' //export { AmbientLightProbe } from 'three/src/lights/AmbientLightProbe.js' //export { LightShadow } from 'three/src/lights/LightShadow.js' export { Light } from 'three/src/lights/Light.js' //export { LightProbe } from 'three/src/lights/LightProbe.js' //export { StereoCamera } from 'three/src/cameras/StereoCamera.js' export { PerspectiveCamera } from 'three/src/cameras/PerspectiveCamera.js' export { OrthographicCamera } from 'three/src/cameras/OrthographicCamera.js' //export { CubeCamera } from 'three/src/cameras/CubeCamera.js' //export { ArrayCamera } from 'three/src/cameras/ArrayCamera.js' export { Camera } from 'three/src/cameras/Camera.js' //export { AudioListener } from 'three/src/audio/AudioListener.js' //export { PositionalAudio } from 'three/src/audio/PositionalAudio.js' //export { AudioContext } from 'three/src/audio/AudioContext.js' //export { AudioAnalyser } from 'three/src/audio/AudioAnalyser.js' //export { Audio } from 'three/src/audio/Audio.js' //export { VectorKeyframeTrack } from 'three/src/animation/tracks/VectorKeyframeTrack.js' export class VectorKeyframeTrack {} //export { StringKeyframeTrack } from 'three/src/animation/tracks/StringKeyframeTrack.js' //export { QuaternionKeyframeTrack } from 'three/src/animation/tracks/QuaternionKeyframeTrack.js' export class QuaternionKeyframeTrack {} //export { NumberKeyframeTrack } from 'three/src/animation/tracks/NumberKeyframeTrack.js' export class NumberKeyframeTrack {} //export { ColorKeyframeTrack } from 'three/src/animation/tracks/ColorKeyframeTrack.js' //export { BooleanKeyframeTrack } from 'three/src/animation/tracks/BooleanKeyframeTrack.js' //export { PropertyMixer } from 'three/src/animation/PropertyMixer.js' export { PropertyBinding } from 'three/src/animation/PropertyBinding.js' //export { KeyframeTrack } from 'three/src/animation/KeyframeTrack.js' //export { AnimationUtils } from 'three/src/animation/AnimationUtils.js' //export { AnimationObjectGroup } from 'three/src/animation/AnimationObjectGroup.js' //export { AnimationMixer } from 'three/src/animation/AnimationMixer.js' //export { AnimationClip } from 'three/src/animation/AnimationClip.js' export class AnimationClip {} export { Uniform } from 'three/src/core/Uniform.js' export { InstancedBufferGeometry } from 'three/src/core/InstancedBufferGeometry.js' export { BufferGeometry } from 'three/src/core/BufferGeometry.js' export { InterleavedBufferAttribute } from 'three/src/core/InterleavedBufferAttribute.js' export { InstancedInterleavedBuffer } from 'three/src/core/InstancedInterleavedBuffer.js' export { InterleavedBuffer } from 'three/src/core/InterleavedBuffer.js' export { InstancedBufferAttribute } from 'three/src/core/InstancedBufferAttribute.js' //export { GLBufferAttribute } from 'three/src/core/GLBufferAttribute.js' export * from 'three/src/core/BufferAttribute.js' //export { Face3 } from 'three/src/core/Face3.js' export { Object3D } from 'three/src/core/Object3D.js' //export { Raycaster } from 'three/src/core/Raycaster.js' export class Raycaster { setFromCamera() {} intersectObjects() { return [] } } //export { Layers } from 'three/src/core/Layers.js' export class Layers {} //export { EventDispatcher } from 'three/src/core/EventDispatcher.js' export { Clock } from 'three/src/core/Clock.js' //export { QuaternionLinearInterpolant } from 'three/src/math/interpolants/QuaternionLinearInterpolant.js' //export { LinearInterpolant } from 'three/src/math/interpolants/LinearInterpolant.js' //export { DiscreteInterpolant } from 'three/src/math/interpolants/DiscreteInterpolant.js' //export { CubicInterpolant } from 'three/src/math/interpolants/CubicInterpolant.js' //export { Interpolant } from 'three/src/math/Interpolant.js' export class Interpolant {} //export { Triangle } from 'three/src/math/Triangle.js' //export { MathUtils } from 'three/src/math/MathUtils.js' export function MathUtils() {} MathUtils.lerp = lerp //export { Spherical } from 'three/src/math/Spherical.js' //export { Cylindrical } from 'three/src/math/Cylindrical.js' //export { Plane } from 'three/src/math/Plane.js' //export { Frustum } from 'three/src/math/Frustum.js' export { Sphere } from 'three/src/math/Sphere.js' //export { Ray } from 'three/src/math/Ray.js' export { Matrix4 } from 'three/src/math/Matrix4.js' export { Matrix3 } from 'three/src/math/Matrix3.js' export { Box3 } from 'three/src/math/Box3.js' export { Box2 } from 'three/src/math/Box2.js' export { Line3 } from 'three/src/math/Line3.js' export { Euler } from 'three/src/math/Euler.js' export { Vector4 } from 'three/src/math/Vector4.js' export { Vector3 } from 'three/src/math/Vector3.js' export { Vector2 } from 'three/src/math/Vector2.js' export { Quaternion } from 'three/src/math/Quaternion.js' export { Color } from 'three/src/math/Color.js' //export { SphericalHarmonics3 } from 'three/src/math/SphericalHarmonics3.js' //export { ImmediateRenderObject } from 'three/src/extras/objects/ImmediateRenderObject.js' //export { SpotLightHelper } from 'three/src/helpers/SpotLightHelper.js' //export { SkeletonHelper } from 'three/src/helpers/SkeletonHelper.js' //export { PointLightHelper } from 'three/src/helpers/PointLightHelper.js' //export { HemisphereLightHelper } from 'three/src/helpers/HemisphereLightHelper.js' //export { GridHelper } from 'three/src/helpers/GridHelper.js' //export { PolarGridHelper } from 'three/src/helpers/PolarGridHelper.js' //export { DirectionalLightHelper } from 'three/src/helpers/DirectionalLightHelper.js' //export { CameraHelper } from 'three/src/helpers/CameraHelper.js' //export { BoxHelper } from 'three/src/helpers/BoxHelper.js' //export { Box3Helper } from 'three/src/helpers/Box3Helper.js' //export { PlaneHelper } from 'three/src/helpers/PlaneHelper.js' //export { ArrowHelper } from 'three/src/helpers/ArrowHelper.js' //export { AxesHelper } from 'three/src/helpers/AxesHelper.js' //export * from 'three/src/extras/curves/Curves.js' //export { Shape } from 'three/src/extras/core/Shape.js' //export { Path } from 'three/src/extras/core/Path.js' //export { ShapePath } from 'three/src/extras/core/ShapePath.js' //export { Font } from 'three/src/extras/core/Font.js' //export { CurvePath } from 'three/src/extras/core/CurvePath.js' //export { Curve } from 'three/src/extras/core/Curve.js' //export { ImageUtils } from 'three/src/extras/ImageUtils.js' //export { ShapeUtils } from 'three/src/extras/ShapeUtils.js' //export { PMREMGenerator } from 'three/src/extras/PMREMGenerator.js' //export { WebGLUtils } from 'three/src/renderers/webgl/WebGLUtils.js' //export * from 'three/src/constants.js' export const PCFSoftShadowMap = 2 export const FrontSide = 0 export const BackSide = 1 export const DoubleSide = 2 export const FlatShading = 1 export const ACESFilmicToneMapping = 4 export const RepeatWrapping = 1000 export const ClampToEdgeWrapping = 1001 export const MirroredRepeatWrapping = 1002 export const NearestFilter = 1003 export const NearestMipmapNearestFilter = 1004 export const NearestMipMapNearestFilter = 1004 export const NearestMipmapLinearFilter = 1005 export const NearestMipMapLinearFilter = 1005 export const LinearFilter = 1006 export const LinearMipmapNearestFilter = 1007 export const LinearMipMapNearestFilter = 1007 export const LinearMipmapLinearFilter = 1008 export const LinearMipMapLinearFilter = 1008 export const RGBFormat = 1022 export const RGBAFormat = 1023 export const LuminanceFormat = 1024 export const LuminanceAlphaFormat = 1025 export const RGBEFormat = RGBAFormat export const DepthFormat = 1026 export const DepthStencilFormat = 1027 export const RedFormat = 1028 export const RedIntegerFormat = 1029 export const RGFormat = 1030 export const RGIntegerFormat = 1031 export const RGBIntegerFormat = 1032 export const RGBAIntegerFormat = 1033 export const InterpolateDiscrete = 2300 export const InterpolateLinear = 2301 export const InterpolateSmooth = 2302 export const ZeroCurvatureEnding = 2400 export const ZeroSlopeEnding = 2401 export const WrapAroundEnding = 2402 export const NormalAnimationBlendMode = 2500 export const AdditiveAnimationBlendMode = 2501 export const TrianglesDrawMode = 0 export const TriangleStripDrawMode = 1 export const TriangleFanDrawMode = 2 export const LinearEncoding = 3000 export const sRGBEncoding = 3001 export const GammaEncoding = 3007 export const RGBEEncoding = 3002 export const LogLuvEncoding = 3003 export const RGBM7Encoding = 3004 export const RGBM16Encoding = 3005 export const RGBDEncoding = 3006 export const BasicDepthPacking = 3200 export const RGBADepthPacking = 3201 export const TangentSpaceNormalMap = 0 export const ObjectSpaceNormalMap = 1
the_stack
import { VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE, eventTypes, defaultOffsets, } from './constants.js'; import type { ScrollMonitorContainer } from './container.js'; import type { EventName, Listener, Offsets, ScrollEvent, WatchItem, WatchItemInput } from './types'; type ListenerItem = { callback: Listener; isOne: boolean; }; export class Watcher { constructor( public container: ScrollMonitorContainer, public watchItem: WatchItem, offsets: Offsets ) { var self = this; if (!offsets) { this.offsets = defaultOffsets; } else if (typeof offsets === 'number') { this.offsets = { top: offsets, bottom: offsets }; } else { this.offsets = { top: 'top' in offsets ? offsets.top : defaultOffsets.top, bottom: 'bottom' in offsets ? offsets.bottom : defaultOffsets.bottom, }; } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport: boolean; var wasFullyInViewport: boolean; var wasAboveViewport: boolean; var wasBelowViewport: boolean; var listenerToTriggerListI; var listener; let needToTriggerStateChange = false; function triggerCallbackArray(listeners: ListenerItem[], event: ScrollEvent) { needToTriggerStateChange = true; if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while (listenerToTriggerListI--) { listener = listeners[listenerToTriggerListI]; listener.callback.call(self, event, self); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks(event: ScrollEvent) { if (this.isInViewport && !wasInViewport) { triggerCallbackArray(this.callbacks[ENTERVIEWPORT], event); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray(this.callbacks[FULLYENTERVIEWPORT], event); } if ( this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport ) { triggerCallbackArray(this.callbacks[VISIBILITYCHANGE], event); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray(this.callbacks[FULLYENTERVIEWPORT], event); triggerCallbackArray(this.callbacks[PARTIALLYEXITVIEWPORT], event); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray(this.callbacks[ENTERVIEWPORT], event); triggerCallbackArray(this.callbacks[EXITVIEWPORT], event); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray(this.callbacks[PARTIALLYEXITVIEWPORT], event); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray(this.callbacks[EXITVIEWPORT], event); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray(this.callbacks[VISIBILITYCHANGE], event); } if (needToTriggerStateChange) { needToTriggerStateChange = false; triggerCallbackArray(this.callbacks[STATECHANGE], event); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function () { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var containerOffset = 0; var container = this.container; while (container.containerWatcher) { containerOffset += container.containerWatcher.top - container.containerWatcher.container.viewportTop; container = container.containerWatcher.container; } var boundingRect = this.watchItem.getBoundingClientRect(); this.top = boundingRect.top + this.container.viewportTop - containerOffset; this.bottom = boundingRect.bottom + this.container.viewportTop - containerOffset; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = this.container.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray(this.callbacks[LOCATIONCHANGE], undefined); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } height: number; top: number; bottom: number; offsets: { top: number; bottom: number }; isInViewport: boolean; isFullyInViewport: boolean; isAboveViewport: boolean; isBelowViewport: boolean; locked: boolean = false; callbacks: Record<string, { callback: Listener; isOne: boolean }[]> = {}; triggerCallbacks: (event: ScrollEvent) => void; recalculateLocation: () => void; visibilityChange: (callback: Listener, isOne: boolean) => void; enterViewport: (callback: Listener, isOne: boolean) => void; fullyEnterViewport: (callback: Listener, isOne: boolean) => void; exitViewport: (callback: Listener, isOne: boolean) => void; partiallyExitViewport: (callback: Listener, isOne: boolean) => void; locationChange: (callback: Listener, isOne: boolean) => void; stateChange: (callback: Listener, isOne: boolean) => void; on(event: EventName, callback: Listener, isOne = false) { // trigger the event if it applies to the element right now. switch (true) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isInViewport && this.isAboveViewport: callback.call(this, this); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({ callback, isOne }); } else { throw new Error( 'Tried to add a scroll monitor listener of type ' + event + '. Your options are: ' + eventTypes.join(', ') ); } } off(event: EventName, callback: Listener) { if (this.callbacks[event]) { for (var i = 0, item; (item = this.callbacks[event][i]); i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error( 'Tried to remove a scroll monitor listener of type ' + event + '. Your options are: ' + eventTypes.join(', ') ); } } one(event: EventName, callback: Listener) { this.on(event, callback, true); } recalculateSize() { if (this.watchItem instanceof HTMLElement) { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; } } update() { this.isAboveViewport = this.top < this.container.viewportTop; this.isBelowViewport = this.bottom > this.container.viewportBottom; this.isInViewport = this.top < this.container.viewportBottom && this.bottom > this.container.viewportTop; this.isFullyInViewport = (this.top >= this.container.viewportTop && this.bottom <= this.container.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); } destroy() { var index = this.container.watchers.indexOf(this), self = this; this.container.watchers.splice(index, 1); self.callbacks = {}; } // prevent recalculating the element location lock() { this.locked = true; } unlock() { this.locked = false; } } var eventHandlerFactory = function (type: EventName) { return function (callback: Listener, isOne = false) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; Watcher.prototype[type] = eventHandlerFactory(type); }
the_stack
import { LevelDBLogServer, HtmlToOperationLogMapping, LocStore, LocLogs, traverseDomOrigin, } from "@fromjs/core"; import { traverse, TraversalStep } from "./src/traverse"; import StackFrameResolver from "./src/StackFrameResolver"; import * as fs from "fs"; import * as crypto from "crypto"; import * as path from "path"; import * as express from "express"; import * as bodyParser from "body-parser"; import * as WebSocket from "ws"; import { BackendOptions } from "./BackendOptions"; import * as responseTime from "response-time"; import { config } from "@fromjs/core"; import { RequestHandler } from "./RequestHandler"; import * as puppeteer from "puppeteer"; import { initSessionDirectory } from "./initSession"; import { compileNodeApp } from "./compileNodeApp"; import * as axios from "axios"; import { traverseObject } from "@fromjs/core"; import { prettifyAndMapFrameObject } from "./src/prettify"; import { fixOffByOneTraversalError } from "./src/fixOffByOneTraversalError"; import { resolve } from "dns"; const ENABLE_DERIVED = false; const SAVE_LOG_USES = false; const GENERATE_DERIVED = process.env.GENERATE_DERIVED; let reportHtmlFileInfo = { url: "http://localhost:4444/report.html", sourceOperationLog: parseFloat(process.env.REPORT_TV!), sourceOffset: 0, }; let uiDir = require .resolve("@fromjs/ui") .split(/[\/\\]/g) .slice(0, -1) .join("/"); let coreDir = require .resolve("@fromjs/core") .split(/[\/\\]/g) .slice(0, -1) .join("/"); let extensionDir = require .resolve("@fromjs/proxy-extension") .split(/[\/\\]/g) .slice(0, -1) .join("/") + "/dist"; let fromJSInternalDir = path.resolve(__dirname + "/../fromJSInternal"); let startPageDir = path.resolve(__dirname + "/../start-page"); function createBackendCerts(options: BackendOptions) { fs.mkdirSync(options.getBackendServerCertDirPath()); const Forge = require("node-forge"); const pki = Forge.pki; var keys = pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 }); var cert = pki.createCertificate(); cert.publicKey = keys.publicKey; cert.validity.notBefore = new Date(); cert.validity.notBefore.setDate(cert.validity.notBefore.getDate() - 1); cert.validity.notAfter = new Date(); cert.validity.notAfter.setFullYear( cert.validity.notBefore.getFullYear() + 10 ); cert.sign(keys.privateKey, Forge.md.sha256.create()); fs.writeFileSync( options.getBackendServerCertPath(), pki.certificateToPem(cert) ); fs.writeFileSync( options.getBackendServerPrivateKeyPath(), pki.privateKeyToPem(keys.privateKey) ); } const DELETE_EXISTING_LOGS_AT_START = false; const LOG_PERF = config.LOG_PERF; if (LOG_PERF) { require("./timeJson"); } async function generateLocLogs({ logServer, locLogs }) { console.log("will generate locLogs"); await new Promise((resolve) => locLogs._db.clear(resolve)); console.time("Couting logs"); let totalLogs = (await new Promise((resolve) => { let totalLogs = 0; let i = logServer.db.iterator(); function iterate(error, key, value) { if (value) { totalLogs++; i.next(iterate); } else { resolve(totalLogs); } } i.next(iterate); })) as number; console.timeEnd("Couting logs"); console.log({ totalLogs }); console.time("generateLocLogs"); return new Promise((resolve, reject) => { let locs: any[] = []; let num = 0; let i = logServer.db.iterator(); let locLogsToSave = {}; async function doAdd() { // console.log( // "doAdd", // JSON.stringify(locLogsToSave, null, 2).slice(0, 500) // ); let locIds = Object.keys(locLogsToSave); for (const locId of locIds) { // console.log(locLogsToSave); await locLogs.addLogs(locId, locLogsToSave[locId]); } locLogsToSave = {}; } async function iterate(error, key, value) { num++; if (num % 50000 === 0) { await doAdd(); console.log({ num, p: Math.round((num / totalLogs) * 1000) / 10 }); } if (value) { value = JSON.parse(value); locLogsToSave[value.l] = locLogsToSave[value.l] || []; locLogsToSave[value.l].push(key.toString()); i.next(iterate); } else { await doAdd(); console.timeEnd("generateLocLogs"); resolve(); } // if (value) { // value = JSON.parse(value); // if (value.url.includes(url)) { // locs.push({ key: key.toString(), value }); // } // } // if (key) { // i.next(iterate); // } else { // resolve(locs); // } } i.next(iterate); }); // for (const log of req.body.logs) { // await locLogs.addLog(log.loc, log.index); // } // console.timeEnd(id); } export default class Backend { sessionConfig = null; handleTraverse = null as any; doStoreLogs = null as any; constructor(private options: BackendOptions) { console.time("create backend"); if (DELETE_EXISTING_LOGS_AT_START) { console.log( "deleting existing log data, this makes sure perf data is more comparable... presumably leveldb slows down with more data" ); require("rimraf").sync(options.getLocStorePath()); require("rimraf").sync(options.getTrackingDataDirectory()); } initSessionDirectory(options); // seems like sometimes get-folder-size runs into max call stack size exceeded, so disable it // getFolderSize(options.sessionDirectory, (err, size) => { // console.log( // "Session size: ", // (size / 1024 / 1024).toFixed(2) + // " MB" + // " (" + // path.resolve(options.sessionDirectory) + // ")" // ); // }); let sessionConfig; function saveSessionConfig() { fs.writeFileSync( options.getSessionJsonPath(), JSON.stringify(sessionConfig, null, 4) ); } if (fs.existsSync(options.getSessionJsonPath())) { const json = fs.readFileSync(options.getSessionJsonPath()).toString(); sessionConfig = JSON.parse(json); } else { sessionConfig = { accessToken: crypto.randomBytes(32).toString("hex"), }; saveSessionConfig(); console.log("Saved session config"); } this.sessionConfig = sessionConfig; var { bePort, proxyPort } = options; const app = express(); var compression = require("compression"); app.use(compression()); if (LOG_PERF) { console.log("will log perf"); app.use( responseTime((req, res, time) => { console.log(req.method, req.url, Math.round(time) + "ms"); }) ); } app.use(bodyParser.text({ limit: "500mb" })); app.post("/storeLogs", async (req, res) => { app.verifyToken(req); res.set("Access-Control-Allow-Origin", "*"); res.set( "Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" ); // console.log("store logs", JSON.stringify(req.body, null, 2)) await doStoreLogs(req.body); res.end(JSON.stringify({ ok: true })); }); app.use(bodyParser.json({ limit: "500mb" })); if (!fs.existsSync(options.getBackendServerCertDirPath())) { createBackendCerts(options); } const http = require("http"); const server = http.createServer(app); const wss = new WebSocket.Server({ server, }); // Needed or else websocket connection doesn't work because of self-signed cert // process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // "Access-Control-Allow-Origin: *" allows any website to send data to local server // but that might be bad, so limit access to code generated by Babel plugin app.verifyToken = function verifyToken(req) { // const { authorization } = req.headers; // const { accessToken } = sessionConfig; // if (authorization !== accessToken) { // throw Error( // "Token invalid: " + // authorization + // " should be " + // accessToken + // ` | Request: ${req.method} + ${req.path}` // ); // } }; function getProxy() { return proxyInterface; } const files = fs.existsSync(options.sessionDirectory + "/files.json") ? JSON.parse( fs.readFileSync( options.sessionDirectory + "/" + "files.json", "utf-8" ) ) : []; const locLogs = new LocLogs(options.sessionDirectory + "/locLogs"); const logUses = fs.existsSync(options.sessionDirectory + "/logUses.json") ? JSON.parse( fs.readFileSync( options.sessionDirectory + "/" + "logUses.json", "utf-8" ) ) : {}; let requestHandler; const locStore = new LocStore(options.getLocStorePath()); const logServer = new LevelDBLogServer( options.getTrackingDataDirectory(), locStore ); if (GENERATE_DERIVED) { generateLocLogs({ logServer, locLogs }); generateUrlLocs({ locStore, options }); } let { storeLocs, handleTraverse, doStoreLogs } = setupBackend( options, app, wss, getProxy, files, locLogs, logUses, () => requestHandler, locStore, logServer ); setupUI(options, app, wss, getProxy, files, () => requestHandler); this.handleTraverse = handleTraverse; this.doStoreLogs = doStoreLogs; requestHandler = makeRequestHandler({ accessToken: sessionConfig.accessToken, options, storeLocs, files, }); if (process.env.NODE_TEST) { compileNodeApp({ directory: process.env.NODE_TEST, outdir: "node-test-compiled", requestHandler: requestHandler, }); } let proxyInterface; const proxyReady = Promise.resolve(); // const proxyReady = createProxy({ // accessToken: sessionConfig.accessToken, // options, // storeLocs // }); // proxyReady.then(pInterface => { // proxyInterface = pInterface; // "justtotest" && getProxy(); // if (options.onReady) { // options.onReady(); // } // }); ["/storeLogs", "/inspect", "/inspectDOM"].forEach((path) => { // todo: don't allow requests from any site app.options(path, allowCrossOriginRequests); }); const serverReady = new Promise((resolve) => { server.listen(bePort, "0.0.0.0", () => resolve()); }); console.timeLog("create backend", "end of function"); Promise.all([proxyReady, serverReady]).then(async () => { console.timeEnd("create backend"); console.log("Server listening on port " + bePort); if (process.env.PROCESS_REQUEST_QUEUE) { await this.processRequestQueue(); } options.onReady({ requestHandler, logServer }); }); } async processRequestQueue() { const queueFiles = fs.readdirSync( this.options.sessionDirectory + "/requestQueue" ); let i = 0; for (const queueFile of queueFiles) { i++; let filePath = this.options.sessionDirectory + "/requestQueue/" + queueFile; const content = fs.readFileSync(filePath, "utf-8"); let firstLineBreakIndex = content.indexOf("\n"); const path = content.slice(0, firstLineBreakIndex); const body = content.slice(firstLineBreakIndex + 1); if (path === "/storeLogs") { await this.doStoreLogs(body); } else { //@ts-ignore await axios({ url: "http://localhost:" + this.options.bePort + path, method: "POST", headers: { "Content-Type": "application/json", Authorization: (this.sessionConfig! as any).accessToken, }, data: body, }); } if (i % 10 === 0) { console.log( "done process queue file", queueFile, i + "/" + queueFiles.length ); } fs.unlinkSync(filePath); } } } const pageSessionsById = {}; function getPageSession(pageSessionId) { let session = pageSessionsById[pageSessionId]; if (!session) { pageSessionsById[pageSessionId] = {}; } // console.log("Page session", pageSessionId, pageSessionsById[pageSessionId]); return pageSessionsById[pageSessionId]; } function setupUI(options, app, wss, getProxy, files, getRequestHandler) { wss.on("connection", (ws: WebSocket, req) => { let pageSessionId = req.url.match(/pageSessionId=([a-zA-Z0-9_]+)/)[1]; console.log("On ws connection", { pageSessionId }); ws.pageSessionId = pageSessionId; let pageSession = getPageSession(pageSessionId); if (pageSession.domToInspect) { ws.send( JSON.stringify({ type: "inspectDOM", ...getDomToInspectMessage(pageSessionId), }) ); } else if (pageSession.logToInspect) { broadcast( wss, JSON.stringify({ type: "inspectOperationLog", operationLogId: getPageSession(pageSessionId).logToInspect, }), pageSessionId ); } }); /* capture snapshot with this code: function readElement(el) { let className = el.className function getNodes(el) { let nodes = [] el.childNodes.forEach(node => { let isElement = node.nodeType === 1 nodes.push({ elOrigin: {...node.__elOrigin, contents: undefined}, type: node.nodeType, tagName: node.tagName, isSVG: node instanceof SVGElement, nodes: isElement ? getNodes(node) : [], attributes: isElement ? node.getAttributeNames().map(attrName => ({ name: attrName, value: node.getAttribute(attrName) })) : [], textContent: isElement ? undefined : node.textContent }) }) return nodes } const nodes = getNodes(el) return { className, nodes } } Array.from(document.querySelectorAll("script")).forEach(script => script.remove()); Array.from(document.querySelectorAll(".fromjs-element-marker")).forEach(marker => marker.remove()); if (document.querySelector("#fromjs-inspect-dom-button")) { document.querySelector("#fromjs-inspect-dom-button").remove() } if (document.querySelector(".fromjs-inspector-container")) { document.querySelector(".fromjs-inspector-container").remove() } var res= { body: readElement(document.body), head: readElement(document.head) } console.log(res) copy(JSON.stringify(res, null, 2)) */ app.get("/snapshot/lighthouse", async (req, res) => { const { code } = await (await getRequestHandler()).processCode( "console.log('Hello')", "http://nothing.com?asdfadsfsf", {} ); res.end(`<!doctype html> <html> <head> </head> <body> <div id="loading-snapshot">Loading snapshot...</div> <script> window.backendPort = 7000; </script> <script> ${code} </script> <script> function restoreEl(el, elData) { el.className = elData.className function addNodes(el, nodes) { for (const node of nodes) { if (node.type === 1) { let child if (node.isSVG) { child = document.createElementNS("http://www.w3.org/2000/svg", node.tagName) } else { child = document.createElement(node.tagName) } el.appendChild(child) for (const attr of node.attributes) { child.setAttribute(attr.name, attr.value) } child.__elOrigin = node.elOrigin addNodes(child, node.nodes) } else if (node.type === 3) { let child = document.createTextNode(node.textContent) child.__elOrigin = node.elOrigin el.appendChild(child) } else { console.log("ignoring node type", node.type) } } } addNodes(el, elData.nodes) } function waitForElement(elSelector){ return new Promise(resolve => { let i = setInterval(() => { if (document.querySelector(elSelector)) { clearInterval(i) resolve() } }, 100) }) } fetch("/snapshotData/lighthouse").then(r => r.json()).then(snapshotData => { restoreEl(document.head, snapshotData.head); restoreEl(document.body, snapshotData.body); document.querySelector("#loading-snapshot").remove(); // I think waiting is only needed on local because the snapshot loads really quickly waitForElement("#fromjs-inspect-dom-button").then(() => { document.querySelector("#fromjs-inspect-dom-button").click(); setTimeout(() => { fromJSDomInspectorInspect(document.querySelector(".lh-metric__title")); }, 250) }); }) </script> </body> </html>`); }); app.get("/snapshotData/lighthouse", (req, res) => { res.json( JSON.parse(fs.readFileSync("./snapshots/lighthouse.json", "utf-8")) ); }); app.get("/sessionInfo", (req, res) => { console.log("req to /sessionInfo"); res.json({ requestQueueDirectory: options.sessionDirectory + "/requestQueue", }); }); app.get("/fromJSInitPage", (req, res) => { res.end(`<!doctype html> <head> <title>fromJSInitPage</title> </head> <body> Initializing... </body> </html>`); }); app.get("/enableDebugger", (req, res) => { res.end(`<!doctype html> <body> Enabling request interception... </body> </html>`); }); app.get("/", (req, res) => { let html = fs.readFileSync(uiDir + "/index.html").toString(); html = html.replace(/BACKEND_PORT_PLACEHOLDER/g, options.bePort.toString()); console.log(options, process.env); html = html.replace( /BACKEND_ORIGIN_WITHOUT_PORT_PLACEHOLDER/g, options.backendOriginWithoutPort.toString() ); // getProxy() // ._getEnableInstrumentation() Promise.resolve(true).then(function (enabled) { html = html.replace( /BACKEND_PORT_PLACEHOLDER/g, options.bePort.toString() ); html = html.replace( /ENABLE_INSTRUMENTATION_PLACEHOLDER/g, enabled.toString() ); res.send(html); }); }); app.post("/makeProxyRequest", async (req, res) => { const url = req.body.url; console.log("makeProxyReq", url); const { status, headers, body, fileKey, } = await getRequestHandler().handleRequest(req.body); res.status(status); // I think some headres like allow origin don't reach the client js // and are stripped by the browses // https://stackoverflow.com/questions/43344819/reading-response-headers-with-fetch-api res.set("access-control-expose-headers", "*"); res.set("Access-Control-Allow-Origin", "*"); Object.keys(headers).forEach((headerKey) => { if (headerKey === "content-length") { // was getting this wrong sometimes, easier to just not send it return; } res.set(headerKey, headers[headerKey]); }); res.end(body); // const r = await axios({ // url, // method: req.body.method, // headers: req.body.headers, // validateStatus: status => true, // transformResponse: data => data, // proxy: { // host: "127.0.0.1", // port: options.proxyPort // }, // data: req.body.postData // }); // const data = r.data; // const headers = r.headers; // const hasha = require("hasha"); // const hash = hasha(data, "hex").slice(0, 8); // let fileKey = // url.replace(/\//g, "_").replace(/[^a-zA-Z\-_\.0-9]/g, "") + "_" + hash; // if (!files.find(f => f.key === fileKey)) { // files.push({ // url, // hash, // createdAt: new Date(), // key: fileKey // }); // } // res.status(r.status); // Object.keys(headers).forEach(headerKey => { // res.set(headerKey, headers[headerKey]); // }); // res.end(Buffer.from(data)); }); app.get("/viewFile/", (req, res) => {}); app.use(express.static(uiDir)); app.use("/fromJSInternal", express.static(fromJSInternalDir)); app.use("/start", express.static(startPageDir)); function getDomToInspectMessage(pageSessionId, charIndex?) { let domToInspect = getPageSession(pageSessionId).domToInspect; if (!domToInspect) { return { err: "Backend has no selected DOM to inspect", }; } const mapping = new HtmlToOperationLogMapping((<any>domToInspect).parts); const html = mapping.getHtml(); let goodDefaultCharIndex = 0; if (charIndex !== undefined) { goodDefaultCharIndex = charIndex; } else { const charIndexWhereTextFollows = html.search(/>[^<]/); if ( charIndexWhereTextFollows !== -1 && mapping.getOriginAtCharacterIndex(charIndexWhereTextFollows) ) { goodDefaultCharIndex = charIndexWhereTextFollows; goodDefaultCharIndex++; // the > char const first10Chars = html.slice( goodDefaultCharIndex, goodDefaultCharIndex + 10 ); const firstNonWhitespaceOffset = first10Chars.search(/\S/); goodDefaultCharIndex += firstNonWhitespaceOffset; } } return { html: (<any>domToInspect).parts.map((p) => p[0]).join(""), charIndex: goodDefaultCharIndex, }; } app.post("/inspectDOM", (req, res) => { app.verifyToken(req); res.set("Access-Control-Allow-Origin", "*"); res.set( "Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" ); getPageSession(req.body.pageSessionId).domToInspect = req.body; broadcast( wss, JSON.stringify({ type: "inspectDOM", ...getDomToInspectMessage(req.body.pageSessionId, req.body.charIndex), }), req.body.pageSessionId ); res.end("{}"); }); app.post("/inspectDomChar", (req, res) => { let domToInspect = getPageSession(req.body.pageSessionId).domToInspect; if (!domToInspect) { console.log("no domtoinspect", getPageSession(req.body.pageSessionId)); res.status(500); res.json({ err: "Backend has no selected DOM to inspect", }); res.end(); return; } const mapping = new HtmlToOperationLogMapping((<any>domToInspect).parts); const mappingResult: any = mapping.getOriginAtCharacterIndex( req.body.charIndex ); if (!mappingResult.origin) { res.end( JSON.stringify({ logId: null, }) ); return; } const origin = mappingResult.origin; res.end( JSON.stringify({ logId: origin.trackingValue, charIndex: traverseDomOrigin(origin, mappingResult.charIndex), }) ); }); app.post("/inspect", (req, res) => { allowCrossOrigin(res); app.verifyToken(req); getPageSession(req.body.pageSessionId).logToInspect = req.body.logId; res.end("{}"); broadcast( wss, JSON.stringify({ type: "inspectOperationLog", operationLogId: getPageSession(req.body.pageSessionId).logToInspect, }), req.body.pageSessionId ); }); } function getUrlLocsPath(options: BackendOptions, url) { return ( options.sessionDirectory + "/locsByUrl/" + url.replace(/[^a-zA-Z0-9]/g, "_") ); } async function generateUrlLocs({ locStore, options, }: { locStore: LocStore; options: BackendOptions; }) { return new Promise((resolve, reject) => { let locsByUrl = {}; let i = locStore.db.iterator(); function iterate(error, key, value) { if (value) { value = JSON.parse(value); locsByUrl[value.url] = locsByUrl[value.url] || []; locsByUrl[value.url].push(key.toString()); } if (key) { i.next(iterate); } else { for (const url of Object.keys(locsByUrl)) { fs.writeFileSync( getUrlLocsPath(options, url), JSON.stringify(locsByUrl[url], null, 2) ); } console.log("Done generate url locs"); } } i.next(iterate); }); } function setupBackend( options: BackendOptions, app, wss, getProxy, files, locLogs, logUses, getRequestHandler, locStore: LocStore, logServer: LevelDBLogServer ) { function getLocs(url) { return JSON.parse(fs.readFileSync(getUrlLocsPath(options, url), "utf-8")); return new Promise((resolve, reject) => { let locs: any[] = []; let i = locStore.db.iterator(); function iterate(error, key, value) { if (value) { value = JSON.parse(value); if (value.url.includes(url)) { locs.push({ key: key.toString(), value }); } } if (key) { i.next(iterate); } else { resolve(locs); } } i.next(iterate); }); } app.get("/xyzviewer", async (req, res) => { res.end(`<!doctype html> <style> .myInlineDecoration-multiline-start { background: cyan; cursor: pointer; } .myInlineDecoration-has { background: yellow; cursor: pointer; } .myInlineDecoration-hasMany { background: orange; cursor: pointer; } .myInlineDecoration-none { background: #ddd; cursor: pointer; } </style> <script> window["backendPort"] =7000; window["backendOriginWithoutPort"] = "${options.backendOriginWithoutPort}" </script> <div> <div id="appx"></div> </div> <script src="http://localhost:7000/dist/bundle.js"></script> `); }); app.get("/xyzviewer/fileInfo", (req, res) => { res.json(files); }); app.get("/xyzviewer/fileDetails/:fileKey", async (req, res) => { let file = files.find((f) => f.fileKey === req.params.fileKey); let url = file.url; const { body: fileContent } = await getRequestHandler().handleRequest({ url: url + "?dontprocess", method: "GET", }); const locKeys = (await getLocs(url)) as any; const locs = await Promise.all( locKeys.map(async (locKey) => { let loc = (await new Promise((resolve) => locStore.getLoc(locKey, resolve) )) as any; let logs = await locLogs.getLogs(locKey); loc.logCount = logs.length; loc.key = locKey; return loc; }) ); res.json({ fileContent, locs }); }); function getLogs(locId) { return new Promise((resolve, reject) => { let iterator = logServer.db.iterator(); let logs: any[] = []; async function iterate(err, key, value) { if (value) { value = JSON.parse(value.toString()); if (value.loc === locId) { logs.push({ key: key.toString(), value: value, }); } iterator.next(iterate); } else { resolve(logs); } } iterator.next(iterate); }); } function getLogsWhere(whereFn) { return new Promise((resolve, reject) => { let iterator = logServer.db.iterator(); let logs: any[] = []; async function iterate(err, key, value) { if (value) { value = JSON.parse(value.toString()); if (whereFn(value)) { logs.push({ key: key.toString(), value: value, }); } iterator.next(iterate); } else { resolve(logs); } } iterator.next(iterate); }); } async function findUses(logIndex) { let uses: any[] = []; let lookupQueue = [logIndex]; while (lookupQueue.length > 0) { let lookupIndex = lookupQueue.shift(); let u = (await Promise.all( (logUses[lookupIndex] || []).map(async (uIndex) => { return { value: await logServer.loadLogAwaitable(uIndex, 0), }; }) )) as any[]; for (const uu of u) { lookupQueue.push(uu.value.index); uses.push({ use: uu, lookupIndex }); } } return uses; // let uses = []; // let lookupQueue = [logIndex]; // while (lookupQueue.length > 0) { // let lookupIndex = lookupQueue.shift(); // let u = await getLogsWhere(log => { // return Object.keys(log.args || {}).some(k => { // let v = log.args[k]; // if (typeof v === "number") { // return v === lookupIndex; // } else if (Array.isArray(v)) { // return v.includes(lookupIndex); // } else if (v) { // throw Error("not possible i think"); // } // return false; // }); // // return log.index === 624973639059090; // }); // for (const uu of u) { // lookupQueue.push(uu.value.index); // uses.push(uu); // } // } // return uses; } app.get("/xyzviewer/getUses/:logId", async (req, res) => { let uses = (await findUses(parseFloat(req.params.logId))) as any; if (req.query.operationFilter) { uses = uses.filter( (u) => u.use.value.operation === req.query.operationFilter ); } uses = await Promise.all( uses.map(async (u) => { const log = (await logServer.loadLogAwaitable( u.use.value.index, 1 )) as any; const arg = Object.entries(log.args).filter( //@ts-ignore ([i, l]) => l && l.index === u.lookupIndex ); const argName = arg && arg[0] && arg[0][0]; return { use: log, argName, }; }) ); res.json(uses); }); app.get("/xyzviewer/trackingDataForLoc/:locId", async (req, res) => { console.time("get logs"); // let locs = (await getLogs(req.params.locId)) as any; let logs = await locLogs.getLogs(req.params.locId); console.timeEnd("get logs"); console.log(logs); logs = await Promise.all( logs.map(async (logIndex) => { let v2; try { v2 = await logServer.loadLogAwaitable(parseFloat(logIndex), 0); } catch (err) { return null; } return { key: logIndex, value: v2, }; }) ); logs = logs.filter((l) => !!l); res.json(logs); }); app.get("/jsFiles/compileInBrowser.js", (req, res) => { const code = fs .readFileSync(coreDir + "/../compileInBrowser.js") .toString(); res.end(code); }); app.get("/jsFiles/babel-standalone.js", (req, res) => { const code = fs .readFileSync(coreDir + "/../babel-standalone.js") .toString(); res.end(code); }); let eventsPath = options.sessionDirectory + "/events.json"; function readEvents() { let events = []; if (fs.existsSync(eventsPath)) { events = JSON.parse(fs.readFileSync(eventsPath, "utf-8")); } return events; } function writeEvents(events) { fs.writeFileSync(eventsPath, JSON.stringify(events, null, 2)); } let luckyMatchesPath = options.sessionDirectory + "/luckyMatches.json"; function readLuckyMatches() { let luckyMatches = []; if (fs.existsSync(luckyMatchesPath)) { luckyMatches = JSON.parse(fs.readFileSync(luckyMatchesPath, "utf-8")); } return luckyMatches; } function writeLuckyMatches(luckyMatches) { fs.writeFileSync(luckyMatchesPath, JSON.stringify(luckyMatches, null, 2)); } // app.post("/setEnableInstrumentation", (req, res) => { // const { enableInstrumentation } = req.body; // getProxy().setEnableInstrumentation(enableInstrumentation); // res.end(JSON.stringify(req.body)); // }); async function doStoreLogs(reqBody) { const lines = reqBody.split("\n"); let evalScriptsJson = lines.shift(); let eventsJson = lines.shift(); let luckyMatchesJson = lines.shift(); let logLines = lines; console.log({ luckyMatchesJson }); const logs: any[] = []; for (var i = 0; i < logLines.length - 1; i += 2) { const logItem = [logLines[i], logLines[i + 1]]; logs.push(logItem); } const startTime = new Date(); let evalScripts = JSON.parse(evalScriptsJson); evalScripts.forEach(function (evalScript) { locStore.write(evalScript.locs, () => {}); getRequestHandler()._afterCodeProcessed({ url: evalScript.url, raw: evalScript.code, instrument: evalScript.instrumentedCode, fileKey: "eval-" + Math.random(), details: evalScript.details, }); // getProxy().registerEvalScript(evalScript); }); let events = JSON.parse(eventsJson); if (events.length > 0) { writeEvents([...readEvents(), ...events]); } let luckyMatches = JSON.parse(luckyMatchesJson); if (luckyMatches.length > 0) { writeLuckyMatches([...readLuckyMatches(), ...luckyMatches]); } await new Promise((resolve) => logServer.storeLogs(logs, function () { const timePassed = new Date().valueOf() - startTime.valueOf(); console.log("stored logs", logs.length); if (LOG_PERF) { const timePer1000 = Math.round((timePassed / logs.length) * 1000 * 10) / 10; console.log( "storing logs took " + timePassed + "ms, per 1000 logs: " + timePer1000 + "ms" ); } resolve(); }) ); } app.get("/loadLocForTest/:locId", async (req, res) => { locStore.getLoc(req.params.locId, (loc) => { resolver .resolveFrameFromLoc(loc, req.params.prettify === "prettify") .then((rr) => { res.json({ loc, rr }); }); }); }); app.get("/loadLogForTest/:logId", async (req, res) => { const log = await logServer.loadLogAwaitable( parseFloat(req.params.logId), 1 ); res.json(log); }); app.post("/loadLog", (req, res) => { // crude way to first wait for any new logs to be sent through... setTimeout(function () { // console.log(Object.keys(internalServerInterface._storedLogs)); logServer.loadLog(req.body.id, function (err, log) { res.end(JSON.stringify(log)); }); }, 500); }); async function getNextStepFromFileContents(lastStep, loc: any = null) { console.log("last step op", lastStep.operationLog.operation); if ( lastStep.operationLog.operation !== "stringLiteral" && lastStep.operationLog.operation !== "numericLiteral" && lastStep.operationLog.operation !== "templateLiteral" && lastStep.operationLog.operation !== "initialPageHtml" ) { // if e.g. it's a localstorage value then we don't want to // inspect the code for it!! // really mostly just string literal has that kind of sensible mapping return; } let overwriteFile: any = null; if ( lastStep.operationLog.operation === "initialPageHtml" && process.env.REPORT_TV ) { overwriteFile = reportHtmlFileInfo; } else if (!lastStep.operationLog.loc) { return; } if (!loc) { if (overwriteFile) { loc = { url: overwriteFile.url, start: { line: 1, column: 0, }, }; } else if (lastStep.operationLog.loc) { console.log(JSON.stringify(lastStep, null, 2)); loc = (await new Promise((resolve) => locStore.getLoc(lastStep.operationLog.loc, (loc) => resolve(loc)) )) as any; } } let file = files.find((f) => f.url === loc.url); if (overwriteFile) { file = overwriteFile; } if (file.sourceOperationLog) { // const log = await logServer.loadLogAwaitable( // file.sourceOperationLog, // 1 // ); let { body: fileContent } = await getRequestHandler().handleRequest({ url: loc.url + "?dontprocess", method: "GET", headers: {}, }); let lineColumn = require("line-column"); let charIndex = lineColumn(fileContent.toString()).toIndex({ line: loc.start.line, column: loc.start.column + 1, // lineColumn uses origin of 1, but babel uses 0 }) + file.sourceOffset + lastStep.charIndex; // // this makes stuff better... maybe it adjusts for the quote sign for string literals in the code? // i think it also causes off-by-one errors, but we fix those with fixOffByOneTraversalError charIndex++; console.log("will traverse", file); let operationLog = await logServer.loadLogAwaitable( file.sourceOperationLog, 1 ); return { charIndex, operationLog, }; } } async function getNextStepFromLuckyMatches(lastStep) { let stepToUse = lastStep; if (!stepToUse || stepToUse.operationLog.result.type === "undefined") { return; } const luckyMatches: any[] = readLuckyMatches(); const match = luckyMatches.find( (m) => m.value === stepToUse.operationLog.result.primitive ); if (match) { return { operationLog: match.trackingValue, charIndex: stepToUse.charIndex, }; } } function handleTraverse( logId, charIndex, opts: { keepResultData?: boolean } = {} ): Promise<TraversalStep[]> { return new Promise((resolve) => { const tryTraverse = (previousAttempts = 0) => { logServer.hasLog(logId, (hasLog) => { if (hasLog) { finishRequest(); } else { const timeout = 250; const timeElapsed = timeout * previousAttempts; if (timeElapsed > 5000) { resolve({ err: "Log not found (" + logId + ")- might still be saving data", } as any); return; } else { setTimeout(() => { tryTraverse(previousAttempts + 1); }, timeout); } } }); }; const finishRequest = async function finishRequest() { let steps; try { if (LOG_PERF) { console.time("Traverse " + logId); } steps = await traverse( { operationLog: logId, charIndex: charIndex, }, [], logServer, { optimistic: true, events: readEvents() } ); while (true) { let lastStep = steps[steps.length - 1]; let nextStep = await getNextStepFromFileContents(lastStep); if (!nextStep) { nextStep = await getNextStepFromLuckyMatches(lastStep); if (nextStep) { console.log( "lucky match", JSON.stringify(nextStep).slice(0, 100) ); } } else { console.log("FILE CONT"); } if (nextStep) { fixOffByOneTraversalError(lastStep, nextStep); let s = (await traverse(nextStep as any, [], logServer, { optimistic: true, events: readEvents(), })) as any; steps = [...steps, ...s]; } else { break; } } if (LOG_PERF) { console.timeEnd("Traverse " + logId); } } catch (err) { console.log(err); resolve({ err: "Log not found in backend, or other error(" + logId + ")", } as any); return; } steps.forEach((step) => { let { operationLog, charIndex } = step; const str = operationLog._result && operationLog._result + ""; step.chars = [ str[charIndex - 1] || " ", str[charIndex] || " ", str[charIndex + 1] || " ", ]; }); if (!opts.keepResultData) { // Avoid massive respondes (can be 100s of MB) steps.forEach((step, i) => { traverseObject(step, (keyPath, value, key, obj) => { if ( key === "_result" && value && JSON.stringify(value).length > 250 ) { obj[key] = undefined; } if (key === "jsonIndexToTrackingValue") { obj[key] = "omitted"; } if (key.startsWith("replacement")) { obj[key] = undefined; } }); }); } resolve(steps); }; tryTraverse(); }); } app.get("/search", async (req, res) => { let i = logServer.db.iterator(); let index = 0; let search = "lighthouse"; function iterate(error, key, value) { if (value) { index++; if (index % 50000 === 0) { console.log({ index }); } if (value.includes(search)) { console.log({ key: key.toString(), value: value.toString() }); } i.next(iterate); } else { res.end("done"); } } i.next(iterate); }); app.get("/logResult/:logIndex/:charIndex", async (req, res) => { let log = (await logServer.loadLogAwaitable(req.params.logIndex, 1)) as any; let json; if ( typeof log._result === "string" && log._result.length > 100 && !log._result.includes("\n") ) { try { let parsed = JSON.parse(log._result); let charIndex = req.params.charIndex; const prettier = require("prettier"); json = prettier.formatWithCursor(log._result, { cursorOffset: req.params.charIndex, parser: "json", }); json.charIndex = json.cursorOffset; delete json.cursorOffset; } catch (err) { console.log("not json", err); // not json } } res.json({ json, _result: log._result, }); }); app.get("/traverse", async (req, res) => { const { logId, charIndex } = req.query; const opts = { keepResultData: "keepResultData" in req.query, }; console.log(opts); let ret = (await handleTraverse( parseFloat(logId), parseFloat(charIndex), opts )) as any; if (ret.err) { res.status(500); res.end( JSON.stringify({ err: ret.err, }) ); } else { res.end(JSON.stringify({ steps: ret }, null, 2)); } }); let resolver: StackFrameResolver; setTimeout(() => { resolver = new StackFrameResolver(getRequestHandler()); }, 200); app.get("/resolveStackFrame/:loc/:prettify?", (req, res) => { locStore.getLoc(req.params.loc, async (loc) => { let file = files.find((f) => f.url === loc.url); if (file.sourceOperationLog) { let sourceLog = await logServer.loadLogAwaitable( file.sourceOperationLog, 1 ); if (sourceLog && sourceLog.runtimeArgs && sourceLog.runtimeArgs.url) { file.sourceUrl = sourceLog.runtimeArgs.url; if (file.sourceUrl === reportHtmlFileInfo.url) { let htmlStep = await getNextStepFromFileContents( { operationLog: sourceLog, charIndex: file.sourceOffset, }, loc ); if (htmlStep) { let steps = await handleTraverse( htmlStep.operationLog?.index, htmlStep.charIndex ); file.lastSourceTraversalStep = steps[steps.length - 1]; } } } } resolver .resolveFrameFromLoc(loc, req.params.prettify === "prettify") .then((rr: any) => { res.end(JSON.stringify({ ...rr, file, loc }, null, 4)); }); }); }); app.get("/viewFullCode/:url", (req, res) => { const url = decodeURIComponent(req.params.url); res.end(resolver.getFullSourceCode(url)); }); // app.post("/instrument", (req, res) => { // const code = req.body.code; // getProxy() // .instrumentForEval(code) // .then(babelResult => { // res.end( // JSON.stringify({ instrumentedCode: babelResult.instrumentedCode }) // ); // }); // }); return { storeLocs: async (locs) => { locStore.write(locs, function () {}); }, handleTraverse, doStoreLogs, }; } function broadcast(wss, data, pageSessionId) { wss.clients.forEach(function each(client) { if (client.pageSessionId === pageSessionId) { if (client.readyState === WebSocket.OPEN) { client.send(data); } } else { console.log( "Not broadcasting to client", client.pageSessionId, pageSessionId ); } }); } function allowCrossOriginRequests(req, res) { allowCrossOrigin(res); res.end(); } function allowCrossOrigin(res) { res.set("Access-Control-Allow-Origin", "*"); res.set( "Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" ); } export { BackendOptions }; function makeRequestHandler(options) { let defaultBlockList = [ "inspectlet.com", // does a whole bunch of stuff that really slows page execution down "google-analytics.com", "newrelic.com", // overwrites some native functions used directly in FromJS (shouldn't be done ideally, but for now blocking is easier) "intercom.com", "segment.com", "bugsnag", "mixpanel", "piwik", ]; return new RequestHandler({ shouldInstrument: ({ url }) => { if (options.options.dontTrack.some((dt) => url.includes(dt))) { return false; } if ( url.includes("product_registry_impl_module.js") && url.includes("chrome-devtools-frontend") ) { // External file loaded by Chrome DevTools when opened return false; } let u = new URL(url); return ( parseFloat(u.port) !== options.options.bePort || u.pathname.startsWith("/start") || u.pathname.startsWith("/fromJSInternal") ); }, shouldBlock: ({ url }) => { if (options.options.block.some((dt) => url.includes(dt))) { return true; } if ( !options.options.disableDefaultBlockList && defaultBlockList.some((dt) => url.includes(dt)) ) { console.log( url + " blocked because it's on the default block list. You can disable this by passing in --disableDefaultBlockList" ); return true; } return false; }, backendOriginWithoutPort: options.options.backendOriginWithoutPort, backendPort: options.options.bePort, accessToken: options.accessToken, storeLocs: options.storeLocs, sessionDirectory: options.options.sessionDirectory, files: options.files, onCodeProcessed: ({ url, fileKey, details }) => { options.files.push({ url, createdAt: new Date(), fileKey, nodePath: details && details.nodePath, sourceOperationLog: details && details.sourceOperationLog, sourceOffset: details && details.sourceOffset, }); fs.writeFileSync( options.options.sessionDirectory + "/files.json", JSON.stringify(options.files, null, 2) ); }, }); } export async function openBrowser({ userDataDir, extraArgs, config }) { let extensionPath = path.resolve(extensionDir); const browser = await puppeteer.launch({ headless: false, dumpio: true, ignoreDefaultArgs: ["--disable-extensions"], args: [ `--js-flags="--max_old_space_size=8192"`, // "--proxy-server=127.0.0.1:" + proxyPort, // "--disable-extensions-except=" + extensionPath, "--load-extension=" + extensionPath, // "--ignore-certificate-errors", // "--test-type", // otherwise getting unsupported command line flag: --ignore-certificate-errors ...(userDataDir ? ["--user-data-dir=" + userDataDir] : []), "--disable-infobars", // disable "controlled by automated test software" message, "--allow-running-insecure-content", // load http inspector UI on https pages, ...extraArgs, ], }); let pages = await browser.pages(); const page = pages[0]; // disable puppeteer default window size emulation await page._client.send("Emulation.clearDeviceMetricsOverride"); // await page.goto("http://localhost:" + bePort + "/start"); console.log("will wait 2s"); await page.waitFor(2000); await page.goto( "http://localhost:" + config.backendPort + "/fromJSInitPage?config=" + encodeURIComponent(JSON.stringify(config)) ); console.log("will wait 2s"); await page.waitFor(2000); console.log("PAGE: ", page.url()); console.log("Created browser", { config }); return browser; }
the_stack
import { getBoundingClientRect, getScrollParents, getOffsetParents, canUseDOM, findDOMNode, ownerDocument, ownerWindow } from '@instructure/ui-dom-utils' import type { RectType } from '@instructure/ui-dom-utils' import { mirrorPlacement } from './mirrorPlacement' import { PlacementPropValues, PlacementValues, PositionConstraint, PositionMountNode, ElementPosition, PositionElement, Size, Overflow, Offset } from './PositionPropTypes' import { UIElement } from '@instructure/shared-types' type PlacementValuesWithoutOffscreen = Exclude<PlacementValues, 'offscreen'> type PlacementPropValuesWithoutOffscreen = Exclude< PlacementPropValues, 'offscreen' > type PlacementValuesWithoutOffscreenArray = [ PlacementValuesWithoutOffscreen, PlacementValuesWithoutOffscreen ] type Options = { placement?: PlacementPropValues offsetX?: string | number offsetY?: string | number constrain?: PositionConstraint container?: PositionMountNode over?: boolean } function calculateElementPosition( element?: PositionElement, target?: PositionElement, options: Options = {} ): ElementPosition { if (!element || options.placement === 'offscreen') { // hide offscreen content at the bottom of the DOM from screenreaders // unless content is contained somewhere else const hide = !options.container && element return { placement: options.placement, style: { left: '-9999em', overflow: 'hidden', position: 'absolute', top: 0, display: hide ? 'none' : null } } } const pos = new PositionData(element, target, options) return { placement: pos.placement, style: pos.style } } class PositionedElement { constructor( element: UIElement, placement?: | PlacementPropValuesWithoutOffscreen | PlacementValuesWithoutOffscreenArray, offset: Offset<string | number | undefined> = { top: 0, left: 0 } ) { this.node = findDOMNode(element) if (typeof placement === 'string') { this.placement = parsePlacement(placement) } else if (Array.isArray(placement)) { this.placement = placement } else { this.placement = ['bottom', 'center'] } this.rect = getBoundingClientRect(this.node) this._offset = offsetToPx(offset, this.size) } node?: Node | Window | null placement: PlacementValuesWithoutOffscreenArray rect: RectType _offset: Offset<string | number> get width() { return this.rect.width } get height() { return this.rect.height } get size() { return { width: this.width, height: this.height } } get position() { return { top: this.rect.top, left: this.rect.left } } get hasVerticalPlacement() { return ['top', 'bottom'].indexOf(this.placement[0]) >= 0 } get hasHorizontalPlacement() { return ['start', 'end'].indexOf(this.placement[0]) >= 0 } get shouldStretchVertically() { return this.placement[1] === 'stretch' && this.hasVerticalPlacement } get shouldStretchHorizontally() { return this.placement[1] === 'stretch' && this.hasHorizontalPlacement } get mirroredPlacement() { return mirrorPlacement( this.placement ) as PlacementValuesWithoutOffscreenArray } calculateOffset(placement: PlacementValuesWithoutOffscreenArray) { const offsetMap: Record<PlacementValuesWithoutOffscreen, string | 0> = { top: 0, start: 0, center: '50%', bottom: '100%', end: '100%', stretch: 0 } let [first, second] = placement if (['start', 'end'].indexOf(first) >= 0) { ;[first, second] = [second, first] } let top: string | 0 = 0 let left: string | 0 = 0 if (typeof offsetMap[first] !== 'undefined') { top = offsetMap[first] } if (typeof offsetMap[second] !== 'undefined') { left = offsetMap[second] } return addOffsets([ offsetToPx({ top, left }, this.size), parseOffset(this._offset, this.placement) ]) } get scrollParentsOffset() { const parents = getScrollParents(this.node) let offsetY = 0 let offsetX = 0 for (let i = 1; i < parents.length; i++) { const parent = parents[i] const child = parents[i - 1] if (parent) { offsetY = offsetY + (this.normalizeScrollTop(parent) - this.normalizeScrollTop(child)) offsetX = offsetX + ((parent as Element).scrollLeft - (child as Element).scrollLeft) } } return { top: offsetY, left: offsetX } as Offset } get positionedParentsOffset() { // If the element container is within a positioned // element, it will position absolutely with respect to that // ancestor. We calculate the offset between the child and // positioned parent so we can negate that distance const parents = getOffsetParents(this.node) const doc = ownerDocument(this.node) // If there is more than one parent, the offset on the // documentElement should be calculated appropriately. // Otherwise we need to explictly account for that offset let offsetY = parents.length > 1 ? 0 : getBoundingClientRect(doc.documentElement).top let offsetX = 0 let scrollY = 0 for (let i = 1; i < parents.length; i++) { const parent = getBoundingClientRect(parents[i]) const child = getBoundingClientRect(parents[i - 1]) offsetY = offsetY + (child.top - parent.top) offsetX = offsetX + (child.left - parent.left) if (parents[i] === doc.body) { // accounts for any margin on body offsetY = offsetY + parent.top offsetX = offsetX + parent.left } scrollY = scrollY + this.normalizeScrollTop(parents[i]) } // Account for any scrolling on positioned parents // Without this, unnecessary scroll offset could be applied // to our target element offsetY = offsetY + scrollY return { top: offsetY, left: offsetX } as Offset } normalizeScrollTop(element: Node | Window | null) { // Account for cross browser differences with scrollTop attribute on the // body element https://bugs.chromium.org/p/chromium/issues/detail?id=766938 return ownerDocument(this.node).body === element ? 0 : (element as Element).scrollTop } } class PositionData { constructor( element?: PositionElement, target?: PositionElement, options?: Options ) { this.options = options || {} const { container, constrain, placement, over } = this.options if (!element || placement === 'offscreen') return this.container = container || ownerDocument(element).body this.element = new PositionedElement(element, placement, { top: this.options.offsetY, left: this.options.offsetX }) this.target = new PositionedElement( target || this.container, over ? this.element.placement : this.element.mirroredPlacement ) if (constrain === 'window') { this.constrainTo(ownerWindow(element)) } else if (constrain === 'scroll-parent') { this.constrainTo(getScrollParents(this.target.node)[0]) } else if (constrain === 'parent') { this.constrainTo(this.container) } else if (typeof constrain === 'function') { this.constrainTo(findDOMNode(constrain.call(null))) } else if (typeof constrain === 'object') { this.constrainTo(findDOMNode(constrain)) } } options: Options container?: PositionMountNode element!: PositionedElement target!: PositionedElement get offset(): Offset { const { top, left } = this.target.calculateOffset(this.element.placement) const offset = addOffsets([ this.element.calculateOffset(this.target.placement), this.element.scrollParentsOffset, this.element.positionedParentsOffset ]) return { top: top - offset.top, left: left - offset.left } } get placement() { return formatPlacement(this.element.placement) } get minWidth() { return this.element.shouldStretchVertically ? this.target.width : null } get minHeight() { return this.element.shouldStretchHorizontally ? this.target.height : null } get position() { const win = ownerWindow(this.target.node) let { left, top } = addOffsets([this.target.position, this.offset]) if (canUseDOM && win?.matchMedia) { const retina = win.matchMedia('only screen and (min-resolution: 1.3dppx)').matches || win.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3)') .matches if (!retina) { left = Math.round(left) top = Math.round(top) } } return { left, top } as Offset } get style(): ElementPosition['style'] { // when rendered offscreen first, element has no dimension on first calculation, // so we hide it offscreen until measurements are completed const { width, height } = this.element.size const elementNotFullyRendered = width === 0 && height === 0 return { top: 0, left: elementNotFullyRendered ? '-9999em' : 0, minWidth: this.minWidth, minHeight: this.minHeight, position: 'absolute', transform: `translateX(${this.position.left}px) translateY(${this.position.top}px) translateZ(0)` } } overflow(element: PositionElement): Overflow { const parentWindow = ownerWindow(element) const elementBounds = getBoundingClientRect(element) const windowBounds = getBoundingClientRect(parentWindow) const offsets = addOffsets([this.target.position, this.offset]) const parentOffset: Offset = { top: this.element.positionedParentsOffset.top + this.element.scrollParentsOffset.top, left: this.element.positionedParentsOffset.left + this.element.scrollParentsOffset.left } let left = offsets.left + parentOffset.left let right = offsets.left + this.element.width + parentOffset.left let top = offsets.top + parentOffset.top let bottom = offsets.top + this.element.height + parentOffset.top // adjust for vertical placements if (this.element.placement[0] === 'bottom') { top -= this.element.height + this.target.height } else if (this.element.placement[0] === 'top') { bottom += this.element.height + this.target.height } if (this.element.placement[1] === 'start') { left -= this.element.width - this.target.width } else if (this.element.placement[1] === 'end') { right += this.element.width - this.target.width } // adjust for horizontal placements if (this.element.placement[1] === 'top') { top -= this.element.height - this.target.height } else if (this.element.placement[1] === 'bottom') { bottom += this.element.height - this.target.height } if (this.element.placement[0] === 'end') { left -= this.element.width + this.target.width } else if (this.element.placement[0] === 'start') { right += this.element.width + this.target.width } const bounds = element === parentWindow ? elementBounds : { top: windowBounds.top + elementBounds.top, bottom: elementBounds.top + elementBounds.height, left: windowBounds.left + elementBounds.left, right: elementBounds.left + elementBounds.width } return { top: top < bounds.top ? bounds.top - top : 0, bottom: bottom > bounds.bottom ? bottom - bounds.bottom : 0, left: left < bounds.left ? bounds.left - left : 0, right: right > bounds.right ? right - bounds.right : 0 } } constrainTo(element?: PositionElement) { if (!element) return const overflow = this.overflow(element) const oob = { top: overflow.top > 0, bottom: overflow.bottom > 0, left: overflow.left > 0, right: overflow.right > 0 } if (this.element.hasVerticalPlacement) { if (this.element.placement[1] !== 'stretch') { if (oob.left && oob.right) { this.element.placement[1] = 'center' this.target.placement[1] = 'center' } else if (oob.left) { this.element.placement[1] = 'start' this.target.placement[1] = 'start' } else if (oob.right) { this.element.placement[1] = 'end' this.target.placement[1] = 'end' } } if (oob.top && oob.bottom) { // if top and bottom bounds broken if (overflow.bottom < overflow.top) { // more room on bottom, position below this.element.placement[0] = 'bottom' this.target.placement[0] = 'top' } else if (overflow.bottom > overflow.top) { // more room on top, position above this.element.placement[0] = 'top' this.target.placement[0] = 'bottom' } } else if (oob.top) { // if top bound broken, position below this.element.placement[0] = 'bottom' this.target.placement[0] = 'top' } else if (oob.bottom) { // if bottom bound broken, position above this.element.placement[0] = 'top' this.target.placement[0] = 'bottom' } } else if (this.element.hasHorizontalPlacement) { if (oob.top && oob.bottom) { this.element.placement[1] = 'center' this.target.placement[1] = 'center' } else if (oob.top) { this.element.placement[1] = 'top' this.target.placement[1] = 'top' } else if (oob.bottom) { this.element.placement[1] = 'bottom' this.target.placement[1] = 'bottom' } if (oob.left && oob.right) { // if left and right bounds broken if (overflow.left > overflow.right) { // more room at end, position after this.element.placement[0] = 'end' this.target.placement[0] = 'start' } else if (overflow.left < overflow.right) { // more room at start, position before this.element.placement[0] = 'start' this.target.placement[0] = 'end' } } else { if (oob.left) { this.element.placement[0] = 'end' this.target.placement[0] = 'start' } else if (oob.right) { this.element.placement[0] = 'start' this.target.placement[0] = 'end' } } } } } function addOffsets(offsets: Offset[]) { return offsets.reduce( (sum, offset) => { return { top: sum.top + offset.top, left: sum.left + offset.left } }, { top: 0, left: 0 } ) } function parseOffset( offset: Offset<number | string>, placement: PlacementValuesWithoutOffscreenArray ) { let { top, left } = offset if (typeof left === 'string') { left = parseFloat(left) } if (typeof top === 'string') { top = parseFloat(top) } if (placement[0] === 'bottom') { top = 0 - top } if (placement[0] === 'end') { left = 0 - left } return { top, left } as Offset } function offsetToPx(offset: Offset<string | number | undefined>, size: Size) { let { left, top } = offset if (typeof left === 'string' && left.indexOf('%') !== -1) { left = (parseFloat(left) / 100) * size.width // eslint-disable-line no-mixed-operators } if (typeof top === 'string' && top.indexOf('%') !== -1) { top = (parseFloat(top) / 100) * size.height // eslint-disable-line no-mixed-operators } return { top, left } as Offset<number> } function sortPlacement(placement: PlacementValuesWithoutOffscreenArray) { let [first, second] = placement if (first === 'center' || first === 'stretch') { ;[first, second] = [second, first] } return [first, second] as PlacementValuesWithoutOffscreenArray } function parsePlacement(placement: PlacementPropValues) { let parsed = placement.split(' ') as PlacementValuesWithoutOffscreenArray if ((parsed as Partial<PlacementValuesWithoutOffscreenArray>).length === 1) { parsed = [placement as PlacementValuesWithoutOffscreen, 'center'] } return sortPlacement(parsed) } function formatPlacement(placement: PlacementValuesWithoutOffscreenArray) { return placement.join(' ') as PlacementPropValuesWithoutOffscreen } export default calculateElementPosition export { /** * --- * category: utilities/position * --- * * Calculate the coordinates to attach an element * to a designated target with specified constraints * @module * @param {ReactComponent|DomNode} el - component or DOM node * @param {DomNode} target - the target DOM node * @param {Object} options - constraints for the positioning * @param {string} options.placement - designates where the element will be attached * ('top', 'bottom', 'left', 'right', 'top left' etc.) * @param {DomNode} options.container - DOM node where the element is contained * @param {boolean} options.over - whether or not you want the element to position over the target * @param {string} options.constrain - if the element should be constrained to 'window', * 'scroll-parent', 'parent', or 'none' * @param {string|number} options.offsetX - the horizontal offset for the positioned element * @param {string|number} options.offsetY - the vertical offset for the positioned element * @returns {Object} object containing style with the calculated position in the 'transform' * property */ calculateElementPosition, parsePlacement }
the_stack
import { AfterContentInit, ContentChildren, Directive, ElementRef, HostBinding, Input, OnDestroy, QueryList, Renderer2, Output, EventEmitter, HostListener, Inject } from '@angular/core'; import { MDCMenuSurfaceFoundation, MDCMenuSurfaceAdapter, util, cssClasses, Corner } from '@material/menu-surface'; import { asBoolean } from '../../utils/value.utils'; import { DOCUMENT } from '@angular/common'; /** * The `mdcMenuSurface` is a reusable surface that appears above the content of the page * and can be positioned adjacent to an element. It is required as the surface for an `mdcMenu` * but can also be used by itself. */ @Directive({ selector: '[mdcMenuSurface],[mdcMenu],[mdcSelectMenu]' }) export class MdcMenuSurfaceDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-menu-surface') readonly _cls = true; private _open = false; private _openFrom: 'tl' | 'tr' | 'bl' | 'br' | 'ts' | 'te' | 'bs' | 'be' = 'ts'; // the anchor to use if no menuAnchor is provided (a direct parent MdcMenuAnchor if available): /** @internal */ _parentAnchor: MdcMenuAnchorDirective | null = null; /** * Assign an (optional) element or `mdcMenuAnchor`. If set the menu * will position itself relative to this anchor element. Assigning this property is not needed * if you wrap your surface inside an `mdcMenuAnchor`. */ @Input() menuAnchor: MdcMenuAnchorDirective | Element | null = null; /** * Assign any `HTMLElement` to this property to use as the viewport instead of * the window object. The menu will choose to open from the top or bottom, and * from the left or right, based on the space available inside the viewport. * * You should probably not use this property. We only use it to keep the documentation * snippets on our demo website contained in their window. */ @Input() viewport: HTMLElement | null = null; /** * Event emitted when the menu is opened or closed. (When this event is triggered, the * surface is starting to open/close, but the animation may not have fully completed * yet). */ @Output() readonly openChange: EventEmitter<boolean> = new EventEmitter(); /** * Event emitted after the menu has fully opened. When this event is emitted the full * opening animation has completed, and the menu is visible. */ @Output() readonly afterOpened: EventEmitter<void> = new EventEmitter(); /** * Event emitted after the menu has fully closed. When this event is emitted the full * closing animation has completed, and the menu is not visible anymore. */ @Output() readonly afterClosed: EventEmitter<void> = new EventEmitter(); private _prevFocus: Element | null = null; private _hoisted = false; private _fixed = false; private _handleBodyClick = (event: MouseEvent) => this.handleBodyClick(event); private mdcAdapter: MDCMenuSurfaceAdapter = { addClass: (className: string) => this.rndr.addClass(this._elm.nativeElement, className), removeClass: (className: string) => this.rndr.removeClass(this._elm.nativeElement, className), hasClass: (className: string) => { if (className === cssClasses.ROOT) return true; if (className === cssClasses.OPEN) return this._open; return this._elm.nativeElement.classList.contains(className); }, hasAnchor: () => !!this._parentAnchor || !!this.menuAnchor, isElementInContainer: (el: Element) => this._elm.nativeElement.contains(el), isFocused: () => this.document.activeElement === this._elm.nativeElement, isRtl: () => getComputedStyle(this._elm.nativeElement).getPropertyValue('direction') === 'rtl', getInnerDimensions: () => ({width: this._elm.nativeElement.offsetWidth, height: this._elm.nativeElement.offsetHeight}), getAnchorDimensions: () => { const anchor = this.menuAnchor || this._parentAnchor; if (!anchor) return null; if (!this.viewport) return anchor.getBoundingClientRect(); let viewportRect = this.viewport.getBoundingClientRect(); let anchorRect = anchor.getBoundingClientRect(); return { bottom: anchorRect.bottom - viewportRect.top, left: anchorRect.left - viewportRect.left, right: anchorRect.right - viewportRect.left, top: anchorRect.top - viewportRect.top, width: anchorRect.width, height: anchorRect.height }; }, getWindowDimensions: () => ({ width: this.viewport ? this.viewport.clientWidth : this.document.defaultView!.innerWidth, height: this.viewport ? this.viewport.clientHeight : this.document.defaultView!.innerHeight }), getBodyDimensions: () => ({ width: this.viewport ? this.viewport.scrollWidth : this.document.body.clientWidth, height: this.viewport ? this.viewport.scrollHeight : this.document.body.clientHeight}), getWindowScroll: () => ({ x: this.viewport ? this.viewport.scrollLeft : this.document.defaultView!.pageXOffset, y: this.viewport ? this.viewport.scrollTop : this.document.defaultView!.pageYOffset }), setPosition: (position) => { let el = this._elm.nativeElement; this.rndr.setStyle(el, 'left', 'left' in position ? `${position.left}px` : ''); this.rndr.setStyle(el, 'right', 'right' in position ? `${position.right}px` : ''); this.rndr.setStyle(el, 'top', 'top' in position ? `${position.top}px` : ''); this.rndr.setStyle(el, 'bottom', 'bottom' in position ? `${position.bottom}px` : ''); }, setMaxHeight: (height: string) => this._elm.nativeElement.style.maxHeight = height, setTransformOrigin: (origin: string) => this.rndr.setStyle(this._elm.nativeElement, `${util.getTransformPropertyName(this.document.defaultView!)}-origin`, origin), saveFocus: () => this._prevFocus = this.document.activeElement, restoreFocus: () => this._elm.nativeElement.contains(this.document.activeElement) && this._prevFocus && (this._prevFocus as any)['focus'] && (this._prevFocus as any)['focus'](), notifyClose: () => { this.afterClosed.emit(); this.document.removeEventListener('click', this._handleBodyClick); }, notifyOpen: () => { this.afterOpened.emit(); this.document.addEventListener('click', this._handleBodyClick); } }; /** @docs-private */ private foundation: MDCMenuSurfaceFoundation | null = null; private document: Document; constructor(private _elm: ElementRef, private rndr: Renderer2, @Inject(DOCUMENT) doc: any) { this.document = doc as Document; // work around ngc issue https://github.com/angular/angular/issues/20351 } ngAfterContentInit() { this.foundation = new MDCMenuSurfaceFoundation(this.mdcAdapter); this.foundation.init(); this.foundation.setFixedPosition(this._fixed); this.foundation.setIsHoisted(this._hoisted); this.updateFoundationCorner(); if (this._open) this.foundation.open(); } ngOnDestroy() { // when we're destroying a closing surface, the event listener may not be removed yet: this.document.removeEventListener('click', this._handleBodyClick); this.foundation?.destroy(); this.foundation = null; } /** * When this input is defined and does not have value false, the menu will be opened, * otherwise the menu will be closed. */ @Input() @HostBinding('class.mdc-menu-surface--open') get open() { return this._open; } set open(val: boolean) { let newValue = asBoolean(val); if (newValue !== this._open) { this._open = newValue; if (newValue) this.foundation?.open(); else this.foundation?.close(); this.openChange.emit(newValue); } } static ngAcceptInputType_open: boolean | ''; /** @internal */ closeWithoutFocusRestore() { if (this._open) { this._open = false; this.foundation?.close(true); this.openChange.emit(false); } } /** * Set this value if you want to customize the direction from which the menu will be opened. * Use `tl` for top-left, `br` for bottom-right, etc. * When the left/right position depends on the text directionality, use `ts` for top-start, * `te` for top-end, etc. Start will map to left in left-to-right text directionality, and to * to right in right-to-left text directionality. End maps the other way around. * The default value is 'ts'. */ @Input() get openFrom(): 'tl' | 'tr' | 'bl' | 'br' | 'ts' | 'te' | 'bs' | 'be' { return this._openFrom; } set openFrom(val: 'tl' | 'tr' | 'bl' | 'br' | 'ts' | 'te' | 'bs' | 'be') { if (val !== this.openFrom) { if (['tl', 'tr', 'bl', 'br', 'ts', 'te', 'bs', 'be'].indexOf(val) !== -1) this._openFrom = val; else this._openFrom = 'ts'; this.updateFoundationCorner(); } } private updateFoundationCorner() { const corner: Corner = { 'tl': Corner.TOP_LEFT, 'tr': Corner.TOP_RIGHT, 'bl': Corner.BOTTOM_LEFT, 'br': Corner.BOTTOM_RIGHT, 'ts': Corner.TOP_START, 'te': Corner.TOP_END, 'bs': Corner.BOTTOM_START, 'be': Corner.BOTTOM_END }[this._openFrom]; this.foundation?.setAnchorCorner(corner); } /** @internal */ setFoundationAnchorCorner(corner: Corner) { this.foundation?.setAnchorCorner(corner); } /** * Set to a value other then false to hoist the menu surface to the body so that the position offsets * are calculated relative to the page and not the anchor. (When a `viewport` is set, hoisting is done to * the viewport instead of the body). */ @Input() get hoisted() { return this._hoisted; } set hoisted(val: boolean) { let newValue = asBoolean(val); if (newValue !== this._hoisted) { this._hoisted = newValue; this.foundation?.setIsHoisted(newValue); } } static ngAcceptInputType_hoisted: boolean | ''; /** * Set to a value other then false use fixed positioning, so that the menu stays in the * same place on the window (or viewport) even if the page (or viewport) is * scrolled. */ @Input() @HostBinding('class.mdc-menu-surface--fixed') get fixed() { return this._fixed; } set fixed(val: boolean) { let newValue = asBoolean(val); if (newValue !== this._fixed) { this._fixed = newValue; this.foundation?.setFixedPosition(newValue); } } static ngAcceptInputType_fixed: boolean | ''; // listened after notifyOpen, listening stopped after notifyClose /** @internal */ handleBodyClick(event: MouseEvent) { if (this.foundation) { this.foundation.handleBodyClick(event); if (this._open && this._open !== this.foundation.isOpen()) {// if just closed: this._open = false; this.openChange.emit(false); } } } /** @internal */ @HostListener('keydown', ['$event']) handleKeydow(event: KeyboardEvent) { if (this.foundation) { this.foundation.handleKeydown(event); if (this._open && this._open !== this.foundation.isOpen()) {// if just closed: this._open = false; this.openChange.emit(false); } } } } /** * Defines an anchor to position an `mdcMenuSurface` to. If this directive is used as the direct parent of an `mdcMenuSurface`, * it will automatically be used as the anchor point. (Unless de `mdcMenuSurface` sets another anchor via its `menuAnchor`property). */ @Directive({ selector: '[mdcMenuAnchor]' }) export class MdcMenuAnchorDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-menu-surface--anchor') readonly _cls = true; /** @internal */ @ContentChildren(MdcMenuSurfaceDirective) private surfaces?: QueryList<MdcMenuSurfaceDirective>; constructor(public _elm: ElementRef) {} ngAfterContentInit() { this.surfaces!.changes.subscribe(_ => { this.setSurfaces(this); }); this.setSurfaces(this); } ngOnDestroy() { this.setSurfaces(null); } private setSurfaces(anchor: MdcMenuAnchorDirective | null) { this.surfaces?.toArray().forEach(surface => { surface._parentAnchor = anchor; }); } /** @internal */ public getBoundingClientRect() { return this._elm.nativeElement.getBoundingClientRect(); } } export const MENU_SURFACE_DIRECTIVES = [ MdcMenuAnchorDirective, MdcMenuSurfaceDirective ];
the_stack
import { mocked } from "ts-jest"; import { QAClient } from "./"; import { initModel } from "./models"; import { RuntimeType } from "./runtimes"; import { Tokenizer } from "./tokenizers"; const basicQuestion = "What was the final score?"; const basicContext = ` Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. `; describe("QAClient", () => { describe("fromOptions", () => { // eslint-disable-next-line jest/no-disabled-tests it.skip("instantiates a QAClient with custom tokenizer when provided", async () => { const tokenizer = jest.fn(); const qaClient = await QAClient.fromOptions({ tokenizer: (tokenizer as unknown) as Tokenizer }); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((qaClient as any).tokenizer).toBe(tokenizer); }); it("leads to answer without inference time by default", async () => { const qaClient = await QAClient.fromOptions(); const predOne = await qaClient.predict(basicQuestion, basicContext); expect(predOne?.inferenceTime).toBeUndefined(); }); it("leads to answer with inference time when `timeIt` is `true`", async () => { const qaClient = await QAClient.fromOptions({ timeIt: true }); const predOne = await qaClient.predict(basicQuestion, basicContext); expect(typeof predOne?.inferenceTime).toBe("number"); }); }); describe("predict", () => { let qa: QAClient; const shorts = [ { context: ` Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. `, question: ["Who won the Super Bowl?", "Denver Broncos"] }, { context: ` One of the most famous people born in Warsaw was Maria Skłodowska-Curie, who achieved international recognition for her research on radioactivity and was the first female recipient of the Nobel Prize. Famous musicians include Władysław Szpilman and Frédéric Chopin. Though Chopin was born in the village of Żelazowa Wola, about 60 km (37 mi) from Warsaw, he moved to the city with his family when he was seven months old. Casimir Pulaski, a Polish general and hero of the American Revolutionary War, was born here in 1745. `, question: ["Where was Chopin born?", "Żelazowa Wola"] } ]; const long = { context: ` At his father's death on 16 September 1380, Charles VI inherited the throne of France. His coronation took place on 4 November 1380, at Reims Cathedral. Charles VI was only 11 years old when he was crowned King of France. During his minority, France was ruled by Charles' uncles, as regents. Although the royal age of majority was 14 (the "age of accountability" under Roman Catholic canon law), Charles terminated the regency only at the age of 21. The regents were Philip the Bold, Duke of Burgundy, Louis I, Duke of Anjou, and John, Duke of Berry – all brothers of Charles V – along with Louis II, Duke of Bourbon, Charles VI's maternal uncle. Philip took the dominant role during the regency. Louis of Anjou was fighting for his claim to the Kingdom of Naples after 1382, dying in 1384; John of Berry was interested mainly in the Languedoc, and not particularly interested in politics; and Louis of Bourbon was a largely unimportant figure, owing to his personality (showing signs of mental instability) and status (since he was not the son of a king). During the rule of his uncles, the financial resources of the kingdom, painstakingly built up by his father, were squandered for the personal profit of the dukes, whose interests were frequently divergent or even opposing. During that time, the power of the royal administration was strengthened and taxes re-established. The latter policy represented a reversal of the deathbed decision of the king's father Charles V to repeal taxes, and led to tax revolts, known as the Harelle. Increased tax revenues were needed to support the self-serving policies of the king's uncles, whose interests were frequently in conflict with those of the crown and with each other. The Battle of Roosebeke (1382), for example, brilliantly won by the royal troops, was prosecuted solely for the benefit of Philip of Burgundy. The treasury surplus carefully accumulated by Charles V was quickly squandered. Charles VI brought the regency to an end in 1388, taking up personal rule. He restored to power the highly competent advisors of Charles V, known as the Marmousets, who ushered in a new period of high esteem for the crown. Charles VI was widely referred to as Charles the Beloved by his subjects. He married Isabeau of Bavaria on 17 July 1385, when he was 17 and she 14 (and considered an adult at the time). Isabeau had 12 children, most of whom died young. Isabeau's first child, named Charles, was born in 1386, and was Dauphin of Viennois (heir apparent), but survived only 3 months. Her second child, Joan, was born on 14 June 1388, but died in 1390. Her third child, Isabella, was born in 1389. She was married to Richard II, King of England in 1396, at the age of 6, and became Queen of England. Richard died in 1400 and they had no children. Richard's successor, Henry IV, wanted Isabella then to marry his son, 14-year-old future king Henry V, but she refused. She was married again in 1406, this time to her cousin, Charles, Duke of Orléans, at the age of 17. She died in childbirth at the age of 19. Isabeau's fourth child, Joan, was born in 1391, and was married to John VI, Duke of Brittany in 1396, at an age of 5; they had children. Isabeau's fifth child born in 1392 was also named Charles, and was Dauphin. The young Charles was betrothed to Margaret of Burgundy in 1396, but died at the age of 9. Isabeau's sixth child, Mary, was born in 1393. She was never married, and had no children. Isabeau's seventh child, Michelle, was born in 1395. She was engaged to Philip, son of John the Fearless, Duke of Burgundy, in 1404 (both were then aged 8) and they were married in 1409, aged 14. She had one child who died in infancy, before she died in 1422, aged 27. Isabeau's eighth child, Louis, was born in 1397, and was also Dauphin. He married Margaret of Burgundy, who had previously been betrothed to his brother Charles. The marriage produced no children by the time of Louis's death in 1415, aged 18. Isabeau's ninth child, John, was born in 1398, and was also Dauphin from 1415, after the death of his brother Louis. He was married to Jacqueline, Countess of Hainaut in 1415, then aged 17, but they did not have any children before he died in 1417, aged 19. Isabeau's tenth child, Catherine, was born in 1401. She was married firstly to Henry V, King of England in 1420, and they had one child, who became Henry VI of England. Henry V died suddenly in 1422. Catherine may then have secretly married Owen Tudor in 1429 and had additional children, including Edmund Tudor, the father of Henry VII. She died in 1437, aged 36. `, questions: [ ["When did his father die?", "16 September 1380"], ["Who did Charles VI marry?", "Isabeau of Bavaria"], ["What was the name of Isabeau's tenth child?", "Catherine"] ] }; describe("using SavedModel format", () => { beforeAll(async () => { qa = await QAClient.fromOptions(); }, 100000000); it.each(shorts)("gives the correct answer with short contexts", async short => { const result = await qa.predict(short.question[0], short.context); expect(result?.text).toEqual(short.question[1]); }); for (const question of long.questions) { it("gives the correct answer with long contexts", async () => { const result = await qa.predict(question[0], long.context); expect(result?.text).toEqual(question[1]); }); } it("is non-blocking", async () => { const mockCb = jest.fn(); qa.predict(basicQuestion, basicContext).then(mockCb); await new Promise(r => setTimeout(r, 0)); expect(mockCb).not.toHaveBeenCalled(); }); }); describe("using TFJS format", () => { beforeAll(async () => { const model = await initModel({ name: "distilbert-base-cased-distilled-squad", runtime: RuntimeType.TFJS }); qa = await QAClient.fromOptions({ model }); }, 100000000); it.each(shorts)("gives the correct answer with short contexts", async short => { const result = await qa.predict(short.question[0], short.context); expect(result?.text).toEqual(short.question[1]); }); for (const question of long.questions) { it("gives the correct answer with long contexts", async () => { const result = await qa.predict(question[0], long.context); expect(result?.text).toEqual(question[1]); }); } }); }); }); it("supports big charge", async done => { const qaClientOne = await QAClient.fromOptions(); const model = await initModel({ name: "deepset/roberta-base-squad2" }); const qaClientTwo = await QAClient.fromOptions({ model }); await qaClientOne.predict(basicQuestion, basicContext); await qaClientTwo.predict(basicQuestion, basicContext); let cbCount = 0; function callback(): void { if (++cbCount === 120) { done(); } } for (let index = 0; index < 20; index++) { for (const qaClient of [qaClientOne, qaClientTwo]) { qaClient.predict(basicQuestion, basicContext).then(callback); qaClient.predict("What was the final score?", basicContext).then(callback); qaClient.predict("When was the game played?", basicContext).then(callback); } } const beforePromise = Date.now(); await new Promise(r => setTimeout(r, 3000)); const afterPromise = Date.now(); expect(afterPromise - beforePromise).toBeLessThan(3100); }, 60000);
the_stack
import { afterEach, beforeEach, describe, it } from 'mocha' import { expect } from 'chai' import sinon from 'sinon' import TestCaseRunner from './test_case_runner' import { EventEmitter } from 'events' import { IdGenerator } from '@cucumber/messages' import * as messages from '@cucumber/messages' import { parse } from '../../test/gherkin_helpers' import { buildSupportCodeLibrary } from '../../test/runtime_helpers' import FakeTimers, { InstalledClock } from '@sinonjs/fake-timers' import timeMethods from '../time' import { getBaseSupportCodeLibrary } from '../../test/fixtures/steps' import { ISupportCodeLibrary } from '../support_code_library_builder/types' import { valueOrDefault } from '../value_checker' import { PredictableTestRunStopwatch } from './stopwatch' import { assembleTestCases } from './assemble_test_cases' import IEnvelope = messages.Envelope interface ITestRunnerRequest { gherkinDocument: messages.GherkinDocument pickle: messages.Pickle retries?: number skip?: boolean supportCodeLibrary: ISupportCodeLibrary } interface ITestRunnerResponse { envelopes: messages.Envelope[] result: messages.TestStepResultStatus } async function testRunner( options: ITestRunnerRequest ): Promise<ITestRunnerResponse> { const envelopes: IEnvelope[] = [] const eventBroadcaster = new EventEmitter() const newId = IdGenerator.incrementing() const testCase = ( await assembleTestCases({ eventBroadcaster, newId, pickles: [options.pickle], supportCodeLibrary: options.supportCodeLibrary, }) )[options.pickle.id] // listen for envelopers _after_ we've assembled test cases eventBroadcaster.on('envelope', (e) => envelopes.push(e)) const runner = new TestCaseRunner({ eventBroadcaster, stopwatch: new PredictableTestRunStopwatch(), gherkinDocument: options.gherkinDocument, newId, pickle: options.pickle, testCase, retries: valueOrDefault(options.retries, 0), skip: valueOrDefault(options.skip, false), supportCodeLibrary: options.supportCodeLibrary, worldParameters: {}, }) const result = await runner.run() return { envelopes, result } } function predictableTimestamp(counter: number): messages.Timestamp { return { nanos: 1000000 * counter, seconds: 0, } } describe('TestCaseRunner', () => { let clock: InstalledClock beforeEach(() => { clock = FakeTimers.withGlobal(timeMethods).install() }) afterEach(() => { clock.uninstall() }) describe('run()', () => { describe('with a passing step', () => { it('emits testCase / testCaseStarted / testStepStarted / testStepFinished / testCaseFinished envelopes and returns the result', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary(({ Given }) => { Given('a step', function () { clock.tick(1) }) }) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) const passedTestResult: messages.TestStepResult = { duration: messages.TimeConversion.millisecondsToDuration(1), status: messages.TestStepResultStatus.PASSED, message: undefined, } // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert const expectedtEnvelopes: messages.Envelope[] = [ { testCaseStarted: { attempt: 0, id: '2', testCaseId: '0', timestamp: predictableTimestamp(0), }, }, { testStepStarted: { testCaseStartedId: '2', testStepId: '1', timestamp: predictableTimestamp(1), }, }, { testStepFinished: { testCaseStartedId: '2', testStepResult: passedTestResult, testStepId: '1', timestamp: predictableTimestamp(2), }, }, { testCaseFinished: { testCaseStartedId: '2', timestamp: predictableTimestamp(3), willBeRetried: false, }, }, ] expect(envelopes).to.eql(expectedtEnvelopes) expect(result).to.eql(messages.TestStepResultStatus.PASSED) }) }) describe('with a failing step', () => { it('emits and returns failing results', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary(({ Given }) => { Given('a step', function () { throw 'fail' // eslint-disable-line @typescript-eslint/no-throw-literal }) }) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) const failingTestResult: messages.TestStepResult = { duration: messages.TimeConversion.millisecondsToDuration(0), status: messages.TestStepResultStatus.FAILED, message: 'fail', } // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(4) expect(envelopes[2].testStepFinished.testStepResult).to.eql( failingTestResult ) expect(result).to.eql(messages.TestStepResultStatus.FAILED) }) }) describe('with an ambiguous step', () => { it('emits the expected envelopes and returns an ambiguous result', async () => { // Arrange const supportCodeLibrary = getBaseSupportCodeLibrary() const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given an ambiguous step'].join( '\n' ), uri: 'a.feature', }) const message = [ 'Multiple step definitions match:', ' an ambiguous step - steps.ts:13', ' /an? ambiguous step/ - steps.ts:14', ].join('\n') // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(4) const expected: messages.TestStepResult = { message, status: messages.TestStepResultStatus.AMBIGUOUS, duration: messages.TimeConversion.millisecondsToDuration(0), } expect(envelopes[2].testStepFinished.testStepResult).to.eql(expected) expect(result).to.eql( envelopes[2].testStepFinished.testStepResult.status ) }) }) describe('with a undefined step', () => { it('emits the expected envelopes and returns a undefined result', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary() const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(4) const expected: messages.TestStepResult = { status: messages.TestStepResultStatus.UNDEFINED, duration: messages.TimeConversion.millisecondsToDuration(0), } expect(envelopes[2].testStepFinished.testStepResult).to.eql(expected) expect(result).to.eql( envelopes[2].testStepFinished.testStepResult.status ) }) }) describe('with a flaky step and a positive retries value', () => { it('emits the expected envelopes and returns a passing result', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary(({ Given }) => { let willPass = false Given('a step', function () { if (willPass) { return } willPass = true throw 'error' // eslint-disable-line @typescript-eslint/no-throw-literal }) }) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, retries: 1, supportCodeLibrary, }) // Assert const expected: messages.Envelope[] = [ { testCaseStarted: { attempt: 0, id: '2', testCaseId: '0', timestamp: predictableTimestamp(0), }, }, { testStepStarted: { testCaseStartedId: '2', testStepId: '1', timestamp: predictableTimestamp(1), }, }, { testStepFinished: { testCaseStartedId: '2', testStepResult: { duration: messages.TimeConversion.millisecondsToDuration(0), message: 'error', status: messages.TestStepResultStatus.FAILED, }, testStepId: '1', timestamp: predictableTimestamp(2), }, }, { testCaseFinished: { testCaseStartedId: '2', timestamp: predictableTimestamp(3), willBeRetried: true, }, }, { testCaseStarted: { attempt: 1, id: '3', testCaseId: '0', timestamp: predictableTimestamp(4), }, }, { testStepStarted: { testCaseStartedId: '3', testStepId: '1', timestamp: predictableTimestamp(5), }, }, { testStepFinished: { testCaseStartedId: '3', testStepResult: { duration: messages.TimeConversion.millisecondsToDuration(0), message: undefined, status: messages.TestStepResultStatus.PASSED, }, testStepId: '1', timestamp: predictableTimestamp(6), }, }, { testCaseFinished: { testCaseStartedId: '3', timestamp: predictableTimestamp(7), willBeRetried: false, }, }, ] expect(envelopes).to.eql(expected) expect(result).to.eql(messages.TestStepResultStatus.PASSED) }) }) describe('with a step when skipping', () => { it('emits the expected envelopes and returns a skipped result', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary(({ Given }) => { Given('a step', function () { clock.tick(1) }) }) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, skip: true, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(4) const expected: messages.TestStepResult = { status: messages.TestStepResultStatus.SKIPPED, duration: messages.TimeConversion.millisecondsToDuration(0), } expect(envelopes[2].testStepFinished.testStepResult).to.eql(expected) expect(result).to.eql( envelopes[2].testStepFinished.testStepResult.status ) }) }) describe('with test case hooks', () => { it('emits the expected envelopes and returns a skipped result', async () => { // Arrange const supportCodeLibrary = buildSupportCodeLibrary( ({ Given, Before, After }) => { Given('a step', function () { clock.tick(1) }) Before(function () {}) // eslint-disable-line @typescript-eslint/no-empty-function After(function () {}) // eslint-disable-line @typescript-eslint/no-empty-function } ) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(8) expect(result).to.eql( envelopes[6].testStepFinished.testStepResult.status ) }) }) describe('with step hooks', () => { it('emits the expected envelopes and returns a skipped result', async () => { const beforeStep = sinon.stub() const afterStep = sinon.stub() // Arrange const supportCodeLibrary = buildSupportCodeLibrary( ({ Given, BeforeStep, AfterStep }) => { Given('a step', function () { clock.tick(1) }) BeforeStep(beforeStep) // eslint-disable-line @typescript-eslint/no-empty-function AfterStep(afterStep) // eslint-disable-line @typescript-eslint/no-empty-function } ) const { gherkinDocument, pickles: [pickle], } = await parse({ data: ['Feature: a', 'Scenario: b', 'Given a step'].join('\n'), uri: 'a.feature', }) // Act const { envelopes, result } = await testRunner({ gherkinDocument, pickle, supportCodeLibrary, }) // Assert expect(envelopes).to.have.lengthOf(4) expect(result).to.eql( envelopes[2].testStepFinished.testStepResult.status ) expect(beforeStep).to.have.been.calledOnceWith({ gherkinDocument, pickle, pickleStep: pickle.steps[0], testCaseStartedId: envelopes[1].testStepStarted.testCaseStartedId, testStepId: envelopes[1].testStepStarted.testStepId, result: undefined, }) expect(afterStep).to.have.been.calledOnceWith({ gherkinDocument, pickle, pickleStep: pickle.steps[0], testCaseStartedId: envelopes[2].testStepFinished.testCaseStartedId, testStepId: envelopes[2].testStepFinished.testStepId, result: envelopes[2].testStepFinished.testStepResult, }) }) }) }) })
the_stack
// ==================================================== // GraphQL query operation: ChannelBlokksPaginated // ==================================================== export interface ChannelBlokksPaginated_channel_blokks_Attachment_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Attachment_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Attachment_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Attachment_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Attachment { __typename: "Attachment"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Attachment_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Attachment_connection | null; source: ChannelBlokksPaginated_channel_blokks_Attachment_source | null; counts: ChannelBlokksPaginated_channel_blokks_Attachment_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; file_extension: string | null; can: ChannelBlokksPaginated_channel_blokks_Attachment_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Embed_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Embed_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Embed_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Embed_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Embed { __typename: "Embed"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Embed_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Embed_connection | null; source: ChannelBlokksPaginated_channel_blokks_Embed_source | null; counts: ChannelBlokksPaginated_channel_blokks_Embed_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; can: ChannelBlokksPaginated_channel_blokks_Embed_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Image_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Image_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Image_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Image_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_original_dimensions { __typename: "Dimensions"; width: number | null; height: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Image_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Image { __typename: "Image"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Image_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Image_connection | null; source: ChannelBlokksPaginated_channel_blokks_Image_source | null; counts: ChannelBlokksPaginated_channel_blokks_Image_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; original_dimensions: ChannelBlokksPaginated_channel_blokks_Image_original_dimensions | null; can: ChannelBlokksPaginated_channel_blokks_Image_can | null; find_original_url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Link_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Link_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Link_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Link_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Link_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Link_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Link_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Link_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Link_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Link { __typename: "Link"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Link_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Link_connection | null; source: ChannelBlokksPaginated_channel_blokks_Link_source | null; counts: ChannelBlokksPaginated_channel_blokks_Link_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; external_url: string | null; can: ChannelBlokksPaginated_channel_blokks_Link_can | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_PendingBlock_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_PendingBlock_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_PendingBlock { __typename: "PendingBlock"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_PendingBlock_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_PendingBlock_connection | null; source: ChannelBlokksPaginated_channel_blokks_PendingBlock_source | null; counts: ChannelBlokksPaginated_channel_blokks_PendingBlock_counts | null; can: ChannelBlokksPaginated_channel_blokks_PendingBlock_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Text_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Text_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Text_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Text_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Text_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Text_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Text_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Text_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Text_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Text { __typename: "Text"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Text_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Text_connection | null; source: ChannelBlokksPaginated_channel_blokks_Text_source | null; counts: ChannelBlokksPaginated_channel_blokks_Text_counts | null; content: string; can: ChannelBlokksPaginated_channel_blokks_Text_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Channel_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelBlokksPaginated_channel_blokks_Channel_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel_connection { __typename: "Connection"; created_at: string | null; user: ChannelBlokksPaginated_channel_blokks_Channel_connection_user | null; can: ChannelBlokksPaginated_channel_blokks_Channel_connection_can | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel_counts { __typename: "ChannelCounts"; contents: number | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel_owner_Group { __typename: "Group"; id: number; name: string; visibility: string; } export interface ChannelBlokksPaginated_channel_blokks_Channel_owner_User { __typename: "User"; id: number; name: string; } export type ChannelBlokksPaginated_channel_blokks_Channel_owner = ChannelBlokksPaginated_channel_blokks_Channel_owner_Group | ChannelBlokksPaginated_channel_blokks_Channel_owner_User; export interface ChannelBlokksPaginated_channel_blokks_Channel_can { __typename: "ChannelCan"; mute: boolean | null; } export interface ChannelBlokksPaginated_channel_blokks_Channel { __typename: "Channel"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelBlokksPaginated_channel_blokks_Channel_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelBlokksPaginated_channel_blokks_Channel_connection | null; source: ChannelBlokksPaginated_channel_blokks_Channel_source | null; truncatedTitle: string; visibility: string; counts: ChannelBlokksPaginated_channel_blokks_Channel_counts | null; owner: ChannelBlokksPaginated_channel_blokks_Channel_owner; label: string; can: ChannelBlokksPaginated_channel_blokks_Channel_can | null; } export type ChannelBlokksPaginated_channel_blokks = ChannelBlokksPaginated_channel_blokks_Attachment | ChannelBlokksPaginated_channel_blokks_Embed | ChannelBlokksPaginated_channel_blokks_Image | ChannelBlokksPaginated_channel_blokks_Link | ChannelBlokksPaginated_channel_blokks_PendingBlock | ChannelBlokksPaginated_channel_blokks_Text | ChannelBlokksPaginated_channel_blokks_Channel; export interface ChannelBlokksPaginated_channel_counts { __typename: "ChannelCounts"; contents: number | null; blocks: number | null; channels: number | null; } export interface ChannelBlokksPaginated_channel { __typename: "Channel"; id: number; blokks: ChannelBlokksPaginated_channel_blokks[] | null; counts: ChannelBlokksPaginated_channel_counts | null; } export interface ChannelBlokksPaginated { /** * A single channel */ channel: ChannelBlokksPaginated_channel | null; } export interface ChannelBlokksPaginatedVariables { id: string; page: number; per: number; }
the_stack
import { ChainId, ContractAddresses, getContractAddressesForChainOrThrow } from '@0x/contract-addresses'; import { artifacts as assetProxyArtifacts, ERC20ProxyContract } from '@0x/contracts-asset-proxy'; import { artifacts as erc20Artifacts, DummyERC20TokenContract, WETH9Contract } from '@0x/contracts-erc20'; import { artifacts as stakingArtifacts, StakingProxyContract, TestStakingContract, ZrxVaultContract, } from '@0x/contracts-staking'; import { AffiliateFeeTransformerContract, artifacts as exchangeProxyArtifacts, BridgeAdapterContract, FillQuoteTransformerContract, fullMigrateAsync as fullMigrateExchangeProxyAsync, PayTakerTransformerContract, PositiveSlippageFeeTransformerContract, WethTransformerContract, } from '@0x/contracts-zero-ex'; import { Web3ProviderEngine } from '@0x/subproviders'; import { BigNumber, providerUtils } from '@0x/utils'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { SupportedProvider, TxData } from 'ethereum-types'; import { bufferToHex, rlphash } from 'ethereumjs-util'; import { constants } from './utils/constants'; import { erc20TokenInfo } from './utils/token_info'; const allArtifacts = { ...assetProxyArtifacts, ...stakingArtifacts, ...exchangeProxyArtifacts, ...assetProxyArtifacts, }; const { NULL_ADDRESS } = constants; // tslint:disable:custom-no-magic-numbers function getDeploymentNonce(deployer: string, address: string): number { for (let i = 0; i < 10000; i++) { const candidate = bufferToHex(rlphash([deployer, i]).slice(12)); if (candidate.toLowerCase() === address.toLowerCase()) { return i; } } throw new Error(`Exhausted all attempts to find ${address} deployed by ${deployer}`); } async function deployAtAddressAsync<T>( cb: () => Promise<T>, provider: SupportedProvider, txDefaults: TxData, wantedAddress: string, ): Promise<T> { await untilWantedAddressAsync(wantedAddress, provider, txDefaults); return cb(); } /** * Increases addresses nonce until the deployment of a contract would occur at the wanted address. */ async function untilWantedAddressAsync( wantedAddress: string, provider: SupportedProvider, txDefaults: TxData, offset: number = 0, ): Promise<void> { const web3Wrapper = new Web3Wrapper(provider); const from = txDefaults.from; const currentNonce = await web3Wrapper.getAccountNonceAsync(from); const wantedNonce = getDeploymentNonce(from, wantedAddress); if (currentNonce > wantedNonce) { throw new Error(`Current nonce is ${currentNonce} but wanted nonce is ${wantedNonce}`); } for (let i = 0; i < wantedNonce - currentNonce + offset; i++) { await web3Wrapper.sendTransactionAsync({ from, to: from, value: new BigNumber(0) }); } } /** * Creates and deploys all the contracts that are required for the latest * version of the 0x protocol. * @param supportedProvider Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to. * @param txDefaults Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter). * @returns The addresses of the contracts that were deployed. */ export async function runMigrationsAsync( supportedProvider: SupportedProvider, txDefaults: TxData, ): Promise<ContractAddresses> { const provider = providerUtils.standardizeOrThrow(supportedProvider); const expectedAddresses = getContractAddressesForChainOrThrow(ChainId.Ganache); const erc20Proxy = await deployAtAddressAsync( () => ERC20ProxyContract.deployFrom0xArtifactAsync( assetProxyArtifacts.ERC20Proxy, provider, txDefaults, allArtifacts, ), provider, txDefaults, expectedAddresses.erc20Proxy, ); // ZRX const zrxToken = await deployAtAddressAsync( () => DummyERC20TokenContract.deployFrom0xArtifactAsync( erc20Artifacts.DummyERC20Token, provider, txDefaults, allArtifacts, '0x Protocol Token', 'ZRX', new BigNumber(18), new BigNumber(1000000000000000000000000000), ), provider, txDefaults, expectedAddresses.zrxToken, ); // Ether token const etherToken = await deployAtAddressAsync( () => WETH9Contract.deployFrom0xArtifactAsync(erc20Artifacts.WETH9, provider, txDefaults, allArtifacts), provider, txDefaults, expectedAddresses.etherToken, ); // Dummy ERC20 tokens for (const token of erc20TokenInfo) { const totalSupply = new BigNumber(1000000000000000000000000000); // tslint:disable-next-line:no-unused-variable const dummyErc20Token = await DummyERC20TokenContract.deployFrom0xArtifactAsync( erc20Artifacts.DummyERC20Token, provider, txDefaults, allArtifacts, token.name, token.symbol, token.decimals, totalSupply, ); } const zrxProxy = erc20Proxy.address; const zrxVault = await deployAtAddressAsync( () => ZrxVaultContract.deployFrom0xArtifactAsync( stakingArtifacts.ZrxVault, provider, txDefaults, allArtifacts, zrxProxy, zrxToken.address, ), provider, txDefaults, expectedAddresses.zrxVault, ); // Note we use TestStakingContract as the deployed bytecode of a StakingContract // has the tokens hardcoded const stakingLogic = await deployAtAddressAsync( () => TestStakingContract.deployFrom0xArtifactAsync( stakingArtifacts.TestStaking, provider, txDefaults, allArtifacts, etherToken.address, zrxVault.address, ), provider, txDefaults, expectedAddresses.staking, ); const stakingProxy = await deployAtAddressAsync( () => StakingProxyContract.deployFrom0xArtifactAsync( stakingArtifacts.StakingProxy, provider, txDefaults, allArtifacts, stakingLogic.address, ), provider, txDefaults, expectedAddresses.stakingProxy, ); await erc20Proxy.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync(txDefaults); // Reference the Proxy as the StakingContract for setup await new TestStakingContract(stakingProxy.address, provider, txDefaults); await stakingProxy.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults); await zrxVault.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults); await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync(txDefaults); await stakingLogic.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults); // Exchange Proxy ////////////////////////////////////////////////////////// const bridgeAdapter = await BridgeAdapterContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.BridgeAdapter, provider, txDefaults, allArtifacts, etherToken.address, ); // HACK: Full migration first deploys a Migrator await untilWantedAddressAsync(expectedAddresses.exchangeProxy, provider, txDefaults, -1); const exchangeProxy = await fullMigrateExchangeProxyAsync(txDefaults.from, provider, txDefaults); const exchangeProxyFlashWalletAddress = await exchangeProxy.getTransformWallet().callAsync(); // Deploy transformers. const wethTransformer = await deployAtAddressAsync( () => WethTransformerContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.WethTransformer, provider, txDefaults, allArtifacts, etherToken.address, ), provider, txDefaults, expectedAddresses.transformers.wethTransformer, ); const payTakerTransformer = await deployAtAddressAsync( () => PayTakerTransformerContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.PayTakerTransformer, provider, txDefaults, allArtifacts, ), provider, txDefaults, expectedAddresses.transformers.payTakerTransformer, ); const affiliateFeeTransformer = await deployAtAddressAsync( () => AffiliateFeeTransformerContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.AffiliateFeeTransformer, provider, txDefaults, allArtifacts, ), provider, txDefaults, expectedAddresses.transformers.affiliateFeeTransformer, ); const fillQuoteTransformer = await deployAtAddressAsync( () => FillQuoteTransformerContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.FillQuoteTransformer, provider, txDefaults, allArtifacts, bridgeAdapter.address, exchangeProxy.address, ), provider, txDefaults, expectedAddresses.transformers.fillQuoteTransformer, ); const positiveSlippageFeeTransformer = await deployAtAddressAsync( () => PositiveSlippageFeeTransformerContract.deployFrom0xArtifactAsync( exchangeProxyArtifacts.PositiveSlippageFeeTransformer, provider, txDefaults, allArtifacts, ), provider, txDefaults, expectedAddresses.transformers.positiveSlippageFeeTransformer, ); const contractAddresses = { erc20Proxy: erc20Proxy.address, erc721Proxy: NULL_ADDRESS, erc1155Proxy: NULL_ADDRESS, zrxToken: zrxToken.address, etherToken: etherToken.address, exchange: NULL_ADDRESS, assetProxyOwner: NULL_ADDRESS, erc20BridgeProxy: NULL_ADDRESS, zeroExGovernor: NULL_ADDRESS, forwarder: NULL_ADDRESS, coordinatorRegistry: NULL_ADDRESS, coordinator: NULL_ADDRESS, multiAssetProxy: NULL_ADDRESS, staticCallProxy: NULL_ADDRESS, devUtils: NULL_ADDRESS, exchangeV2: NULL_ADDRESS, zrxVault: zrxVault.address, staking: stakingLogic.address, stakingProxy: stakingProxy.address, erc20BridgeSampler: NULL_ADDRESS, chaiBridge: NULL_ADDRESS, dydxBridge: NULL_ADDRESS, godsUnchainedValidator: NULL_ADDRESS, broker: NULL_ADDRESS, chainlinkStopLimit: NULL_ADDRESS, maximumGasPrice: NULL_ADDRESS, dexForwarderBridge: NULL_ADDRESS, exchangeProxyGovernor: NULL_ADDRESS, exchangeProxy: exchangeProxy.address, exchangeProxyTransformerDeployer: txDefaults.from, exchangeProxyFlashWallet: exchangeProxyFlashWalletAddress, exchangeProxyLiquidityProviderSandbox: NULL_ADDRESS, zrxTreasury: NULL_ADDRESS, transformers: { wethTransformer: wethTransformer.address, payTakerTransformer: payTakerTransformer.address, fillQuoteTransformer: fillQuoteTransformer.address, affiliateFeeTransformer: affiliateFeeTransformer.address, positiveSlippageFeeTransformer: positiveSlippageFeeTransformer.address, }, }; return contractAddresses; } let _cachedContractAddresses: ContractAddresses; /** * Exactly like runMigrationsAsync but will only run the migrations the first * time it is called. Any subsequent calls will return the cached contract * addresses. * @param provider Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to. * @param txDefaults Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter). * @returns The addresses of the contracts that were deployed. */ export async function runMigrationsOnceAsync( provider: Web3ProviderEngine, txDefaults: TxData, ): Promise<ContractAddresses> { if (_cachedContractAddresses !== undefined) { return _cachedContractAddresses; } _cachedContractAddresses = await runMigrationsAsync(provider, txDefaults); return _cachedContractAddresses; }
the_stack
import { AST, Scope, SourceCode } from 'eslint'; import * as ESTree from 'estree'; type CommentOrToken = ESTree.Comment | AST.Token; /** * Find the variable of a given name. * @param initialScope The scope to start finding. * @param nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node. * @returns The found variable or null. */ export function findVariable(initialScope: Scope.Scope, nameOrNode: string | ESTree.Identifier): Scope.Variable | null; /** * Get the location of the given function node for reporting. * @param node The function node to get. * @param sourceCode The source code object to get tokens. * @returns The location of the function node for reporting. */ export function getFunctionHeadLocation( node: ESTree.ArrowFunctionExpression | ESTree.FunctionDeclaration | ESTree.FunctionExpression, sourceCode: SourceCode, ): ESTree.SourceLocation; /** * Get the name and kind of the given function node. * @param node The function node to get. * @param sourceCode The source code object to get the code of computed property keys. * @returns The name and kind of the function node. */ export function getFunctionNameWithKind(node: ESTree.Node, sourceCode?: SourceCode): string; /** * Get the innermost scope which contains a given location. * @param initialScope The initial scope to search. * @param node The location to search. * @returns The innermost scope. */ export function getInnermostScope(initialScope: Scope.Scope, node: ESTree.Node): Scope.Scope; /** * Get the property name from a MemberExpression node or a Property node. * @param node The node to get. * @param initialScope The scope to start finding variable. * @returns The property name of the node. * @remarks * If the node is a computed property node and a scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it. */ export function getPropertyName( node: ESTree.MemberExpression | ESTree.MethodDefinition | ESTree.Property | ESTree.PropertyDefinition, initialScope?: Scope.Scope, ): string | null; export type StaticValue = StaticValueProvided | StaticValueOptional; export interface StaticValueProvided { value: unknown; } export interface StaticValueOptional { optional?: true; value: undefined; } /** * Get the value of a given node if it's a static value. * @param node The node to get. * @param [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible. * @returns The static value of the node, or `null`. */ export function getStaticValue(node: ESTree.Node, initialScope?: Scope.Scope): StaticValue | null; /** * Get the value of a given node if it's a literal or a template literal. * @param node The node to get. * @param initialScope The scope to start finding variable. * @returns The value of the node, or `null`. * @remarks * If the node is an Identifier node and scope was given, this checks the variable of the identifier, * and returns the value of it if the variable is a constant. */ export function getStringIfConstant(node: ESTree.Node, initialScope?: Scope.Scope): string | null; /** * Options for `hasSideEffect`, optionally. */ export interface HasSideEffectOptions { /** * If `true` then it considers member accesses as the node which has side effects. */ considerGetters?: boolean; /** * If `true` then it considers implicit type conversion as the node which has side effects. */ considerImplicitTypeConversion?: boolean; } /** * Check whether a given node has any side effect or not. * @param node The node to get. * @param sourceCode The source code object. * @param options The option object. * @returns `true` if the node has a certain side effect. */ export function hasSideEffect(node: ESTree.Node, sourceCode: SourceCode, options?: HasSideEffectOptions): boolean; /** * Check whether a given node is parenthesized or not. * @param times The number of parantheses. * @param node The AST node to check. * @param sourceCode The source code object to get tokens. * @returns `true` if the node is parenthesized the given times. */ export function isParenthesized(times: number, node: ESTree.Node, sourceCode: SourceCode): boolean; /** * Check whether a given node is parenthesized or not. * @param node The AST node to check. * @param sourceCode The source code object to get tokens. * @returns `true` if the node is parenthesized. */ export function isParenthesized(node: ESTree.Node, sourceCode: SourceCode): boolean; export interface PunctuatorToken<Value extends string> extends AST.Token { type: 'Punctuator'; value: Value; } export interface ArrowToken extends PunctuatorToken<'=>'> {} export interface CommaToken extends PunctuatorToken<','> {} export interface SemicolonToken extends PunctuatorToken<';'> {} export interface ColonToken extends PunctuatorToken<':'> {} export interface OpeningParenToken extends PunctuatorToken<'('> {} export interface ClosingParenToken extends PunctuatorToken<')'> {} export interface OpeningBracketToken extends PunctuatorToken<'['> {} export interface ClosingBracketToken extends PunctuatorToken<']'> {} export interface OpeningBraceToken extends PunctuatorToken<'{'> {} export interface ClosingBraceToken extends PunctuatorToken<'}'> {} /** * Checks if the given token is an arrow token or not. * @param node The comment or token to check. * @returns `true` if the token is an arrow token. */ export function isArrowToken(node: CommentOrToken): node is ArrowToken; /** * Checks if the given token is a comma token or not. * @param node The comment or token to check. * @returns `true` if the token is a comma token. */ export function isCommaToken(node: CommentOrToken): node is CommaToken; /** * Checks if the given token is a semicolon token or not. * @param node The comment or token to check. * @returns `true` if the token is a semicolon token. */ export function isSemicolonToken(node: CommentOrToken): node is SemicolonToken; /** * Checks if the given token is a colon token or not. * @param node The comment or token to check. * @returns `true` if the token is a colon token. */ export function isColonToken(node: CommentOrToken): node is ColonToken; /** * Checks if the given token is an opening parenthesis token or not. * @param node The comment or token to check. * @returns `true` if the token is an opening parenthesis token. */ export function isOpeningParenToken(node: CommentOrToken): node is OpeningParenToken; /** * Checks if the given token is a closing parenthesis token or not. * @param node The comment or token to check. * @returns `true` if the token is a closing parenthesis token. */ export function isClosingParenToken(node: CommentOrToken): node is ClosingParenToken; /** * Checks if the given token is an opening square bracket token or not. * @param node The comment or token to check. * @returns `true` if the token is an opening square bracket token. */ export function isOpeningBracketToken(node: CommentOrToken): node is OpeningBracketToken; /** * Checks if the given token is a closing square bracket token or not. * @param node The comment or token to check. * @returns `true` if the token is a closing square bracket token. */ export function isClosingBracketToken(node: CommentOrToken): node is ClosingBracketToken; /** * Checks if the given token is an opening brace token or not. * @param node The comment or token to check. * @returns `true` if the token is an opening brace token. */ export function isOpeningBraceToken(node: CommentOrToken): node is OpeningBraceToken; /** * Checks if the given token is a closing brace token or not. * @param node The comment or token to check. * @returns `true` if the token is a closing brace token. */ export function isClosingBraceToken(node: CommentOrToken): node is ClosingBraceToken; /** * Checks if the given token is a comment token or not. * @param node The comment or token to check. * @returns `true` if the token is a comment token. */ export function isCommentToken(node: CommentOrToken): node is ESTree.Comment; /** * Checks if the given token is an not arrow token. * @param node The comment or token to check. * @returns `true` if the token is not an arrow token. */ export function isNotArrowToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a comma token. * @param node The comment or token to check. * @returns `true` if the token not is a comma token. */ export function isNotCommaToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a semicolon token. * @param node The comment or token to check. * @returns `true` if the token not is a semicolon token. */ export function isNotSemicolonToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a colon token. * @param node The comment or token to check. * @returns `true` if the token not is a colon token. */ export function isNotColonToken(node: CommentOrToken): boolean; /** * Checks if the given token is not an opening parenthesis token. * @param node The comment or token to check. * @returns `true` if the token not is an opening parenthesis token. */ export function isNotOpeningParenToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a closing parenthesis token. * @param node The comment or token to check. * @returns `true` if the token not is a closing parenthesis token. */ export function isNotClosingParenToken(node: CommentOrToken): boolean; /** * Checks if the given token is not an opening square bracket token. * @param node The comment or token to check. * @returns `true` if the token not is an opening square bracket token. */ export function isNotOpeningBracketToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a closing square bracket token. * @param node The comment or token to check. * @returns `true` if the token not is a closing square bracket token. */ export function isNotClosingBracketToken(node: CommentOrToken): boolean; /** * Checks if the given token is not an opening brace token. * @param node The comment or token to check. * @returns `true` if the token not is an opening brace token. */ export function isNotOpeningBraceToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a closing brace token. * @param node The comment or token to check. * @returns `true` if the token not is a closing brace token. */ export function isNotClosingBraceToken(node: CommentOrToken): boolean; /** * Checks if the given token is not a comment token. * @param node The comment or token to check. * @returns `true` if the token is not a comment token. */ export function isNotCommentToken(node: CommentOrToken): boolean; export * from './patternMatcher'; export * from './referenceTracker';
the_stack
module es { class CharacterRaycastOrigins { public topLeft: Vector2; public bottomRight: Vector2; public bottomLeft: Vector2; public constructor() { this.topLeft = Vector2.zero; this.bottomRight = Vector2.zero; this.bottomLeft = Vector2.zero; } } class CharacterCollisionState2D { public right: boolean = false; public left: boolean = false; public above: boolean = false; public below: boolean = false; public becameGroundedThisFrame: boolean = false; public wasGroundedLastFrame: boolean = false; public movingDownSlope: boolean = false; public slopeAngle: number = 0; public hasCollision(): boolean { return this.below || this.right || this.left || this.above; } public reset(): void { this.right = this.left = false; this.above = this.below = false; this.becameGroundedThisFrame = this.movingDownSlope = false; this.slopeAngle = 0; } public toString(): string { return `[CharacterCollisionState2D] r: ${this.right}, l: ${this.left}, a: ${this.above}, b: ${this.below}, movingDownSlope: ${this.movingDownSlope}, angle: ${this.slopeAngle}, wasGroundedLastFrame: ${this.wasGroundedLastFrame}, becameGroundedThisFrame: ${this.becameGroundedThisFrame}`; } } export class CharacterController implements ITriggerListener { public onControllerCollidedEvent: ObservableT<RaycastHit>; public onTriggerEnterEvent: ObservableT<Collider>; public onTriggerExitEvent: ObservableT<Collider>; /** * 如果为 true,则在垂直移动单帧时将忽略平台的一种方式 */ public ignoreOneWayPlatformsTime: number; public supportSlopedOneWayPlatforms: boolean; public ignoredColliders: Set<Collider> = new Set(); /** * 定义距离碰撞射线的边缘有多远。 * 如果使用 0 范围进行投射,则通常会导致不需要的光线击中(例如,直接从表面水平投射的足部碰撞器可能会导致击中) */ public get skinWidth() { return this._skinWidth; } public set skinWidth(value: number) { this._skinWidth = value; this.recalculateDistanceBetweenRays(); } /** * CC2D 可以爬升的最大坡度角 */ public slopeLimit: number = 30; /** * 构成跳跃的帧之间垂直运动变化的阈值 */ public jumpingThreshold: number = -7; /** * 基于斜率乘以速度的曲线(负 = 下坡和正 = 上坡) */ public slopeSpeedMultiplier: AnimCurve; public totalHorizontalRays: number = 5; public totalVerticalRays: number = 3; public collisionState: CharacterCollisionState2D = new CharacterCollisionState2D(); public velocity: Vector2 = new Vector2(0, 0); public get isGrounded(): boolean { return this.collisionState.below; } public get raycastHitsThisFrame(): RaycastHit[] { return this._raycastHitsThisFrame; } public constructor( player: Entity, skinWidth?: number, platformMask: number = -1, onewayPlatformMask: number = -1, triggerMask: number = -1 ) { this.onTriggerEnterEvent = new ObservableT(); this.onTriggerExitEvent = new ObservableT(); this.onControllerCollidedEvent = new ObservableT(); this.platformMask = platformMask; this.oneWayPlatformMask = onewayPlatformMask; this.triggerMask = triggerMask; // 将我们的单向平台添加到我们的普通平台掩码中,以便我们可以从上方降落 this.platformMask |= this.oneWayPlatformMask; this._player = player; let collider = null; for (let i = 0; i < this._player.components.buffer.length; i++) { let component = this._player.components.buffer[i]; if (component instanceof Collider) { collider = component; break; } } collider.isTrigger = false; if (collider instanceof BoxCollider) { this._collider = collider as BoxCollider; } else { throw new Error('player collider must be box'); } // 在这里,我们触发了具有主体的 setter 的属性 this.skinWidth = skinWidth || collider.width * 0.05; this._slopeLimitTangent = Math.tan(75 * MathHelper.Deg2Rad); this._triggerHelper = new ColliderTriggerHelper(this._player); // 我们想设置我们的 CC2D 忽略所有碰撞层,除了我们的 triggerMask for (let i = 0; i < 32; i++) { // 查看我们的 triggerMask 是否包含此层,如果不包含则忽略它 if ((this.triggerMask & (1 << i)) === 0) { Flags.unsetFlag(this._collider.collidesWithLayers, i); } } } public onTriggerEnter(other: Collider, local: Collider): void { this.onTriggerEnterEvent.notify(other); } public onTriggerExit(other: Collider, local: Collider): void { this.onTriggerExitEvent.notify(other); } /** * 尝试将角色移动到位置 + deltaMovement。 任何挡路的碰撞器都会在遇到时导致运动停止 * @param deltaMovement * @param deltaTime */ public move(deltaMovement: Vector2, deltaTime: number): void { this.collisionState.wasGroundedLastFrame = this.collisionState.below; this.collisionState.reset(); this._raycastHitsThisFrame = []; this._isGoingUpSlope = false; this.primeRaycastOrigins(); if (deltaMovement.y > 0 && this.collisionState.wasGroundedLastFrame) { deltaMovement = this.handleVerticalSlope(deltaMovement); } if (deltaMovement.x !== 0) { deltaMovement = this.moveHorizontally(deltaMovement); } if (deltaMovement.y !== 0) { deltaMovement = this.moveVertically(deltaMovement); } this._player.setPosition( this._player.position.x + deltaMovement.x, this._player.position.y + deltaMovement.y ); if (deltaTime > 0) { this.velocity.x = deltaMovement.x / deltaTime; this.velocity.y = deltaMovement.y / deltaTime; } if ( !this.collisionState.wasGroundedLastFrame && this.collisionState.below ) { this.collisionState.becameGroundedThisFrame = true; } if (this._isGoingUpSlope) { this.velocity.y = 0; } if (!this._isWarpingToGround) { this._triggerHelper.update(); } for (let i = 0; i < this._raycastHitsThisFrame.length; i++) { this.onControllerCollidedEvent.notify(this._raycastHitsThisFrame[i]); } if (this.ignoreOneWayPlatformsTime > 0) { this.ignoreOneWayPlatformsTime -= deltaTime; } } /** * 直接向下移动直到接地 * @param maxDistance */ public warpToGrounded(maxDistance: number = 1000): void { this.ignoreOneWayPlatformsTime = 0; this._isWarpingToGround = true; let delta = 0; do { delta += 1; this.move(new Vector2(0, 1), 0.02); if (delta > maxDistance) { break; } } while (!this.isGrounded); this._isWarpingToGround = false; } /** * 这应该在您必须在运行时修改 BoxCollider2D 的任何时候调用。 * 它将重新计算用于碰撞检测的光线之间的距离。 * 它也用于 skinWidth setter,以防在运行时更改。 */ public recalculateDistanceBetweenRays(): void { const colliderUsableHeight = this._collider.height * Math.abs(this._player.scale.y) - 2 * this._skinWidth; this._verticalDistanceBetweenRays = colliderUsableHeight / (this.totalHorizontalRays - 1); const colliderUsableWidth = this._collider.width * Math.abs(this._player.scale.x) - 2 * this._skinWidth; this._horizontalDistanceBetweenRays = colliderUsableWidth / (this.totalVerticalRays - 1); } /** * 将 raycastOrigins 重置为由 skinWidth 插入的框碰撞器的当前范围。 * 插入它是为了避免从直接接触另一个碰撞器的位置投射光线,从而导致不稳定的法线数据。 */ private primeRaycastOrigins(): void { const rect = this._collider.bounds; this._raycastOrigins.topLeft = new Vector2( rect.x + this._skinWidth, rect.y + this._skinWidth ); this._raycastOrigins.bottomRight = new Vector2( rect.right - this._skinWidth, rect.bottom - this._skinWidth ); this._raycastOrigins.bottomLeft = new Vector2( rect.x + this._skinWidth, rect.bottom - this._skinWidth ); } /** * 我们必须在这方面使用一些技巧。 * 光线必须从我们的碰撞器(skinWidth)内部的一小段距离投射,以避免零距离光线会得到错误的法线。 * 由于这个小偏移,我们必须增加光线距离 skinWidth 然后记住在实际移动玩家之前从 deltaMovement 中删除 skinWidth * @param deltaMovement * @returns */ private moveHorizontally(deltaMovement: Vector2): Vector2 { const isGoingRight = deltaMovement.x > 0; let rayDistance = Math.abs(deltaMovement.x) + this._skinWidth * this.rayOriginSkinMutiplier; const rayDirection: Vector2 = isGoingRight ? Vector2.right : Vector2.left; const initialRayOriginY = this._raycastOrigins.bottomLeft.y; const initialRayOriginX = isGoingRight ? this._raycastOrigins.bottomRight.x - this._skinWidth * (this.rayOriginSkinMutiplier - 1) : this._raycastOrigins.bottomLeft.x + this._skinWidth * (this.rayOriginSkinMutiplier - 1); for (let i = 0; i < this.totalHorizontalRays; i++) { const ray = new Vector2( initialRayOriginX, initialRayOriginY - i * this._verticalDistanceBetweenRays ); // 如果我们接地,我们将只在第一条射线(底部)上包含 oneWayPlatforms。 // 允许我们走上倾斜的 oneWayPlatforms if ( i === 0 && this.supportSlopedOneWayPlatforms && this.collisionState.wasGroundedLastFrame ) { this._raycastHit = Physics.linecast( ray, ray.add(rayDirection.scaleEqual(rayDistance)), this.platformMask, this.ignoredColliders ); } else { this._raycastHit = Physics.linecast( ray, ray.add(rayDirection.scaleEqual(rayDistance)), this.platformMask & ~this.oneWayPlatformMask, this.ignoredColliders ); } if (this._raycastHit.collider) { if ( i === 0 && this.handleHorizontalSlope( deltaMovement, Vector2.unsignedAngle(this._raycastHit.normal, Vector2.up) ) ) { this._raycastHitsThisFrame.push(this._raycastHit); break; } deltaMovement.x = this._raycastHit.point.x - ray.x; rayDistance = Math.abs(deltaMovement.x); if (isGoingRight) { deltaMovement.x -= this._skinWidth * this.rayOriginSkinMutiplier; this.collisionState.right = true; } else { deltaMovement.x += this._skinWidth * this.rayOriginSkinMutiplier; this.collisionState.left = true; } this._raycastHitsThisFrame.push(this._raycastHit); if ( rayDistance < this._skinWidth * this.rayOriginSkinMutiplier + this.kSkinWidthFloatFudgeFactor ) { break; } } } return deltaMovement; } private moveVertically(deltaMovement: Vector2): Vector2 { const isGoingUp = deltaMovement.y < 0; let rayDistance = Math.abs(deltaMovement.y) + this._skinWidth * this.rayOriginSkinMutiplier; const rayDirection = isGoingUp ? Vector2.up : Vector2.down; let initialRayOriginX = this._raycastOrigins.topLeft.x; const initialRayOriginY = isGoingUp ? this._raycastOrigins.topLeft.y + this._skinWidth * (this.rayOriginSkinMutiplier - 1) : this._raycastOrigins.bottomLeft.y - this._skinWidth * (this.rayOriginSkinMutiplier - 1); initialRayOriginX += deltaMovement.x; let mask = this.platformMask; if (isGoingUp || this.ignoreOneWayPlatformsTime > 0) { mask &= ~this.oneWayPlatformMask; } for (let i = 0; i < this.totalVerticalRays; i++) { const rayStart = new Vector2( initialRayOriginX + i * this._horizontalDistanceBetweenRays, initialRayOriginY ); this._raycastHit = Physics.linecast( rayStart, rayStart.add(rayDirection.scaleEqual(rayDistance)), mask, this.ignoredColliders ); if (this._raycastHit.collider) { deltaMovement.y = this._raycastHit.point.y - rayStart.y; rayDistance = Math.abs(deltaMovement.y); if (isGoingUp) { deltaMovement.y += this._skinWidth * this.rayOriginSkinMutiplier; this.collisionState.above = true; } else { deltaMovement.y -= this._skinWidth * this.rayOriginSkinMutiplier; this.collisionState.below = true; } this._raycastHitsThisFrame.push(this._raycastHit); if (!isGoingUp && deltaMovement.y < -0.00001) { this._isGoingUpSlope = true; } if ( rayDistance < this._skinWidth * this.rayOriginSkinMutiplier + this.kSkinWidthFloatFudgeFactor ) { break; } } } return deltaMovement; } /** * 检查 BoxCollider2D 下的中心点是否存在坡度。 * 如果找到一个,则调整 deltaMovement 以便玩家保持接地,并考虑slopeSpeedModifier 以加快移动速度。 * @param deltaMovement * @returns */ private handleVerticalSlope(deltaMovement: Vector2): Vector2 { const centerOfCollider = (this._raycastOrigins.bottomLeft.x + this._raycastOrigins.bottomRight.x) * 0.5; const rayDirection = Vector2.down; const slopeCheckRayDistance = this._slopeLimitTangent * (this._raycastOrigins.bottomRight.x - centerOfCollider); const slopeRay = new Vector2( centerOfCollider, this._raycastOrigins.bottomLeft.y ); this._raycastHit = Physics.linecast( slopeRay, slopeRay.add(rayDirection.scaleEqual(slopeCheckRayDistance)), this.platformMask, this.ignoredColliders ); if (this._raycastHit.collider) { const angle = Vector2.unsignedAngle(this._raycastHit.normal, Vector2.up); if (angle === 0) { return deltaMovement; } const isMovingDownSlope = Math.sign(this._raycastHit.normal.x) === Math.sign(deltaMovement.x); if (isMovingDownSlope) { const slopeModifier = this.slopeSpeedMultiplier ? this.slopeSpeedMultiplier.lerp(-angle) : 1; deltaMovement.y += this._raycastHit.point.y - slopeRay.y - this.skinWidth; deltaMovement.x *= slopeModifier; this.collisionState.movingDownSlope = true; this.collisionState.slopeAngle = angle; } } return deltaMovement; } /** * 如果我们要上坡,则处理调整 deltaMovement * @param deltaMovement * @param angle * @returns */ private handleHorizontalSlope( deltaMovement: Vector2, angle: number ): boolean { if (Math.round(angle) === 90) { return false; } if (angle < this.slopeLimit) { if (deltaMovement.y > this.jumpingThreshold) { const slopeModifier = this.slopeSpeedMultiplier ? this.slopeSpeedMultiplier.lerp(angle) : 1; deltaMovement.x *= slopeModifier; deltaMovement.y = Math.abs( Math.tan(angle * MathHelper.Deg2Rad) * deltaMovement.x ); const isGoingRight = deltaMovement.x > 0; const ray = isGoingRight ? this._raycastOrigins.bottomRight : this._raycastOrigins.bottomLeft; let raycastHit = null; if ( this.supportSlopedOneWayPlatforms && this.collisionState.wasGroundedLastFrame ) { raycastHit = Physics.linecast( ray, ray.add(deltaMovement), this.platformMask, this.ignoredColliders ); } else { raycastHit = Physics.linecast( ray, ray.add(deltaMovement), this.platformMask & ~this.oneWayPlatformMask, this.ignoredColliders ); } if (raycastHit.collider) { deltaMovement.x = raycastHit.point.x - ray.x; deltaMovement.y = raycastHit.point.y - ray.y; if (isGoingRight) { deltaMovement.x -= this._skinWidth; } else { deltaMovement.x += this._skinWidth; } } this._isGoingUpSlope = true; this.collisionState.below = true; } } else { deltaMovement.x = 0; } return true; } private _player: Entity; private _collider: BoxCollider; private _skinWidth: number = 0.02; private _triggerHelper: ColliderTriggerHelper; /** * 这用于计算为检查坡度而投射的向下光线。 * 我们使用有点随意的值 75 度来计算检查斜率的射线的长度。 */ private _slopeLimitTangent: number; private readonly kSkinWidthFloatFudgeFactor: number = 0.001; /** * 我们的光线投射原点角的支架(TR、TL、BR、BL) */ private _raycastOrigins: CharacterRaycastOrigins = new CharacterRaycastOrigins(); /** * 存储我们在移动过程中命中的光线投射 */ private _raycastHit: RaycastHit = new RaycastHit(); /** * 存储此帧发生的任何光线投射命中。 * 我们必须存储它们,以防我们遇到水平和垂直移动的碰撞,以便我们可以在设置所有碰撞状态后发送事件 */ private _raycastHitsThisFrame: RaycastHit[]; // 水平/垂直移动数据 private _verticalDistanceBetweenRays: number; private _horizontalDistanceBetweenRays: number; /** * 我们使用这个标志来标记我们正在爬坡的情况,我们修改了 delta.y 以允许爬升。 * 原因是,如果我们到达斜坡的尽头,我们可以进行调整以保持接地 */ private _isGoingUpSlope: boolean = false; private _isWarpingToGround: boolean = true; private platformMask: number = -1; private triggerMask: number = -1; private oneWayPlatformMask: number = -1; private readonly rayOriginSkinMutiplier = 4; } }
the_stack
import { expect } from 'chai'; import { Flow } from '../src/engine'; // @todo Add test to pause flow without tasks // @todo Add test to stop flow without tasks // Created this class to test protected and private methods in Flow class PublicFlow extends Flow { public finished(error: Error | boolean = false) { if (error === false) { // This conditional makes possible to test default params in this.runStatus.state.finished this.runStatus.state.finished(); } else { this.runStatus.state.finished(error); } } public paused(error: Error | boolean = false) { if (error === false) { // This conditional makes possible to test default params in this.runStatus.state.paused this.runStatus.state.paused(); } else { this.runStatus.state.paused(error); } } public stopped(error: Error | boolean = false) { if (error === false) { // This conditional makes possible to test default params in this.runStatus.state.stopped this.runStatus.state.stopped(); } else { this.runStatus.state.stopped(error); } } } describe('a flow in state', () => { it('ready can only be started', async () => { // Prepare a flow is Ready state const flow = new Flow(); const pubFlow = new PublicFlow(); // Invalid transitions/operations expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Ready.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Ready.'); expect(() => flow.stop()).to.throw('Cannot execute transition Stop in current state Ready.'); expect(() => flow.reset()).to.throw('Cannot execute transition Reset in current state Ready.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Ready.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Ready.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Ready.'); // Valid transitions/operations flow.getSerializableState(); await flow.start(); }); it('finished can only be reset', async () => { // Prepare a flow is Finished state const flow = new Flow(); await flow.start(); const pubFlow = new PublicFlow(); await pubFlow.start(); // Invalid transitions/operations expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Finished.'); expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Finished.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Finished.'); expect(() => flow.stop()).to.throw('Cannot execute transition Stop in current state Finished.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Finished.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Finished.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Finished.'); // Valid transitions/operations flow.getSerializableState(); flow.reset(); }); it('running can only be paused, or stopped', async () => { const initRunningFlow = () => { const newFlow = new Flow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); newFlow.start(); return newFlow; }; const initRunningPublicFlow = () => { const newFlow = new PublicFlow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); newFlow.start(); return newFlow; }; // Prepare a flow is Running state let flow = initRunningFlow(); let pubFlow = initRunningPublicFlow(); // Invalid transitions/operations expect(() => flow.getSerializableState()).to.throw('Cannot execute method getSerializableState in current state Running.'); expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Running.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Running.'); expect(() => flow.reset()).to.throw('Cannot execute transition Reset in current state Running.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Running.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Running.'); // Valid transitions/operations await flow.pause(); flow = initRunningFlow(); // Prepare a new flow in Running state await flow.stop(); pubFlow = initRunningPublicFlow(); // Prepare a new flow in Running state pubFlow.finished(); }); it('pausing has no valid public transitions', async () => { // Prepare a flow is Pausing state const flow = new Flow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); flow.start(); flow.pause(); const pubFlow = new PublicFlow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); pubFlow.start(); pubFlow.pause(); // Invalid transitions/operations (all public transitions are invalid) expect(() => flow.getSerializableState()).to.throw('Cannot execute method getSerializableState in current state Pausing.'); expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Pausing.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Pausing.'); expect(() => flow.stop()).to.throw('Cannot execute transition Stop in current state Pausing.'); expect(() => flow.reset()).to.throw('Cannot execute transition Reset in current state Pausing.'); expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Pausing.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Pausing.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Pausing.'); // Valid transitions/operations pubFlow.paused(); }); it('paused can only be resumed or stopped', async () => { // Prepare a flow is Paused state const initPausedFlow = async () => { const newFlow = new Flow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); newFlow.start(); await newFlow.pause(); return newFlow; }; const initPausedPublicFlow = async () => { const newFlow = new PublicFlow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); newFlow.start(); await newFlow.pause(); return newFlow; }; // Prepare a flow is Running state let flow = await initPausedFlow(); const pubFlow = await initPausedPublicFlow(); // Invalid transitions/operations expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Paused.'); expect(() => flow.reset()).to.throw('Cannot execute transition Reset in current state Paused.'); expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Paused.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Paused.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Paused.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Paused.'); // Valid transitions/operations flow.getSerializableState(); flow.resume(); flow = await initPausedFlow(); // Prepare a new flow in Paused state await flow.stop(); // @todo Check why here the flow remain in Stopping, and not is in Stopped. }); it('stopping has no valid public transitions', async () => { // Prepare a flow is Stopping state const flow = new Flow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); flow.start(); flow.stop(); const pubFlow = new PublicFlow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); pubFlow.start(); pubFlow.stop(); // Invalid transitions/operations (all public transitions are invalid) expect(() => flow.getSerializableState()).to.throw('Cannot execute method getSerializableState in current state Stopping.'); expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Stopping.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Stopping.'); expect(() => flow.stop()).to.throw('Cannot execute transition Stop in current state Stopping.'); expect(() => flow.reset()).to.throw('Cannot execute transition Reset in current state Stopping.'); expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Stopping.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Stopping.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Stopping.'); // Valid transitions/operations pubFlow.stopped(); }); it('stopped can only be reset', async () => { // Prepare a flow is Stopped state const flow = new Flow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); flow.start(); await flow.stop(); const pubFlow = new PublicFlow({ tasks: { aTask: { resolver: { name: 'flowed::Noop' } } }, }); pubFlow.start(); await pubFlow.stop(); // Invalid transitions/operations expect(() => flow.pause()).to.throw('Cannot execute transition Pause in current state Stopped.'); expect(() => flow.resume()).to.throw('Cannot execute transition Resume in current state Stopped.'); expect(() => flow.stop()).to.throw('Cannot execute transition Stop in current state Stopped.'); expect(() => flow.start()).to.throw('Cannot execute transition Start in current state Stopped.'); expect(() => pubFlow.finished()).to.throw('Cannot execute transition Finished in current state Stopped.'); expect(() => pubFlow.stopped()).to.throw('Cannot execute transition Stopped in current state Stopped.'); expect(() => pubFlow.paused()).to.throw('Cannot execute transition Paused in current state Stopped.'); // Valid transitions/operations flow.getSerializableState(); flow.reset(); }); // @todo add test for finished status // @todo add test for stopped status // @todo add test for paused status });
the_stack
import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export const DESKTOP_APP_INFO_LOOKUP_EXTENSION_POINT_NAME: string; export const DRIVE_IDENTIFIER_KIND_UNIX_DEVICE: string; export const FILE_ATTRIBUTE_ACCESS_CAN_DELETE: string; export const FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE: string; export const FILE_ATTRIBUTE_ACCESS_CAN_READ: string; export const FILE_ATTRIBUTE_ACCESS_CAN_RENAME: string; export const FILE_ATTRIBUTE_ACCESS_CAN_TRASH: string; export const FILE_ATTRIBUTE_ACCESS_CAN_WRITE: string; export const FILE_ATTRIBUTE_DOS_IS_ARCHIVE: string; export const FILE_ATTRIBUTE_DOS_IS_MOUNTPOINT: string; export const FILE_ATTRIBUTE_DOS_IS_SYSTEM: string; export const FILE_ATTRIBUTE_DOS_REPARSE_POINT_TAG: string; export const FILE_ATTRIBUTE_ETAG_VALUE: string; export const FILE_ATTRIBUTE_FILESYSTEM_FREE: string; export const FILE_ATTRIBUTE_FILESYSTEM_READONLY: string; export const FILE_ATTRIBUTE_FILESYSTEM_REMOTE: string; export const FILE_ATTRIBUTE_FILESYSTEM_SIZE: string; export const FILE_ATTRIBUTE_FILESYSTEM_TYPE: string; export const FILE_ATTRIBUTE_FILESYSTEM_USED: string; export const FILE_ATTRIBUTE_FILESYSTEM_USE_PREVIEW: string; export const FILE_ATTRIBUTE_GVFS_BACKEND: string; export const FILE_ATTRIBUTE_ID_FILE: string; export const FILE_ATTRIBUTE_ID_FILESYSTEM: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_EJECT: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_MOUNT: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_POLL: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_START: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_START_DEGRADED: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_STOP: string; export const FILE_ATTRIBUTE_MOUNTABLE_CAN_UNMOUNT: string; export const FILE_ATTRIBUTE_MOUNTABLE_HAL_UDI: string; export const FILE_ATTRIBUTE_MOUNTABLE_IS_MEDIA_CHECK_AUTOMATIC: string; export const FILE_ATTRIBUTE_MOUNTABLE_START_STOP_TYPE: string; export const FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE: string; export const FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE_FILE: string; export const FILE_ATTRIBUTE_OWNER_GROUP: string; export const FILE_ATTRIBUTE_OWNER_USER: string; export const FILE_ATTRIBUTE_OWNER_USER_REAL: string; export const FILE_ATTRIBUTE_PREVIEW_ICON: string; export const FILE_ATTRIBUTE_RECENT_MODIFIED: string; export const FILE_ATTRIBUTE_SELINUX_CONTEXT: string; export const FILE_ATTRIBUTE_STANDARD_ALLOCATED_SIZE: string; export const FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE: string; export const FILE_ATTRIBUTE_STANDARD_COPY_NAME: string; export const FILE_ATTRIBUTE_STANDARD_DESCRIPTION: string; export const FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME: string; export const FILE_ATTRIBUTE_STANDARD_EDIT_NAME: string; export const FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE: string; export const FILE_ATTRIBUTE_STANDARD_ICON: string; export const FILE_ATTRIBUTE_STANDARD_IS_BACKUP: string; export const FILE_ATTRIBUTE_STANDARD_IS_HIDDEN: string; export const FILE_ATTRIBUTE_STANDARD_IS_SYMLINK: string; export const FILE_ATTRIBUTE_STANDARD_IS_VIRTUAL: string; export const FILE_ATTRIBUTE_STANDARD_IS_VOLATILE: string; export const FILE_ATTRIBUTE_STANDARD_NAME: string; export const FILE_ATTRIBUTE_STANDARD_SIZE: string; export const FILE_ATTRIBUTE_STANDARD_SORT_ORDER: string; export const FILE_ATTRIBUTE_STANDARD_SYMBOLIC_ICON: string; export const FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET: string; export const FILE_ATTRIBUTE_STANDARD_TARGET_URI: string; export const FILE_ATTRIBUTE_STANDARD_TYPE: string; export const FILE_ATTRIBUTE_THUMBNAILING_FAILED: string; export const FILE_ATTRIBUTE_THUMBNAIL_IS_VALID: string; export const FILE_ATTRIBUTE_THUMBNAIL_PATH: string; export const FILE_ATTRIBUTE_TIME_ACCESS: string; export const FILE_ATTRIBUTE_TIME_ACCESS_USEC: string; export const FILE_ATTRIBUTE_TIME_CHANGED: string; export const FILE_ATTRIBUTE_TIME_CHANGED_USEC: string; export const FILE_ATTRIBUTE_TIME_CREATED: string; export const FILE_ATTRIBUTE_TIME_CREATED_USEC: string; export const FILE_ATTRIBUTE_TIME_MODIFIED: string; export const FILE_ATTRIBUTE_TIME_MODIFIED_USEC: string; export const FILE_ATTRIBUTE_TRASH_DELETION_DATE: string; export const FILE_ATTRIBUTE_TRASH_ITEM_COUNT: string; export const FILE_ATTRIBUTE_TRASH_ORIG_PATH: string; export const FILE_ATTRIBUTE_UNIX_BLOCKS: string; export const FILE_ATTRIBUTE_UNIX_BLOCK_SIZE: string; export const FILE_ATTRIBUTE_UNIX_DEVICE: string; export const FILE_ATTRIBUTE_UNIX_GID: string; export const FILE_ATTRIBUTE_UNIX_INODE: string; export const FILE_ATTRIBUTE_UNIX_IS_MOUNTPOINT: string; export const FILE_ATTRIBUTE_UNIX_MODE: string; export const FILE_ATTRIBUTE_UNIX_NLINK: string; export const FILE_ATTRIBUTE_UNIX_RDEV: string; export const FILE_ATTRIBUTE_UNIX_UID: string; export const MEMORY_MONITOR_EXTENSION_POINT_NAME: string; export const MENU_ATTRIBUTE_ACTION: string; export const MENU_ATTRIBUTE_ACTION_NAMESPACE: string; export const MENU_ATTRIBUTE_ICON: string; export const MENU_ATTRIBUTE_LABEL: string; export const MENU_ATTRIBUTE_TARGET: string; export const MENU_LINK_SECTION: string; export const MENU_LINK_SUBMENU: string; export const NATIVE_VOLUME_MONITOR_EXTENSION_POINT_NAME: string; export const NETWORK_MONITOR_EXTENSION_POINT_NAME: string; export const PROXY_EXTENSION_POINT_NAME: string; export const PROXY_RESOLVER_EXTENSION_POINT_NAME: string; export const SETTINGS_BACKEND_EXTENSION_POINT_NAME: string; export const TLS_BACKEND_EXTENSION_POINT_NAME: string; export const TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT: string; export const TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER: string; export const VFS_EXTENSION_POINT_NAME: string; export const VOLUME_IDENTIFIER_KIND_CLASS: string; export const VOLUME_IDENTIFIER_KIND_HAL_UDI: string; export const VOLUME_IDENTIFIER_KIND_LABEL: string; export const VOLUME_IDENTIFIER_KIND_NFS_MOUNT: string; export const VOLUME_IDENTIFIER_KIND_UNIX_DEVICE: string; export const VOLUME_IDENTIFIER_KIND_UUID: string; export const VOLUME_MONITOR_EXTENSION_POINT_NAME: string; export function action_name_is_valid(action_name: string): boolean; export function action_parse_detailed_name(detailed_name: string): [boolean, string, GLib.Variant]; export function action_print_detailed_name(action_name: string, target_value?: GLib.Variant | null): string; export function app_info_create_from_commandline( commandline: string, application_name: string | null, flags: AppInfoCreateFlags ): AppInfo; export function app_info_get_all(): AppInfo[]; export function app_info_get_all_for_type(content_type: string): AppInfo[]; export function app_info_get_default_for_type(content_type: string, must_support_uris: boolean): AppInfo | null; export function app_info_get_default_for_uri_scheme(uri_scheme: string): AppInfo | null; export function app_info_get_fallback_for_type(content_type: string): AppInfo[]; export function app_info_get_recommended_for_type(content_type: string): AppInfo[]; export function app_info_launch_default_for_uri(uri: string, context?: AppLaunchContext | null): boolean; export function app_info_launch_default_for_uri_async( uri: string, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; export function app_info_launch_default_for_uri_async( uri: string, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<string> | null ): void; export function app_info_launch_default_for_uri_async( uri: string, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<string> | null ): Promise<boolean> | void; export function app_info_launch_default_for_uri_finish(result: AsyncResult): boolean; export function app_info_reset_type_associations(content_type: string): void; export function async_initable_newv_async( object_type: GObject.GType, n_parameters: number, parameters: GObject.Parameter, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<GObject.GType> | null ): void; export function bus_get(bus_type: BusType, cancellable?: Cancellable | null): Promise<DBusConnection>; export function bus_get( bus_type: BusType, cancellable: Cancellable | null, callback: AsyncReadyCallback<BusType> | null ): void; export function bus_get( bus_type: BusType, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<BusType> | null ): Promise<DBusConnection> | void; export function bus_get_finish(res: AsyncResult): DBusConnection; export function bus_get_sync(bus_type: BusType, cancellable?: Cancellable | null): DBusConnection; export function bus_own_name_on_connection( connection: DBusConnection, name: string, flags: BusNameOwnerFlags, name_acquired_closure?: GObject.Closure | null, name_lost_closure?: GObject.Closure | null ): number; export function bus_own_name( bus_type: BusType, name: string, flags: BusNameOwnerFlags, bus_acquired_closure?: GObject.Closure | null, name_acquired_closure?: GObject.Closure | null, name_lost_closure?: GObject.Closure | null ): number; export function bus_unown_name(owner_id: number): void; export function bus_unwatch_name(watcher_id: number): void; export function bus_watch_name_on_connection( connection: DBusConnection, name: string, flags: BusNameWatcherFlags, name_appeared_closure?: GObject.Closure | null, name_vanished_closure?: GObject.Closure | null ): number; export function bus_watch_name( bus_type: BusType, name: string, flags: BusNameWatcherFlags, name_appeared_closure?: GObject.Closure | null, name_vanished_closure?: GObject.Closure | null ): number; export function content_type_can_be_executable(type: string): boolean; export function content_type_equals(type1: string, type2: string): boolean; export function content_type_from_mime_type(mime_type: string): string | null; export function content_type_get_description(type: string): string; export function content_type_get_generic_icon_name(type: string): string | null; export function content_type_get_icon(type: string): Icon; export function content_type_get_mime_dirs(): string[]; export function content_type_get_mime_type(type: string): string | null; export function content_type_get_symbolic_icon(type: string): Icon; export function content_type_guess(filename?: string | null, data?: Uint8Array | null): [string, boolean | null]; export function content_type_guess_for_tree(root: File): string[]; export function content_type_is_a(type: string, supertype: string): boolean; export function content_type_is_mime_type(type: string, mime_type: string): boolean; export function content_type_is_unknown(type: string): boolean; export function content_type_set_mime_dirs(dirs?: string[] | null): void; export function content_types_get_registered(): string[]; export function dbus_address_escape_value(string: string): string; export function dbus_address_get_for_bus_sync(bus_type: BusType, cancellable?: Cancellable | null): string; export function dbus_address_get_stream( address: string, cancellable?: Cancellable | null ): Promise<[IOStream, string | null]>; export function dbus_address_get_stream( address: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<string> | null ): void; export function dbus_address_get_stream( address: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<string> | null ): Promise<[IOStream, string | null]> | void; export function dbus_address_get_stream_finish(res: AsyncResult): [IOStream, string | null]; export function dbus_address_get_stream_sync( address: string, cancellable?: Cancellable | null ): [IOStream, string | null]; export function dbus_annotation_info_lookup(annotations: DBusAnnotationInfo[] | null, name: string): string; export function dbus_error_encode_gerror(error: GLib.Error): string; export function dbus_error_get_remote_error(error: GLib.Error): string; export function dbus_error_is_remote_error(error: GLib.Error): boolean; export function dbus_error_new_for_dbus_error(dbus_error_name: string, dbus_error_message: string): GLib.Error; export function dbus_error_quark(): GLib.Quark; export function dbus_error_register_error( error_domain: GLib.Quark, error_code: number, dbus_error_name: string ): boolean; export function dbus_error_register_error_domain( error_domain_quark_name: string, quark_volatile: number, entries: DBusErrorEntry[] ): void; export function dbus_error_strip_remote_error(error: GLib.Error): boolean; export function dbus_error_unregister_error( error_domain: GLib.Quark, error_code: number, dbus_error_name: string ): boolean; export function dbus_generate_guid(): string; export function dbus_gvalue_to_gvariant(gvalue: any, type: GLib.VariantType): GLib.Variant; export function dbus_gvariant_to_gvalue(value: GLib.Variant): unknown; export function dbus_is_address(string: string): boolean; export function dbus_is_guid(string: string): boolean; export function dbus_is_interface_name(string: string): boolean; export function dbus_is_member_name(string: string): boolean; export function dbus_is_name(string: string): boolean; export function dbus_is_supported_address(string: string): boolean; export function dbus_is_unique_name(string: string): boolean; export function dtls_client_connection_new( base_socket: DatagramBased, server_identity?: SocketConnectable | null ): DtlsClientConnection; export function dtls_server_connection_new( base_socket: DatagramBased, certificate?: TlsCertificate | null ): DtlsServerConnection; export function file_new_for_commandline_arg(arg: string): File; export function file_new_for_commandline_arg_and_cwd(arg: string, cwd: string): File; export function file_new_for_path(path: string): File; export function file_new_for_uri(uri: string): File; export function file_new_tmp(tmpl: string | null): [File, FileIOStream]; export function file_parse_name(parse_name: string): File; export function icon_deserialize(value: GLib.Variant): Icon; export function icon_hash(icon: any): number; export function icon_new_for_string(str: string): Icon; export function initable_newv<T = GObject.Object>( object_type: GObject.GType, parameters: GObject.Parameter[], cancellable?: Cancellable | null ): T; export function io_error_from_errno(err_no: number): IOErrorEnum; export function io_error_quark(): GLib.Quark; export function io_extension_point_implement( extension_point_name: string, type: GObject.GType, extension_name: string, priority: number ): IOExtension; export function io_extension_point_lookup(name: string): IOExtensionPoint; export function io_extension_point_register(name: string): IOExtensionPoint; export function io_modules_load_all_in_directory(dirname: string): IOModule[]; export function io_modules_load_all_in_directory_with_scope(dirname: string, scope: IOModuleScope): IOModule[]; export function io_modules_scan_all_in_directory(dirname: string): void; export function io_modules_scan_all_in_directory_with_scope(dirname: string, scope: IOModuleScope): void; export function io_scheduler_cancel_all_jobs(): void; export function io_scheduler_push_job( job_func: IOSchedulerJobFunc, notify: GLib.DestroyNotify | null, io_priority: number, cancellable?: Cancellable | null ): void; export function keyfile_settings_backend_new( filename: string, root_path: string, root_group?: string | null ): SettingsBackend; export function memory_monitor_dup_default(): MemoryMonitor; export function memory_settings_backend_new(): SettingsBackend; export function network_monitor_get_default(): NetworkMonitor; export function networking_init(): void; export function null_settings_backend_new(): SettingsBackend; export function pollable_source_new(pollable_stream: GObject.Object): GLib.Source; export function pollable_source_new_full( pollable_stream: GObject.Object, child_source?: GLib.Source | null, cancellable?: Cancellable | null ): GLib.Source; export function pollable_stream_read( stream: InputStream, buffer: Uint8Array | string, blocking: boolean, cancellable?: Cancellable | null ): number; export function pollable_stream_write( stream: OutputStream, buffer: Uint8Array | string, blocking: boolean, cancellable?: Cancellable | null ): number; export function pollable_stream_write_all( stream: OutputStream, buffer: Uint8Array | string, blocking: boolean, cancellable?: Cancellable | null ): [boolean, number]; export function proxy_get_default_for_protocol(protocol: string): Proxy; export function proxy_resolver_get_default(): ProxyResolver; export function resolver_error_quark(): GLib.Quark; export function resource_error_quark(): GLib.Quark; export function resource_load(filename: string): Resource; export function resources_enumerate_children(path: string, lookup_flags: ResourceLookupFlags): string[]; export function resources_get_info( path: string, lookup_flags: ResourceLookupFlags ): [boolean, number | null, number | null]; export function resources_lookup_data(path: string, lookup_flags: ResourceLookupFlags): GLib.Bytes; export function resources_open_stream(path: string, lookup_flags: ResourceLookupFlags): InputStream; export function resources_register(resource: Resource): void; export function resources_unregister(resource: Resource): void; export function settings_schema_source_get_default(): SettingsSchemaSource | null; export function simple_async_report_gerror_in_idle( object: GObject.Object | null, callback: AsyncReadyCallback<GObject.Object | null> | null, error: GLib.Error ): void; export function tls_backend_get_default(): TlsBackend; export function tls_channel_binding_error_quark(): GLib.Quark; export function tls_client_connection_new( base_io_stream: IOStream, server_identity?: SocketConnectable | null ): TlsClientConnection; export function tls_error_quark(): GLib.Quark; export function tls_file_database_new(anchors: string): TlsFileDatabase; export function tls_server_connection_new( base_io_stream: IOStream, certificate?: TlsCertificate | null ): TlsServerConnection; export function unix_is_mount_path_system_internal(mount_path: string): boolean; export function unix_is_system_device_path(device_path: string): boolean; export function unix_is_system_fs_type(fs_type: string): boolean; export function unix_mount_at(mount_path: string): [UnixMountEntry, number | null]; export function unix_mount_compare(mount1: UnixMountEntry, mount2: UnixMountEntry): number; export function unix_mount_copy(mount_entry: UnixMountEntry): UnixMountEntry; export function unix_mount_for(file_path: string): [UnixMountEntry, number | null]; export function unix_mount_free(mount_entry: UnixMountEntry): void; export function unix_mount_get_device_path(mount_entry: UnixMountEntry): string; export function unix_mount_get_fs_type(mount_entry: UnixMountEntry): string; export function unix_mount_get_mount_path(mount_entry: UnixMountEntry): string; export function unix_mount_get_options(mount_entry: UnixMountEntry): string | null; export function unix_mount_get_root_path(mount_entry: UnixMountEntry): string | null; export function unix_mount_guess_can_eject(mount_entry: UnixMountEntry): boolean; export function unix_mount_guess_icon(mount_entry: UnixMountEntry): Icon; export function unix_mount_guess_name(mount_entry: UnixMountEntry): string; export function unix_mount_guess_should_display(mount_entry: UnixMountEntry): boolean; export function unix_mount_guess_symbolic_icon(mount_entry: UnixMountEntry): Icon; export function unix_mount_is_readonly(mount_entry: UnixMountEntry): boolean; export function unix_mount_is_system_internal(mount_entry: UnixMountEntry): boolean; export function unix_mount_point_at(mount_path: string): [UnixMountPoint | null, number | null]; export function unix_mount_points_changed_since(time: number): boolean; export function unix_mount_points_get(): [UnixMountPoint[], number | null]; export function unix_mounts_changed_since(time: number): boolean; export function unix_mounts_get(): [UnixMountEntry[], number | null]; export type AsyncReadyCallback<A = GObject.Object> = (source_object: A | null, res: AsyncResult) => void; export type BusAcquiredCallback = (connection: DBusConnection, name: string) => void; export type BusNameAcquiredCallback = (connection: DBusConnection, name: string) => void; export type BusNameAppearedCallback = (connection: DBusConnection, name: string, name_owner: string) => void; export type BusNameLostCallback = (connection: DBusConnection, name: string) => void; export type BusNameVanishedCallback = (connection: DBusConnection, name: string) => void; export type CancellableSourceFunc = (cancellable?: Cancellable | null) => boolean; export type DBusInterfaceGetPropertyFunc = ( connection: DBusConnection, sender: string, object_path: string, interface_name: string, property_name: string, error: GLib.Error ) => GLib.Variant; export type DBusInterfaceMethodCallFunc = ( connection: DBusConnection, sender: string, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant, invocation: DBusMethodInvocation ) => void; export type DBusInterfaceSetPropertyFunc = ( connection: DBusConnection, sender: string, object_path: string, interface_name: string, property_name: string, value: GLib.Variant, error: GLib.Error ) => boolean; export type DBusMessageFilterFunction = ( connection: DBusConnection, message: DBusMessage, incoming: boolean ) => DBusMessage | null; export type DBusProxyTypeFunc = ( manager: DBusObjectManagerClient, object_path: string, interface_name?: string | null ) => GObject.GType; export type DBusSignalCallback = ( connection: DBusConnection, sender_name: string | null, object_path: string, interface_name: string, signal_name: string, parameters: GLib.Variant ) => void; export type DBusSubtreeDispatchFunc = ( connection: DBusConnection, sender: string, object_path: string, interface_name: string, node: string, out_user_data: any ) => DBusInterfaceVTable; export type DBusSubtreeIntrospectFunc = ( connection: DBusConnection, sender: string, object_path: string, node: string ) => DBusInterfaceInfo; export type DatagramBasedSourceFunc = (datagram_based: DatagramBased, condition: GLib.IOCondition) => boolean; export type DesktopAppLaunchCallback = (appinfo: DesktopAppInfo, pid: GLib.Pid) => void; export type FileMeasureProgressCallback = ( reporting: boolean, current_size: number, num_dirs: number, num_files: number ) => void; export type FileProgressCallback = (current_num_bytes: number, total_num_bytes: number) => void; export type FileReadMoreCallback = (file_contents: string, file_size: number) => boolean; export type IOSchedulerJobFunc = (job: IOSchedulerJob, cancellable?: Cancellable | null) => boolean; export type PollableSourceFunc<A = GObject.Object> = (pollable_stream: A) => boolean; export type ReallocFunc = (data: any | null, size: number) => any | null; export type SettingsBindGetMapping = (value: any, variant: GLib.Variant) => boolean; export type SettingsBindSetMapping = (value: any, expected_type: GLib.VariantType) => GLib.Variant; export type SettingsGetMapping = (value: GLib.Variant) => boolean; export type SimpleAsyncThreadFunc<A = GObject.Object> = ( res: SimpleAsyncResult, object: A, cancellable?: Cancellable | null ) => void; export type SocketSourceFunc = (socket: Socket, condition: GLib.IOCondition) => boolean; export type TaskThreadFunc<A = GObject.Object> = ( task: Task, source_object: A, task_data?: any | null, cancellable?: Cancellable | null ) => void; export type VfsFileLookupFunc = (vfs: Vfs, identifier: string) => File; export namespace BusType { export const $gtype: GObject.GType<BusType>; } export enum BusType { STARTER = -1, NONE = 0, SYSTEM = 1, SESSION = 2, } export namespace ConverterResult { export const $gtype: GObject.GType<ConverterResult>; } export enum ConverterResult { ERROR = 0, CONVERTED = 1, FINISHED = 2, FLUSHED = 3, } export namespace CredentialsType { export const $gtype: GObject.GType<CredentialsType>; } export enum CredentialsType { INVALID = 0, LINUX_UCRED = 1, FREEBSD_CMSGCRED = 2, OPENBSD_SOCKPEERCRED = 3, SOLARIS_UCRED = 4, NETBSD_UNPCBID = 5, APPLE_XUCRED = 6, } export class DBusError extends GLib.Error { static $gtype: GObject.GType<DBusError>; constructor(options: { message: string; code: number }); constructor(copy: DBusError); // Properties static FAILED: number; static NO_MEMORY: number; static SERVICE_UNKNOWN: number; static NAME_HAS_NO_OWNER: number; static NO_REPLY: number; static IO_ERROR: number; static BAD_ADDRESS: number; static NOT_SUPPORTED: number; static LIMITS_EXCEEDED: number; static ACCESS_DENIED: number; static AUTH_FAILED: number; static NO_SERVER: number; static TIMEOUT: number; static NO_NETWORK: number; static ADDRESS_IN_USE: number; static DISCONNECTED: number; static INVALID_ARGS: number; static FILE_NOT_FOUND: number; static FILE_EXISTS: number; static UNKNOWN_METHOD: number; static TIMED_OUT: number; static MATCH_RULE_NOT_FOUND: number; static MATCH_RULE_INVALID: number; static SPAWN_EXEC_FAILED: number; static SPAWN_FORK_FAILED: number; static SPAWN_CHILD_EXITED: number; static SPAWN_CHILD_SIGNALED: number; static SPAWN_FAILED: number; static SPAWN_SETUP_FAILED: number; static SPAWN_CONFIG_INVALID: number; static SPAWN_SERVICE_INVALID: number; static SPAWN_SERVICE_NOT_FOUND: number; static SPAWN_PERMISSIONS_INVALID: number; static SPAWN_FILE_INVALID: number; static SPAWN_NO_MEMORY: number; static UNIX_PROCESS_ID_UNKNOWN: number; static INVALID_SIGNATURE: number; static INVALID_FILE_CONTENT: number; static SELINUX_SECURITY_CONTEXT_UNKNOWN: number; static ADT_AUDIT_DATA_UNKNOWN: number; static OBJECT_PATH_IN_USE: number; static UNKNOWN_OBJECT: number; static UNKNOWN_INTERFACE: number; static UNKNOWN_PROPERTY: number; static PROPERTY_READ_ONLY: number; // Members static encode_gerror(error: GLib.Error): string; static get_remote_error(error: GLib.Error): string; static is_remote_error(error: GLib.Error): boolean; static new_for_dbus_error(dbus_error_name: string, dbus_error_message: string): GLib.Error; static quark(): GLib.Quark; static register_error(error_domain: GLib.Quark, error_code: number, dbus_error_name: string): boolean; static register_error_domain( error_domain_quark_name: string, quark_volatile: number, entries: DBusErrorEntry[] ): void; static set_dbus_error( error: GLib.Error, dbus_error_name: string, dbus_error_message: string, format: string | null, ___: any[] ): void; static set_dbus_error_valist( error: GLib.Error, dbus_error_name: string, dbus_error_message: string, format: string | null, var_args: any ): void; static strip_remote_error(error: GLib.Error): boolean; static unregister_error(error_domain: GLib.Quark, error_code: number, dbus_error_name: string): boolean; } export namespace DBusMessageByteOrder { export const $gtype: GObject.GType<DBusMessageByteOrder>; } export enum DBusMessageByteOrder { BIG_ENDIAN = 66, LITTLE_ENDIAN = 108, } export namespace DBusMessageHeaderField { export const $gtype: GObject.GType<DBusMessageHeaderField>; } export enum DBusMessageHeaderField { INVALID = 0, PATH = 1, INTERFACE = 2, MEMBER = 3, ERROR_NAME = 4, REPLY_SERIAL = 5, DESTINATION = 6, SENDER = 7, SIGNATURE = 8, NUM_UNIX_FDS = 9, } export namespace DBusMessageType { export const $gtype: GObject.GType<DBusMessageType>; } export enum DBusMessageType { INVALID = 0, METHOD_CALL = 1, METHOD_RETURN = 2, ERROR = 3, SIGNAL = 4, } export namespace DataStreamByteOrder { export const $gtype: GObject.GType<DataStreamByteOrder>; } export enum DataStreamByteOrder { BIG_ENDIAN = 0, LITTLE_ENDIAN = 1, HOST_ENDIAN = 2, } export namespace DataStreamNewlineType { export const $gtype: GObject.GType<DataStreamNewlineType>; } export enum DataStreamNewlineType { LF = 0, CR = 1, CR_LF = 2, ANY = 3, } export namespace DriveStartStopType { export const $gtype: GObject.GType<DriveStartStopType>; } export enum DriveStartStopType { UNKNOWN = 0, SHUTDOWN = 1, NETWORK = 2, MULTIDISK = 3, PASSWORD = 4, } export namespace EmblemOrigin { export const $gtype: GObject.GType<EmblemOrigin>; } export enum EmblemOrigin { UNKNOWN = 0, DEVICE = 1, LIVEMETADATA = 2, TAG = 3, } export namespace FileAttributeStatus { export const $gtype: GObject.GType<FileAttributeStatus>; } export enum FileAttributeStatus { UNSET = 0, SET = 1, ERROR_SETTING = 2, } export namespace FileAttributeType { export const $gtype: GObject.GType<FileAttributeType>; } export enum FileAttributeType { INVALID = 0, STRING = 1, BYTE_STRING = 2, BOOLEAN = 3, UINT32 = 4, INT32 = 5, UINT64 = 6, INT64 = 7, OBJECT = 8, STRINGV = 9, } export namespace FileMonitorEvent { export const $gtype: GObject.GType<FileMonitorEvent>; } export enum FileMonitorEvent { CHANGED = 0, CHANGES_DONE_HINT = 1, DELETED = 2, CREATED = 3, ATTRIBUTE_CHANGED = 4, PRE_UNMOUNT = 5, UNMOUNTED = 6, MOVED = 7, RENAMED = 8, MOVED_IN = 9, MOVED_OUT = 10, } export namespace FileType { export const $gtype: GObject.GType<FileType>; } export enum FileType { UNKNOWN = 0, REGULAR = 1, DIRECTORY = 2, SYMBOLIC_LINK = 3, SPECIAL = 4, SHORTCUT = 5, MOUNTABLE = 6, } export namespace FilesystemPreviewType { export const $gtype: GObject.GType<FilesystemPreviewType>; } export enum FilesystemPreviewType { IF_ALWAYS = 0, IF_LOCAL = 1, NEVER = 2, } export class IOErrorEnum extends GLib.Error { static $gtype: GObject.GType<IOErrorEnum>; constructor(options: { message: string; code: number }); constructor(copy: IOErrorEnum); // Properties static FAILED: number; static NOT_FOUND: number; static EXISTS: number; static IS_DIRECTORY: number; static NOT_DIRECTORY: number; static NOT_EMPTY: number; static NOT_REGULAR_FILE: number; static NOT_SYMBOLIC_LINK: number; static NOT_MOUNTABLE_FILE: number; static FILENAME_TOO_LONG: number; static INVALID_FILENAME: number; static TOO_MANY_LINKS: number; static NO_SPACE: number; static INVALID_ARGUMENT: number; static PERMISSION_DENIED: number; static NOT_SUPPORTED: number; static NOT_MOUNTED: number; static ALREADY_MOUNTED: number; static CLOSED: number; static CANCELLED: number; static PENDING: number; static READ_ONLY: number; static CANT_CREATE_BACKUP: number; static WRONG_ETAG: number; static TIMED_OUT: number; static WOULD_RECURSE: number; static BUSY: number; static WOULD_BLOCK: number; static HOST_NOT_FOUND: number; static WOULD_MERGE: number; static FAILED_HANDLED: number; static TOO_MANY_OPEN_FILES: number; static NOT_INITIALIZED: number; static ADDRESS_IN_USE: number; static PARTIAL_INPUT: number; static INVALID_DATA: number; static DBUS_ERROR: number; static HOST_UNREACHABLE: number; static NETWORK_UNREACHABLE: number; static CONNECTION_REFUSED: number; static PROXY_FAILED: number; static PROXY_AUTH_FAILED: number; static PROXY_NEED_AUTH: number; static PROXY_NOT_ALLOWED: number; static BROKEN_PIPE: number; static CONNECTION_CLOSED: number; static NOT_CONNECTED: number; static MESSAGE_TOO_LARGE: number; } export namespace IOModuleScopeFlags { export const $gtype: GObject.GType<IOModuleScopeFlags>; } export enum IOModuleScopeFlags { NONE = 0, BLOCK_DUPLICATES = 1, } export namespace MemoryMonitorWarningLevel { export const $gtype: GObject.GType<MemoryMonitorWarningLevel>; } export enum MemoryMonitorWarningLevel { LOW = 50, MEDIUM = 100, CRITICAL = 255, } export namespace MountOperationResult { export const $gtype: GObject.GType<MountOperationResult>; } export enum MountOperationResult { HANDLED = 0, ABORTED = 1, UNHANDLED = 2, } export namespace NetworkConnectivity { export const $gtype: GObject.GType<NetworkConnectivity>; } export enum NetworkConnectivity { LOCAL = 1, LIMITED = 2, PORTAL = 3, FULL = 4, } export namespace NotificationPriority { export const $gtype: GObject.GType<NotificationPriority>; } export enum NotificationPriority { NORMAL = 0, LOW = 1, HIGH = 2, URGENT = 3, } export namespace PasswordSave { export const $gtype: GObject.GType<PasswordSave>; } export enum PasswordSave { NEVER = 0, FOR_SESSION = 1, PERMANENTLY = 2, } export namespace PollableReturn { export const $gtype: GObject.GType<PollableReturn>; } export enum PollableReturn { FAILED = 0, OK = 1, WOULD_BLOCK = -27, } export class ResolverError extends GLib.Error { static $gtype: GObject.GType<ResolverError>; constructor(options: { message: string; code: number }); constructor(copy: ResolverError); // Properties static NOT_FOUND: number; static TEMPORARY_FAILURE: number; static INTERNAL: number; // Members static quark(): GLib.Quark; } export namespace ResolverRecordType { export const $gtype: GObject.GType<ResolverRecordType>; } export enum ResolverRecordType { SRV = 1, MX = 2, TXT = 3, SOA = 4, NS = 5, } export class ResourceError extends GLib.Error { static $gtype: GObject.GType<ResourceError>; constructor(options: { message: string; code: number }); constructor(copy: ResourceError); // Properties static NOT_FOUND: number; static INTERNAL: number; // Members static quark(): GLib.Quark; } export namespace SocketClientEvent { export const $gtype: GObject.GType<SocketClientEvent>; } export enum SocketClientEvent { RESOLVING = 0, RESOLVED = 1, CONNECTING = 2, CONNECTED = 3, PROXY_NEGOTIATING = 4, PROXY_NEGOTIATED = 5, TLS_HANDSHAKING = 6, TLS_HANDSHAKED = 7, COMPLETE = 8, } export namespace SocketFamily { export const $gtype: GObject.GType<SocketFamily>; } export enum SocketFamily { INVALID = 0, UNIX = 1, IPV4 = 2, IPV6 = 10, } export namespace SocketListenerEvent { export const $gtype: GObject.GType<SocketListenerEvent>; } export enum SocketListenerEvent { BINDING = 0, BOUND = 1, LISTENING = 2, LISTENED = 3, } export namespace SocketProtocol { export const $gtype: GObject.GType<SocketProtocol>; } export enum SocketProtocol { UNKNOWN = -1, DEFAULT = 0, TCP = 6, UDP = 17, SCTP = 132, } export namespace SocketType { export const $gtype: GObject.GType<SocketType>; } export enum SocketType { INVALID = 0, STREAM = 1, DATAGRAM = 2, SEQPACKET = 3, } export namespace TlsAuthenticationMode { export const $gtype: GObject.GType<TlsAuthenticationMode>; } export enum TlsAuthenticationMode { NONE = 0, REQUESTED = 1, REQUIRED = 2, } export namespace TlsCertificateRequestFlags { export const $gtype: GObject.GType<TlsCertificateRequestFlags>; } export enum TlsCertificateRequestFlags { NONE = 0, } export class TlsChannelBindingError extends GLib.Error { static $gtype: GObject.GType<TlsChannelBindingError>; constructor(options: { message: string; code: number }); constructor(copy: TlsChannelBindingError); // Properties static NOT_IMPLEMENTED: number; static INVALID_STATE: number; static NOT_AVAILABLE: number; static NOT_SUPPORTED: number; static GENERAL_ERROR: number; // Members static quark(): GLib.Quark; } export namespace TlsChannelBindingType { export const $gtype: GObject.GType<TlsChannelBindingType>; } export enum TlsChannelBindingType { UNIQUE = 0, SERVER_END_POINT = 1, } export namespace TlsDatabaseLookupFlags { export const $gtype: GObject.GType<TlsDatabaseLookupFlags>; } export enum TlsDatabaseLookupFlags { NONE = 0, KEYPAIR = 1, } export class TlsError extends GLib.Error { static $gtype: GObject.GType<TlsError>; constructor(options: { message: string; code: number }); constructor(copy: TlsError); // Properties static UNAVAILABLE: number; static MISC: number; static BAD_CERTIFICATE: number; static NOT_TLS: number; static HANDSHAKE: number; static CERTIFICATE_REQUIRED: number; static EOF: number; static INAPPROPRIATE_FALLBACK: number; // Members static quark(): GLib.Quark; } export namespace TlsInteractionResult { export const $gtype: GObject.GType<TlsInteractionResult>; } export enum TlsInteractionResult { UNHANDLED = 0, HANDLED = 1, FAILED = 2, } export namespace TlsRehandshakeMode { export const $gtype: GObject.GType<TlsRehandshakeMode>; } export enum TlsRehandshakeMode { NEVER = 0, SAFELY = 1, UNSAFELY = 2, } export namespace UnixSocketAddressType { export const $gtype: GObject.GType<UnixSocketAddressType>; } export enum UnixSocketAddressType { INVALID = 0, ANONYMOUS = 1, PATH = 2, ABSTRACT = 3, ABSTRACT_PADDED = 4, } export namespace ZlibCompressorFormat { export const $gtype: GObject.GType<ZlibCompressorFormat>; } export enum ZlibCompressorFormat { ZLIB = 0, GZIP = 1, RAW = 2, } export namespace AppInfoCreateFlags { export const $gtype: GObject.GType<AppInfoCreateFlags>; } export enum AppInfoCreateFlags { NONE = 0, NEEDS_TERMINAL = 1, SUPPORTS_URIS = 2, SUPPORTS_STARTUP_NOTIFICATION = 4, } export namespace ApplicationFlags { export const $gtype: GObject.GType<ApplicationFlags>; } export enum ApplicationFlags { FLAGS_NONE = 0, IS_SERVICE = 1, IS_LAUNCHER = 2, HANDLES_OPEN = 4, HANDLES_COMMAND_LINE = 8, SEND_ENVIRONMENT = 16, NON_UNIQUE = 32, CAN_OVERRIDE_APP_ID = 64, ALLOW_REPLACEMENT = 128, REPLACE = 256, } export namespace AskPasswordFlags { export const $gtype: GObject.GType<AskPasswordFlags>; } export enum AskPasswordFlags { NEED_PASSWORD = 1, NEED_USERNAME = 2, NEED_DOMAIN = 4, SAVING_SUPPORTED = 8, ANONYMOUS_SUPPORTED = 16, TCRYPT = 32, } export namespace BusNameOwnerFlags { export const $gtype: GObject.GType<BusNameOwnerFlags>; } export enum BusNameOwnerFlags { NONE = 0, ALLOW_REPLACEMENT = 1, REPLACE = 2, DO_NOT_QUEUE = 4, } export namespace BusNameWatcherFlags { export const $gtype: GObject.GType<BusNameWatcherFlags>; } export enum BusNameWatcherFlags { NONE = 0, AUTO_START = 1, } export namespace ConverterFlags { export const $gtype: GObject.GType<ConverterFlags>; } export enum ConverterFlags { NONE = 0, INPUT_AT_END = 1, FLUSH = 2, } export namespace DBusCallFlags { export const $gtype: GObject.GType<DBusCallFlags>; } export enum DBusCallFlags { NONE = 0, NO_AUTO_START = 1, ALLOW_INTERACTIVE_AUTHORIZATION = 2, } export namespace DBusCapabilityFlags { export const $gtype: GObject.GType<DBusCapabilityFlags>; } export enum DBusCapabilityFlags { NONE = 0, UNIX_FD_PASSING = 1, } export namespace DBusConnectionFlags { export const $gtype: GObject.GType<DBusConnectionFlags>; } export enum DBusConnectionFlags { NONE = 0, AUTHENTICATION_CLIENT = 1, AUTHENTICATION_SERVER = 2, AUTHENTICATION_ALLOW_ANONYMOUS = 4, MESSAGE_BUS_CONNECTION = 8, DELAY_MESSAGE_PROCESSING = 16, } export namespace DBusInterfaceSkeletonFlags { export const $gtype: GObject.GType<DBusInterfaceSkeletonFlags>; } export enum DBusInterfaceSkeletonFlags { NONE = 0, HANDLE_METHOD_INVOCATIONS_IN_THREAD = 1, } export namespace DBusMessageFlags { export const $gtype: GObject.GType<DBusMessageFlags>; } export enum DBusMessageFlags { NONE = 0, NO_REPLY_EXPECTED = 1, NO_AUTO_START = 2, ALLOW_INTERACTIVE_AUTHORIZATION = 4, } export namespace DBusObjectManagerClientFlags { export const $gtype: GObject.GType<DBusObjectManagerClientFlags>; } export enum DBusObjectManagerClientFlags { NONE = 0, DO_NOT_AUTO_START = 1, } export namespace DBusPropertyInfoFlags { export const $gtype: GObject.GType<DBusPropertyInfoFlags>; } export enum DBusPropertyInfoFlags { NONE = 0, READABLE = 1, WRITABLE = 2, } export namespace DBusProxyFlags { export const $gtype: GObject.GType<DBusProxyFlags>; } export enum DBusProxyFlags { NONE = 0, DO_NOT_LOAD_PROPERTIES = 1, DO_NOT_CONNECT_SIGNALS = 2, DO_NOT_AUTO_START = 4, GET_INVALIDATED_PROPERTIES = 8, DO_NOT_AUTO_START_AT_CONSTRUCTION = 16, } export namespace DBusSendMessageFlags { export const $gtype: GObject.GType<DBusSendMessageFlags>; } export enum DBusSendMessageFlags { NONE = 0, PRESERVE_SERIAL = 1, } export namespace DBusServerFlags { export const $gtype: GObject.GType<DBusServerFlags>; } export enum DBusServerFlags { NONE = 0, RUN_IN_THREAD = 1, AUTHENTICATION_ALLOW_ANONYMOUS = 2, } export namespace DBusSignalFlags { export const $gtype: GObject.GType<DBusSignalFlags>; } export enum DBusSignalFlags { NONE = 0, NO_MATCH_RULE = 1, MATCH_ARG0_NAMESPACE = 2, MATCH_ARG0_PATH = 4, } export namespace DBusSubtreeFlags { export const $gtype: GObject.GType<DBusSubtreeFlags>; } export enum DBusSubtreeFlags { NONE = 0, DISPATCH_TO_UNENUMERATED_NODES = 1, } export namespace DriveStartFlags { export const $gtype: GObject.GType<DriveStartFlags>; } export enum DriveStartFlags { NONE = 0, } export namespace FileAttributeInfoFlags { export const $gtype: GObject.GType<FileAttributeInfoFlags>; } export enum FileAttributeInfoFlags { NONE = 0, COPY_WITH_FILE = 1, COPY_WHEN_MOVED = 2, } export namespace FileCopyFlags { export const $gtype: GObject.GType<FileCopyFlags>; } export enum FileCopyFlags { NONE = 0, OVERWRITE = 1, BACKUP = 2, NOFOLLOW_SYMLINKS = 4, ALL_METADATA = 8, NO_FALLBACK_FOR_MOVE = 16, TARGET_DEFAULT_PERMS = 32, } export namespace FileCreateFlags { export const $gtype: GObject.GType<FileCreateFlags>; } export enum FileCreateFlags { NONE = 0, PRIVATE = 1, REPLACE_DESTINATION = 2, } export namespace FileMeasureFlags { export const $gtype: GObject.GType<FileMeasureFlags>; } export enum FileMeasureFlags { NONE = 0, REPORT_ANY_ERROR = 2, APPARENT_SIZE = 4, NO_XDEV = 8, } export namespace FileMonitorFlags { export const $gtype: GObject.GType<FileMonitorFlags>; } export enum FileMonitorFlags { NONE = 0, WATCH_MOUNTS = 1, SEND_MOVED = 2, WATCH_HARD_LINKS = 4, WATCH_MOVES = 8, } export namespace FileQueryInfoFlags { export const $gtype: GObject.GType<FileQueryInfoFlags>; } export enum FileQueryInfoFlags { NONE = 0, NOFOLLOW_SYMLINKS = 1, } export namespace IOStreamSpliceFlags { export const $gtype: GObject.GType<IOStreamSpliceFlags>; } export enum IOStreamSpliceFlags { NONE = 0, CLOSE_STREAM1 = 1, CLOSE_STREAM2 = 2, WAIT_FOR_BOTH = 4, } export namespace MountMountFlags { export const $gtype: GObject.GType<MountMountFlags>; } export enum MountMountFlags { NONE = 0, } export namespace MountUnmountFlags { export const $gtype: GObject.GType<MountUnmountFlags>; } export enum MountUnmountFlags { NONE = 0, FORCE = 1, } export namespace OutputStreamSpliceFlags { export const $gtype: GObject.GType<OutputStreamSpliceFlags>; } export enum OutputStreamSpliceFlags { NONE = 0, CLOSE_SOURCE = 1, CLOSE_TARGET = 2, } export namespace ResolverNameLookupFlags { export const $gtype: GObject.GType<ResolverNameLookupFlags>; } export enum ResolverNameLookupFlags { DEFAULT = 0, IPV4_ONLY = 1, IPV6_ONLY = 2, } export namespace ResourceFlags { export const $gtype: GObject.GType<ResourceFlags>; } export enum ResourceFlags { NONE = 0, COMPRESSED = 1, } export namespace ResourceLookupFlags { export const $gtype: GObject.GType<ResourceLookupFlags>; } export enum ResourceLookupFlags { NONE = 0, } export namespace SettingsBindFlags { export const $gtype: GObject.GType<SettingsBindFlags>; } export enum SettingsBindFlags { DEFAULT = 0, GET = 1, SET = 2, NO_SENSITIVITY = 4, GET_NO_CHANGES = 8, INVERT_BOOLEAN = 16, } export namespace SocketMsgFlags { export const $gtype: GObject.GType<SocketMsgFlags>; } export enum SocketMsgFlags { NONE = 0, OOB = 1, PEEK = 2, DONTROUTE = 4, } export namespace SubprocessFlags { export const $gtype: GObject.GType<SubprocessFlags>; } export enum SubprocessFlags { NONE = 0, STDIN_PIPE = 1, STDIN_INHERIT = 2, STDOUT_PIPE = 4, STDOUT_SILENCE = 8, STDERR_PIPE = 16, STDERR_SILENCE = 32, STDERR_MERGE = 64, INHERIT_FDS = 128, } export namespace TestDBusFlags { export const $gtype: GObject.GType<TestDBusFlags>; } export enum TestDBusFlags { NONE = 0, } export namespace TlsCertificateFlags { export const $gtype: GObject.GType<TlsCertificateFlags>; } export enum TlsCertificateFlags { UNKNOWN_CA = 1, BAD_IDENTITY = 2, NOT_ACTIVATED = 4, EXPIRED = 8, REVOKED = 16, INSECURE = 32, GENERIC_ERROR = 64, VALIDATE_ALL = 127, } export namespace TlsDatabaseVerifyFlags { export const $gtype: GObject.GType<TlsDatabaseVerifyFlags>; } export enum TlsDatabaseVerifyFlags { NONE = 0, } export namespace TlsPasswordFlags { export const $gtype: GObject.GType<TlsPasswordFlags>; } export enum TlsPasswordFlags { NONE = 0, RETRY = 2, MANY_TRIES = 4, FINAL_TRY = 8, } export module AppInfoMonitor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class AppInfoMonitor extends GObject.Object { static $gtype: GObject.GType<AppInfoMonitor>; constructor(properties?: Partial<AppInfoMonitor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AppInfoMonitor.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "changed", callback: (_source: this) => void): number; connect_after(signal: "changed", callback: (_source: this) => void): number; emit(signal: "changed"): void; // Members static get(): AppInfoMonitor; } export module AppLaunchContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class AppLaunchContext extends GObject.Object { static $gtype: GObject.GType<AppLaunchContext>; constructor(properties?: Partial<AppLaunchContext.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AppLaunchContext.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "launch-failed", callback: (_source: this, startup_notify_id: string) => void): number; connect_after(signal: "launch-failed", callback: (_source: this, startup_notify_id: string) => void): number; emit(signal: "launch-failed", startup_notify_id: string): void; connect(signal: "launched", callback: (_source: this, info: AppInfo, platform_data: GLib.Variant) => void): number; connect_after( signal: "launched", callback: (_source: this, info: AppInfo, platform_data: GLib.Variant) => void ): number; emit(signal: "launched", info: AppInfo, platform_data: GLib.Variant): void; // Constructors static ["new"](): AppLaunchContext; // Members get_display(info: AppInfo, files: File[]): string; get_environment(): string[]; get_startup_notify_id(info: AppInfo, files: File[]): string; launch_failed(startup_notify_id: string): void; setenv(variable: string, value: string): void; unsetenv(variable: string): void; vfunc_get_display(info: AppInfo, files: File[]): string; vfunc_get_startup_notify_id(info: AppInfo, files: File[]): string; vfunc_launch_failed(startup_notify_id: string): void; vfunc_launched(info: AppInfo, platform_data: GLib.Variant): void; } export module Application { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; action_group: ActionGroup; actionGroup: ActionGroup; application_id: string; applicationId: string; flags: ApplicationFlags; inactivity_timeout: number; inactivityTimeout: number; is_busy: boolean; isBusy: boolean; is_registered: boolean; isRegistered: boolean; is_remote: boolean; isRemote: boolean; resource_base_path: string; resourceBasePath: string; } } export class Application extends GObject.Object implements ActionGroup, ActionMap { static $gtype: GObject.GType<Application>; constructor(properties?: Partial<Application.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Application.ConstructorProperties>, ...args: any[]): void; // Properties action_group: ActionGroup; actionGroup: ActionGroup; application_id: string; applicationId: string; flags: ApplicationFlags; inactivity_timeout: number; inactivityTimeout: number; is_busy: boolean; isBusy: boolean; is_registered: boolean; isRegistered: boolean; is_remote: boolean; isRemote: boolean; resource_base_path: string; resourceBasePath: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "activate", callback: (_source: this) => void): number; connect_after(signal: "activate", callback: (_source: this) => void): number; emit(signal: "activate"): void; connect(signal: "command-line", callback: (_source: this, command_line: ApplicationCommandLine) => number): number; connect_after( signal: "command-line", callback: (_source: this, command_line: ApplicationCommandLine) => number ): number; emit(signal: "command-line", command_line: ApplicationCommandLine): void; connect(signal: "handle-local-options", callback: (_source: this, options: GLib.VariantDict) => number): number; connect_after( signal: "handle-local-options", callback: (_source: this, options: GLib.VariantDict) => number ): number; emit(signal: "handle-local-options", options: GLib.VariantDict): void; connect(signal: "name-lost", callback: (_source: this) => boolean): number; connect_after(signal: "name-lost", callback: (_source: this) => boolean): number; emit(signal: "name-lost"): void; connect(signal: "open", callback: (_source: this, files: File[], n_files: number, hint: string) => void): number; connect_after( signal: "open", callback: (_source: this, files: File[], n_files: number, hint: string) => void ): number; emit(signal: "open", files: File[], n_files: number, hint: string): void; connect(signal: "shutdown", callback: (_source: this) => void): number; connect_after(signal: "shutdown", callback: (_source: this) => void): number; emit(signal: "shutdown"): void; connect(signal: "startup", callback: (_source: this) => void): number; connect_after(signal: "startup", callback: (_source: this) => void): number; emit(signal: "startup"): void; // Constructors static ["new"](application_id: string | null, flags: ApplicationFlags): Application; // Members activate(): void; add_main_option( long_name: string, short_name: number, flags: GLib.OptionFlags, arg: GLib.OptionArg, description: string, arg_description?: string | null ): void; add_main_option_entries(entries: GLib.OptionEntry[]): void; add_option_group(group: GLib.OptionGroup): void; bind_busy_property(object: GObject.Object, property: string): void; get_application_id(): string; get_dbus_connection(): DBusConnection; get_dbus_object_path(): string; get_flags(): ApplicationFlags; get_inactivity_timeout(): number; get_is_busy(): boolean; get_is_registered(): boolean; get_is_remote(): boolean; get_resource_base_path(): string | null; hold(): void; mark_busy(): void; open(files: File[], hint: string): void; quit(): void; register(cancellable?: Cancellable | null): boolean; release(): void; run(argv?: string[] | null): number; send_notification(id: string | null, notification: Notification): void; set_action_group(action_group?: ActionGroup | null): void; set_application_id(application_id?: string | null): void; set_default(): void; set_flags(flags: ApplicationFlags): void; set_inactivity_timeout(inactivity_timeout: number): void; set_option_context_description(description?: string | null): void; set_option_context_parameter_string(parameter_string?: string | null): void; set_option_context_summary(summary?: string | null): void; set_resource_base_path(resource_path?: string | null): void; unbind_busy_property(object: GObject.Object, property: string): void; unmark_busy(): void; withdraw_notification(id: string): void; vfunc_activate(): void; vfunc_add_platform_data(builder: GLib.VariantBuilder): void; vfunc_after_emit(platform_data: GLib.Variant): void; vfunc_before_emit(platform_data: GLib.Variant): void; vfunc_command_line(command_line: ApplicationCommandLine): number; vfunc_dbus_register(connection: DBusConnection, object_path: string): boolean; vfunc_dbus_unregister(connection: DBusConnection, object_path: string): void; vfunc_handle_local_options(options: GLib.VariantDict): number; vfunc_local_command_line(_arguments: string[]): [boolean, string[], number]; vfunc_name_lost(): boolean; vfunc_open(files: File[], hint: string): void; vfunc_quit_mainloop(): void; vfunc_run_mainloop(): void; vfunc_shutdown(): void; vfunc_startup(): void; static get_default(): Application; static id_is_valid(application_id: string): boolean; // Implemented Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action(action_name: string, parameter?: GLib.Variant | null): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type(action_name: string): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; add_action(action: Action): void; add_action_entries(entries: ActionEntry[], user_data?: any | null): void; lookup_action(action_name: string): Action; remove_action(action_name: string): void; vfunc_add_action(action: Action): void; vfunc_lookup_action(action_name: string): Action; vfunc_remove_action(action_name: string): void; } export module ApplicationCommandLine { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; arguments: GLib.Variant; is_remote: boolean; isRemote: boolean; options: GLib.Variant; platform_data: GLib.Variant; platformData: GLib.Variant; } } export class ApplicationCommandLine extends GObject.Object { static $gtype: GObject.GType<ApplicationCommandLine>; constructor(properties?: Partial<ApplicationCommandLine.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ApplicationCommandLine.ConstructorProperties>, ...args: any[]): void; // Properties "arguments": GLib.Variant; is_remote: boolean; isRemote: boolean; options: GLib.Variant; platform_data: GLib.Variant; platformData: GLib.Variant; // Members create_file_for_arg(arg: string): File; get_arguments(): string[]; get_cwd(): string | null; get_environ(): string[]; get_exit_status(): number; get_is_remote(): boolean; get_options_dict(): GLib.VariantDict; get_platform_data(): GLib.Variant | null; get_stdin(): InputStream; getenv(name: string): string; set_exit_status(exit_status: number): void; vfunc_get_stdin(): InputStream; vfunc_print_literal(message: string): void; vfunc_printerr_literal(message: string): void; } export module BufferedInputStream { export interface ConstructorProperties extends FilterInputStream.ConstructorProperties { [key: string]: any; buffer_size: number; bufferSize: number; } } export class BufferedInputStream extends FilterInputStream implements Seekable { static $gtype: GObject.GType<BufferedInputStream>; constructor(properties?: Partial<BufferedInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<BufferedInputStream.ConstructorProperties>, ...args: any[]): void; // Properties buffer_size: number; bufferSize: number; // Constructors static ["new"](base_stream: InputStream): BufferedInputStream; static new_sized(base_stream: InputStream, size: number): BufferedInputStream; // Members fill(count: number, cancellable?: Cancellable | null): number; fill_async(count: number, io_priority: number, cancellable?: Cancellable | null): Promise<number>; fill_async( count: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; fill_async( count: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; fill_finish(result: AsyncResult): number; get_available(): number; get_buffer_size(): number; peek(buffer: Uint8Array | string, offset: number): number; peek_buffer(): Uint8Array; read_byte(cancellable?: Cancellable | null): number; set_buffer_size(size: number): void; vfunc_fill(count: number, cancellable?: Cancellable | null): number; vfunc_fill_async(count: number, io_priority: number, cancellable?: Cancellable | null): Promise<number>; vfunc_fill_async( count: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_fill_async( count: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; vfunc_fill_finish(result: AsyncResult): number; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module BufferedOutputStream { export interface ConstructorProperties extends FilterOutputStream.ConstructorProperties { [key: string]: any; auto_grow: boolean; autoGrow: boolean; buffer_size: number; bufferSize: number; } } export class BufferedOutputStream extends FilterOutputStream implements Seekable { static $gtype: GObject.GType<BufferedOutputStream>; constructor(properties?: Partial<BufferedOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<BufferedOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties auto_grow: boolean; autoGrow: boolean; buffer_size: number; bufferSize: number; // Fields priv: BufferedOutputStreamPrivate; // Constructors static ["new"](base_stream: OutputStream): BufferedOutputStream; static new_sized(base_stream: OutputStream, size: number): BufferedOutputStream; // Members get_auto_grow(): boolean; get_buffer_size(): number; set_auto_grow(auto_grow: boolean): void; set_buffer_size(size: number): void; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module BytesIcon { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; bytes: GLib.Bytes; } } export class BytesIcon extends GObject.Object implements Icon, LoadableIcon { static $gtype: GObject.GType<BytesIcon>; constructor(properties?: Partial<BytesIcon.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<BytesIcon.ConstructorProperties>, ...args: any[]): void; // Properties bytes: GLib.Bytes; // Constructors static ["new"](bytes: GLib.Bytes | Uint8Array): BytesIcon; // Members get_bytes(): GLib.Bytes; // Implemented Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; load_finish(res: AsyncResult): [InputStream, string | null]; vfunc_load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; vfunc_load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; vfunc_load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; vfunc_load_finish(res: AsyncResult): [InputStream, string | null]; } export module Cancellable { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Cancellable extends GObject.Object { static $gtype: GObject.GType<Cancellable>; constructor(properties?: Partial<Cancellable.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Cancellable.ConstructorProperties>, ...args: any[]): void; // Signals connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect_after(signal: "cancelled", callback: (_source: this) => void): number; emit(signal: "cancelled"): void; // Constructors static ["new"](): Cancellable; // Members cancel(): void; connect(callback: GObject.Callback, data_destroy_func?: GLib.DestroyNotify | null): number; connect(...args: never[]): never; disconnect(handler_id: number): void; get_fd(): number; is_cancelled(): boolean; make_pollfd(pollfd: GLib.PollFD): boolean; pop_current(): void; push_current(): void; release_fd(): void; reset(): void; set_error_if_cancelled(): boolean; source_new(): GLib.Source; vfunc_cancelled(): void; static get_current(): Cancellable | null; } export module CharsetConverter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; from_charset: string; fromCharset: string; to_charset: string; toCharset: string; use_fallback: boolean; useFallback: boolean; } } export class CharsetConverter extends GObject.Object implements Converter, Initable { static $gtype: GObject.GType<CharsetConverter>; constructor(properties?: Partial<CharsetConverter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<CharsetConverter.ConstructorProperties>, ...args: any[]): void; // Properties from_charset: string; fromCharset: string; to_charset: string; toCharset: string; use_fallback: boolean; useFallback: boolean; // Constructors static ["new"](to_charset: string, from_charset: string): CharsetConverter; // Members get_num_fallbacks(): number; get_use_fallback(): boolean; set_use_fallback(use_fallback: boolean): void; // Implemented Members convert( inbuf: Uint8Array | string, outbuf: Uint8Array | string, flags: ConverterFlags ): [ConverterResult, number, number]; reset(): void; vfunc_convert( inbuf: Uint8Array | null, outbuf: Uint8Array | null, flags: ConverterFlags ): [ConverterResult, number, number]; vfunc_reset(): void; init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module ConverterInputStream { export interface ConstructorProperties extends FilterInputStream.ConstructorProperties { [key: string]: any; converter: Converter; } } export class ConverterInputStream extends FilterInputStream implements PollableInputStream { static $gtype: GObject.GType<ConverterInputStream>; constructor(properties?: Partial<ConverterInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ConverterInputStream.ConstructorProperties>, ...args: any[]): void; // Properties converter: Converter; // Constructors static ["new"](base_stream: InputStream, converter: Converter): ConverterInputStream; // Members get_converter(): Converter; // Implemented Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_readable(): boolean; read_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_readable(): boolean; vfunc_read_nonblocking(buffer?: Uint8Array | null): number; } export module ConverterOutputStream { export interface ConstructorProperties extends FilterOutputStream.ConstructorProperties { [key: string]: any; converter: Converter; } } export class ConverterOutputStream extends FilterOutputStream implements PollableOutputStream { static $gtype: GObject.GType<ConverterOutputStream>; constructor(properties?: Partial<ConverterOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ConverterOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties converter: Converter; // Constructors static ["new"](base_stream: OutputStream, converter: Converter): ConverterOutputStream; // Members get_converter(): Converter; // Implemented Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_writable(): boolean; write_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; writev_nonblocking(vectors: OutputVector[], cancellable?: Cancellable | null): [PollableReturn, number | null]; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_writable(): boolean; vfunc_write_nonblocking(buffer?: Uint8Array | null): number; vfunc_writev_nonblocking(vectors: OutputVector[]): [PollableReturn, number | null]; } export module Credentials { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Credentials extends GObject.Object { static $gtype: GObject.GType<Credentials>; constructor(properties?: Partial<Credentials.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Credentials.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Credentials; // Members get_unix_pid(): number; get_unix_user(): number; is_same_user(other_credentials: Credentials): boolean; set_native(native_type: CredentialsType, _native: any): void; set_unix_user(uid: number): boolean; to_string(): string; } export module DBusActionGroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class DBusActionGroup extends GObject.Object implements ActionGroup, RemoteActionGroup { static $gtype: GObject.GType<DBusActionGroup>; constructor(properties?: Partial<DBusActionGroup.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusActionGroup.ConstructorProperties>, ...args: any[]): void; // Members static get(connection: DBusConnection, bus_name: string | null, object_path: string): DBusActionGroup; // Implemented Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action(action_name: string, parameter?: GLib.Variant | null): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type(action_name: string): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; activate_action_full(action_name: string, parameter: GLib.Variant | null, platform_data: GLib.Variant): void; change_action_state_full(action_name: string, value: GLib.Variant, platform_data: GLib.Variant): void; vfunc_activate_action_full(action_name: string, parameter: GLib.Variant | null, platform_data: GLib.Variant): void; vfunc_change_action_state_full(action_name: string, value: GLib.Variant, platform_data: GLib.Variant): void; } export module DBusAuthObserver { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class DBusAuthObserver extends GObject.Object { static $gtype: GObject.GType<DBusAuthObserver>; constructor(properties?: Partial<DBusAuthObserver.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusAuthObserver.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "allow-mechanism", callback: (_source: this, mechanism: string) => boolean): number; connect_after(signal: "allow-mechanism", callback: (_source: this, mechanism: string) => boolean): number; emit(signal: "allow-mechanism", mechanism: string): void; connect( signal: "authorize-authenticated-peer", callback: (_source: this, stream: IOStream, credentials: Credentials | null) => boolean ): number; connect_after( signal: "authorize-authenticated-peer", callback: (_source: this, stream: IOStream, credentials: Credentials | null) => boolean ): number; emit(signal: "authorize-authenticated-peer", stream: IOStream, credentials: Credentials | null): void; // Constructors static ["new"](): DBusAuthObserver; // Members allow_mechanism(mechanism: string): boolean; authorize_authenticated_peer(stream: IOStream, credentials?: Credentials | null): boolean; } export module DBusConnection { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; address: string; authentication_observer: DBusAuthObserver; authenticationObserver: DBusAuthObserver; capabilities: DBusCapabilityFlags; closed: boolean; exit_on_close: boolean; exitOnClose: boolean; flags: DBusConnectionFlags; guid: string; stream: IOStream; unique_name: string; uniqueName: string; } } export class DBusConnection extends GObject.Object implements AsyncInitable<DBusConnection>, Initable { static $gtype: GObject.GType<DBusConnection>; constructor(properties?: Partial<DBusConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusConnection.ConstructorProperties>, ...args: any[]): void; // Properties address: string; authentication_observer: DBusAuthObserver; authenticationObserver: DBusAuthObserver; capabilities: DBusCapabilityFlags; closed: boolean; exit_on_close: boolean; exitOnClose: boolean; flags: DBusConnectionFlags; guid: string; stream: IOStream; unique_name: string; uniqueName: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "closed", callback: (_source: this, remote_peer_vanished: boolean, error: GLib.Error | null) => void ): number; connect_after( signal: "closed", callback: (_source: this, remote_peer_vanished: boolean, error: GLib.Error | null) => void ): number; emit(signal: "closed", remote_peer_vanished: boolean, error: GLib.Error | null): void; // Constructors static new_finish(res: AsyncResult): DBusConnection; static new_finish(...args: never[]): never; static new_for_address_finish(res: AsyncResult): DBusConnection; static new_for_address_sync( address: string, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null ): DBusConnection; static new_sync( stream: IOStream, guid: string | null, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null ): DBusConnection; // Members add_filter(filter_function: DBusMessageFilterFunction): number; call<T extends string = any>( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType<T> | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null ): Promise<GLib.Variant<T>>; call<T extends string = any>( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType<T> | null, flags: DBusCallFlags, timeout_msec: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; call<T extends string = any>( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType<T> | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<GLib.Variant<T>> | void; call_finish<T extends string = any>(res: AsyncResult): GLib.Variant<T>; call_sync( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null ): GLib.Variant; call_with_unix_fd_list( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null ): Promise<[GLib.Variant, UnixFDList | null]>; call_with_unix_fd_list( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, flags: DBusCallFlags, timeout_msec: number, fd_list: UnixFDList | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; call_with_unix_fd_list( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[GLib.Variant, UnixFDList | null]> | void; call_with_unix_fd_list_finish(res: AsyncResult): [GLib.Variant, UnixFDList | null]; call_with_unix_fd_list_sync( bus_name: string | null, object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null ): [GLib.Variant, UnixFDList | null]; close(cancellable?: Cancellable | null): Promise<boolean>; close(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close(cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null): Promise<boolean> | void; close_finish(res: AsyncResult): boolean; close_sync(cancellable?: Cancellable | null): boolean; emit_signal( destination_bus_name: string | null, object_path: string, interface_name: string, signal_name: string, parameters?: GLib.Variant | null ): boolean; export_action_group(object_path: string, action_group: ActionGroup): number; export_menu_model(object_path: string, menu: MenuModel): number; flush(cancellable?: Cancellable | null): Promise<boolean>; flush(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; flush(cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null): Promise<boolean> | void; flush_finish(res: AsyncResult): boolean; flush_sync(cancellable?: Cancellable | null): boolean; get_capabilities(): DBusCapabilityFlags; get_exit_on_close(): boolean; get_flags(): DBusConnectionFlags; get_guid(): string; get_last_serial(): number; get_peer_credentials(): Credentials | null; get_stream(): IOStream; get_unique_name(): string | null; is_closed(): boolean; register_object( object_path: string, interface_info: DBusInterfaceInfo, vtable?: DBusInterfaceVTable | null, user_data?: any | null ): number; register_object( object_path: string, interface_info: DBusInterfaceInfo, method_call_closure?: GObject.Closure | null, get_property_closure?: GObject.Closure | null, set_property_closure?: GObject.Closure | null ): number; register_subtree( object_path: string, vtable: DBusSubtreeVTable, flags: DBusSubtreeFlags, user_data?: any | null ): number; remove_filter(filter_id: number): void; send_message(message: DBusMessage, flags: DBusSendMessageFlags): [boolean, number | null]; send_message_with_reply( message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: number, cancellable?: Cancellable | null ): [Promise<DBusMessage>, number | null]; send_message_with_reply( message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): number | null; send_message_with_reply( message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): [Promise<DBusMessage> | void, number | null]; send_message_with_reply_finish(res: AsyncResult): DBusMessage; send_message_with_reply_sync( message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: number, cancellable?: Cancellable | null ): [DBusMessage, number | null]; set_exit_on_close(exit_on_close: boolean): void; signal_subscribe( sender: string | null, interface_name: string | null, member: string | null, object_path: string | null, arg0: string | null, flags: DBusSignalFlags, callback: DBusSignalCallback, user_data_free_func?: GLib.DestroyNotify | null ): number; signal_unsubscribe(subscription_id: number): void; start_message_processing(): void; unexport_action_group(export_id: number): void; unexport_menu_model(export_id: number): void; unregister_object(registration_id: number): boolean; unregister_subtree(registration_id: number): boolean; static new( stream: IOStream, guid: string | null, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null ): Promise<DBusConnection>; static new( stream: IOStream, guid: string | null, flags: DBusConnectionFlags, observer: DBusAuthObserver | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusConnection> | null ): void; static new( stream: IOStream, guid: string | null, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusConnection> | null ): Promise<DBusConnection> | void; static new_for_address( address: string, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null ): Promise<DBusConnection>; static new_for_address( address: string, flags: DBusConnectionFlags, observer: DBusAuthObserver | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusConnection> | null ): void; static new_for_address( address: string, flags: DBusConnectionFlags, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusConnection> | null ): Promise<DBusConnection> | void; watch_name( name: string, flags: BusNameWatcherFlags, name_appeared_closure?: GObject.Closure | null, name_vanished_closure?: GObject.Closure | null ): number; unwatch_name(watcher_id: number): void; own_name( name: string, flags: BusNameOwnerFlags, name_acquired_closure?: GObject.Closure | null, name_lost_closure?: GObject.Closure | null ): number; unown_name(owner_id: number): void; // Implemented Members init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; init_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: AsyncResult): boolean; new_finish(res: AsyncResult): DBusConnection; vfunc_init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: AsyncResult): boolean; init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module DBusInterfaceSkeleton { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; g_flags: DBusInterfaceSkeletonFlags; gFlags: DBusInterfaceSkeletonFlags; } } export abstract class DBusInterfaceSkeleton extends GObject.Object implements DBusInterface { static $gtype: GObject.GType<DBusInterfaceSkeleton>; constructor(properties?: Partial<DBusInterfaceSkeleton.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusInterfaceSkeleton.ConstructorProperties>, ...args: any[]): void; // Properties g_flags: DBusInterfaceSkeletonFlags; gFlags: DBusInterfaceSkeletonFlags; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "g-authorize-method", callback: (_source: this, invocation: DBusMethodInvocation) => boolean ): number; connect_after( signal: "g-authorize-method", callback: (_source: this, invocation: DBusMethodInvocation) => boolean ): number; emit(signal: "g-authorize-method", invocation: DBusMethodInvocation): void; // Members ["export"](connection: DBusConnection, object_path: string): boolean; flush(): void; get_connection(): DBusConnection; get_connections(): DBusConnection[]; get_flags(): DBusInterfaceSkeletonFlags; get_info(): DBusInterfaceInfo; get_object_path(): string; get_properties(): GLib.Variant; has_connection(connection: DBusConnection): boolean; set_flags(flags: DBusInterfaceSkeletonFlags): void; unexport(): void; unexport_from_connection(connection: DBusConnection): void; vfunc_flush(): void; vfunc_g_authorize_method(invocation: DBusMethodInvocation): boolean; vfunc_get_info(): DBusInterfaceInfo; vfunc_get_properties(): GLib.Variant; // Implemented Members get_object(): DBusObject; set_object(object?: DBusObject | null): void; vfunc_dup_object(): DBusObject; vfunc_set_object(object?: DBusObject | null): void; } export module DBusMenuModel { export interface ConstructorProperties extends MenuModel.ConstructorProperties { [key: string]: any; } } export class DBusMenuModel extends MenuModel { static $gtype: GObject.GType<DBusMenuModel>; constructor(properties?: Partial<DBusMenuModel.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusMenuModel.ConstructorProperties>, ...args: any[]): void; // Members static get(connection: DBusConnection, bus_name: string | null, object_path: string): DBusMenuModel; } export module DBusMessage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; locked: boolean; } } export class DBusMessage extends GObject.Object { static $gtype: GObject.GType<DBusMessage>; constructor(properties?: Partial<DBusMessage.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusMessage.ConstructorProperties>, ...args: any[]): void; // Properties locked: boolean; // Constructors static ["new"](): DBusMessage; static new_from_blob(blob: Uint8Array | string, capabilities: DBusCapabilityFlags): DBusMessage; static new_method_call(name: string | null, path: string, interface_: string | null, method: string): DBusMessage; static new_signal(path: string, interface_: string, signal: string): DBusMessage; // Members copy(): DBusMessage; get_arg0(): string; get_body(): GLib.Variant; get_byte_order(): DBusMessageByteOrder; get_destination(): string; get_error_name(): string; get_flags(): DBusMessageFlags; get_header(header_field: DBusMessageHeaderField): GLib.Variant | null; get_header_fields(): Uint8Array; get_interface(): string; get_locked(): boolean; get_member(): string; get_message_type(): DBusMessageType; get_num_unix_fds(): number; get_path(): string; get_reply_serial(): number; get_sender(): string; get_serial(): number; get_signature(): string; get_unix_fd_list(): UnixFDList; lock(): void; new_method_error_literal(error_name: string, error_message: string): DBusMessage; new_method_reply(): DBusMessage; print(indent: number): string; set_body(body: GLib.Variant): void; set_byte_order(byte_order: DBusMessageByteOrder): void; set_destination(value: string): void; set_error_name(value: string): void; set_flags(flags: DBusMessageFlags): void; set_header(header_field: DBusMessageHeaderField, value?: GLib.Variant | null): void; set_interface(value: string): void; set_member(value: string): void; set_message_type(type: DBusMessageType): void; set_num_unix_fds(value: number): void; set_path(value: string): void; set_reply_serial(value: number): void; set_sender(value: string): void; set_serial(serial: number): void; set_signature(value: string): void; set_unix_fd_list(fd_list?: UnixFDList | null): void; to_blob(capabilities: DBusCapabilityFlags): Uint8Array; to_gerror(): boolean; static bytes_needed(blob: Uint8Array | string): number; } export module DBusMethodInvocation { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class DBusMethodInvocation extends GObject.Object { static $gtype: GObject.GType<DBusMethodInvocation>; constructor(properties?: Partial<DBusMethodInvocation.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusMethodInvocation.ConstructorProperties>, ...args: any[]): void; // Members get_connection(): DBusConnection; get_interface_name(): string; get_message(): DBusMessage; get_method_info(): DBusMethodInfo; get_method_name(): string; get_object_path(): string; get_parameters(): GLib.Variant; get_property_info(): DBusPropertyInfo; get_sender(): string; return_dbus_error(error_name: string, error_message: string): void; return_error_literal(domain: GLib.Quark, code: number, message: string): void; return_gerror(error: GLib.Error): void; return_value(parameters?: GLib.Variant | null): void; return_value_with_unix_fd_list(parameters?: GLib.Variant | null, fd_list?: UnixFDList | null): void; } export module DBusObjectManagerClient { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; bus_type: BusType; busType: BusType; connection: DBusConnection; flags: DBusObjectManagerClientFlags; get_proxy_type_destroy_notify: any; getProxyTypeDestroyNotify: any; get_proxy_type_func: any; getProxyTypeFunc: any; get_proxy_type_user_data: any; getProxyTypeUserData: any; name: string; name_owner: string; nameOwner: string; object_path: string; objectPath: string; } } export class DBusObjectManagerClient extends GObject.Object implements AsyncInitable<DBusObjectManagerClient>, DBusObjectManager, Initable { static $gtype: GObject.GType<DBusObjectManagerClient>; constructor(properties?: Partial<DBusObjectManagerClient.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusObjectManagerClient.ConstructorProperties>, ...args: any[]): void; // Properties bus_type: BusType; busType: BusType; connection: DBusConnection; flags: DBusObjectManagerClientFlags; get_proxy_type_destroy_notify: any; getProxyTypeDestroyNotify: any; get_proxy_type_func: any; getProxyTypeFunc: any; get_proxy_type_user_data: any; getProxyTypeUserData: any; name: string; name_owner: string; nameOwner: string; object_path: string; objectPath: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "interface-proxy-properties-changed", callback: ( _source: this, object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, changed_properties: GLib.Variant, invalidated_properties: string[] ) => void ): number; connect_after( signal: "interface-proxy-properties-changed", callback: ( _source: this, object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, changed_properties: GLib.Variant, invalidated_properties: string[] ) => void ): number; emit( signal: "interface-proxy-properties-changed", object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, changed_properties: GLib.Variant, invalidated_properties: string[] ): void; connect( signal: "interface-proxy-signal", callback: ( _source: this, object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, sender_name: string, signal_name: string, parameters: GLib.Variant ) => void ): number; connect_after( signal: "interface-proxy-signal", callback: ( _source: this, object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, sender_name: string, signal_name: string, parameters: GLib.Variant ) => void ): number; emit( signal: "interface-proxy-signal", object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, sender_name: string, signal_name: string, parameters: GLib.Variant ): void; // Constructors static new_finish(res: AsyncResult): DBusObjectManagerClient; static new_finish(...args: never[]): never; static new_for_bus_finish(res: AsyncResult): DBusObjectManagerClient; static new_for_bus_sync( bus_type: BusType, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null ): DBusObjectManagerClient; static new_sync( connection: DBusConnection, flags: DBusObjectManagerClientFlags, name: string | null, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null ): DBusObjectManagerClient; // Members get_connection(): DBusConnection; get_flags(): DBusObjectManagerClientFlags; get_name(): string; get_name_owner(): string | null; vfunc_interface_proxy_properties_changed( object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, changed_properties: GLib.Variant, invalidated_properties: string ): void; vfunc_interface_proxy_signal( object_proxy: DBusObjectProxy, interface_proxy: DBusProxy, sender_name: string, signal_name: string, parameters: GLib.Variant ): void; static new( connection: DBusConnection, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null ): Promise<DBusObjectManagerClient>; static new( connection: DBusConnection, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify: GLib.DestroyNotify | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusObjectManagerClient> | null ): void; static new( connection: DBusConnection, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusObjectManagerClient> | null ): Promise<DBusObjectManagerClient> | void; static new_for_bus( bus_type: BusType, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null ): Promise<DBusObjectManagerClient>; static new_for_bus( bus_type: BusType, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify: GLib.DestroyNotify | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusObjectManagerClient> | null ): void; static new_for_bus( bus_type: BusType, flags: DBusObjectManagerClientFlags, name: string, object_path: string, get_proxy_type_func?: DBusProxyTypeFunc | null, get_proxy_type_destroy_notify?: GLib.DestroyNotify | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusObjectManagerClient> | null ): Promise<DBusObjectManagerClient> | void; // Implemented Members init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; init_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: AsyncResult): boolean; new_finish(res: AsyncResult): DBusObjectManagerClient; vfunc_init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: AsyncResult): boolean; get_interface(object_path: string, interface_name: string): DBusInterface; get_object(object_path: string): DBusObject; get_object_path(): string; get_objects(): DBusObject[]; vfunc_get_interface(object_path: string, interface_name: string): DBusInterface; vfunc_get_object(object_path: string): DBusObject; vfunc_get_object_path(): string; vfunc_get_objects(): DBusObject[]; vfunc_interface_added(object: DBusObject, interface_: DBusInterface): void; vfunc_interface_removed(object: DBusObject, interface_: DBusInterface): void; vfunc_object_added(object: DBusObject): void; vfunc_object_removed(object: DBusObject): void; init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module DBusObjectManagerServer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; connection: DBusConnection; object_path: string; objectPath: string; } } export class DBusObjectManagerServer extends GObject.Object implements DBusObjectManager { static $gtype: GObject.GType<DBusObjectManagerServer>; constructor(properties?: Partial<DBusObjectManagerServer.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusObjectManagerServer.ConstructorProperties>, ...args: any[]): void; // Properties connection: DBusConnection; object_path: string; objectPath: string; // Constructors static ["new"](object_path: string): DBusObjectManagerServer; // Members ["export"](object: DBusObjectSkeleton): void; export_uniquely(object: DBusObjectSkeleton): void; get_connection(): DBusConnection; is_exported(object: DBusObjectSkeleton): boolean; set_connection(connection?: DBusConnection | null): void; unexport(object_path: string): boolean; // Implemented Members get_interface(object_path: string, interface_name: string): DBusInterface; get_object(object_path: string): DBusObject; get_object_path(): string; get_objects(): DBusObject[]; vfunc_get_interface(object_path: string, interface_name: string): DBusInterface; vfunc_get_object(object_path: string): DBusObject; vfunc_get_object_path(): string; vfunc_get_objects(): DBusObject[]; vfunc_interface_added(object: DBusObject, interface_: DBusInterface): void; vfunc_interface_removed(object: DBusObject, interface_: DBusInterface): void; vfunc_object_added(object: DBusObject): void; vfunc_object_removed(object: DBusObject): void; } export module DBusObjectProxy { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; g_connection: DBusConnection; gConnection: DBusConnection; g_object_path: string; gObjectPath: string; } } export class DBusObjectProxy extends GObject.Object implements DBusObject { static $gtype: GObject.GType<DBusObjectProxy>; constructor(properties?: Partial<DBusObjectProxy.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusObjectProxy.ConstructorProperties>, ...args: any[]): void; // Properties g_connection: DBusConnection; gConnection: DBusConnection; g_object_path: string; gObjectPath: string; // Constructors static ["new"](connection: DBusConnection, object_path: string): DBusObjectProxy; // Members get_connection(): DBusConnection; // Implemented Members get_interface(interface_name: string): DBusInterface; get_interfaces(): DBusInterface[]; get_object_path(): string; vfunc_get_interface(interface_name: string): DBusInterface; vfunc_get_interfaces(): DBusInterface[]; vfunc_get_object_path(): string; vfunc_interface_added(interface_: DBusInterface): void; vfunc_interface_removed(interface_: DBusInterface): void; } export module DBusObjectSkeleton { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; g_object_path: string; gObjectPath: string; } } export class DBusObjectSkeleton extends GObject.Object implements DBusObject { static $gtype: GObject.GType<DBusObjectSkeleton>; constructor(properties?: Partial<DBusObjectSkeleton.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusObjectSkeleton.ConstructorProperties>, ...args: any[]): void; // Properties g_object_path: string; gObjectPath: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "authorize-method", callback: (_source: this, _interface: DBusInterfaceSkeleton, invocation: DBusMethodInvocation) => boolean ): number; connect_after( signal: "authorize-method", callback: (_source: this, _interface: DBusInterfaceSkeleton, invocation: DBusMethodInvocation) => boolean ): number; emit(signal: "authorize-method", _interface: DBusInterfaceSkeleton, invocation: DBusMethodInvocation): void; // Constructors static ["new"](object_path: string): DBusObjectSkeleton; // Members add_interface(interface_: DBusInterfaceSkeleton): void; flush(): void; remove_interface(interface_: DBusInterfaceSkeleton): void; remove_interface_by_name(interface_name: string): void; set_object_path(object_path: string): void; vfunc_authorize_method(interface_: DBusInterfaceSkeleton, invocation: DBusMethodInvocation): boolean; // Implemented Members get_interface(interface_name: string): DBusInterface; get_interfaces(): DBusInterface[]; get_object_path(): string; vfunc_get_interface(interface_name: string): DBusInterface; vfunc_get_interfaces(): DBusInterface[]; vfunc_get_object_path(): string; vfunc_interface_added(interface_: DBusInterface): void; vfunc_interface_removed(interface_: DBusInterface): void; } export module DBusProxy { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; g_bus_type: BusType; gBusType: BusType; g_connection: DBusConnection; gConnection: DBusConnection; g_default_timeout: number; gDefaultTimeout: number; g_flags: DBusProxyFlags; gFlags: DBusProxyFlags; g_interface_info: DBusInterfaceInfo; gInterfaceInfo: DBusInterfaceInfo; g_interface_name: string; gInterfaceName: string; g_name: string; gName: string; g_name_owner: string; gNameOwner: string; g_object_path: string; gObjectPath: string; } } export class DBusProxy extends GObject.Object implements AsyncInitable<DBusProxy>, DBusInterface, Initable { [key: string]: any; static $gtype: GObject.GType<DBusProxy>; constructor(properties?: Partial<DBusProxy.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusProxy.ConstructorProperties>, ...args: any[]): void; // Properties g_bus_type: BusType; gBusType: BusType; g_connection: DBusConnection; gConnection: DBusConnection; g_default_timeout: number; gDefaultTimeout: number; g_flags: DBusProxyFlags; gFlags: DBusProxyFlags; g_interface_info: DBusInterfaceInfo; gInterfaceInfo: DBusInterfaceInfo; g_interface_name: string; gInterfaceName: string; g_name: string; gName: string; g_name_owner: string; gNameOwner: string; g_object_path: string; gObjectPath: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "g-properties-changed", callback: (_source: this, changed_properties: GLib.Variant, invalidated_properties: string[]) => void ): number; connect_after( signal: "g-properties-changed", callback: (_source: this, changed_properties: GLib.Variant, invalidated_properties: string[]) => void ): number; emit(signal: "g-properties-changed", changed_properties: GLib.Variant, invalidated_properties: string[]): void; connect( signal: "g-signal", callback: (_source: this, sender_name: string | null, signal_name: string, parameters: GLib.Variant) => void ): number; connect_after( signal: "g-signal", callback: (_source: this, sender_name: string | null, signal_name: string, parameters: GLib.Variant) => void ): number; emit(signal: "g-signal", sender_name: string | null, signal_name: string, parameters: GLib.Variant): void; // Constructors static new_finish(res: AsyncResult): DBusProxy; static new_finish(...args: never[]): never; static new_for_bus_finish(res: AsyncResult): DBusProxy; static new_for_bus_sync( bus_type: BusType, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string, object_path: string, interface_name: string, cancellable?: Cancellable | null ): DBusProxy; static new_sync( connection: DBusConnection, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string | null, object_path: string, interface_name: string, cancellable?: Cancellable | null ): DBusProxy; // Members call( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null ): Promise<GLib.Variant>; call( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; call( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<GLib.Variant> | void; call_finish(res: AsyncResult): GLib.Variant; call_sync( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, cancellable?: Cancellable | null ): GLib.Variant; call_with_unix_fd_list( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null ): Promise<[GLib.Variant, UnixFDList | null]>; call_with_unix_fd_list( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, fd_list: UnixFDList | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; call_with_unix_fd_list( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[GLib.Variant, UnixFDList | null]> | void; call_with_unix_fd_list_finish(res: AsyncResult): [GLib.Variant, UnixFDList | null]; call_with_unix_fd_list_sync( method_name: string, parameters: GLib.Variant | null, flags: DBusCallFlags, timeout_msec: number, fd_list?: UnixFDList | null, cancellable?: Cancellable | null ): [GLib.Variant, UnixFDList | null]; get_cached_property(property_name: string): GLib.Variant | null; get_cached_property_names(): string[] | null; get_connection(): DBusConnection; get_default_timeout(): number; get_flags(): DBusProxyFlags; get_interface_info(): DBusInterfaceInfo | null; get_interface_name(): string; get_name(): string; get_name_owner(): string | null; get_object_path(): string; set_cached_property(property_name: string, value?: GLib.Variant | null): void; set_default_timeout(timeout_msec: number): void; set_interface_info(info?: DBusInterfaceInfo | null): void; vfunc_g_properties_changed(changed_properties: GLib.Variant, invalidated_properties: string): void; vfunc_g_signal(sender_name: string, signal_name: string, parameters: GLib.Variant): void; static new( connection: DBusConnection, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string | null, object_path: string, interface_name: string, cancellable?: Cancellable | null ): Promise<DBusProxy>; static new( connection: DBusConnection, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string | null, object_path: string, interface_name: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusProxy> | null ): void; static new( connection: DBusConnection, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string | null, object_path: string, interface_name: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusProxy> | null ): Promise<DBusProxy> | void; static new_for_bus( bus_type: BusType, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string, object_path: string, interface_name: string, cancellable?: Cancellable | null ): Promise<DBusProxy>; static new_for_bus( bus_type: BusType, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string, object_path: string, interface_name: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<DBusProxy> | null ): void; static new_for_bus( bus_type: BusType, flags: DBusProxyFlags, info: DBusInterfaceInfo | null, name: string, object_path: string, interface_name: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<DBusProxy> | null ): Promise<DBusProxy> | void; static makeProxyWrapper(...args: any[]): any; connectSignal(...args: any[]): any; disconnectSignal(...args: any[]): any; // Implemented Members init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; init_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: AsyncResult): boolean; new_finish(res: AsyncResult): DBusProxy; vfunc_init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: AsyncResult): boolean; get_object(): DBusObject; get_info(): DBusInterfaceInfo; set_object(object?: DBusObject | null): void; vfunc_dup_object(): DBusObject; vfunc_get_info(): DBusInterfaceInfo; vfunc_set_object(object?: DBusObject | null): void; init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module DBusServer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; active: boolean; address: string; authentication_observer: DBusAuthObserver; authenticationObserver: DBusAuthObserver; client_address: string; clientAddress: string; flags: DBusServerFlags; guid: string; } } export class DBusServer extends GObject.Object implements Initable { static $gtype: GObject.GType<DBusServer>; constructor(properties?: Partial<DBusServer.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusServer.ConstructorProperties>, ...args: any[]): void; // Properties active: boolean; address: string; authentication_observer: DBusAuthObserver; authenticationObserver: DBusAuthObserver; client_address: string; clientAddress: string; flags: DBusServerFlags; guid: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "new-connection", callback: (_source: this, connection: DBusConnection) => boolean): number; connect_after(signal: "new-connection", callback: (_source: this, connection: DBusConnection) => boolean): number; emit(signal: "new-connection", connection: DBusConnection): void; // Constructors static new_sync( address: string, flags: DBusServerFlags, guid: string, observer?: DBusAuthObserver | null, cancellable?: Cancellable | null ): DBusServer; // Members get_client_address(): string; get_flags(): DBusServerFlags; get_guid(): string; is_active(): boolean; start(): void; stop(): void; // Implemented Members init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module DataInputStream { export interface ConstructorProperties extends BufferedInputStream.ConstructorProperties { [key: string]: any; byte_order: DataStreamByteOrder; byteOrder: DataStreamByteOrder; newline_type: DataStreamNewlineType; newlineType: DataStreamNewlineType; } } export class DataInputStream extends BufferedInputStream implements Seekable { static $gtype: GObject.GType<DataInputStream>; constructor(properties?: Partial<DataInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DataInputStream.ConstructorProperties>, ...args: any[]): void; // Properties byte_order: DataStreamByteOrder; byteOrder: DataStreamByteOrder; newline_type: DataStreamNewlineType; newlineType: DataStreamNewlineType; // Constructors static ["new"](base_stream: InputStream): DataInputStream; // Members get_byte_order(): DataStreamByteOrder; get_newline_type(): DataStreamNewlineType; read_byte(cancellable?: Cancellable | null): number; read_int16(cancellable?: Cancellable | null): number; read_int32(cancellable?: Cancellable | null): number; read_int64(cancellable?: Cancellable | null): number; read_line(cancellable?: Cancellable | null): [Uint8Array | null, number | null]; read_line_async(io_priority: number, cancellable?: Cancellable | null): Promise<[Uint8Array | null, number | null]>; read_line_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; read_line_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[Uint8Array | null, number | null]> | void; read_line_finish(result: AsyncResult): [Uint8Array | null, number | null]; read_line_finish_utf8(result: AsyncResult): [string | null, number | null]; read_line_utf8(cancellable?: Cancellable | null): [string | null, number | null]; read_uint16(cancellable?: Cancellable | null): number; read_uint32(cancellable?: Cancellable | null): number; read_uint64(cancellable?: Cancellable | null): number; read_until(stop_chars: string, cancellable?: Cancellable | null): [string, number | null]; read_until_async( stop_chars: string, io_priority: number, cancellable?: Cancellable | null ): Promise<[string, number | null]>; read_until_async( stop_chars: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; read_until_async( stop_chars: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[string, number | null]> | void; read_until_finish(result: AsyncResult): [string, number | null]; read_upto(stop_chars: string, stop_chars_len: number, cancellable?: Cancellable | null): [string, number | null]; read_upto_async( stop_chars: string, stop_chars_len: number, io_priority: number, cancellable?: Cancellable | null ): Promise<[string, number | null]>; read_upto_async( stop_chars: string, stop_chars_len: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; read_upto_async( stop_chars: string, stop_chars_len: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[string, number | null]> | void; read_upto_finish(result: AsyncResult): [string, number | null]; set_byte_order(order: DataStreamByteOrder): void; set_newline_type(type: DataStreamNewlineType): void; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module DataOutputStream { export interface ConstructorProperties extends FilterOutputStream.ConstructorProperties { [key: string]: any; byte_order: DataStreamByteOrder; byteOrder: DataStreamByteOrder; } } export class DataOutputStream extends FilterOutputStream implements Seekable { static $gtype: GObject.GType<DataOutputStream>; constructor(properties?: Partial<DataOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DataOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties byte_order: DataStreamByteOrder; byteOrder: DataStreamByteOrder; // Constructors static ["new"](base_stream: OutputStream): DataOutputStream; // Members get_byte_order(): DataStreamByteOrder; put_byte(data: number, cancellable?: Cancellable | null): boolean; put_int16(data: number, cancellable?: Cancellable | null): boolean; put_int32(data: number, cancellable?: Cancellable | null): boolean; put_int64(data: number, cancellable?: Cancellable | null): boolean; put_string(str: string, cancellable?: Cancellable | null): boolean; put_uint16(data: number, cancellable?: Cancellable | null): boolean; put_uint32(data: number, cancellable?: Cancellable | null): boolean; put_uint64(data: number, cancellable?: Cancellable | null): boolean; set_byte_order(order: DataStreamByteOrder): void; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module DesktopAppInfo { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; filename: string; } } export class DesktopAppInfo extends GObject.Object implements AppInfo { static $gtype: GObject.GType<DesktopAppInfo>; constructor(properties?: Partial<DesktopAppInfo.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DesktopAppInfo.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; // Constructors static ["new"](desktop_id: string): DesktopAppInfo; static new_from_filename(filename: string): DesktopAppInfo; static new_from_keyfile(key_file: GLib.KeyFile): DesktopAppInfo; // Members get_action_name(action_name: string): string; get_boolean(key: string): boolean; get_categories(): string; get_filename(): string; get_generic_name(): string; get_is_hidden(): boolean; get_keywords(): string[]; get_locale_string(key: string): string | null; get_nodisplay(): boolean; get_show_in(desktop_env?: string | null): boolean; get_startup_wm_class(): string; get_string(key: string): string; get_string_list(key: string): string[]; has_key(key: string): boolean; launch_action(action_name: string, launch_context?: AppLaunchContext | null): void; launch_uris_as_manager( uris: string[], launch_context: AppLaunchContext | null, spawn_flags: GLib.SpawnFlags ): boolean; launch_uris_as_manager_with_fds( uris: string[], launch_context: AppLaunchContext | null, spawn_flags: GLib.SpawnFlags, stdin_fd: number, stdout_fd: number, stderr_fd: number ): boolean; list_actions(): string[]; static get_implementations(_interface: string): DesktopAppInfo[]; static search(search_string: string): string[][]; static set_desktop_env(desktop_env: string): void; // Implemented Members add_supports_type(content_type: string): boolean; can_delete(): boolean; can_remove_supports_type(): boolean; ["delete"](): boolean; dup(): AppInfo; equal(appinfo2: AppInfo): boolean; get_commandline(): string; get_description(): string; get_display_name(): string; get_executable(): string; get_icon(): Icon; get_id(): string; get_name(): string; get_supported_types(): string[]; launch(files?: File[] | null, context?: AppLaunchContext | null): boolean; launch_uris(uris?: string[] | null, context?: AppLaunchContext | null): boolean; launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; launch_uris_async( uris: string[] | null, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; launch_uris_finish(result: AsyncResult): boolean; remove_supports_type(content_type: string): boolean; set_as_default_for_extension(extension: string): boolean; set_as_default_for_type(content_type: string): boolean; set_as_last_used_for_type(content_type: string): boolean; should_show(): boolean; supports_files(): boolean; supports_uris(): boolean; vfunc_add_supports_type(content_type: string): boolean; vfunc_can_delete(): boolean; vfunc_can_remove_supports_type(): boolean; vfunc_do_delete(): boolean; vfunc_dup(): AppInfo; vfunc_equal(appinfo2: AppInfo): boolean; vfunc_get_commandline(): string; vfunc_get_description(): string; vfunc_get_display_name(): string; vfunc_get_executable(): string; vfunc_get_icon(): Icon; vfunc_get_id(): string; vfunc_get_name(): string; vfunc_get_supported_types(): string[]; vfunc_launch(files?: File[] | null, context?: AppLaunchContext | null): boolean; vfunc_launch_uris(uris?: string[] | null, context?: AppLaunchContext | null): boolean; vfunc_launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_launch_uris_async( uris: string[] | null, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_launch_uris_finish(result: AsyncResult): boolean; vfunc_remove_supports_type(content_type: string): boolean; vfunc_set_as_default_for_extension(extension: string): boolean; vfunc_set_as_default_for_type(content_type: string): boolean; vfunc_set_as_last_used_for_type(content_type: string): boolean; vfunc_should_show(): boolean; vfunc_supports_files(): boolean; vfunc_supports_uris(): boolean; } export module Emblem { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; icon: GObject.Object; origin: EmblemOrigin; } } export class Emblem extends GObject.Object implements Icon { static $gtype: GObject.GType<Emblem>; constructor(properties?: Partial<Emblem.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Emblem.ConstructorProperties>, ...args: any[]): void; // Properties icon: GObject.Object; origin: EmblemOrigin; // Constructors static ["new"](icon: Icon): Emblem; static new_with_origin(icon: Icon, origin: EmblemOrigin): Emblem; // Members get_icon(): Icon; get_origin(): EmblemOrigin; // Implemented Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; } export module EmblemedIcon { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; gicon: Icon; } } export class EmblemedIcon extends GObject.Object implements Icon { static $gtype: GObject.GType<EmblemedIcon>; constructor(properties?: Partial<EmblemedIcon.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<EmblemedIcon.ConstructorProperties>, ...args: any[]): void; // Properties gicon: Icon; // Constructors static ["new"](icon: Icon, emblem?: Emblem | null): EmblemedIcon; // Members add_emblem(emblem: Emblem): void; clear_emblems(): void; get_emblems(): Emblem[]; get_icon(): Icon; // Implemented Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; } export module FileEnumerator { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; container: File; } } export class FileEnumerator extends GObject.Object { static $gtype: GObject.GType<FileEnumerator>; constructor(properties?: Partial<FileEnumerator.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileEnumerator.ConstructorProperties>, ...args: any[]): void; // Properties container: File; // Members close(cancellable?: Cancellable | null): boolean; close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; close_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; close_finish(result: AsyncResult): boolean; get_child(info: FileInfo): File; get_container(): File; has_pending(): boolean; is_closed(): boolean; iterate(cancellable?: Cancellable | null): [boolean, FileInfo | null, File | null]; next_file(cancellable?: Cancellable | null): FileInfo | null; next_files_async(num_files: number, io_priority: number, cancellable?: Cancellable | null): Promise<FileInfo[]>; next_files_async( num_files: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; next_files_async( num_files: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo[]> | void; next_files_finish(result: AsyncResult): FileInfo[]; set_pending(pending: boolean): void; vfunc_close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_close_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_close_finish(result: AsyncResult): boolean; vfunc_close_fn(cancellable?: Cancellable | null): boolean; vfunc_next_file(cancellable?: Cancellable | null): FileInfo | null; vfunc_next_files_async( num_files: number, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo[]>; vfunc_next_files_async( num_files: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_next_files_async( num_files: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo[]> | void; vfunc_next_files_finish(result: AsyncResult): FileInfo[]; } export module FileIOStream { export interface ConstructorProperties extends IOStream.ConstructorProperties { [key: string]: any; } } export class FileIOStream extends IOStream implements Seekable { static $gtype: GObject.GType<FileIOStream>; constructor(properties?: Partial<FileIOStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileIOStream.ConstructorProperties>, ...args: any[]): void; // Members get_etag(): string; query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; query_info_async(attributes: string, io_priority: number, cancellable?: Cancellable | null): Promise<FileInfo>; query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; query_info_finish(result: AsyncResult): FileInfo; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_get_etag(): string; vfunc_query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; vfunc_query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; vfunc_query_info_finish(result: AsyncResult): FileInfo; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(size: number, cancellable?: Cancellable | null): boolean; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; } export module FileIcon { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; file: File; } } export class FileIcon extends GObject.Object implements Icon, LoadableIcon { static $gtype: GObject.GType<FileIcon>; constructor(properties?: Partial<FileIcon.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileIcon.ConstructorProperties>, ...args: any[]): void; // Properties file: File; // Constructors static ["new"](file: File): FileIcon; // Members get_file(): File; // Implemented Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; load_finish(res: AsyncResult): [InputStream, string | null]; vfunc_load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; vfunc_load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; vfunc_load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; vfunc_load_finish(res: AsyncResult): [InputStream, string | null]; } export module FileInfo { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class FileInfo extends GObject.Object { static $gtype: GObject.GType<FileInfo>; constructor(properties?: Partial<FileInfo.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileInfo.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): FileInfo; // Members clear_status(): void; copy_into(dest_info: FileInfo): void; dup(): FileInfo; get_attribute_as_string(attribute: string): string | null; get_attribute_boolean(attribute: string): boolean; get_attribute_byte_string(attribute: string): string | null; get_attribute_data(attribute: string): [boolean, FileAttributeType | null, any | null, FileAttributeStatus | null]; get_attribute_int32(attribute: string): number; get_attribute_int64(attribute: string): number; get_attribute_object<T = GObject.Object>(attribute: string): T; get_attribute_status(attribute: string): FileAttributeStatus; get_attribute_string(attribute: string): string | null; get_attribute_stringv(attribute: string): string[] | null; get_attribute_type(attribute: string): FileAttributeType; get_attribute_uint32(attribute: string): number; get_attribute_uint64(attribute: string): number; get_content_type(): string | null; get_deletion_date(): GLib.DateTime | null; get_display_name(): string; get_edit_name(): string; get_etag(): string; get_file_type(): FileType; get_icon(): Icon; get_is_backup(): boolean; get_is_hidden(): boolean; get_is_symlink(): boolean; get_modification_date_time(): GLib.DateTime | null; get_modification_time(): GLib.TimeVal; get_name(): string; get_size(): number; get_sort_order(): number; get_symbolic_icon(): Icon; get_symlink_target(): string; has_attribute(attribute: string): boolean; has_namespace(name_space: string): boolean; list_attributes(name_space?: string | null): string[] | null; remove_attribute(attribute: string): void; set_attribute(attribute: string, type: FileAttributeType, value_p: any): void; set_attribute_boolean(attribute: string, attr_value: boolean): void; set_attribute_byte_string(attribute: string, attr_value: string): void; set_attribute_int32(attribute: string, attr_value: number): void; set_attribute_int64(attribute: string, attr_value: number): void; set_attribute_mask(mask: FileAttributeMatcher): void; set_attribute_object(attribute: string, attr_value: GObject.Object): void; set_attribute_status(attribute: string, status: FileAttributeStatus): boolean; set_attribute_string(attribute: string, attr_value: string): void; set_attribute_stringv(attribute: string, attr_value: string[]): void; set_attribute_uint32(attribute: string, attr_value: number): void; set_attribute_uint64(attribute: string, attr_value: number): void; set_content_type(content_type: string): void; set_display_name(display_name: string): void; set_edit_name(edit_name: string): void; set_file_type(type: FileType): void; set_icon(icon: Icon): void; set_is_hidden(is_hidden: boolean): void; set_is_symlink(is_symlink: boolean): void; set_modification_date_time(mtime: GLib.DateTime): void; set_modification_time(mtime: GLib.TimeVal): void; set_name(name: string): void; set_size(size: number): void; set_sort_order(sort_order: number): void; set_symbolic_icon(icon: Icon): void; set_symlink_target(symlink_target: string): void; unset_attribute_mask(): void; } export module FileInputStream { export interface ConstructorProperties extends InputStream.ConstructorProperties { [key: string]: any; } } export class FileInputStream extends InputStream implements Seekable { static $gtype: GObject.GType<FileInputStream>; constructor(properties?: Partial<FileInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileInputStream.ConstructorProperties>, ...args: any[]): void; // Members query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; query_info_async(attributes: string, io_priority: number, cancellable?: Cancellable | null): Promise<FileInfo>; query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; query_info_finish(result: AsyncResult): FileInfo; vfunc_can_seek(): boolean; vfunc_query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; vfunc_query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; vfunc_query_info_finish(result: AsyncResult): FileInfo; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_truncate(): boolean; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module FileMonitor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; cancelled: boolean; rate_limit: number; rateLimit: number; } } export abstract class FileMonitor extends GObject.Object { static $gtype: GObject.GType<FileMonitor>; constructor(properties?: Partial<FileMonitor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileMonitor.ConstructorProperties>, ...args: any[]): void; // Properties cancelled: boolean; rate_limit: number; rateLimit: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "changed", callback: (_source: this, file: File, other_file: File | null, event_type: FileMonitorEvent) => void ): number; connect_after( signal: "changed", callback: (_source: this, file: File, other_file: File | null, event_type: FileMonitorEvent) => void ): number; emit(signal: "changed", file: File, other_file: File | null, event_type: FileMonitorEvent): void; // Members cancel(): boolean; emit_event(child: File, other_file: File, event_type: FileMonitorEvent): void; is_cancelled(): boolean; set_rate_limit(limit_msecs: number): void; vfunc_cancel(): boolean; vfunc_changed(file: File, other_file: File, event_type: FileMonitorEvent): void; } export module FileOutputStream { export interface ConstructorProperties extends OutputStream.ConstructorProperties { [key: string]: any; } } export class FileOutputStream extends OutputStream implements Seekable { static $gtype: GObject.GType<FileOutputStream>; constructor(properties?: Partial<FileOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FileOutputStream.ConstructorProperties>, ...args: any[]): void; // Members get_etag(): string; query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; query_info_async(attributes: string, io_priority: number, cancellable?: Cancellable | null): Promise<FileInfo>; query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; query_info_finish(result: AsyncResult): FileInfo; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_get_etag(): string; vfunc_query_info(attributes: string, cancellable?: Cancellable | null): FileInfo; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; vfunc_query_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_query_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; vfunc_query_info_finish(result: AsyncResult): FileInfo; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(size: number, cancellable?: Cancellable | null): boolean; // Implemented Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; } export module FilenameCompleter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class FilenameCompleter extends GObject.Object { static $gtype: GObject.GType<FilenameCompleter>; constructor(properties?: Partial<FilenameCompleter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FilenameCompleter.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "got-completion-data", callback: (_source: this) => void): number; connect_after(signal: "got-completion-data", callback: (_source: this) => void): number; emit(signal: "got-completion-data"): void; // Constructors static ["new"](): FilenameCompleter; // Members get_completion_suffix(initial_text: string): string; get_completions(initial_text: string): string[]; set_dirs_only(dirs_only: boolean): void; vfunc_got_completion_data(): void; } export module FilterInputStream { export interface ConstructorProperties extends InputStream.ConstructorProperties { [key: string]: any; base_stream: InputStream; baseStream: InputStream; close_base_stream: boolean; closeBaseStream: boolean; } } export abstract class FilterInputStream extends InputStream { static $gtype: GObject.GType<FilterInputStream>; constructor(properties?: Partial<FilterInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FilterInputStream.ConstructorProperties>, ...args: any[]): void; // Properties base_stream: InputStream; baseStream: InputStream; close_base_stream: boolean; closeBaseStream: boolean; // Members get_base_stream(): InputStream; get_close_base_stream(): boolean; set_close_base_stream(close_base: boolean): void; } export module FilterOutputStream { export interface ConstructorProperties extends OutputStream.ConstructorProperties { [key: string]: any; base_stream: OutputStream; baseStream: OutputStream; close_base_stream: boolean; closeBaseStream: boolean; } } export abstract class FilterOutputStream extends OutputStream { static $gtype: GObject.GType<FilterOutputStream>; constructor(properties?: Partial<FilterOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<FilterOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties base_stream: OutputStream; baseStream: OutputStream; close_base_stream: boolean; closeBaseStream: boolean; // Members get_base_stream(): OutputStream; get_close_base_stream(): boolean; set_close_base_stream(close_base: boolean): void; } export module IOModule { export interface ConstructorProperties extends GObject.TypeModule.ConstructorProperties { [key: string]: any; } } export class IOModule extends GObject.TypeModule implements GObject.TypePlugin { static $gtype: GObject.GType<IOModule>; constructor(properties?: Partial<IOModule.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<IOModule.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](filename: string): IOModule; // Members load(): void; unload(): void; static query(): string[]; // Implemented Members complete_interface_info( instance_type: GObject.GType, interface_type: GObject.GType, info: GObject.InterfaceInfo ): void; complete_type_info(g_type: GObject.GType, info: GObject.TypeInfo, value_table: GObject.TypeValueTable): void; unuse(): void; use(): void; use(...args: never[]): never; } export module IOStream { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; closed: boolean; input_stream: InputStream; inputStream: InputStream; output_stream: OutputStream; outputStream: OutputStream; } } export abstract class IOStream extends GObject.Object { static $gtype: GObject.GType<IOStream>; constructor(properties?: Partial<IOStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<IOStream.ConstructorProperties>, ...args: any[]): void; // Properties closed: boolean; input_stream: InputStream; inputStream: InputStream; output_stream: OutputStream; outputStream: OutputStream; // Members clear_pending(): void; close(cancellable?: Cancellable | null): boolean; close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; close_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; close_finish(result: AsyncResult): boolean; get_input_stream(): InputStream; get_output_stream(): OutputStream; has_pending(): boolean; is_closed(): boolean; set_pending(): boolean; splice_async( stream2: IOStream, flags: IOStreamSpliceFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): void; vfunc_close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_close_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_close_finish(result: AsyncResult): boolean; vfunc_close_fn(cancellable?: Cancellable | null): boolean; vfunc_get_input_stream(): InputStream; vfunc_get_output_stream(): OutputStream; static splice_finish(result: AsyncResult): boolean; } export module InetAddress { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; bytes: any; family: SocketFamily; is_any: boolean; isAny: boolean; is_link_local: boolean; isLinkLocal: boolean; is_loopback: boolean; isLoopback: boolean; is_mc_global: boolean; isMcGlobal: boolean; is_mc_link_local: boolean; isMcLinkLocal: boolean; is_mc_node_local: boolean; isMcNodeLocal: boolean; is_mc_org_local: boolean; isMcOrgLocal: boolean; is_mc_site_local: boolean; isMcSiteLocal: boolean; is_multicast: boolean; isMulticast: boolean; is_site_local: boolean; isSiteLocal: boolean; } } export class InetAddress extends GObject.Object { static $gtype: GObject.GType<InetAddress>; constructor(properties?: Partial<InetAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<InetAddress.ConstructorProperties>, ...args: any[]): void; // Properties bytes: any; family: SocketFamily; is_any: boolean; isAny: boolean; is_link_local: boolean; isLinkLocal: boolean; is_loopback: boolean; isLoopback: boolean; is_mc_global: boolean; isMcGlobal: boolean; is_mc_link_local: boolean; isMcLinkLocal: boolean; is_mc_node_local: boolean; isMcNodeLocal: boolean; is_mc_org_local: boolean; isMcOrgLocal: boolean; is_mc_site_local: boolean; isMcSiteLocal: boolean; is_multicast: boolean; isMulticast: boolean; is_site_local: boolean; isSiteLocal: boolean; // Constructors static new_any(family: SocketFamily): InetAddress; static new_from_bytes(bytes: Uint8Array | string, family: SocketFamily): InetAddress; static new_from_string(string: string): InetAddress; static new_loopback(family: SocketFamily): InetAddress; // Members equal(other_address: InetAddress): boolean; get_family(): SocketFamily; get_is_any(): boolean; get_is_link_local(): boolean; get_is_loopback(): boolean; get_is_mc_global(): boolean; get_is_mc_link_local(): boolean; get_is_mc_node_local(): boolean; get_is_mc_org_local(): boolean; get_is_mc_site_local(): boolean; get_is_multicast(): boolean; get_is_site_local(): boolean; get_native_size(): number; to_string(): string; vfunc_to_string(): string; } export module InetAddressMask { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; address: InetAddress; family: SocketFamily; length: number; } } export class InetAddressMask extends GObject.Object implements Initable { static $gtype: GObject.GType<InetAddressMask>; constructor(properties?: Partial<InetAddressMask.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<InetAddressMask.ConstructorProperties>, ...args: any[]): void; // Properties address: InetAddress; family: SocketFamily; length: number; // Constructors static ["new"](addr: InetAddress, length: number): InetAddressMask; static new_from_string(mask_string: string): InetAddressMask; // Members equal(mask2: InetAddressMask): boolean; get_address(): InetAddress; get_family(): SocketFamily; get_length(): number; matches(address: InetAddress): boolean; to_string(): string; // Implemented Members init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module InetSocketAddress { export interface ConstructorProperties extends SocketAddress.ConstructorProperties { [key: string]: any; address: InetAddress; flowinfo: number; port: number; scope_id: number; scopeId: number; } } export class InetSocketAddress extends SocketAddress implements SocketConnectable { static $gtype: GObject.GType<InetSocketAddress>; constructor(properties?: Partial<InetSocketAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<InetSocketAddress.ConstructorProperties>, ...args: any[]): void; // Properties address: InetAddress; flowinfo: number; port: number; scope_id: number; scopeId: number; // Constructors static ["new"](address: InetAddress, port: number): InetSocketAddress; static new_from_string(address: string, port: number): InetSocketAddress; // Members get_address(): InetAddress; get_flowinfo(): number; get_port(): number; get_scope_id(): number; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module InputStream { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class InputStream extends GObject.Object { static $gtype: GObject.GType<InputStream>; constructor(properties?: Partial<InputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<InputStream.ConstructorProperties>, ...args: any[]): void; // Members clear_pending(): void; close(cancellable?: Cancellable | null): boolean; close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; close_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; close_finish(result: AsyncResult): boolean; has_pending(): boolean; is_closed(): boolean; read(cancellable?: Cancellable | null): [number, Uint8Array]; read_all(cancellable?: Cancellable | null): [boolean, Uint8Array, number]; read_all_async(io_priority: number, cancellable?: Cancellable | null): [Promise<[number]>, Uint8Array]; read_all_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): Uint8Array; read_all_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): [Promise<[number]> | void, Uint8Array]; read_all_finish(result: AsyncResult): [boolean, number]; read_async(io_priority: number, cancellable?: Cancellable | null): [Promise<number>, Uint8Array]; read_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): Uint8Array; read_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): [Promise<number> | void, Uint8Array]; read_bytes(count: number, cancellable?: Cancellable | null): GLib.Bytes; read_bytes_async(count: number, io_priority: number, cancellable?: Cancellable | null): Promise<GLib.Bytes>; read_bytes_async( count: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; read_bytes_async( count: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<GLib.Bytes> | void; read_bytes_finish(result: AsyncResult): GLib.Bytes; read_finish(result: AsyncResult): number; set_pending(): boolean; skip(count: number, cancellable?: Cancellable | null): number; skip_async(count: number, io_priority: number, cancellable?: Cancellable | null): Promise<number>; skip_async( count: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; skip_async( count: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; skip_finish(result: AsyncResult): number; vfunc_close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_close_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_close_finish(result: AsyncResult): boolean; vfunc_close_fn(cancellable?: Cancellable | null): boolean; vfunc_read_async(io_priority: number, cancellable?: Cancellable | null): [Promise<number>, Uint8Array | null]; vfunc_read_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): Uint8Array | null; vfunc_read_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): [Promise<number> | void, Uint8Array | null]; vfunc_read_finish(result: AsyncResult): number; vfunc_read_fn(buffer: any | null, count: number, cancellable?: Cancellable | null): number; vfunc_skip(count: number, cancellable?: Cancellable | null): number; vfunc_skip_async(count: number, io_priority: number, cancellable?: Cancellable | null): Promise<number>; vfunc_skip_async( count: number, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_skip_async( count: number, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; vfunc_skip_finish(result: AsyncResult): number; } export module ListStore { export interface ConstructorProperties<A extends GObject.Object = GObject.Object> extends GObject.Object.ConstructorProperties { [key: string]: any; item_type: GObject.GType; itemType: GObject.GType; } } export class ListStore<A extends GObject.Object = GObject.Object> extends GObject.Object implements ListModel<A> { static $gtype: GObject.GType<ListStore>; constructor(properties?: Partial<ListStore.ConstructorProperties<A>>, ...args: any[]); _init(properties?: Partial<ListStore.ConstructorProperties<A>>, ...args: any[]): void; // Properties item_type: GObject.GType; itemType: GObject.GType; // Fields [Symbol.iterator]: () => IterableIterator<A>; // Constructors static ["new"](item_type: GObject.GType): ListStore; // Members append(item: A): void; find(item: A): [boolean, number | null]; find_with_equal_func(item: A, equal_func: GLib.EqualFunc): [boolean, number | null]; insert(position: number, item: A): void; insert_sorted(item: A, compare_func: GLib.CompareDataFunc): number; remove(position: number): void; remove_all(): void; sort(compare_func: GLib.CompareDataFunc): void; splice(position: number, n_removals: number, additions: A[]): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export module MemoryInputStream { export interface ConstructorProperties extends InputStream.ConstructorProperties { [key: string]: any; } } export class MemoryInputStream extends InputStream implements PollableInputStream, Seekable { static $gtype: GObject.GType<MemoryInputStream>; constructor(properties?: Partial<MemoryInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MemoryInputStream.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): MemoryInputStream; static new_from_bytes(bytes: GLib.Bytes | Uint8Array): MemoryInputStream; static new_from_data(data: Uint8Array | string, destroy?: GLib.DestroyNotify | null): MemoryInputStream; // Members add_bytes(bytes: GLib.Bytes | Uint8Array): void; add_data(data: Uint8Array | string, destroy?: GLib.DestroyNotify | null): void; // Implemented Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_readable(): boolean; read_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_readable(): boolean; vfunc_read_nonblocking(buffer?: Uint8Array | null): number; can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module MemoryOutputStream { export interface ConstructorProperties extends OutputStream.ConstructorProperties { [key: string]: any; data: any; data_size: number; dataSize: number; size: number; } } export class MemoryOutputStream extends OutputStream implements PollableOutputStream, Seekable { static $gtype: GObject.GType<MemoryOutputStream>; constructor(properties?: Partial<MemoryOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MemoryOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties data: any; data_size: number; dataSize: number; size: number; // Constructors static new_resizable(): MemoryOutputStream; // Members get_data(): any | null; get_data(...args: never[]): never; get_data_size(): number; get_size(): number; steal_as_bytes(): GLib.Bytes; steal_data(): any | null; steal_data(...args: never[]): never; // Implemented Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_writable(): boolean; write_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; writev_nonblocking(vectors: OutputVector[], cancellable?: Cancellable | null): [PollableReturn, number | null]; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_writable(): boolean; vfunc_write_nonblocking(buffer?: Uint8Array | null): number; vfunc_writev_nonblocking(vectors: OutputVector[]): [PollableReturn, number | null]; can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export module Menu { export interface ConstructorProperties extends MenuModel.ConstructorProperties { [key: string]: any; } } export class Menu extends MenuModel { static $gtype: GObject.GType<Menu>; constructor(properties?: Partial<Menu.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Menu.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Menu; // Members append(label?: string | null, detailed_action?: string | null): void; append_item(item: MenuItem): void; append_section(label: string | null, section: MenuModel): void; append_submenu(label: string | null, submenu: MenuModel): void; freeze(): void; insert(position: number, label?: string | null, detailed_action?: string | null): void; insert_item(position: number, item: MenuItem): void; insert_section(position: number, label: string | null, section: MenuModel): void; insert_submenu(position: number, label: string | null, submenu: MenuModel): void; prepend(label?: string | null, detailed_action?: string | null): void; prepend_item(item: MenuItem): void; prepend_section(label: string | null, section: MenuModel): void; prepend_submenu(label: string | null, submenu: MenuModel): void; remove(position: number): void; remove_all(): void; } export module MenuAttributeIter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class MenuAttributeIter extends GObject.Object { static $gtype: GObject.GType<MenuAttributeIter>; constructor(properties?: Partial<MenuAttributeIter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MenuAttributeIter.ConstructorProperties>, ...args: any[]): void; // Fields priv: MenuAttributeIterPrivate; // Members get_name(): string; get_next(): [boolean, string | null, GLib.Variant | null]; get_value(): GLib.Variant; next(): boolean; vfunc_get_next(): [boolean, string | null, GLib.Variant | null]; } export module MenuItem { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class MenuItem extends GObject.Object { static $gtype: GObject.GType<MenuItem>; constructor(properties?: Partial<MenuItem.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MenuItem.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](label?: string | null, detailed_action?: string | null): MenuItem; static new_from_model(model: MenuModel, item_index: number): MenuItem; static new_section(label: string | null, section: MenuModel): MenuItem; static new_submenu(label: string | null, submenu: MenuModel): MenuItem; // Members get_attribute_value(attribute: string, expected_type?: GLib.VariantType | null): GLib.Variant; get_link(link: string): MenuModel; set_action_and_target_value(action?: string | null, target_value?: GLib.Variant | null): void; set_attribute_value(attribute: string, value?: GLib.Variant | null): void; set_detailed_action(detailed_action: string): void; set_icon(icon: Icon): void; set_label(label?: string | null): void; set_link(link: string, model?: MenuModel | null): void; set_section(section?: MenuModel | null): void; set_submenu(submenu?: MenuModel | null): void; } export module MenuLinkIter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class MenuLinkIter extends GObject.Object { static $gtype: GObject.GType<MenuLinkIter>; constructor(properties?: Partial<MenuLinkIter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MenuLinkIter.ConstructorProperties>, ...args: any[]): void; // Fields priv: MenuLinkIterPrivate; // Members get_name(): string; get_next(): [boolean, string | null, MenuModel | null]; get_value(): MenuModel; next(): boolean; vfunc_get_next(): [boolean, string | null, MenuModel | null]; } export module MenuModel { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class MenuModel extends GObject.Object { static $gtype: GObject.GType<MenuModel>; constructor(properties?: Partial<MenuModel.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MenuModel.ConstructorProperties>, ...args: any[]): void; // Fields priv: MenuModelPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "items-changed", callback: (_source: this, position: number, removed: number, added: number) => void ): number; connect_after( signal: "items-changed", callback: (_source: this, position: number, removed: number, added: number) => void ): number; emit(signal: "items-changed", position: number, removed: number, added: number): void; // Members get_item_attribute_value( item_index: number, attribute: string, expected_type?: GLib.VariantType | null ): GLib.Variant; get_item_link(item_index: number, link: string): MenuModel; get_n_items(): number; is_mutable(): boolean; items_changed(position: number, removed: number, added: number): void; iterate_item_attributes(item_index: number): MenuAttributeIter; iterate_item_links(item_index: number): MenuLinkIter; vfunc_get_item_attribute_value( item_index: number, attribute: string, expected_type?: GLib.VariantType | null ): GLib.Variant; vfunc_get_item_attributes(item_index: number): GLib.HashTable<string, GLib.Variant>; vfunc_get_item_link(item_index: number, link: string): MenuModel; vfunc_get_item_links(item_index: number): GLib.HashTable<string, MenuModel>; vfunc_get_n_items(): number; vfunc_is_mutable(): boolean; vfunc_iterate_item_attributes(item_index: number): MenuAttributeIter; vfunc_iterate_item_links(item_index: number): MenuLinkIter; } export module MountOperation { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; anonymous: boolean; choice: number; domain: string; is_tcrypt_hidden_volume: boolean; isTcryptHiddenVolume: boolean; is_tcrypt_system_volume: boolean; isTcryptSystemVolume: boolean; password: string; password_save: PasswordSave; passwordSave: PasswordSave; pim: number; username: string; } } export class MountOperation extends GObject.Object { static $gtype: GObject.GType<MountOperation>; constructor(properties?: Partial<MountOperation.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MountOperation.ConstructorProperties>, ...args: any[]): void; // Properties anonymous: boolean; choice: number; domain: string; is_tcrypt_hidden_volume: boolean; isTcryptHiddenVolume: boolean; is_tcrypt_system_volume: boolean; isTcryptSystemVolume: boolean; password: string; password_save: PasswordSave; passwordSave: PasswordSave; pim: number; username: string; // Fields priv: MountOperationPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "aborted", callback: (_source: this) => void): number; connect_after(signal: "aborted", callback: (_source: this) => void): number; emit(signal: "aborted"): void; connect( signal: "ask-password", callback: ( _source: this, message: string, default_user: string, default_domain: string, flags: AskPasswordFlags ) => void ): number; connect_after( signal: "ask-password", callback: ( _source: this, message: string, default_user: string, default_domain: string, flags: AskPasswordFlags ) => void ): number; emit( signal: "ask-password", message: string, default_user: string, default_domain: string, flags: AskPasswordFlags ): void; connect(signal: "ask-question", callback: (_source: this, message: string, choices: string[]) => void): number; connect_after( signal: "ask-question", callback: (_source: this, message: string, choices: string[]) => void ): number; emit(signal: "ask-question", message: string, choices: string[]): void; connect(signal: "reply", callback: (_source: this, result: MountOperationResult) => void): number; connect_after(signal: "reply", callback: (_source: this, result: MountOperationResult) => void): number; emit(signal: "reply", result: MountOperationResult): void; connect( signal: "show-processes", callback: (_source: this, message: string, processes: GLib.Pid[], choices: string[]) => void ): number; connect_after( signal: "show-processes", callback: (_source: this, message: string, processes: GLib.Pid[], choices: string[]) => void ): number; emit(signal: "show-processes", message: string, processes: GLib.Pid[], choices: string[]): void; connect( signal: "show-unmount-progress", callback: (_source: this, message: string, time_left: number, bytes_left: number) => void ): number; connect_after( signal: "show-unmount-progress", callback: (_source: this, message: string, time_left: number, bytes_left: number) => void ): number; emit(signal: "show-unmount-progress", message: string, time_left: number, bytes_left: number): void; // Constructors static ["new"](): MountOperation; // Members get_anonymous(): boolean; get_choice(): number; get_domain(): string; get_is_tcrypt_hidden_volume(): boolean; get_is_tcrypt_system_volume(): boolean; get_password(): string; get_password_save(): PasswordSave; get_pim(): number; get_username(): string; reply(result: MountOperationResult): void; set_anonymous(anonymous: boolean): void; set_choice(choice: number): void; set_domain(domain: string): void; set_is_tcrypt_hidden_volume(hidden_volume: boolean): void; set_is_tcrypt_system_volume(system_volume: boolean): void; set_password(password: string): void; set_password_save(save: PasswordSave): void; set_pim(pim: number): void; set_username(username: string): void; vfunc_aborted(): void; vfunc_ask_password(message: string, default_user: string, default_domain: string, flags: AskPasswordFlags): void; vfunc_ask_question(message: string, choices: string[]): void; vfunc_reply(result: MountOperationResult): void; vfunc_show_processes(message: string, processes: GLib.Pid[], choices: string[]): void; vfunc_show_unmount_progress(message: string, time_left: number, bytes_left: number): void; } export module NativeSocketAddress { export interface ConstructorProperties extends SocketAddress.ConstructorProperties { [key: string]: any; } } export class NativeSocketAddress extends SocketAddress implements SocketConnectable { static $gtype: GObject.GType<NativeSocketAddress>; constructor(properties?: Partial<NativeSocketAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NativeSocketAddress.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](_native: any | null, len: number): NativeSocketAddress; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module NativeVolumeMonitor { export interface ConstructorProperties extends VolumeMonitor.ConstructorProperties { [key: string]: any; } } export abstract class NativeVolumeMonitor extends VolumeMonitor { static $gtype: GObject.GType<NativeVolumeMonitor>; constructor(properties?: Partial<NativeVolumeMonitor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NativeVolumeMonitor.ConstructorProperties>, ...args: any[]): void; } export module NetworkAddress { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; hostname: string; port: number; scheme: string; } } export class NetworkAddress extends GObject.Object implements SocketConnectable { static $gtype: GObject.GType<NetworkAddress>; constructor(properties?: Partial<NetworkAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NetworkAddress.ConstructorProperties>, ...args: any[]): void; // Properties hostname: string; port: number; scheme: string; // Constructors static ["new"](hostname: string, port: number): NetworkAddress; static new_loopback(port: number): NetworkAddress; // Members get_hostname(): string; get_port(): number; get_scheme(): string; static parse(host_and_port: string, default_port: number): NetworkAddress; static parse_uri(uri: string, default_port: number): NetworkAddress; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module NetworkService { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; domain: string; protocol: string; scheme: string; service: string; } } export class NetworkService extends GObject.Object implements SocketConnectable { static $gtype: GObject.GType<NetworkService>; constructor(properties?: Partial<NetworkService.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NetworkService.ConstructorProperties>, ...args: any[]): void; // Properties domain: string; protocol: string; scheme: string; service: string; // Constructors static ["new"](service: string, protocol: string, domain: string): NetworkService; // Members get_domain(): string; get_protocol(): string; get_scheme(): string; get_service(): string; set_scheme(scheme: string): void; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module Notification { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Notification extends GObject.Object { static $gtype: GObject.GType<Notification>; constructor(properties?: Partial<Notification.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Notification.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](title: string): Notification; // Members add_button(label: string, detailed_action: string): void; add_button_with_target(label: string, action: string, target?: GLib.Variant | null): void; set_body(body?: string | null): void; set_default_action(detailed_action: string): void; set_default_action_and_target(action: string, target?: GLib.Variant | null): void; set_icon(icon: Icon): void; set_priority(priority: NotificationPriority): void; set_title(title: string): void; set_urgent(urgent: boolean): void; } export module OutputStream { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class OutputStream extends GObject.Object { static $gtype: GObject.GType<OutputStream>; constructor(properties?: Partial<OutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<OutputStream.ConstructorProperties>, ...args: any[]): void; // Members clear_pending(): void; close(cancellable?: Cancellable | null): boolean; close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; close_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; close_finish(result: AsyncResult): boolean; flush(cancellable?: Cancellable | null): boolean; flush_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; flush_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; flush_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; flush_finish(result: AsyncResult): boolean; has_pending(): boolean; is_closed(): boolean; is_closing(): boolean; set_pending(): boolean; splice(source: InputStream, flags: OutputStreamSpliceFlags, cancellable?: Cancellable | null): number; splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<number>; splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; splice_finish(result: AsyncResult): number; write(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; write_all(buffer: Uint8Array | string, cancellable?: Cancellable | null): [boolean, number | null]; write_all_async( buffer: Uint8Array | string, io_priority: number, cancellable?: Cancellable | null ): Promise<[number | null]>; write_all_async( buffer: Uint8Array | string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; write_all_async( buffer: Uint8Array | string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[number | null]> | void; write_all_finish(result: AsyncResult): [boolean, number | null]; write_async(buffer: Uint8Array | string, io_priority: number, cancellable?: Cancellable | null): Promise<number>; write_async( buffer: Uint8Array | string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; write_async( buffer: Uint8Array | string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; write_bytes(bytes: GLib.Bytes | Uint8Array, cancellable?: Cancellable | null): number; write_bytes_async( bytes: GLib.Bytes | Uint8Array, io_priority: number, cancellable?: Cancellable | null ): Promise<number>; write_bytes_async( bytes: GLib.Bytes | Uint8Array, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; write_bytes_async( bytes: GLib.Bytes | Uint8Array, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; write_bytes_finish(result: AsyncResult): number; write_finish(result: AsyncResult): number; writev(vectors: OutputVector[], cancellable?: Cancellable | null): [boolean, number | null]; writev_all(vectors: OutputVector[], cancellable?: Cancellable | null): [boolean, number | null]; writev_all_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null ): Promise<[number | null]>; writev_all_async( vectors: OutputVector[], io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; writev_all_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[number | null]> | void; writev_all_finish(result: AsyncResult): [boolean, number | null]; writev_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null ): Promise<[number | null]>; writev_async( vectors: OutputVector[], io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; writev_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[number | null]> | void; writev_finish(result: AsyncResult): [boolean, number | null]; vfunc_close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_close_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_close_finish(result: AsyncResult): boolean; vfunc_close_fn(cancellable?: Cancellable | null): boolean; vfunc_flush(cancellable?: Cancellable | null): boolean; vfunc_flush_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_flush_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_flush_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_flush_finish(result: AsyncResult): boolean; vfunc_splice(source: InputStream, flags: OutputStreamSpliceFlags, cancellable?: Cancellable | null): number; vfunc_splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<number>; vfunc_splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_splice_async( source: InputStream, flags: OutputStreamSpliceFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; vfunc_splice_finish(result: AsyncResult): number; vfunc_write_async( buffer: Uint8Array | null, io_priority: number, cancellable?: Cancellable | null ): Promise<number>; vfunc_write_async( buffer: Uint8Array | null, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_write_async( buffer: Uint8Array | null, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<number> | void; vfunc_write_finish(result: AsyncResult): number; vfunc_write_fn(buffer?: Uint8Array | null, cancellable?: Cancellable | null): number; vfunc_writev_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null ): Promise<[number | null]>; vfunc_writev_async( vectors: OutputVector[], io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_writev_async( vectors: OutputVector[], io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[number | null]> | void; vfunc_writev_finish(result: AsyncResult): [boolean, number | null]; vfunc_writev_fn(vectors: OutputVector[], cancellable?: Cancellable | null): [boolean, number | null]; } export module Permission { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; allowed: boolean; can_acquire: boolean; canAcquire: boolean; can_release: boolean; canRelease: boolean; } } export abstract class Permission extends GObject.Object { static $gtype: GObject.GType<Permission>; constructor(properties?: Partial<Permission.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Permission.ConstructorProperties>, ...args: any[]): void; // Properties allowed: boolean; can_acquire: boolean; canAcquire: boolean; can_release: boolean; canRelease: boolean; // Members acquire(cancellable?: Cancellable | null): boolean; acquire_async(cancellable?: Cancellable | null): Promise<boolean>; acquire_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; acquire_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; acquire_finish(result: AsyncResult): boolean; get_allowed(): boolean; get_can_acquire(): boolean; get_can_release(): boolean; impl_update(allowed: boolean, can_acquire: boolean, can_release: boolean): void; release(cancellable?: Cancellable | null): boolean; release_async(cancellable?: Cancellable | null): Promise<boolean>; release_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; release_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; release_finish(result: AsyncResult): boolean; vfunc_acquire(cancellable?: Cancellable | null): boolean; vfunc_acquire_async(cancellable?: Cancellable | null): Promise<boolean>; vfunc_acquire_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_acquire_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_acquire_finish(result: AsyncResult): boolean; vfunc_release(cancellable?: Cancellable | null): boolean; vfunc_release_async(cancellable?: Cancellable | null): Promise<boolean>; vfunc_release_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_release_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_release_finish(result: AsyncResult): boolean; } export module PropertyAction { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; enabled: boolean; invert_boolean: boolean; invertBoolean: boolean; name: string; object: GObject.Object; parameter_type: GLib.VariantType; parameterType: GLib.VariantType; property_name: string; propertyName: string; state: GLib.Variant; state_type: GLib.VariantType; stateType: GLib.VariantType; } } export class PropertyAction extends GObject.Object implements Action { static $gtype: GObject.GType<PropertyAction>; constructor(properties?: Partial<PropertyAction.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PropertyAction.ConstructorProperties>, ...args: any[]): void; // Properties enabled: boolean; invert_boolean: boolean; invertBoolean: boolean; name: string; object: GObject.Object; parameter_type: GLib.VariantType; parameterType: GLib.VariantType; property_name: string; propertyName: string; state: GLib.Variant; state_type: GLib.VariantType; stateType: GLib.VariantType; // Constructors static ["new"](name: string, object: GObject.Object, property_name: string): PropertyAction; // Implemented Members activate(parameter?: GLib.Variant | null): void; change_state(value: GLib.Variant): void; get_enabled(): boolean; get_name(): string; get_parameter_type(): GLib.VariantType | null; get_state(): GLib.Variant; get_state_hint(): GLib.Variant | null; get_state_type(): GLib.VariantType | null; vfunc_activate(parameter?: GLib.Variant | null): void; vfunc_change_state(value: GLib.Variant): void; vfunc_get_enabled(): boolean; vfunc_get_name(): string; vfunc_get_parameter_type(): GLib.VariantType | null; vfunc_get_state(): GLib.Variant; vfunc_get_state_hint(): GLib.Variant | null; vfunc_get_state_type(): GLib.VariantType | null; } export module ProxyAddress { export interface ConstructorProperties extends InetSocketAddress.ConstructorProperties { [key: string]: any; destination_hostname: string; destinationHostname: string; destination_port: number; destinationPort: number; destination_protocol: string; destinationProtocol: string; password: string; protocol: string; uri: string; username: string; } } export class ProxyAddress extends InetSocketAddress implements SocketConnectable { static $gtype: GObject.GType<ProxyAddress>; constructor(properties?: Partial<ProxyAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ProxyAddress.ConstructorProperties>, ...args: any[]): void; // Properties destination_hostname: string; destinationHostname: string; destination_port: number; destinationPort: number; destination_protocol: string; destinationProtocol: string; password: string; protocol: string; uri: string; username: string; // Constructors static ["new"]( inetaddr: InetAddress, port: number, protocol: string, dest_hostname: string, dest_port: number, username?: string | null, password?: string | null ): ProxyAddress; static ["new"](...args: never[]): never; // Members get_destination_hostname(): string; get_destination_port(): number; get_destination_protocol(): string; get_password(): string; get_protocol(): string; get_uri(): string; get_username(): string; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module ProxyAddressEnumerator { export interface ConstructorProperties extends SocketAddressEnumerator.ConstructorProperties { [key: string]: any; connectable: SocketConnectable; default_port: number; defaultPort: number; proxy_resolver: ProxyResolver; proxyResolver: ProxyResolver; uri: string; } } export class ProxyAddressEnumerator extends SocketAddressEnumerator { static $gtype: GObject.GType<ProxyAddressEnumerator>; constructor(properties?: Partial<ProxyAddressEnumerator.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ProxyAddressEnumerator.ConstructorProperties>, ...args: any[]): void; // Properties connectable: SocketConnectable; default_port: number; defaultPort: number; proxy_resolver: ProxyResolver; proxyResolver: ProxyResolver; uri: string; } export module Resolver { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class Resolver extends GObject.Object { static $gtype: GObject.GType<Resolver>; constructor(properties?: Partial<Resolver.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Resolver.ConstructorProperties>, ...args: any[]): void; // Fields priv: ResolverPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "reload", callback: (_source: this) => void): number; connect_after(signal: "reload", callback: (_source: this) => void): number; emit(signal: "reload"): void; // Members lookup_by_address(address: InetAddress, cancellable?: Cancellable | null): string; lookup_by_address_async(address: InetAddress, cancellable?: Cancellable | null): Promise<string>; lookup_by_address_async( address: InetAddress, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_by_address_async( address: InetAddress, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string> | void; lookup_by_address_finish(result: AsyncResult): string; lookup_by_name(hostname: string, cancellable?: Cancellable | null): InetAddress[]; lookup_by_name_async(hostname: string, cancellable?: Cancellable | null): Promise<InetAddress[]>; lookup_by_name_async( hostname: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_by_name_async( hostname: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<InetAddress[]> | void; lookup_by_name_finish(result: AsyncResult): InetAddress[]; lookup_by_name_with_flags( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null ): InetAddress[]; lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null ): Promise<InetAddress[]>; lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<InetAddress[]> | void; lookup_by_name_with_flags_finish(result: AsyncResult): InetAddress[]; lookup_records(rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null): GLib.Variant[]; lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null ): Promise<GLib.Variant[]>; lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<GLib.Variant[]> | void; lookup_records_finish(result: AsyncResult): GLib.Variant[]; lookup_service(service: string, protocol: string, domain: string, cancellable?: Cancellable | null): SrvTarget[]; lookup_service_async( service: string, protocol: string, domain: string, cancellable?: Cancellable | null ): Promise<SrvTarget[]>; lookup_service_async( service: string, protocol: string, domain: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_service_async( service: string, protocol: string, domain: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SrvTarget[]> | void; lookup_service_finish(result: AsyncResult): SrvTarget[]; set_default(): void; vfunc_lookup_by_address(address: InetAddress, cancellable?: Cancellable | null): string; vfunc_lookup_by_address_async(address: InetAddress, cancellable?: Cancellable | null): Promise<string>; vfunc_lookup_by_address_async( address: InetAddress, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_by_address_async( address: InetAddress, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string> | void; vfunc_lookup_by_address_finish(result: AsyncResult): string; vfunc_lookup_by_name(hostname: string, cancellable?: Cancellable | null): InetAddress[]; vfunc_lookup_by_name_async(hostname: string, cancellable?: Cancellable | null): Promise<InetAddress[]>; vfunc_lookup_by_name_async( hostname: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_by_name_async( hostname: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<InetAddress[]> | void; vfunc_lookup_by_name_finish(result: AsyncResult): InetAddress[]; vfunc_lookup_by_name_with_flags( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null ): InetAddress[]; vfunc_lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null ): Promise<InetAddress[]>; vfunc_lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_by_name_with_flags_async( hostname: string, flags: ResolverNameLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<InetAddress[]> | void; vfunc_lookup_by_name_with_flags_finish(result: AsyncResult): InetAddress[]; vfunc_lookup_records( rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null ): GLib.Variant[]; vfunc_lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null ): Promise<GLib.Variant[]>; vfunc_lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_records_async( rrname: string, record_type: ResolverRecordType, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<GLib.Variant[]> | void; vfunc_lookup_records_finish(result: AsyncResult): GLib.Variant[]; vfunc_lookup_service_async(rrname: string, cancellable?: Cancellable | null): Promise<SrvTarget[]>; vfunc_lookup_service_async( rrname: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_service_async( rrname: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SrvTarget[]> | void; vfunc_lookup_service_finish(result: AsyncResult): SrvTarget[]; vfunc_reload(): void; static get_default(): Resolver; } export module Settings { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: SettingsBackend; delay_apply: boolean; delayApply: boolean; has_unapplied: boolean; hasUnapplied: boolean; path: string; schema: string; schema_id: string; schemaId: string; settings_schema: SettingsSchema; settingsSchema: SettingsSchema; } } export class Settings extends GObject.Object { static $gtype: GObject.GType<Settings>; constructor(properties?: Partial<Settings.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Settings.ConstructorProperties>, ...args: any[]): void; // Properties backend: SettingsBackend; delay_apply: boolean; delayApply: boolean; has_unapplied: boolean; hasUnapplied: boolean; path: string; schema: string; schema_id: string; schemaId: string; settings_schema: SettingsSchema; settingsSchema: SettingsSchema; // Fields priv: SettingsPrivate; _realInit: (...args: any[]) => any; _realMethods: typeof Settings.prototype; _keys: string[]; _children: string[]; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "change-event", callback: (_source: this, keys: GLib.Quark[] | null, n_keys: number) => boolean ): number; connect_after( signal: "change-event", callback: (_source: this, keys: GLib.Quark[] | null, n_keys: number) => boolean ): number; emit(signal: "change-event", keys: GLib.Quark[] | null, n_keys: number): void; connect(signal: "changed", callback: (_source: this, key: string) => void): number; connect_after(signal: "changed", callback: (_source: this, key: string) => void): number; emit(signal: "changed", key: string): void; connect(signal: "writable-change-event", callback: (_source: this, key: number) => boolean): number; connect_after(signal: "writable-change-event", callback: (_source: this, key: number) => boolean): number; emit(signal: "writable-change-event", key: number): void; connect(signal: "writable-changed", callback: (_source: this, key: string) => void): number; connect_after(signal: "writable-changed", callback: (_source: this, key: string) => void): number; emit(signal: "writable-changed", key: string): void; // Constructors static ["new"](schema_id: string): Settings; static new_full(schema: SettingsSchema, backend?: SettingsBackend | null, path?: string | null): Settings; static new_with_backend(schema_id: string, backend: SettingsBackend): Settings; static new_with_backend_and_path(schema_id: string, backend: SettingsBackend, path: string): Settings; static new_with_path(schema_id: string, path: string): Settings; // Members apply(): void; bind(key: string, object: GObject.Object, property: string, flags: SettingsBindFlags): void; bind_writable(key: string, object: GObject.Object, property: string, inverted: boolean): void; create_action(key: string): Action; delay(): void; get_boolean(key: string): boolean; get_child(name: string): Settings; get_default_value<T extends string = any>(key: string): GLib.Variant<T> | null; get_double(key: string): number; get_enum(key: string): number; get_flags(key: string): number; get_has_unapplied(): boolean; get_int(key: string): number; get_int64(key: string): number; get_mapped(key: string, mapping: SettingsGetMapping): any | null; get_range(key: string): GLib.Variant; get_string(key: string): string; get_strv(key: string): string[]; get_uint(key: string): number; get_uint64(key: string): number; get_user_value<T extends string = any>(key: string): GLib.Variant<T> | null; get_value<T extends string = any>(key: string): GLib.Variant<T>; is_writable(name: string): boolean; list_children(): string[]; list_keys(): string[]; range_check(key: string, value: GLib.Variant): boolean; reset(key: string): void; revert(): void; set_boolean(key: string, value: boolean): boolean; set_double(key: string, value: number): boolean; set_enum(key: string, value: number): boolean; set_flags(key: string, value: number): boolean; set_int(key: string, value: number): boolean; set_int64(key: string, value: number): boolean; set_string(key: string, value: string): boolean; set_strv(key: string, value?: string[] | null): boolean; set_uint(key: string, value: number): boolean; set_uint64(key: string, value: number): boolean; set_value(key: string, value: GLib.Variant): boolean; vfunc_change_event(keys: GLib.Quark, n_keys: number): boolean; vfunc_changed(key: string): void; vfunc_writable_change_event(key: GLib.Quark): boolean; vfunc_writable_changed(key: string): void; static list_relocatable_schemas(): string[]; static list_schemas(): string[]; static sync(): void; static unbind(object: GObject.Object, property: string): void; } export module SettingsBackend { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class SettingsBackend extends GObject.Object { static $gtype: GObject.GType<SettingsBackend>; constructor(properties?: Partial<SettingsBackend.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingsBackend.ConstructorProperties>, ...args: any[]): void; // Members changed(key: string, origin_tag?: any | null): void; changed_tree(tree: GLib.Tree, origin_tag?: any | null): void; keys_changed(path: string, items: string[], origin_tag?: any | null): void; path_changed(path: string, origin_tag?: any | null): void; path_writable_changed(path: string): void; writable_changed(key: string): void; vfunc_get_writable(key: string): boolean; vfunc_read(key: string, expected_type: GLib.VariantType, default_value: boolean): GLib.Variant; vfunc_read_user_value(key: string, expected_type: GLib.VariantType): GLib.Variant; vfunc_reset(key: string, origin_tag?: any | null): void; vfunc_subscribe(name: string): void; vfunc_sync(): void; vfunc_unsubscribe(name: string): void; vfunc_write(key: string, value: GLib.Variant, origin_tag?: any | null): boolean; vfunc_write_tree(tree: GLib.Tree, origin_tag?: any | null): boolean; static flatten_tree(tree: GLib.Tree): [string, string[], GLib.Variant[] | null]; static get_default(): SettingsBackend; } export module SimpleAction { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; enabled: boolean; name: string; parameter_type: GLib.VariantType; parameterType: GLib.VariantType; state: GLib.Variant; state_type: GLib.VariantType; stateType: GLib.VariantType; } } export class SimpleAction extends GObject.Object implements Action { static $gtype: GObject.GType<SimpleAction>; constructor(properties?: Partial<SimpleAction.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleAction.ConstructorProperties>, ...args: any[]): void; // Properties enabled: boolean; name: string; parameter_type: GLib.VariantType; parameterType: GLib.VariantType; state: GLib.Variant; state_type: GLib.VariantType; stateType: GLib.VariantType; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "activate", callback: (_source: this, parameter: GLib.Variant | null) => void): number; connect_after(signal: "activate", callback: (_source: this, parameter: GLib.Variant | null) => void): number; emit(signal: "activate", parameter: GLib.Variant | null): void; connect(signal: "change-state", callback: (_source: this, value: GLib.Variant | null) => void): number; connect_after(signal: "change-state", callback: (_source: this, value: GLib.Variant | null) => void): number; emit(signal: "change-state", value: GLib.Variant | null): void; // Constructors static ["new"](name: string, parameter_type?: GLib.VariantType | null): SimpleAction; static new_stateful(name: string, parameter_type: GLib.VariantType | null, state: GLib.Variant): SimpleAction; // Members set_enabled(enabled: boolean): void; set_state(value: GLib.Variant): void; set_state_hint(state_hint?: GLib.Variant | null): void; // Implemented Members activate(parameter?: GLib.Variant | null): void; change_state(value: GLib.Variant): void; get_enabled(): boolean; get_name(): string; get_parameter_type(): GLib.VariantType | null; get_state(): GLib.Variant; get_state_hint(): GLib.Variant | null; get_state_type(): GLib.VariantType | null; vfunc_activate(parameter?: GLib.Variant | null): void; vfunc_change_state(value: GLib.Variant): void; vfunc_get_enabled(): boolean; vfunc_get_name(): string; vfunc_get_parameter_type(): GLib.VariantType | null; vfunc_get_state(): GLib.Variant; vfunc_get_state_hint(): GLib.Variant | null; vfunc_get_state_type(): GLib.VariantType | null; } export module SimpleActionGroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class SimpleActionGroup extends GObject.Object implements ActionGroup, ActionMap { static $gtype: GObject.GType<SimpleActionGroup>; constructor(properties?: Partial<SimpleActionGroup.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleActionGroup.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SimpleActionGroup; // Members add_entries(entries: ActionEntry[], user_data?: any | null): void; insert(action: Action): void; lookup(action_name: string): Action; remove(action_name: string): void; // Implemented Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action(action_name: string, parameter?: GLib.Variant | null): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type(action_name: string): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; add_action(action: Action): void; add_action_entries(entries: ActionEntry[], user_data?: any | null): void; lookup_action(action_name: string): Action; remove_action(action_name: string): void; vfunc_add_action(action: Action): void; vfunc_lookup_action(action_name: string): Action; vfunc_remove_action(action_name: string): void; } export module SimpleAsyncResult { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class SimpleAsyncResult extends GObject.Object implements AsyncResult { static $gtype: GObject.GType<SimpleAsyncResult>; constructor(properties?: Partial<SimpleAsyncResult.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleAsyncResult.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"]( source_object?: GObject.Object | null, callback?: AsyncReadyCallback | null, source_tag?: any | null ): SimpleAsyncResult; static new_from_error( source_object: GObject.Object | null, callback: AsyncReadyCallback | null, error: GLib.Error ): SimpleAsyncResult; // Members complete(): void; complete_in_idle(): void; get_op_res_gboolean(): boolean; get_op_res_gssize(): number; propagate_error(): boolean; set_check_cancellable(check_cancellable?: Cancellable | null): void; set_from_error(error: GLib.Error): void; set_handle_cancellation(handle_cancellation: boolean): void; set_op_res_gboolean(op_res: boolean): void; set_op_res_gssize(op_res: number): void; static is_valid(result: AsyncResult, source?: GObject.Object | null, source_tag?: any | null): boolean; // Implemented Members get_source_object<T = GObject.Object>(): T; get_user_data(): any | null; is_tagged(source_tag?: any | null): boolean; legacy_propagate_error(): boolean; vfunc_get_source_object<T = GObject.Object>(): T; vfunc_get_user_data(): any | null; vfunc_is_tagged(source_tag?: any | null): boolean; } export module SimpleIOStream { export interface ConstructorProperties extends IOStream.ConstructorProperties { [key: string]: any; input_stream: InputStream; inputStream: InputStream; output_stream: OutputStream; outputStream: OutputStream; } } export class SimpleIOStream extends IOStream { static $gtype: GObject.GType<SimpleIOStream>; constructor(properties?: Partial<SimpleIOStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleIOStream.ConstructorProperties>, ...args: any[]): void; // Properties input_stream: InputStream; inputStream: InputStream; output_stream: OutputStream; outputStream: OutputStream; // Constructors static ["new"](input_stream: InputStream, output_stream: OutputStream): SimpleIOStream; } export module SimplePermission { export interface ConstructorProperties extends Permission.ConstructorProperties { [key: string]: any; } } export class SimplePermission extends Permission { static $gtype: GObject.GType<SimplePermission>; constructor(properties?: Partial<SimplePermission.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimplePermission.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](allowed: boolean): SimplePermission; } export module SimpleProxyResolver { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; default_proxy: string; defaultProxy: string; ignore_hosts: string[]; ignoreHosts: string[]; } } export class SimpleProxyResolver extends GObject.Object implements ProxyResolver { static $gtype: GObject.GType<SimpleProxyResolver>; constructor(properties?: Partial<SimpleProxyResolver.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleProxyResolver.ConstructorProperties>, ...args: any[]): void; // Properties default_proxy: string; defaultProxy: string; ignore_hosts: string[]; ignoreHosts: string[]; // Members set_default_proxy(default_proxy: string): void; set_ignore_hosts(ignore_hosts: string): void; set_uri_proxy(uri_scheme: string, proxy: string): void; static new(default_proxy?: string | null, ignore_hosts?: string | null): ProxyResolver; // Implemented Members is_supported(): boolean; lookup(uri: string, cancellable?: Cancellable | null): string[]; lookup_async(uri: string, cancellable?: Cancellable | null): Promise<string[]>; lookup_async(uri: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; lookup_async( uri: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; lookup_finish(result: AsyncResult): string[]; vfunc_is_supported(): boolean; vfunc_lookup(uri: string, cancellable?: Cancellable | null): string[]; vfunc_lookup_async(uri: string, cancellable?: Cancellable | null): Promise<string[]>; vfunc_lookup_async(uri: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_lookup_async( uri: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; vfunc_lookup_finish(result: AsyncResult): string[]; } export module Socket { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; blocking: boolean; broadcast: boolean; family: SocketFamily; fd: number; keepalive: boolean; listen_backlog: number; listenBacklog: number; local_address: SocketAddress; localAddress: SocketAddress; multicast_loopback: boolean; multicastLoopback: boolean; multicast_ttl: number; multicastTtl: number; protocol: SocketProtocol; remote_address: SocketAddress; remoteAddress: SocketAddress; timeout: number; ttl: number; type: SocketType; } } export class Socket extends GObject.Object implements DatagramBased, Initable { static $gtype: GObject.GType<Socket>; constructor(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]): void; // Properties blocking: boolean; broadcast: boolean; family: SocketFamily; fd: number; keepalive: boolean; listen_backlog: number; listenBacklog: number; local_address: SocketAddress; localAddress: SocketAddress; multicast_loopback: boolean; multicastLoopback: boolean; multicast_ttl: number; multicastTtl: number; protocol: SocketProtocol; remote_address: SocketAddress; remoteAddress: SocketAddress; timeout: number; ttl: number; type: SocketType; // Fields priv: SocketPrivate; // Constructors static ["new"](family: SocketFamily, type: SocketType, protocol: SocketProtocol): Socket; static new_from_fd(fd: number): Socket; // Members accept(cancellable?: Cancellable | null): Socket; bind(address: SocketAddress, allow_reuse: boolean): boolean; check_connect_result(): boolean; close(): boolean; condition_check(condition: GLib.IOCondition): GLib.IOCondition; condition_timed_wait(condition: GLib.IOCondition, timeout_us: number, cancellable?: Cancellable | null): boolean; condition_wait(condition: GLib.IOCondition, cancellable?: Cancellable | null): boolean; condition_wait(...args: never[]): never; connect(address: SocketAddress, cancellable?: Cancellable | null): boolean; connect(...args: never[]): never; connection_factory_create_connection(): SocketConnection; get_available_bytes(): number; get_blocking(): boolean; get_broadcast(): boolean; get_credentials(): Credentials; get_family(): SocketFamily; get_fd(): number; get_keepalive(): boolean; get_listen_backlog(): number; get_local_address(): SocketAddress; get_multicast_loopback(): boolean; get_multicast_ttl(): number; get_option(level: number, optname: number): [boolean, number]; get_protocol(): SocketProtocol; get_remote_address(): SocketAddress; get_socket_type(): SocketType; get_timeout(): number; get_ttl(): number; is_closed(): boolean; is_connected(): boolean; join_multicast_group(group: InetAddress, source_specific: boolean, iface?: string | null): boolean; join_multicast_group_ssm(group: InetAddress, source_specific?: InetAddress | null, iface?: string | null): boolean; leave_multicast_group(group: InetAddress, source_specific: boolean, iface?: string | null): boolean; leave_multicast_group_ssm(group: InetAddress, source_specific?: InetAddress | null, iface?: string | null): boolean; listen(): boolean; receive(cancellable?: Cancellable | null): [number, Uint8Array]; receive_from(cancellable?: Cancellable | null): [number, SocketAddress | null, Uint8Array]; receive_message( vectors: InputVector[], flags: number, cancellable?: Cancellable | null ): [number, SocketAddress | null, SocketControlMessage[] | null, number]; receive_messages(messages: InputMessage[], flags: number, cancellable?: Cancellable | null): number; receive_messages(...args: never[]): never; receive_with_blocking(blocking: boolean, cancellable?: Cancellable | null): [number, Uint8Array]; send(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; send_message( address: SocketAddress | null, vectors: OutputVector[], messages: SocketControlMessage[] | null, flags: number, cancellable?: Cancellable | null ): number; send_message_with_timeout( address: SocketAddress | null, vectors: OutputVector[], messages: SocketControlMessage[] | null, flags: number, timeout_us: number, cancellable?: Cancellable | null ): [PollableReturn, number | null]; send_messages(messages: OutputMessage[], flags: number, cancellable?: Cancellable | null): number; send_messages(...args: never[]): never; send_to(address: SocketAddress | null, buffer: Uint8Array | string, cancellable?: Cancellable | null): number; send_with_blocking(buffer: Uint8Array | string, blocking: boolean, cancellable?: Cancellable | null): number; set_blocking(blocking: boolean): void; set_broadcast(broadcast: boolean): void; set_keepalive(keepalive: boolean): void; set_listen_backlog(backlog: number): void; set_multicast_loopback(loopback: boolean): void; set_multicast_ttl(ttl: number): void; set_option(level: number, optname: number, value: number): boolean; set_timeout(timeout: number): void; set_ttl(ttl: number): void; shutdown(shutdown_read: boolean, shutdown_write: boolean): boolean; speaks_ipv4(): boolean; // Implemented Members create_source(condition: GLib.IOCondition, cancellable?: Cancellable | null): GLib.Source; vfunc_condition_check(condition: GLib.IOCondition): GLib.IOCondition; vfunc_condition_wait(condition: GLib.IOCondition, timeout: number, cancellable?: Cancellable | null): boolean; vfunc_create_source(condition: GLib.IOCondition, cancellable?: Cancellable | null): GLib.Source; vfunc_receive_messages( messages: InputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null ): number; vfunc_send_messages( messages: OutputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null ): number; init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module SocketAddress { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; family: SocketFamily; } } export abstract class SocketAddress extends GObject.Object implements SocketConnectable { static $gtype: GObject.GType<SocketAddress>; constructor(properties?: Partial<SocketAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketAddress.ConstructorProperties>, ...args: any[]): void; // Properties family: SocketFamily; // Constructors static new_from_native(_native: any, len: number): SocketAddress; // Members get_family(): SocketFamily; get_native_size(): number; to_native(dest: any | null, destlen: number): boolean; vfunc_get_family(): SocketFamily; vfunc_get_native_size(): number; vfunc_to_native(dest: any | null, destlen: number): boolean; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module SocketAddressEnumerator { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class SocketAddressEnumerator extends GObject.Object { static $gtype: GObject.GType<SocketAddressEnumerator>; constructor(properties?: Partial<SocketAddressEnumerator.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketAddressEnumerator.ConstructorProperties>, ...args: any[]): void; // Members next(cancellable?: Cancellable | null): SocketAddress; next_async(cancellable?: Cancellable | null): Promise<SocketAddress>; next_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; next_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketAddress> | void; next_finish(result: AsyncResult): SocketAddress; vfunc_next(cancellable?: Cancellable | null): SocketAddress; vfunc_next_async(cancellable?: Cancellable | null): Promise<SocketAddress>; vfunc_next_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_next_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketAddress> | void; vfunc_next_finish(result: AsyncResult): SocketAddress; } export module SocketClient { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; enable_proxy: boolean; enableProxy: boolean; family: SocketFamily; local_address: SocketAddress; localAddress: SocketAddress; protocol: SocketProtocol; proxy_resolver: ProxyResolver; proxyResolver: ProxyResolver; timeout: number; tls: boolean; tls_validation_flags: TlsCertificateFlags; tlsValidationFlags: TlsCertificateFlags; type: SocketType; } } export class SocketClient extends GObject.Object { static $gtype: GObject.GType<SocketClient>; constructor(properties?: Partial<SocketClient.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketClient.ConstructorProperties>, ...args: any[]): void; // Properties enable_proxy: boolean; enableProxy: boolean; family: SocketFamily; local_address: SocketAddress; localAddress: SocketAddress; protocol: SocketProtocol; proxy_resolver: ProxyResolver; proxyResolver: ProxyResolver; timeout: number; tls: boolean; tls_validation_flags: TlsCertificateFlags; tlsValidationFlags: TlsCertificateFlags; type: SocketType; // Fields priv: SocketClientPrivate; // Signals connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect_after( signal: "event", callback: ( _source: this, event: SocketClientEvent, connectable: SocketConnectable, connection: IOStream | null ) => void ): number; emit(signal: "event", event: SocketClientEvent, connectable: SocketConnectable, connection: IOStream | null): void; // Constructors static ["new"](): SocketClient; // Members add_application_proxy(protocol: string): void; connect(connectable: SocketConnectable, cancellable?: Cancellable | null): SocketConnection; connect(...args: never[]): never; connect_async(connectable: SocketConnectable, cancellable?: Cancellable | null): Promise<SocketConnection>; connect_async( connectable: SocketConnectable, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_async( connectable: SocketConnectable, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketConnection> | void; connect_finish(result: AsyncResult): SocketConnection; connect_to_host(host_and_port: string, default_port: number, cancellable?: Cancellable | null): SocketConnection; connect_to_host_async( host_and_port: string, default_port: number, cancellable?: Cancellable | null ): Promise<SocketConnection>; connect_to_host_async( host_and_port: string, default_port: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_to_host_async( host_and_port: string, default_port: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketConnection> | void; connect_to_host_finish(result: AsyncResult): SocketConnection; connect_to_service(domain: string, service: string, cancellable?: Cancellable | null): SocketConnection; connect_to_service_async( domain: string, service: string, cancellable?: Cancellable | null ): Promise<SocketConnection>; connect_to_service_async( domain: string, service: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_to_service_async( domain: string, service: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketConnection> | void; connect_to_service_finish(result: AsyncResult): SocketConnection; connect_to_uri(uri: string, default_port: number, cancellable?: Cancellable | null): SocketConnection; connect_to_uri_async( uri: string, default_port: number, cancellable?: Cancellable | null ): Promise<SocketConnection>; connect_to_uri_async( uri: string, default_port: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_to_uri_async( uri: string, default_port: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<SocketConnection> | void; connect_to_uri_finish(result: AsyncResult): SocketConnection; get_enable_proxy(): boolean; get_family(): SocketFamily; get_local_address(): SocketAddress; get_protocol(): SocketProtocol; get_proxy_resolver(): ProxyResolver; get_socket_type(): SocketType; get_timeout(): number; get_tls(): boolean; get_tls_validation_flags(): TlsCertificateFlags; set_enable_proxy(enable: boolean): void; set_family(family: SocketFamily): void; set_local_address(address?: SocketAddress | null): void; set_protocol(protocol: SocketProtocol): void; set_proxy_resolver(proxy_resolver?: ProxyResolver | null): void; set_socket_type(type: SocketType): void; set_timeout(timeout: number): void; set_tls(tls: boolean): void; set_tls_validation_flags(flags: TlsCertificateFlags): void; vfunc_event(event: SocketClientEvent, connectable: SocketConnectable, connection: IOStream): void; } export module SocketConnection { export interface ConstructorProperties extends IOStream.ConstructorProperties { [key: string]: any; socket: Socket; } } export class SocketConnection extends IOStream { static $gtype: GObject.GType<SocketConnection>; constructor(properties?: Partial<SocketConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketConnection.ConstructorProperties>, ...args: any[]): void; // Properties socket: Socket; // Fields priv: SocketConnectionPrivate; // Members connect(address: SocketAddress, cancellable?: Cancellable | null): boolean; connect(...args: never[]): never; connect_async(address: SocketAddress, cancellable?: Cancellable | null): Promise<boolean>; connect_async( address: SocketAddress, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_async( address: SocketAddress, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; connect_finish(result: AsyncResult): boolean; get_local_address(): SocketAddress; get_remote_address(): SocketAddress; get_socket(): Socket; is_connected(): boolean; static factory_lookup_type(family: SocketFamily, type: SocketType, protocol_id: number): GObject.GType; static factory_register_type(g_type: GObject.GType, family: SocketFamily, type: SocketType, protocol: number): void; } export module SocketControlMessage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class SocketControlMessage extends GObject.Object { static $gtype: GObject.GType<SocketControlMessage>; constructor(properties?: Partial<SocketControlMessage.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketControlMessage.ConstructorProperties>, ...args: any[]): void; // Fields priv: SocketControlMessagePrivate; // Members get_level(): number; get_msg_type(): number; get_size(): number; serialize(data: any): void; vfunc_get_level(): number; vfunc_get_size(): number; vfunc_get_type(): number; vfunc_serialize(data: any): void; static deserialize(level: number, type: number, data: Uint8Array | string): SocketControlMessage; } export module SocketListener { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; listen_backlog: number; listenBacklog: number; } } export class SocketListener extends GObject.Object { static $gtype: GObject.GType<SocketListener>; constructor(properties?: Partial<SocketListener.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketListener.ConstructorProperties>, ...args: any[]): void; // Properties listen_backlog: number; listenBacklog: number; // Fields priv: SocketListenerPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "event", callback: (_source: this, event: SocketListenerEvent, socket: Socket) => void): number; connect_after( signal: "event", callback: (_source: this, event: SocketListenerEvent, socket: Socket) => void ): number; emit(signal: "event", event: SocketListenerEvent, socket: Socket): void; // Constructors static ["new"](): SocketListener; // Members accept(cancellable?: Cancellable | null): [SocketConnection, GObject.Object | null]; accept_async(cancellable?: Cancellable | null): Promise<[SocketConnection, GObject.Object | null]>; accept_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; accept_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[SocketConnection, GObject.Object | null]> | void; accept_finish(result: AsyncResult): [SocketConnection, GObject.Object | null]; accept_socket(cancellable?: Cancellable | null): [Socket, GObject.Object | null]; accept_socket_async(cancellable?: Cancellable | null): Promise<[Socket, GObject.Object | null]>; accept_socket_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; accept_socket_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[Socket, GObject.Object | null]> | void; accept_socket_finish(result: AsyncResult): [Socket, GObject.Object | null]; add_address( address: SocketAddress, type: SocketType, protocol: SocketProtocol, source_object?: GObject.Object | null ): [boolean, SocketAddress | null]; add_any_inet_port(source_object?: GObject.Object | null): number; add_inet_port(port: number, source_object?: GObject.Object | null): boolean; add_socket(socket: Socket, source_object?: GObject.Object | null): boolean; close(): void; set_backlog(listen_backlog: number): void; vfunc_changed(): void; vfunc_event(event: SocketListenerEvent, socket: Socket): void; } export module SocketService { export interface ConstructorProperties extends SocketListener.ConstructorProperties { [key: string]: any; active: boolean; } } export class SocketService extends SocketListener { static $gtype: GObject.GType<SocketService>; constructor(properties?: Partial<SocketService.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SocketService.ConstructorProperties>, ...args: any[]): void; // Properties active: boolean; // Fields priv: SocketServicePrivate | any; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "incoming", callback: (_source: this, connection: SocketConnection, source_object: GObject.Object | null) => boolean ): number; connect_after( signal: "incoming", callback: (_source: this, connection: SocketConnection, source_object: GObject.Object | null) => boolean ): number; emit(signal: "incoming", connection: SocketConnection, source_object: GObject.Object | null): void; // Constructors static ["new"](): SocketService; // Members is_active(): boolean; start(): void; stop(): void; vfunc_incoming(connection: SocketConnection, source_object: GObject.Object): boolean; } export module Subprocess { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; argv: string[]; flags: SubprocessFlags; } } export class Subprocess extends GObject.Object implements Initable { static $gtype: GObject.GType<Subprocess>; constructor(properties?: Partial<Subprocess.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Subprocess.ConstructorProperties>, ...args: any[]): void; // Properties argv: string[]; flags: SubprocessFlags; // Constructors static ["new"](argv: string[], flags: SubprocessFlags): Subprocess; // Members communicate( stdin_buf?: GLib.Bytes | null, cancellable?: Cancellable | null ): [boolean, GLib.Bytes | null, GLib.Bytes | null]; communicate_async( stdin_buf?: GLib.Bytes | null, cancellable?: Cancellable | null ): Promise<[GLib.Bytes | null, GLib.Bytes | null]>; communicate_async( stdin_buf: GLib.Bytes | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; communicate_async( stdin_buf?: GLib.Bytes | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[GLib.Bytes | null, GLib.Bytes | null]> | void; communicate_finish(result: AsyncResult): [boolean, GLib.Bytes | null, GLib.Bytes | null]; communicate_utf8( stdin_buf?: string | null, cancellable?: Cancellable | null ): [boolean, string | null, string | null]; communicate_utf8_async( stdin_buf?: string | null, cancellable?: Cancellable | null ): Promise<[string | null, string | null]>; communicate_utf8_async( stdin_buf: string | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; communicate_utf8_async( stdin_buf?: string | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[string | null, string | null]> | void; communicate_utf8_finish(result: AsyncResult): [boolean, string | null, string | null]; force_exit(): void; get_exit_status(): number; get_identifier(): string | null; get_if_exited(): boolean; get_if_signaled(): boolean; get_status(): number; get_stderr_pipe(): InputStream; get_stdin_pipe(): OutputStream; get_stdout_pipe(): InputStream; get_successful(): boolean; get_term_sig(): number; send_signal(signal_num: number): void; wait(cancellable?: Cancellable | null): boolean; wait_async(cancellable?: Cancellable | null): Promise<boolean>; wait_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; wait_async(cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null): Promise<boolean> | void; wait_check(cancellable?: Cancellable | null): boolean; wait_check_async(cancellable?: Cancellable | null): Promise<boolean>; wait_check_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; wait_check_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; wait_check_finish(result: AsyncResult): boolean; wait_finish(result: AsyncResult): boolean; // Implemented Members init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export module SubprocessLauncher { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; flags: SubprocessFlags; } } export class SubprocessLauncher extends GObject.Object { static $gtype: GObject.GType<SubprocessLauncher>; constructor(properties?: Partial<SubprocessLauncher.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SubprocessLauncher.ConstructorProperties>, ...args: any[]): void; // Properties flags: SubprocessFlags; // Constructors static ["new"](flags: SubprocessFlags): SubprocessLauncher; // Members getenv(variable: string): string; set_cwd(cwd: string): void; set_environ(env: string[]): void; set_flags(flags: SubprocessFlags): void; set_stderr_file_path(path?: string | null): void; set_stdin_file_path(path: string): void; set_stdout_file_path(path?: string | null): void; setenv(variable: string, value: string, overwrite: boolean): void; spawnv(argv: string[]): Subprocess; take_fd(source_fd: number, target_fd: number): void; take_stderr_fd(fd: number): void; take_stdin_fd(fd: number): void; take_stdout_fd(fd: number): void; unsetenv(variable: string): void; } export module Task { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; completed: boolean; } } export class Task extends GObject.Object implements AsyncResult { static $gtype: GObject.GType<Task>; constructor(properties?: Partial<Task.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Task.ConstructorProperties>, ...args: any[]): void; // Properties completed: boolean; // Constructors static ["new"]( source_object?: GObject.Object | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback | null ): Task; // Members get_cancellable(): Cancellable; get_check_cancellable(): boolean; get_completed(): boolean; get_context(): GLib.MainContext; get_name(): string | null; get_priority(): number; get_return_on_cancel(): boolean; get_source_object<T = GObject.Object>(): T; get_source_tag(): any | null; get_task_data(): any | null; had_error(): boolean; propagate_boolean(): boolean; propagate_int(): number; propagate_pointer(): any | null; propagate_value(): [boolean, unknown]; return_boolean(result: boolean): void; return_error(error: GLib.Error): void; return_error_if_cancelled(): boolean; return_int(result: number): void; return_pointer(result?: any | null, result_destroy?: GLib.DestroyNotify | null): void; return_value(result?: GObject.Value | null): void; run_in_thread(task_func: TaskThreadFunc): void; run_in_thread_sync(task_func: TaskThreadFunc): void; set_check_cancellable(check_cancellable: boolean): void; set_name(name?: string | null): void; set_priority(priority: number): void; set_return_on_cancel(return_on_cancel: boolean): boolean; set_source_tag(source_tag?: any | null): void; set_task_data(task_data?: any | null, task_data_destroy?: GLib.DestroyNotify | null): void; static is_valid(result: AsyncResult, source_object?: GObject.Object | null): boolean; static report_error( source_object: GObject.Object | null, callback: AsyncReadyCallback<Task> | null, source_tag: any | null, error: GLib.Error ): void; // Implemented Members get_user_data(): any | null; is_tagged(source_tag?: any | null): boolean; legacy_propagate_error(): boolean; vfunc_get_source_object<T = GObject.Object>(): T; vfunc_get_user_data(): any | null; vfunc_is_tagged(source_tag?: any | null): boolean; } export module TcpConnection { export interface ConstructorProperties extends SocketConnection.ConstructorProperties { [key: string]: any; graceful_disconnect: boolean; gracefulDisconnect: boolean; } } export class TcpConnection extends SocketConnection { static $gtype: GObject.GType<TcpConnection>; constructor(properties?: Partial<TcpConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TcpConnection.ConstructorProperties>, ...args: any[]): void; // Properties graceful_disconnect: boolean; gracefulDisconnect: boolean; // Fields priv: TcpConnectionPrivate | any; // Members get_graceful_disconnect(): boolean; set_graceful_disconnect(graceful_disconnect: boolean): void; } export module TcpWrapperConnection { export interface ConstructorProperties extends TcpConnection.ConstructorProperties { [key: string]: any; base_io_stream: IOStream; baseIoStream: IOStream; } } export class TcpWrapperConnection extends TcpConnection { static $gtype: GObject.GType<TcpWrapperConnection>; constructor(properties?: Partial<TcpWrapperConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TcpWrapperConnection.ConstructorProperties>, ...args: any[]): void; // Properties base_io_stream: IOStream; baseIoStream: IOStream; // Fields priv: TcpWrapperConnectionPrivate | any; // Constructors static ["new"](base_io_stream: IOStream, socket: Socket): TcpWrapperConnection; // Members get_base_io_stream(): IOStream; } export module TestDBus { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; flags: TestDBusFlags; } } export class TestDBus extends GObject.Object { static $gtype: GObject.GType<TestDBus>; constructor(properties?: Partial<TestDBus.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TestDBus.ConstructorProperties>, ...args: any[]): void; // Properties flags: TestDBusFlags; // Constructors static ["new"](flags: TestDBusFlags): TestDBus; // Members add_service_dir(path: string): void; down(): void; get_bus_address(): string | null; get_flags(): TestDBusFlags; stop(): void; up(): void; static unset(): void; } export module ThemedIcon { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; names: string[]; use_default_fallbacks: boolean; useDefaultFallbacks: boolean; } } export class ThemedIcon extends GObject.Object implements Icon { static $gtype: GObject.GType<ThemedIcon>; constructor(properties?: Partial<ThemedIcon.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ThemedIcon.ConstructorProperties>, ...args: any[]): void; // Properties name: string; names: string[]; use_default_fallbacks: boolean; useDefaultFallbacks: boolean; // Constructors static ["new"](iconname: string): ThemedIcon; static new_from_names(iconnames: string[]): ThemedIcon; static new_with_default_fallbacks(iconname: string): ThemedIcon; // Members append_name(iconname: string): void; get_names(): string[]; prepend_name(iconname: string): void; // Implemented Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; } export module ThreadedSocketService { export interface ConstructorProperties extends SocketService.ConstructorProperties { [key: string]: any; max_threads: number; maxThreads: number; } } export class ThreadedSocketService extends SocketService { static $gtype: GObject.GType<ThreadedSocketService>; constructor(properties?: Partial<ThreadedSocketService.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ThreadedSocketService.ConstructorProperties>, ...args: any[]): void; // Properties max_threads: number; maxThreads: number; // Fields priv: ThreadedSocketServicePrivate | any; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "run", callback: (_source: this, connection: SocketConnection, source_object: GObject.Object | null) => boolean ): number; connect_after( signal: "run", callback: (_source: this, connection: SocketConnection, source_object: GObject.Object | null) => boolean ): number; emit(signal: "run", connection: SocketConnection, source_object: GObject.Object | null): void; // Constructors static ["new"](max_threads: number): ThreadedSocketService; static ["new"](...args: never[]): never; // Members vfunc_run(connection: SocketConnection, source_object: GObject.Object): boolean; } export module TlsCertificate { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; certificate: Uint8Array; certificate_pem: string; certificatePem: string; issuer: TlsCertificate; private_key: Uint8Array; privateKey: Uint8Array; private_key_pem: string; privateKeyPem: string; } } export abstract class TlsCertificate extends GObject.Object { static $gtype: GObject.GType<TlsCertificate>; constructor(properties?: Partial<TlsCertificate.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TlsCertificate.ConstructorProperties>, ...args: any[]): void; // Properties certificate: Uint8Array; certificate_pem: string; certificatePem: string; issuer: TlsCertificate; private_key: Uint8Array; privateKey: Uint8Array; private_key_pem: string; privateKeyPem: string; // Fields priv: TlsCertificatePrivate; // Constructors static new_from_file(file: string): TlsCertificate; static new_from_files(cert_file: string, key_file: string): TlsCertificate; static new_from_pem(data: string, length: number): TlsCertificate; // Members get_issuer(): TlsCertificate; is_same(cert_two: TlsCertificate): boolean; verify(identity?: SocketConnectable | null, trusted_ca?: TlsCertificate | null): TlsCertificateFlags; vfunc_verify(identity?: SocketConnectable | null, trusted_ca?: TlsCertificate | null): TlsCertificateFlags; static list_new_from_file(file: string): TlsCertificate[]; } export module TlsConnection { export interface ConstructorProperties extends IOStream.ConstructorProperties { [key: string]: any; advertised_protocols: string[]; advertisedProtocols: string[]; base_io_stream: IOStream; baseIoStream: IOStream; certificate: TlsCertificate; database: TlsDatabase; interaction: TlsInteraction; negotiated_protocol: string; negotiatedProtocol: string; peer_certificate: TlsCertificate; peerCertificate: TlsCertificate; peer_certificate_errors: TlsCertificateFlags; peerCertificateErrors: TlsCertificateFlags; rehandshake_mode: TlsRehandshakeMode; rehandshakeMode: TlsRehandshakeMode; require_close_notify: boolean; requireCloseNotify: boolean; use_system_certdb: boolean; useSystemCertdb: boolean; } } export abstract class TlsConnection extends IOStream { static $gtype: GObject.GType<TlsConnection>; constructor(properties?: Partial<TlsConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TlsConnection.ConstructorProperties>, ...args: any[]): void; // Properties advertised_protocols: string[]; advertisedProtocols: string[]; base_io_stream: IOStream; baseIoStream: IOStream; certificate: TlsCertificate; database: TlsDatabase; interaction: TlsInteraction; negotiated_protocol: string; negotiatedProtocol: string; peer_certificate: TlsCertificate; peerCertificate: TlsCertificate; peer_certificate_errors: TlsCertificateFlags; peerCertificateErrors: TlsCertificateFlags; rehandshake_mode: TlsRehandshakeMode; rehandshakeMode: TlsRehandshakeMode; require_close_notify: boolean; requireCloseNotify: boolean; use_system_certdb: boolean; useSystemCertdb: boolean; // Fields priv: TlsConnectionPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "accept-certificate", callback: (_source: this, peer_cert: TlsCertificate, errors: TlsCertificateFlags) => boolean ): number; connect_after( signal: "accept-certificate", callback: (_source: this, peer_cert: TlsCertificate, errors: TlsCertificateFlags) => boolean ): number; emit(signal: "accept-certificate", peer_cert: TlsCertificate, errors: TlsCertificateFlags): void; // Members emit_accept_certificate(peer_cert: TlsCertificate, errors: TlsCertificateFlags): boolean; get_certificate(): TlsCertificate | null; get_channel_binding_data(type: TlsChannelBindingType): [boolean, Uint8Array | null]; get_database(): TlsDatabase | null; get_interaction(): TlsInteraction | null; get_negotiated_protocol(): string | null; get_peer_certificate(): TlsCertificate | null; get_peer_certificate_errors(): TlsCertificateFlags; get_rehandshake_mode(): TlsRehandshakeMode; get_require_close_notify(): boolean; get_use_system_certdb(): boolean; handshake(cancellable?: Cancellable | null): boolean; handshake_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; handshake_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; handshake_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; handshake_finish(result: AsyncResult): boolean; set_advertised_protocols(protocols?: string[] | null): void; set_certificate(certificate: TlsCertificate): void; set_database(database?: TlsDatabase | null): void; set_interaction(interaction?: TlsInteraction | null): void; set_rehandshake_mode(mode: TlsRehandshakeMode): void; set_require_close_notify(require_close_notify: boolean): void; set_use_system_certdb(use_system_certdb: boolean): void; vfunc_accept_certificate(peer_cert: TlsCertificate, errors: TlsCertificateFlags): boolean; vfunc_get_binding_data(type: TlsChannelBindingType, data: Uint8Array | string): boolean; vfunc_handshake(cancellable?: Cancellable | null): boolean; vfunc_handshake_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_handshake_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_handshake_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_handshake_finish(result: AsyncResult): boolean; } export module TlsDatabase { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class TlsDatabase extends GObject.Object { static $gtype: GObject.GType<TlsDatabase>; constructor(properties?: Partial<TlsDatabase.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TlsDatabase.ConstructorProperties>, ...args: any[]): void; // Fields priv: TlsDatabasePrivate; // Members create_certificate_handle(certificate: TlsCertificate): string | null; lookup_certificate_for_handle( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate | null; lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate>; lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate> | void; lookup_certificate_for_handle_finish(result: AsyncResult): TlsCertificate; lookup_certificate_issuer( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate; lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate>; lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate> | void; lookup_certificate_issuer_finish(result: AsyncResult): TlsCertificate; lookup_certificates_issued_by( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate[]; lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate[]>; lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate[]> | void; lookup_certificates_issued_by_finish(result: AsyncResult): TlsCertificate[]; verify_chain( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null ): TlsCertificateFlags; verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null ): Promise<TlsCertificateFlags>; verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificateFlags> | void; verify_chain_finish(result: AsyncResult): TlsCertificateFlags; vfunc_create_certificate_handle(certificate: TlsCertificate): string | null; vfunc_lookup_certificate_for_handle( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate | null; vfunc_lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate>; vfunc_lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_certificate_for_handle_async( handle: string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate> | void; vfunc_lookup_certificate_for_handle_finish(result: AsyncResult): TlsCertificate; vfunc_lookup_certificate_issuer( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate; vfunc_lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate>; vfunc_lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_certificate_issuer_async( certificate: TlsCertificate, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate> | void; vfunc_lookup_certificate_issuer_finish(result: AsyncResult): TlsCertificate; vfunc_lookup_certificates_issued_by( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): TlsCertificate[]; vfunc_lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null ): Promise<TlsCertificate[]>; vfunc_lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_lookup_certificates_issued_by_async( issuer_raw_dn: Uint8Array | string, interaction: TlsInteraction | null, flags: TlsDatabaseLookupFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificate[]> | void; vfunc_lookup_certificates_issued_by_finish(result: AsyncResult): TlsCertificate[]; vfunc_verify_chain( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null ): TlsCertificateFlags; vfunc_verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null ): Promise<TlsCertificateFlags>; vfunc_verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_verify_chain_async( chain: TlsCertificate, purpose: string, identity: SocketConnectable | null, interaction: TlsInteraction | null, flags: TlsDatabaseVerifyFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsCertificateFlags> | void; vfunc_verify_chain_finish(result: AsyncResult): TlsCertificateFlags; } export module TlsInteraction { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class TlsInteraction extends GObject.Object { static $gtype: GObject.GType<TlsInteraction>; constructor(properties?: Partial<TlsInteraction.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TlsInteraction.ConstructorProperties>, ...args: any[]): void; // Members ask_password(password: TlsPassword, cancellable?: Cancellable | null): TlsInteractionResult; ask_password_async(password: TlsPassword, cancellable?: Cancellable | null): Promise<TlsInteractionResult>; ask_password_async( password: TlsPassword, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; ask_password_async( password: TlsPassword, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsInteractionResult> | void; ask_password_finish(result: AsyncResult): TlsInteractionResult; invoke_ask_password(password: TlsPassword, cancellable?: Cancellable | null): TlsInteractionResult; invoke_request_certificate( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null ): TlsInteractionResult; request_certificate( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null ): TlsInteractionResult; request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null ): Promise<TlsInteractionResult>; request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsInteractionResult> | void; request_certificate_finish(result: AsyncResult): TlsInteractionResult; vfunc_ask_password(password: TlsPassword, cancellable?: Cancellable | null): TlsInteractionResult; vfunc_ask_password_async(password: TlsPassword, cancellable?: Cancellable | null): Promise<TlsInteractionResult>; vfunc_ask_password_async( password: TlsPassword, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_ask_password_async( password: TlsPassword, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsInteractionResult> | void; vfunc_ask_password_finish(result: AsyncResult): TlsInteractionResult; vfunc_request_certificate( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null ): TlsInteractionResult; vfunc_request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null ): Promise<TlsInteractionResult>; vfunc_request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_request_certificate_async( connection: TlsConnection, flags: TlsCertificateRequestFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<TlsInteractionResult> | void; vfunc_request_certificate_finish(result: AsyncResult): TlsInteractionResult; } export module TlsPassword { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; description: string; flags: TlsPasswordFlags; warning: string; } } export class TlsPassword extends GObject.Object { static $gtype: GObject.GType<TlsPassword>; constructor(properties?: Partial<TlsPassword.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TlsPassword.ConstructorProperties>, ...args: any[]): void; // Properties description: string; flags: TlsPasswordFlags; warning: string; // Fields priv: TlsPasswordPrivate; // Constructors static ["new"](flags: TlsPasswordFlags, description: string): TlsPassword; // Members get_description(): string; get_flags(): TlsPasswordFlags; get_value(length?: number | null): number; get_warning(): string; set_description(description: string): void; set_flags(flags: TlsPasswordFlags): void; set_value(value: Uint8Array | string): void; set_value_full(value: Uint8Array | string, destroy?: GLib.DestroyNotify | null): void; set_warning(warning: string): void; vfunc_get_default_warning(): string; vfunc_get_value(length?: number | null): number; vfunc_set_value(value: Uint8Array | string, destroy?: GLib.DestroyNotify | null): void; } export module UnixConnection { export interface ConstructorProperties extends SocketConnection.ConstructorProperties { [key: string]: any; } } export class UnixConnection extends SocketConnection { static $gtype: GObject.GType<UnixConnection>; constructor(properties?: Partial<UnixConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixConnection.ConstructorProperties>, ...args: any[]): void; // Fields priv: UnixConnectionPrivate | any; // Members receive_credentials(cancellable?: Cancellable | null): Credentials; receive_credentials_async(cancellable?: Cancellable | null): Promise<Credentials>; receive_credentials_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; receive_credentials_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<Credentials> | void; receive_credentials_finish(result: AsyncResult): Credentials; receive_fd(cancellable?: Cancellable | null): number; send_credentials(cancellable?: Cancellable | null): boolean; send_credentials_async(cancellable?: Cancellable | null): Promise<boolean>; send_credentials_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; send_credentials_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; send_credentials_finish(result: AsyncResult): boolean; send_fd(fd: number, cancellable?: Cancellable | null): boolean; } export module UnixCredentialsMessage { export interface ConstructorProperties extends SocketControlMessage.ConstructorProperties { [key: string]: any; credentials: Credentials; } } export class UnixCredentialsMessage extends SocketControlMessage { static $gtype: GObject.GType<UnixCredentialsMessage>; constructor(properties?: Partial<UnixCredentialsMessage.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixCredentialsMessage.ConstructorProperties>, ...args: any[]): void; // Properties credentials: Credentials; // Fields priv: UnixCredentialsMessagePrivate | any; // Constructors static ["new"](): UnixCredentialsMessage; static new_with_credentials(credentials: Credentials): UnixCredentialsMessage; // Members get_credentials(): Credentials; static is_supported(): boolean; } export module UnixFDList { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class UnixFDList extends GObject.Object { static $gtype: GObject.GType<UnixFDList>; constructor(properties?: Partial<UnixFDList.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixFDList.ConstructorProperties>, ...args: any[]): void; // Fields priv: UnixFDListPrivate; // Constructors static ["new"](): UnixFDList; static new_from_array(fds: number[]): UnixFDList; // Members append(fd: number): number; get(index_: number): number; get_length(): number; peek_fds(): number[]; steal_fds(): number[]; } export module UnixFDMessage { export interface ConstructorProperties extends SocketControlMessage.ConstructorProperties { [key: string]: any; fd_list: UnixFDList; fdList: UnixFDList; } } export class UnixFDMessage extends SocketControlMessage { static $gtype: GObject.GType<UnixFDMessage>; constructor(properties?: Partial<UnixFDMessage.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixFDMessage.ConstructorProperties>, ...args: any[]): void; // Properties fd_list: UnixFDList; fdList: UnixFDList; // Fields priv: UnixFDMessagePrivate | any; // Constructors static ["new"](): UnixFDMessage; static new_with_fd_list(fd_list: UnixFDList): UnixFDMessage; // Members append_fd(fd: number): boolean; get_fd_list(): UnixFDList; steal_fds(): number[]; } export module UnixInputStream { export interface ConstructorProperties extends InputStream.ConstructorProperties { [key: string]: any; close_fd: boolean; closeFd: boolean; fd: number; } } export class UnixInputStream extends InputStream implements FileDescriptorBased, PollableInputStream { static $gtype: GObject.GType<UnixInputStream>; constructor(properties?: Partial<UnixInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixInputStream.ConstructorProperties>, ...args: any[]): void; // Properties close_fd: boolean; closeFd: boolean; fd: number; // Constructors static ["new"](fd: number, close_fd: boolean): UnixInputStream; // Members get_close_fd(): boolean; get_fd(): number; set_close_fd(close_fd: boolean): void; // Implemented Members vfunc_get_fd(): number; can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_readable(): boolean; read_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_readable(): boolean; vfunc_read_nonblocking(buffer?: Uint8Array | null): number; } export module UnixMountMonitor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class UnixMountMonitor extends GObject.Object { static $gtype: GObject.GType<UnixMountMonitor>; constructor(properties?: Partial<UnixMountMonitor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixMountMonitor.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "mountpoints-changed", callback: (_source: this) => void): number; connect_after(signal: "mountpoints-changed", callback: (_source: this) => void): number; emit(signal: "mountpoints-changed"): void; connect(signal: "mounts-changed", callback: (_source: this) => void): number; connect_after(signal: "mounts-changed", callback: (_source: this) => void): number; emit(signal: "mounts-changed"): void; // Constructors static ["new"](): UnixMountMonitor; // Members set_rate_limit(limit_msec: number): void; static get(): UnixMountMonitor; } export module UnixOutputStream { export interface ConstructorProperties extends OutputStream.ConstructorProperties { [key: string]: any; close_fd: boolean; closeFd: boolean; fd: number; } } export class UnixOutputStream extends OutputStream implements FileDescriptorBased, PollableOutputStream { static $gtype: GObject.GType<UnixOutputStream>; constructor(properties?: Partial<UnixOutputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixOutputStream.ConstructorProperties>, ...args: any[]): void; // Properties close_fd: boolean; closeFd: boolean; fd: number; // Constructors static ["new"](fd: number, close_fd: boolean): UnixOutputStream; // Members get_close_fd(): boolean; get_fd(): number; set_close_fd(close_fd: boolean): void; // Implemented Members vfunc_get_fd(): number; can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_writable(): boolean; write_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; writev_nonblocking(vectors: OutputVector[], cancellable?: Cancellable | null): [PollableReturn, number | null]; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_writable(): boolean; vfunc_write_nonblocking(buffer?: Uint8Array | null): number; vfunc_writev_nonblocking(vectors: OutputVector[]): [PollableReturn, number | null]; } export module UnixSocketAddress { export interface ConstructorProperties extends SocketAddress.ConstructorProperties { [key: string]: any; abstract: boolean; address_type: UnixSocketAddressType; addressType: UnixSocketAddressType; path: string; path_as_array: Uint8Array; pathAsArray: Uint8Array; } } export class UnixSocketAddress extends SocketAddress implements SocketConnectable { static $gtype: GObject.GType<UnixSocketAddress>; constructor(properties?: Partial<UnixSocketAddress.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixSocketAddress.ConstructorProperties>, ...args: any[]): void; // Properties "abstract": boolean; address_type: UnixSocketAddressType; addressType: UnixSocketAddressType; path: string; path_as_array: Uint8Array; pathAsArray: Uint8Array; // Constructors static ["new"](path: string): UnixSocketAddress; static new_abstract(path: number[]): UnixSocketAddress; static new_with_type(path: number[], type: UnixSocketAddressType): UnixSocketAddress; // Members get_address_type(): UnixSocketAddressType; get_is_abstract(): boolean; get_path(): string; get_path_len(): number; static abstract_names_supported(): boolean; // Implemented Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export module Vfs { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Vfs extends GObject.Object { static $gtype: GObject.GType<Vfs>; constructor(properties?: Partial<Vfs.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Vfs.ConstructorProperties>, ...args: any[]): void; // Members get_file_for_path(path: string): File; get_file_for_uri(uri: string): File; get_supported_uri_schemes(): string[]; is_active(): boolean; parse_name(parse_name: string): File; register_uri_scheme( scheme: string, uri_func?: VfsFileLookupFunc | null, uri_destroy?: GLib.DestroyNotify | null, parse_name_func?: VfsFileLookupFunc | null, parse_name_destroy?: GLib.DestroyNotify | null ): boolean; unregister_uri_scheme(scheme: string): boolean; vfunc_add_writable_namespaces(list: FileAttributeInfoList): void; vfunc_get_file_for_path(path: string): File; vfunc_get_file_for_uri(uri: string): File; vfunc_get_supported_uri_schemes(): string[]; vfunc_is_active(): boolean; vfunc_local_file_add_info( filename: string, device: number, attribute_matcher: FileAttributeMatcher, info: FileInfo, cancellable?: Cancellable | null, extra_data?: any | null ): void; vfunc_local_file_moved(source: string, dest: string): void; vfunc_local_file_removed(filename: string): void; vfunc_local_file_set_attributes( filename: string, info: FileInfo, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; vfunc_parse_name(parse_name: string): File; static get_default(): Vfs; static get_local(): Vfs; } export module VolumeMonitor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class VolumeMonitor extends GObject.Object { static $gtype: GObject.GType<VolumeMonitor>; constructor(properties?: Partial<VolumeMonitor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<VolumeMonitor.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "drive-changed", callback: (_source: this, drive: Drive) => void): number; connect_after(signal: "drive-changed", callback: (_source: this, drive: Drive) => void): number; emit(signal: "drive-changed", drive: Drive): void; connect(signal: "drive-connected", callback: (_source: this, drive: Drive) => void): number; connect_after(signal: "drive-connected", callback: (_source: this, drive: Drive) => void): number; emit(signal: "drive-connected", drive: Drive): void; connect(signal: "drive-disconnected", callback: (_source: this, drive: Drive) => void): number; connect_after(signal: "drive-disconnected", callback: (_source: this, drive: Drive) => void): number; emit(signal: "drive-disconnected", drive: Drive): void; connect(signal: "drive-eject-button", callback: (_source: this, drive: Drive) => void): number; connect_after(signal: "drive-eject-button", callback: (_source: this, drive: Drive) => void): number; emit(signal: "drive-eject-button", drive: Drive): void; connect(signal: "drive-stop-button", callback: (_source: this, drive: Drive) => void): number; connect_after(signal: "drive-stop-button", callback: (_source: this, drive: Drive) => void): number; emit(signal: "drive-stop-button", drive: Drive): void; connect(signal: "mount-added", callback: (_source: this, mount: Mount) => void): number; connect_after(signal: "mount-added", callback: (_source: this, mount: Mount) => void): number; emit(signal: "mount-added", mount: Mount): void; connect(signal: "mount-changed", callback: (_source: this, mount: Mount) => void): number; connect_after(signal: "mount-changed", callback: (_source: this, mount: Mount) => void): number; emit(signal: "mount-changed", mount: Mount): void; connect(signal: "mount-pre-unmount", callback: (_source: this, mount: Mount) => void): number; connect_after(signal: "mount-pre-unmount", callback: (_source: this, mount: Mount) => void): number; emit(signal: "mount-pre-unmount", mount: Mount): void; connect(signal: "mount-removed", callback: (_source: this, mount: Mount) => void): number; connect_after(signal: "mount-removed", callback: (_source: this, mount: Mount) => void): number; emit(signal: "mount-removed", mount: Mount): void; connect(signal: "volume-added", callback: (_source: this, volume: Volume) => void): number; connect_after(signal: "volume-added", callback: (_source: this, volume: Volume) => void): number; emit(signal: "volume-added", volume: Volume): void; connect(signal: "volume-changed", callback: (_source: this, volume: Volume) => void): number; connect_after(signal: "volume-changed", callback: (_source: this, volume: Volume) => void): number; emit(signal: "volume-changed", volume: Volume): void; connect(signal: "volume-removed", callback: (_source: this, volume: Volume) => void): number; connect_after(signal: "volume-removed", callback: (_source: this, volume: Volume) => void): number; emit(signal: "volume-removed", volume: Volume): void; // Members get_connected_drives(): Drive[]; get_mount_for_uuid(uuid: string): Mount; get_mounts(): Mount[]; get_volume_for_uuid(uuid: string): Volume; get_volumes(): Volume[]; vfunc_drive_changed(drive: Drive): void; vfunc_drive_connected(drive: Drive): void; vfunc_drive_disconnected(drive: Drive): void; vfunc_drive_eject_button(drive: Drive): void; vfunc_drive_stop_button(drive: Drive): void; vfunc_get_connected_drives(): Drive[]; vfunc_get_mount_for_uuid(uuid: string): Mount; vfunc_get_mounts(): Mount[]; vfunc_get_volume_for_uuid(uuid: string): Volume; vfunc_get_volumes(): Volume[]; vfunc_mount_added(mount: Mount): void; vfunc_mount_changed(mount: Mount): void; vfunc_mount_pre_unmount(mount: Mount): void; vfunc_mount_removed(mount: Mount): void; vfunc_volume_added(volume: Volume): void; vfunc_volume_changed(volume: Volume): void; vfunc_volume_removed(volume: Volume): void; static adopt_orphan_mount(mount: Mount): Volume; static get(): VolumeMonitor; } export module ZlibCompressor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; file_info: FileInfo; fileInfo: FileInfo; format: ZlibCompressorFormat; level: number; } } export class ZlibCompressor extends GObject.Object implements Converter { static $gtype: GObject.GType<ZlibCompressor>; constructor(properties?: Partial<ZlibCompressor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ZlibCompressor.ConstructorProperties>, ...args: any[]): void; // Properties file_info: FileInfo; fileInfo: FileInfo; format: ZlibCompressorFormat; level: number; // Constructors static ["new"](format: ZlibCompressorFormat, level: number): ZlibCompressor; // Members get_file_info(): FileInfo; set_file_info(file_info?: FileInfo | null): void; // Implemented Members convert( inbuf: Uint8Array | string, outbuf: Uint8Array | string, flags: ConverterFlags ): [ConverterResult, number, number]; reset(): void; vfunc_convert( inbuf: Uint8Array | null, outbuf: Uint8Array | null, flags: ConverterFlags ): [ConverterResult, number, number]; vfunc_reset(): void; } export module ZlibDecompressor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; file_info: FileInfo; fileInfo: FileInfo; format: ZlibCompressorFormat; } } export class ZlibDecompressor extends GObject.Object implements Converter { static $gtype: GObject.GType<ZlibDecompressor>; constructor(properties?: Partial<ZlibDecompressor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ZlibDecompressor.ConstructorProperties>, ...args: any[]): void; // Properties file_info: FileInfo; fileInfo: FileInfo; format: ZlibCompressorFormat; // Constructors static ["new"](format: ZlibCompressorFormat): ZlibDecompressor; // Members get_file_info(): FileInfo; // Implemented Members convert( inbuf: Uint8Array | string, outbuf: Uint8Array | string, flags: ConverterFlags ): [ConverterResult, number, number]; reset(): void; vfunc_convert( inbuf: Uint8Array | null, outbuf: Uint8Array | null, flags: ConverterFlags ): [ConverterResult, number, number]; vfunc_reset(): void; } export class ActionEntry { static $gtype: GObject.GType<ActionEntry>; constructor(copy: ActionEntry); // Fields name: string; parameter_type: string; state: string; padding: number[]; } export class AppLaunchContextPrivate { static $gtype: GObject.GType<AppLaunchContextPrivate>; constructor(copy: AppLaunchContextPrivate); } export class ApplicationCommandLinePrivate { static $gtype: GObject.GType<ApplicationCommandLinePrivate>; constructor(copy: ApplicationCommandLinePrivate); } export class ApplicationPrivate { static $gtype: GObject.GType<ApplicationPrivate>; constructor(copy: ApplicationPrivate); } export class BufferedInputStreamPrivate { static $gtype: GObject.GType<BufferedInputStreamPrivate>; constructor(copy: BufferedInputStreamPrivate); } export class BufferedOutputStreamPrivate { static $gtype: GObject.GType<BufferedOutputStreamPrivate>; constructor(copy: BufferedOutputStreamPrivate); } export class CancellablePrivate { static $gtype: GObject.GType<CancellablePrivate>; constructor(copy: CancellablePrivate); } export class ConverterInputStreamPrivate { static $gtype: GObject.GType<ConverterInputStreamPrivate>; constructor(copy: ConverterInputStreamPrivate); } export class ConverterOutputStreamPrivate { static $gtype: GObject.GType<ConverterOutputStreamPrivate>; constructor(copy: ConverterOutputStreamPrivate); } export class DBusAnnotationInfo { static $gtype: GObject.GType<DBusAnnotationInfo>; constructor(copy: DBusAnnotationInfo); // Fields ref_count: number; key: string; value: string; annotations: DBusAnnotationInfo[]; // Members ref(): DBusAnnotationInfo; unref(): void; static lookup(annotations: DBusAnnotationInfo[] | null, name: string): string; } export class DBusArgInfo { static $gtype: GObject.GType<DBusArgInfo>; constructor(copy: DBusArgInfo); // Fields ref_count: number; name: string; signature: string; annotations: DBusAnnotationInfo[]; // Members ref(): DBusArgInfo; unref(): void; } export class DBusErrorEntry { static $gtype: GObject.GType<DBusErrorEntry>; constructor( properties?: Partial<{ error_code?: number; dbus_error_name?: string; }> ); constructor(copy: DBusErrorEntry); // Fields error_code: number; dbus_error_name: string; } export class DBusInterfaceInfo { static $gtype: GObject.GType<DBusInterfaceInfo>; constructor(info: string); constructor(copy: DBusInterfaceInfo); // Fields ref_count: number; name: string; methods: DBusMethodInfo[]; signals: DBusSignalInfo[]; properties: DBusPropertyInfo[]; annotations: DBusAnnotationInfo[]; // Constructors static new_for_xml(info: string): DBusInterfaceInfo; // Members cache_build(): void; cache_release(): void; generate_xml(indent: number, string_builder: GLib.String): void; lookup_method(name: string): DBusMethodInfo; lookup_property(name: string): DBusPropertyInfo; lookup_signal(name: string): DBusSignalInfo; ref(): DBusInterfaceInfo; unref(): void; } export class DBusInterfaceSkeletonPrivate { static $gtype: GObject.GType<DBusInterfaceSkeletonPrivate>; constructor(copy: DBusInterfaceSkeletonPrivate); } export class DBusInterfaceVTable { static $gtype: GObject.GType<DBusInterfaceVTable>; constructor(copy: DBusInterfaceVTable); // Fields method_call: DBusInterfaceMethodCallFunc; get_property: DBusInterfaceGetPropertyFunc; set_property: DBusInterfaceSetPropertyFunc; padding: any[]; } export class DBusMethodInfo { static $gtype: GObject.GType<DBusMethodInfo>; constructor(copy: DBusMethodInfo); // Fields ref_count: number; name: string; in_args: DBusArgInfo[]; out_args: DBusArgInfo[]; annotations: DBusAnnotationInfo[]; // Members ref(): DBusMethodInfo; unref(): void; } export class DBusNodeInfo { static $gtype: GObject.GType<DBusNodeInfo>; constructor(xml_data: string); constructor(copy: DBusNodeInfo); // Fields ref_count: number; path: string; interfaces: DBusInterfaceInfo[]; nodes: DBusNodeInfo[]; annotations: DBusAnnotationInfo[]; // Constructors static new_for_xml(xml_data: string): DBusNodeInfo; static new_for_xml(info: string): DBusNodeInfo; // Members generate_xml(indent: number, string_builder: GLib.String): void; lookup_interface(name: string): DBusInterfaceInfo; ref(): DBusNodeInfo; unref(): void; } export class DBusObjectManagerClientPrivate { static $gtype: GObject.GType<DBusObjectManagerClientPrivate>; constructor(copy: DBusObjectManagerClientPrivate); } export class DBusObjectManagerServerPrivate { static $gtype: GObject.GType<DBusObjectManagerServerPrivate>; constructor(copy: DBusObjectManagerServerPrivate); } export class DBusObjectProxyPrivate { static $gtype: GObject.GType<DBusObjectProxyPrivate>; constructor(copy: DBusObjectProxyPrivate); } export class DBusObjectSkeletonPrivate { static $gtype: GObject.GType<DBusObjectSkeletonPrivate>; constructor(copy: DBusObjectSkeletonPrivate); } export class DBusPropertyInfo { static $gtype: GObject.GType<DBusPropertyInfo>; constructor(copy: DBusPropertyInfo); // Fields ref_count: number; name: string; signature: string; flags: DBusPropertyInfoFlags; annotations: DBusAnnotationInfo[]; // Members ref(): DBusPropertyInfo; unref(): void; } export class DBusProxyPrivate { static $gtype: GObject.GType<DBusProxyPrivate>; constructor(copy: DBusProxyPrivate); } export class DBusSignalInfo { static $gtype: GObject.GType<DBusSignalInfo>; constructor(copy: DBusSignalInfo); // Fields ref_count: number; name: string; args: DBusArgInfo[]; annotations: DBusAnnotationInfo[]; // Members ref(): DBusSignalInfo; unref(): void; } export class DBusSubtreeVTable { static $gtype: GObject.GType<DBusSubtreeVTable>; constructor(copy: DBusSubtreeVTable); // Fields introspect: DBusSubtreeIntrospectFunc; dispatch: DBusSubtreeDispatchFunc; padding: any[]; } export class DataInputStreamPrivate { static $gtype: GObject.GType<DataInputStreamPrivate>; constructor(copy: DataInputStreamPrivate); } export class DataOutputStreamPrivate { static $gtype: GObject.GType<DataOutputStreamPrivate>; constructor(copy: DataOutputStreamPrivate); } export class EmblemedIconPrivate { static $gtype: GObject.GType<EmblemedIconPrivate>; constructor(copy: EmblemedIconPrivate); } export class FileAttributeInfo { static $gtype: GObject.GType<FileAttributeInfo>; constructor(copy: FileAttributeInfo); // Fields name: string; type: FileAttributeType; flags: FileAttributeInfoFlags; } export class FileAttributeInfoList { static $gtype: GObject.GType<FileAttributeInfoList>; constructor(); constructor(copy: FileAttributeInfoList); // Fields infos: FileAttributeInfo; n_infos: number; // Constructors static ["new"](): FileAttributeInfoList; // Members add(name: string, type: FileAttributeType, flags: FileAttributeInfoFlags): void; dup(): FileAttributeInfoList; lookup(name: string): FileAttributeInfo; ref(): FileAttributeInfoList; unref(): void; } export class FileAttributeMatcher { static $gtype: GObject.GType<FileAttributeMatcher>; constructor(attributes: string); constructor(copy: FileAttributeMatcher); // Constructors static ["new"](attributes: string): FileAttributeMatcher; // Members enumerate_namespace(ns: string): boolean; enumerate_next(): string | null; matches(attribute: string): boolean; matches_only(attribute: string): boolean; ref(): FileAttributeMatcher; subtract(subtract: FileAttributeMatcher): FileAttributeMatcher; to_string(): string; unref(): void; } export class FileEnumeratorPrivate { static $gtype: GObject.GType<FileEnumeratorPrivate>; constructor(copy: FileEnumeratorPrivate); } export class FileIOStreamPrivate { static $gtype: GObject.GType<FileIOStreamPrivate>; constructor(copy: FileIOStreamPrivate); } export class FileInputStreamPrivate { static $gtype: GObject.GType<FileInputStreamPrivate>; constructor(copy: FileInputStreamPrivate); } export class FileMonitorPrivate { static $gtype: GObject.GType<FileMonitorPrivate>; constructor(copy: FileMonitorPrivate); } export class FileOutputStreamPrivate { static $gtype: GObject.GType<FileOutputStreamPrivate>; constructor(copy: FileOutputStreamPrivate); } export class IOExtension { static $gtype: GObject.GType<IOExtension>; constructor(copy: IOExtension); // Members get_name(): string; get_priority(): number; get_type(): GObject.GType; } export class IOExtensionPoint { static $gtype: GObject.GType<IOExtensionPoint>; constructor(copy: IOExtensionPoint); // Members get_extension_by_name(name: string): IOExtension; get_extensions(): IOExtension[]; get_required_type(): GObject.GType; set_required_type(type: GObject.GType): void; static implement( extension_point_name: string, type: GObject.GType, extension_name: string, priority: number ): IOExtension; static lookup(name: string): IOExtensionPoint; static register(name: string): IOExtensionPoint; } export class IOModuleScope { static $gtype: GObject.GType<IOModuleScope>; constructor(copy: IOModuleScope); // Members block(basename: string): void; free(): void; } export class IOSchedulerJob { static $gtype: GObject.GType<IOSchedulerJob>; constructor(copy: IOSchedulerJob); // Members send_to_mainloop(func: GLib.SourceFunc, notify?: GLib.DestroyNotify | null): boolean; send_to_mainloop_async(func: GLib.SourceFunc, notify?: GLib.DestroyNotify | null): void; } export class IOStreamAdapter { static $gtype: GObject.GType<IOStreamAdapter>; constructor(copy: IOStreamAdapter); } export class IOStreamPrivate { static $gtype: GObject.GType<IOStreamPrivate>; constructor(copy: IOStreamPrivate); } export class InetAddressMaskPrivate { static $gtype: GObject.GType<InetAddressMaskPrivate>; constructor(copy: InetAddressMaskPrivate); } export class InetAddressPrivate { static $gtype: GObject.GType<InetAddressPrivate>; constructor(copy: InetAddressPrivate); } export class InetSocketAddressPrivate { static $gtype: GObject.GType<InetSocketAddressPrivate>; constructor(copy: InetSocketAddressPrivate); } export class InputMessage { static $gtype: GObject.GType<InputMessage>; constructor(copy: InputMessage); // Fields address: SocketAddress; vectors: InputVector[]; num_vectors: number; bytes_received: number; flags: number; control_messages: SocketControlMessage[]; num_control_messages: number; } export class InputStreamPrivate { static $gtype: GObject.GType<InputStreamPrivate>; constructor(copy: InputStreamPrivate); } export class InputVector { static $gtype: GObject.GType<InputVector>; constructor( properties?: Partial<{ buffer?: any; size?: number; }> ); constructor(copy: InputVector); // Fields buffer: any; size: number; } export class MemoryInputStreamPrivate { static $gtype: GObject.GType<MemoryInputStreamPrivate>; constructor(copy: MemoryInputStreamPrivate); } export class MemoryOutputStreamPrivate { static $gtype: GObject.GType<MemoryOutputStreamPrivate>; constructor(copy: MemoryOutputStreamPrivate); } export class MenuAttributeIterPrivate { static $gtype: GObject.GType<MenuAttributeIterPrivate>; constructor(copy: MenuAttributeIterPrivate); } export class MenuLinkIterPrivate { static $gtype: GObject.GType<MenuLinkIterPrivate>; constructor(copy: MenuLinkIterPrivate); } export class MenuModelPrivate { static $gtype: GObject.GType<MenuModelPrivate>; constructor(copy: MenuModelPrivate); } export class MountOperationPrivate { static $gtype: GObject.GType<MountOperationPrivate>; constructor(copy: MountOperationPrivate); } export class NativeSocketAddressPrivate { static $gtype: GObject.GType<NativeSocketAddressPrivate>; constructor(copy: NativeSocketAddressPrivate); } export class NetworkAddressPrivate { static $gtype: GObject.GType<NetworkAddressPrivate>; constructor(copy: NetworkAddressPrivate); } export class NetworkServicePrivate { static $gtype: GObject.GType<NetworkServicePrivate>; constructor(copy: NetworkServicePrivate); } export class OutputMessage { static $gtype: GObject.GType<OutputMessage>; constructor(copy: OutputMessage); // Fields address: SocketAddress; vectors: OutputVector; num_vectors: number; bytes_sent: number; control_messages: SocketControlMessage[]; num_control_messages: number; } export class OutputStreamPrivate { static $gtype: GObject.GType<OutputStreamPrivate>; constructor(copy: OutputStreamPrivate); } export class OutputVector { static $gtype: GObject.GType<OutputVector>; constructor( properties?: Partial<{ buffer?: any; size?: number; }> ); constructor(copy: OutputVector); // Fields buffer: any; size: number; } export class PermissionPrivate { static $gtype: GObject.GType<PermissionPrivate>; constructor(copy: PermissionPrivate); } export class ProxyAddressEnumeratorPrivate { static $gtype: GObject.GType<ProxyAddressEnumeratorPrivate>; constructor(copy: ProxyAddressEnumeratorPrivate); } export class ProxyAddressPrivate { static $gtype: GObject.GType<ProxyAddressPrivate>; constructor(copy: ProxyAddressPrivate); } export class ResolverPrivate { static $gtype: GObject.GType<ResolverPrivate>; constructor(copy: ResolverPrivate); } export class Resource { static $gtype: GObject.GType<Resource>; constructor(data: GLib.Bytes | Uint8Array); constructor(copy: Resource); // Constructors static new_from_data(data: GLib.Bytes | Uint8Array): Resource; // Members _register(): void; _unregister(): void; enumerate_children(path: string, lookup_flags: ResourceLookupFlags): string[]; get_info(path: string, lookup_flags: ResourceLookupFlags): [boolean, number | null, number | null]; lookup_data(path: string, lookup_flags: ResourceLookupFlags): GLib.Bytes; open_stream(path: string, lookup_flags: ResourceLookupFlags): InputStream; ref(): Resource; unref(): void; static load(filename: string): Resource; } export class SettingsBackendPrivate { static $gtype: GObject.GType<SettingsBackendPrivate>; constructor(copy: SettingsBackendPrivate); } export class SettingsPrivate { static $gtype: GObject.GType<SettingsPrivate>; constructor(copy: SettingsPrivate); } export class SettingsSchema { static $gtype: GObject.GType<SettingsSchema>; constructor(properties?: Partial<{}>); constructor(copy: SettingsSchema); // Fields _realGetKey: typeof SettingsSchema.prototype.get_key; // Members get_id(): string; get_key(name: string): SettingsSchemaKey; get_path(): string; has_key(name: string): boolean; list_children(): string[]; list_keys(): string[]; ref(): SettingsSchema; unref(): void; } export class SettingsSchemaKey { static $gtype: GObject.GType<SettingsSchemaKey>; constructor(copy: SettingsSchemaKey); // Members get_default_value(): GLib.Variant; get_description(): string; get_name(): string; get_range(): GLib.Variant; get_summary(): string; get_value_type(): GLib.VariantType; range_check(value: GLib.Variant): boolean; ref(): SettingsSchemaKey; unref(): void; } export class SettingsSchemaSource { static $gtype: GObject.GType<SettingsSchemaSource>; constructor(directory: string, parent: SettingsSchemaSource | null, trusted: boolean); constructor(copy: SettingsSchemaSource); // Constructors static new_from_directory( directory: string, parent: SettingsSchemaSource | null, trusted: boolean ): SettingsSchemaSource; // Members list_schemas(recursive: boolean): [string[], string[]]; lookup(schema_id: string, recursive: boolean): SettingsSchema | null; ref(): SettingsSchemaSource; unref(): void; static get_default(): SettingsSchemaSource | null; } export class SimpleActionGroupPrivate { static $gtype: GObject.GType<SimpleActionGroupPrivate>; constructor(copy: SimpleActionGroupPrivate); } export class SimpleProxyResolverPrivate { static $gtype: GObject.GType<SimpleProxyResolverPrivate>; constructor(copy: SimpleProxyResolverPrivate); } export class SocketClientPrivate { static $gtype: GObject.GType<SocketClientPrivate>; constructor(copy: SocketClientPrivate); } export class SocketConnectionPrivate { static $gtype: GObject.GType<SocketConnectionPrivate>; constructor(copy: SocketConnectionPrivate); } export class SocketControlMessagePrivate { static $gtype: GObject.GType<SocketControlMessagePrivate>; constructor(copy: SocketControlMessagePrivate); } export class SocketListenerPrivate { static $gtype: GObject.GType<SocketListenerPrivate>; constructor(copy: SocketListenerPrivate); } export class SocketPrivate { static $gtype: GObject.GType<SocketPrivate>; constructor(copy: SocketPrivate); } export class SocketServicePrivate { static $gtype: GObject.GType<SocketServicePrivate>; constructor(copy: SocketServicePrivate); } export class SrvTarget { static $gtype: GObject.GType<SrvTarget>; constructor(hostname: string, port: number, priority: number, weight: number); constructor(copy: SrvTarget); // Constructors static ["new"](hostname: string, port: number, priority: number, weight: number): SrvTarget; // Members copy(): SrvTarget; free(): void; get_hostname(): string; get_port(): number; get_priority(): number; get_weight(): number; } export class StaticResource { static $gtype: GObject.GType<StaticResource>; constructor(copy: StaticResource); // Fields data: number; data_len: number; resource: Resource; next: StaticResource; padding: any; // Members fini(): void; get_resource(): Resource; init(): void; } export class TcpConnectionPrivate { static $gtype: GObject.GType<TcpConnectionPrivate>; constructor(copy: TcpConnectionPrivate); } export class TcpWrapperConnectionPrivate { static $gtype: GObject.GType<TcpWrapperConnectionPrivate>; constructor(copy: TcpWrapperConnectionPrivate); } export class ThreadedSocketServicePrivate { static $gtype: GObject.GType<ThreadedSocketServicePrivate>; constructor(copy: ThreadedSocketServicePrivate); } export class TlsCertificatePrivate { static $gtype: GObject.GType<TlsCertificatePrivate>; constructor(copy: TlsCertificatePrivate); } export class TlsConnectionPrivate { static $gtype: GObject.GType<TlsConnectionPrivate>; constructor(copy: TlsConnectionPrivate); } export class TlsDatabasePrivate { static $gtype: GObject.GType<TlsDatabasePrivate>; constructor(copy: TlsDatabasePrivate); } export class TlsInteractionPrivate { static $gtype: GObject.GType<TlsInteractionPrivate>; constructor(copy: TlsInteractionPrivate); } export class TlsPasswordPrivate { static $gtype: GObject.GType<TlsPasswordPrivate>; constructor(copy: TlsPasswordPrivate); } export class UnixConnectionPrivate { static $gtype: GObject.GType<UnixConnectionPrivate>; constructor(copy: UnixConnectionPrivate); } export class UnixCredentialsMessagePrivate { static $gtype: GObject.GType<UnixCredentialsMessagePrivate>; constructor(copy: UnixCredentialsMessagePrivate); } export class UnixFDListPrivate { static $gtype: GObject.GType<UnixFDListPrivate>; constructor(copy: UnixFDListPrivate); } export class UnixFDMessagePrivate { static $gtype: GObject.GType<UnixFDMessagePrivate>; constructor(copy: UnixFDMessagePrivate); } export class UnixInputStreamPrivate { static $gtype: GObject.GType<UnixInputStreamPrivate>; constructor(copy: UnixInputStreamPrivate); } export class UnixMountEntry { static $gtype: GObject.GType<UnixMountEntry>; constructor(copy: UnixMountEntry); } export class UnixMountPoint { static $gtype: GObject.GType<UnixMountPoint>; constructor(copy: UnixMountPoint); // Members compare(mount2: UnixMountPoint): number; copy(): UnixMountPoint; free(): void; get_device_path(): string; get_fs_type(): string; get_mount_path(): string; get_options(): string; guess_can_eject(): boolean; guess_icon(): Icon; guess_name(): string; guess_symbolic_icon(): Icon; is_loopback(): boolean; is_readonly(): boolean; is_user_mountable(): boolean; static at(mount_path: string): [UnixMountPoint | null, number | null]; } export class UnixOutputStreamPrivate { static $gtype: GObject.GType<UnixOutputStreamPrivate>; constructor(copy: UnixOutputStreamPrivate); } export class UnixSocketAddressPrivate { static $gtype: GObject.GType<UnixSocketAddressPrivate>; constructor(copy: UnixSocketAddressPrivate); } export interface ActionNamespace { $gtype: GObject.GType<Action>; prototype: ActionPrototype; name_is_valid(action_name: string): boolean; parse_detailed_name(detailed_name: string): [boolean, string, GLib.Variant]; print_detailed_name(action_name: string, target_value?: GLib.Variant | null): string; } export type Action = ActionPrototype; export interface ActionPrototype extends GObject.Object { // Properties enabled: boolean; name: string; parameter_type: GLib.VariantType; parameterType: GLib.VariantType; state: GLib.Variant; state_type: GLib.VariantType; stateType: GLib.VariantType; // Members activate(parameter?: GLib.Variant | null): void; change_state(value: GLib.Variant): void; get_enabled(): boolean; get_name(): string; get_parameter_type(): GLib.VariantType | null; get_state(): GLib.Variant; get_state_hint(): GLib.Variant | null; get_state_type(): GLib.VariantType | null; vfunc_activate(parameter?: GLib.Variant | null): void; vfunc_change_state(value: GLib.Variant): void; vfunc_get_enabled(): boolean; vfunc_get_name(): string; vfunc_get_parameter_type(): GLib.VariantType | null; vfunc_get_state(): GLib.Variant; vfunc_get_state_hint(): GLib.Variant | null; vfunc_get_state_type(): GLib.VariantType | null; } export const Action: ActionNamespace; export interface ActionGroupNamespace { $gtype: GObject.GType<ActionGroup>; prototype: ActionGroupPrototype; } export type ActionGroup = ActionGroupPrototype; export interface ActionGroupPrototype extends GObject.Object { // Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action(action_name: string, parameter?: GLib.Variant | null): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type(action_name: string): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null]; } export const ActionGroup: ActionGroupNamespace; export interface ActionMapNamespace { $gtype: GObject.GType<ActionMap>; prototype: ActionMapPrototype; } export type ActionMap = ActionMapPrototype; export interface ActionMapPrototype extends GObject.Object { // Members add_action(action: Action): void; add_action_entries(entries: ActionEntry[], user_data?: any | null): void; lookup_action(action_name: string): Action; remove_action(action_name: string): void; vfunc_add_action(action: Action): void; vfunc_lookup_action(action_name: string): Action; vfunc_remove_action(action_name: string): void; } export const ActionMap: ActionMapNamespace; export interface AppInfoNamespace { $gtype: GObject.GType<AppInfo>; prototype: AppInfoPrototype; create_from_commandline(commandline: string, application_name: string | null, flags: AppInfoCreateFlags): AppInfo; get_all(): AppInfo[]; get_all_for_type(content_type: string): AppInfo[]; get_default_for_type(content_type: string, must_support_uris: boolean): AppInfo | null; get_default_for_uri_scheme(uri_scheme: string): AppInfo | null; get_fallback_for_type(content_type: string): AppInfo[]; get_recommended_for_type(content_type: string): AppInfo[]; launch_default_for_uri(uri: string, context?: AppLaunchContext | null): boolean; launch_default_for_uri_async( uri: string, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; launch_default_for_uri_async( uri: string, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<AppInfo> | null ): void; launch_default_for_uri_async( uri: string, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<AppInfo> | null ): Promise<boolean> | void; launch_default_for_uri_finish(result: AsyncResult): boolean; reset_type_associations(content_type: string): void; } export type AppInfo = AppInfoPrototype; export interface AppInfoPrototype extends GObject.Object { // Members add_supports_type(content_type: string): boolean; can_delete(): boolean; can_remove_supports_type(): boolean; ["delete"](): boolean; dup(): AppInfo; equal(appinfo2: AppInfo): boolean; get_commandline(): string; get_description(): string; get_display_name(): string; get_executable(): string; get_icon(): Icon; get_id(): string; get_name(): string; get_supported_types(): string[]; launch(files?: File[] | null, context?: AppLaunchContext | null): boolean; launch_uris(uris?: string[] | null, context?: AppLaunchContext | null): boolean; launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; launch_uris_async( uris: string[] | null, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; launch_uris_finish(result: AsyncResult): boolean; remove_supports_type(content_type: string): boolean; set_as_default_for_extension(extension: string): boolean; set_as_default_for_type(content_type: string): boolean; set_as_last_used_for_type(content_type: string): boolean; should_show(): boolean; supports_files(): boolean; supports_uris(): boolean; vfunc_add_supports_type(content_type: string): boolean; vfunc_can_delete(): boolean; vfunc_can_remove_supports_type(): boolean; vfunc_do_delete(): boolean; vfunc_dup(): AppInfo; vfunc_equal(appinfo2: AppInfo): boolean; vfunc_get_commandline(): string; vfunc_get_description(): string; vfunc_get_display_name(): string; vfunc_get_executable(): string; vfunc_get_icon(): Icon; vfunc_get_id(): string; vfunc_get_name(): string; vfunc_get_supported_types(): string[]; vfunc_launch(files?: File[] | null, context?: AppLaunchContext | null): boolean; vfunc_launch_uris(uris?: string[] | null, context?: AppLaunchContext | null): boolean; vfunc_launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_launch_uris_async( uris: string[] | null, context: AppLaunchContext | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_launch_uris_async( uris?: string[] | null, context?: AppLaunchContext | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_launch_uris_finish(result: AsyncResult): boolean; vfunc_remove_supports_type(content_type: string): boolean; vfunc_set_as_default_for_extension(extension: string): boolean; vfunc_set_as_default_for_type(content_type: string): boolean; vfunc_set_as_last_used_for_type(content_type: string): boolean; vfunc_should_show(): boolean; vfunc_supports_files(): boolean; vfunc_supports_uris(): boolean; } export const AppInfo: AppInfoNamespace; export interface AsyncInitableNamespace { $gtype: GObject.GType<AsyncInitable>; prototype: AsyncInitablePrototype; newv_async( object_type: GObject.GType, n_parameters: number, parameters: GObject.Parameter, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<AsyncInitable> | null ): void; } export type AsyncInitable<A extends GObject.Object = GObject.Object> = AsyncInitablePrototype<A>; export interface AsyncInitablePrototype<A extends GObject.Object = GObject.Object> extends GObject.Object { // Members init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; init_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: AsyncResult): boolean; new_finish(res: AsyncResult): A; vfunc_init_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: AsyncResult): boolean; } export const AsyncInitable: AsyncInitableNamespace; export interface AsyncResultNamespace { $gtype: GObject.GType<AsyncResult>; prototype: AsyncResultPrototype; } export type AsyncResult = AsyncResultPrototype; export interface AsyncResultPrototype extends GObject.Object { // Members get_source_object<T = GObject.Object>(): T; get_user_data(): any | null; is_tagged(source_tag?: any | null): boolean; legacy_propagate_error(): boolean; vfunc_get_source_object<T = GObject.Object>(): T; vfunc_get_user_data(): any | null; vfunc_is_tagged(source_tag?: any | null): boolean; } export const AsyncResult: AsyncResultNamespace; export interface ConverterNamespace { $gtype: GObject.GType<Converter>; prototype: ConverterPrototype; } export type Converter = ConverterPrototype; export interface ConverterPrototype extends GObject.Object { // Members convert( inbuf: Uint8Array | string, outbuf: Uint8Array | string, flags: ConverterFlags ): [ConverterResult, number, number]; reset(): void; vfunc_convert( inbuf: Uint8Array | null, outbuf: Uint8Array | null, flags: ConverterFlags ): [ConverterResult, number, number]; vfunc_reset(): void; } export const Converter: ConverterNamespace; export interface DBusInterfaceNamespace { $gtype: GObject.GType<DBusInterface>; prototype: DBusInterfacePrototype; } export type DBusInterface = DBusInterfacePrototype; export interface DBusInterfacePrototype extends GObject.Object { // Members get_object(): DBusObject; get_info(): DBusInterfaceInfo; set_object(object?: DBusObject | null): void; vfunc_dup_object(): DBusObject; vfunc_get_info(): DBusInterfaceInfo; vfunc_set_object(object?: DBusObject | null): void; } export const DBusInterface: DBusInterfaceNamespace; export interface DBusObjectNamespace { $gtype: GObject.GType<DBusObject>; prototype: DBusObjectPrototype; } export type DBusObject = DBusObjectPrototype; export interface DBusObjectPrototype extends GObject.Object { // Members get_interface(interface_name: string): DBusInterface; get_interfaces(): DBusInterface[]; get_object_path(): string; vfunc_get_interface(interface_name: string): DBusInterface; vfunc_get_interfaces(): DBusInterface[]; vfunc_get_object_path(): string; vfunc_interface_added(interface_: DBusInterface): void; vfunc_interface_removed(interface_: DBusInterface): void; } export const DBusObject: DBusObjectNamespace; export interface DBusObjectManagerNamespace { $gtype: GObject.GType<DBusObjectManager>; prototype: DBusObjectManagerPrototype; } export type DBusObjectManager = DBusObjectManagerPrototype; export interface DBusObjectManagerPrototype extends GObject.Object { // Members get_interface(object_path: string, interface_name: string): DBusInterface; get_object(object_path: string): DBusObject; get_object_path(): string; get_objects(): DBusObject[]; vfunc_get_interface(object_path: string, interface_name: string): DBusInterface; vfunc_get_object(object_path: string): DBusObject; vfunc_get_object_path(): string; vfunc_get_objects(): DBusObject[]; vfunc_interface_added(object: DBusObject, interface_: DBusInterface): void; vfunc_interface_removed(object: DBusObject, interface_: DBusInterface): void; vfunc_object_added(object: DBusObject): void; vfunc_object_removed(object: DBusObject): void; } export const DBusObjectManager: DBusObjectManagerNamespace; export interface DatagramBasedNamespace { $gtype: GObject.GType<DatagramBased>; prototype: DatagramBasedPrototype; } export type DatagramBased = DatagramBasedPrototype; export interface DatagramBasedPrototype extends GObject.Object { // Members condition_check(condition: GLib.IOCondition): GLib.IOCondition; condition_wait(condition: GLib.IOCondition, timeout: number, cancellable?: Cancellable | null): boolean; create_source(condition: GLib.IOCondition, cancellable?: Cancellable | null): GLib.Source; receive_messages( messages: InputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null ): number; send_messages(messages: OutputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null): number; vfunc_condition_check(condition: GLib.IOCondition): GLib.IOCondition; vfunc_condition_wait(condition: GLib.IOCondition, timeout: number, cancellable?: Cancellable | null): boolean; vfunc_create_source(condition: GLib.IOCondition, cancellable?: Cancellable | null): GLib.Source; vfunc_receive_messages( messages: InputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null ): number; vfunc_send_messages( messages: OutputMessage[], flags: number, timeout: number, cancellable?: Cancellable | null ): number; } export const DatagramBased: DatagramBasedNamespace; export interface DesktopAppInfoLookupNamespace { $gtype: GObject.GType<DesktopAppInfoLookup>; prototype: DesktopAppInfoLookupPrototype; } export type DesktopAppInfoLookup = DesktopAppInfoLookupPrototype; export interface DesktopAppInfoLookupPrototype extends GObject.Object { // Members get_default_for_uri_scheme(uri_scheme: string): AppInfo | null; vfunc_get_default_for_uri_scheme(uri_scheme: string): AppInfo | null; } export const DesktopAppInfoLookup: DesktopAppInfoLookupNamespace; export interface DriveNamespace { $gtype: GObject.GType<Drive>; prototype: DrivePrototype; } export type Drive = DrivePrototype; export interface DrivePrototype extends GObject.Object { // Members can_eject(): boolean; can_poll_for_media(): boolean; can_start(): boolean; can_start_degraded(): boolean; can_stop(): boolean; eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; eject(flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_finish(result: AsyncResult): boolean; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_with_operation_finish(result: AsyncResult): boolean; enumerate_identifiers(): string[]; get_icon(): Icon; get_identifier(kind: string): string | null; get_name(): string; get_sort_key(): string | null; get_start_stop_type(): DriveStartStopType; get_symbolic_icon(): Icon; get_volumes(): Volume[]; has_media(): boolean; has_volumes(): boolean; is_media_check_automatic(): boolean; is_media_removable(): boolean; is_removable(): boolean; poll_for_media(cancellable?: Cancellable | null): Promise<boolean>; poll_for_media(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; poll_for_media( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; poll_for_media_finish(result: AsyncResult): boolean; start( flags: DriveStartFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; start( flags: DriveStartFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; start( flags: DriveStartFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; start_finish(result: AsyncResult): boolean; stop( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; stop( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; stop( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; stop_finish(result: AsyncResult): boolean; vfunc_can_eject(): boolean; vfunc_can_poll_for_media(): boolean; vfunc_can_start(): boolean; vfunc_can_start_degraded(): boolean; vfunc_can_stop(): boolean; vfunc_changed(): void; vfunc_disconnected(): void; vfunc_eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_eject( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_button(): void; vfunc_eject_finish(result: AsyncResult): boolean; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_with_operation_finish(result: AsyncResult): boolean; vfunc_enumerate_identifiers(): string[]; vfunc_get_icon(): Icon; vfunc_get_identifier(kind: string): string | null; vfunc_get_name(): string; vfunc_get_sort_key(): string | null; vfunc_get_start_stop_type(): DriveStartStopType; vfunc_get_symbolic_icon(): Icon; vfunc_get_volumes(): Volume[]; vfunc_has_media(): boolean; vfunc_has_volumes(): boolean; vfunc_is_media_check_automatic(): boolean; vfunc_is_media_removable(): boolean; vfunc_is_removable(): boolean; vfunc_poll_for_media(cancellable?: Cancellable | null): Promise<boolean>; vfunc_poll_for_media(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_poll_for_media( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_poll_for_media_finish(result: AsyncResult): boolean; vfunc_start( flags: DriveStartFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_start( flags: DriveStartFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_start( flags: DriveStartFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_start_finish(result: AsyncResult): boolean; vfunc_stop( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_stop( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_stop( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_stop_button(): void; vfunc_stop_finish(result: AsyncResult): boolean; } export const Drive: DriveNamespace; export interface DtlsClientConnectionNamespace { $gtype: GObject.GType<DtlsClientConnection>; prototype: DtlsClientConnectionPrototype; ["new"](base_socket: DatagramBased, server_identity?: SocketConnectable | null): DtlsClientConnection; } export type DtlsClientConnection = DtlsClientConnectionPrototype; export interface DtlsClientConnectionPrototype extends DatagramBased { // Properties accepted_cas: any[]; acceptedCas: any[]; server_identity: SocketConnectable; serverIdentity: SocketConnectable; validation_flags: TlsCertificateFlags; validationFlags: TlsCertificateFlags; // Members get_accepted_cas(): GLib.List; get_server_identity(): SocketConnectable; get_validation_flags(): TlsCertificateFlags; set_server_identity(identity: SocketConnectable): void; set_validation_flags(flags: TlsCertificateFlags): void; } export const DtlsClientConnection: DtlsClientConnectionNamespace; export interface DtlsConnectionNamespace { $gtype: GObject.GType<DtlsConnection>; prototype: DtlsConnectionPrototype; } export type DtlsConnection = DtlsConnectionPrototype; export interface DtlsConnectionPrototype extends DatagramBased { // Properties advertised_protocols: string[]; advertisedProtocols: string[]; base_socket: DatagramBased; baseSocket: DatagramBased; certificate: TlsCertificate; database: TlsDatabase; interaction: TlsInteraction; negotiated_protocol: string; negotiatedProtocol: string; peer_certificate: TlsCertificate; peerCertificate: TlsCertificate; peer_certificate_errors: TlsCertificateFlags; peerCertificateErrors: TlsCertificateFlags; rehandshake_mode: TlsRehandshakeMode; rehandshakeMode: TlsRehandshakeMode; require_close_notify: boolean; requireCloseNotify: boolean; // Members close(cancellable?: Cancellable | null): boolean; close_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; close_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; close_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; close_finish(result: AsyncResult): boolean; emit_accept_certificate(peer_cert: TlsCertificate, errors: TlsCertificateFlags): boolean; get_certificate(): TlsCertificate | null; get_channel_binding_data(type: TlsChannelBindingType): [boolean, Uint8Array | null]; get_database(): TlsDatabase | null; get_interaction(): TlsInteraction | null; get_negotiated_protocol(): string | null; get_peer_certificate(): TlsCertificate | null; get_peer_certificate_errors(): TlsCertificateFlags; get_rehandshake_mode(): TlsRehandshakeMode; get_require_close_notify(): boolean; handshake(cancellable?: Cancellable | null): boolean; handshake_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; handshake_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; handshake_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; handshake_finish(result: AsyncResult): boolean; set_advertised_protocols(protocols?: string[] | null): void; set_certificate(certificate: TlsCertificate): void; set_database(database?: TlsDatabase | null): void; set_interaction(interaction?: TlsInteraction | null): void; set_rehandshake_mode(mode: TlsRehandshakeMode): void; set_require_close_notify(require_close_notify: boolean): void; shutdown(shutdown_read: boolean, shutdown_write: boolean, cancellable?: Cancellable | null): boolean; shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable?: Cancellable | null ): Promise<boolean>; shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; shutdown_finish(result: AsyncResult): boolean; vfunc_accept_certificate(peer_cert: TlsCertificate, errors: TlsCertificateFlags): boolean; vfunc_get_binding_data(type: TlsChannelBindingType, data: Uint8Array | string): boolean; vfunc_get_negotiated_protocol(): string | null; vfunc_handshake(cancellable?: Cancellable | null): boolean; vfunc_handshake_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_handshake_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_handshake_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_handshake_finish(result: AsyncResult): boolean; vfunc_set_advertised_protocols(protocols?: string[] | null): void; vfunc_shutdown(shutdown_read: boolean, shutdown_write: boolean, cancellable?: Cancellable | null): boolean; vfunc_shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_shutdown_async( shutdown_read: boolean, shutdown_write: boolean, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_shutdown_finish(result: AsyncResult): boolean; } export const DtlsConnection: DtlsConnectionNamespace; export interface DtlsServerConnectionNamespace { $gtype: GObject.GType<DtlsServerConnection>; prototype: DtlsServerConnectionPrototype; ["new"](base_socket: DatagramBased, certificate?: TlsCertificate | null): DtlsServerConnection; } export type DtlsServerConnection = DtlsServerConnectionPrototype; export interface DtlsServerConnectionPrototype extends DatagramBased { // Properties authentication_mode: TlsAuthenticationMode; authenticationMode: TlsAuthenticationMode; } export const DtlsServerConnection: DtlsServerConnectionNamespace; export interface FileNamespace { $gtype: GObject.GType<File>; prototype: FilePrototype; new_for_commandline_arg(arg: string): File; new_for_commandline_arg_and_cwd(arg: string, cwd: string): File; new_for_path(path: string): File; new_for_uri(uri: string): File; new_tmp(tmpl: string | null): [File, FileIOStream]; parse_name(parse_name: string): File; } export type File = FilePrototype; export interface FilePrototype extends GObject.Object { // Members append_to(flags: FileCreateFlags, cancellable?: Cancellable | null): FileOutputStream; append_to_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; append_to_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; append_to_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; append_to_finish(res: AsyncResult): FileOutputStream; copy( destination: File, flags: FileCopyFlags, cancellable?: Cancellable | null, progress_callback?: FileProgressCallback | null ): boolean; copy_async(destination: File, flags: FileCopyFlags, io_priority: number, cancellable?: Cancellable | null): void; copy_attributes(destination: File, flags: FileCopyFlags, cancellable?: Cancellable | null): boolean; copy_finish(res: AsyncResult): boolean; create(flags: FileCreateFlags, cancellable?: Cancellable | null): FileOutputStream; create_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; create_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; create_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; create_finish(res: AsyncResult): FileOutputStream; create_readwrite(flags: FileCreateFlags, cancellable?: Cancellable | null): FileIOStream; create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileIOStream>; create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; create_readwrite_finish(res: AsyncResult): FileIOStream; ["delete"](cancellable?: Cancellable | null): boolean; delete_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; delete_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; delete_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; delete_finish(result: AsyncResult): boolean; dup(): File; eject_mountable(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; eject_mountable( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; eject_mountable( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_mountable_finish(result: AsyncResult): boolean; eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_mountable_with_operation_finish(result: AsyncResult): boolean; enumerate_children(attributes: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null): FileEnumerator; enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileEnumerator>; enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileEnumerator> | void; enumerate_children_finish(res: AsyncResult): FileEnumerator; equal(file2: File): boolean; find_enclosing_mount(cancellable?: Cancellable | null): Mount; find_enclosing_mount_async(io_priority: number, cancellable?: Cancellable | null): Promise<Mount>; find_enclosing_mount_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; find_enclosing_mount_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<Mount> | void; find_enclosing_mount_finish(res: AsyncResult): Mount; get_basename(): string | null; get_child(name: string): File; get_child_for_display_name(display_name: string): File; get_parent(): File | null; get_parse_name(): string; get_path(): string | null; get_relative_path(descendant: File): string | null; get_uri(): string; get_uri_scheme(): string; has_parent(parent?: File | null): boolean; has_prefix(prefix: File): boolean; has_uri_scheme(uri_scheme: string): boolean; hash(): number; is_native(): boolean; load_bytes(cancellable?: Cancellable | null): [GLib.Bytes, string | null]; load_bytes_async(cancellable?: Cancellable | null): Promise<[GLib.Bytes, string | null]>; load_bytes_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; load_bytes_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[GLib.Bytes, string | null]> | void; load_bytes_finish(result: AsyncResult): [GLib.Bytes, string | null]; load_contents(cancellable: Cancellable | null): [boolean, Uint8Array, string | null]; load_contents_async(cancellable?: Cancellable | null): Promise<[Uint8Array, string | null]>; load_contents_async(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; load_contents_async( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[Uint8Array, string | null]> | void; load_contents_finish(res: AsyncResult): [boolean, Uint8Array, string | null]; load_partial_contents_finish(res: AsyncResult): [boolean, Uint8Array, string | null]; make_directory(cancellable?: Cancellable | null): boolean; make_directory_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; make_directory_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; make_directory_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; make_directory_finish(result: AsyncResult): boolean; make_directory_with_parents(cancellable?: Cancellable | null): boolean; make_symbolic_link(symlink_value: string, cancellable?: Cancellable | null): boolean; measure_disk_usage_finish(result: AsyncResult): [boolean, number | null, number | null, number | null]; monitor(flags: FileMonitorFlags, cancellable?: Cancellable | null): FileMonitor; monitor_directory(flags: FileMonitorFlags, cancellable?: Cancellable | null): FileMonitor; monitor_file(flags: FileMonitorFlags, cancellable?: Cancellable | null): FileMonitor; mount_enclosing_volume( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; mount_enclosing_volume( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; mount_enclosing_volume( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; mount_enclosing_volume_finish(result: AsyncResult): boolean; mount_mountable( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<File>; mount_mountable( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; mount_mountable( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<File> | void; mount_mountable_finish(result: AsyncResult): File; move( destination: File, flags: FileCopyFlags, cancellable?: Cancellable | null, progress_callback?: FileProgressCallback | null ): boolean; open_readwrite(cancellable?: Cancellable | null): FileIOStream; open_readwrite_async(io_priority: number, cancellable?: Cancellable | null): Promise<FileIOStream>; open_readwrite_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; open_readwrite_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; open_readwrite_finish(res: AsyncResult): FileIOStream; peek_path(): string | null; poll_mountable(cancellable?: Cancellable | null): Promise<boolean>; poll_mountable(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; poll_mountable( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; poll_mountable_finish(result: AsyncResult): boolean; query_default_handler(cancellable?: Cancellable | null): AppInfo; query_default_handler_async(io_priority: number, cancellable?: Cancellable | null): Promise<AppInfo>; query_default_handler_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_default_handler_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<AppInfo> | void; query_default_handler_finish(result: AsyncResult): AppInfo; query_exists(cancellable?: Cancellable | null): boolean; query_file_type(flags: FileQueryInfoFlags, cancellable?: Cancellable | null): FileType; query_filesystem_info(attributes: string, cancellable?: Cancellable | null): FileInfo; query_filesystem_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; query_filesystem_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_filesystem_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; query_filesystem_info_finish(res: AsyncResult): FileInfo; query_info(attributes: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null): FileInfo; query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; query_info_finish(res: AsyncResult): FileInfo; query_settable_attributes(cancellable?: Cancellable | null): FileAttributeInfoList; query_writable_namespaces(cancellable?: Cancellable | null): FileAttributeInfoList; read(cancellable?: Cancellable | null): FileInputStream; read_async(io_priority: number, cancellable?: Cancellable | null): Promise<FileInputStream>; read_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; read_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInputStream> | void; read_finish(res: AsyncResult): FileInputStream; replace( etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): FileOutputStream; replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; replace_contents( contents: Uint8Array | string, etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): [boolean, string | null]; replace_contents_async( contents: Uint8Array | string, etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): Promise<[string | null]>; replace_contents_async( contents: Uint8Array | string, etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; replace_contents_async( contents: Uint8Array | string, etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[string | null]> | void; replace_contents_bytes_async( contents: GLib.Bytes | Uint8Array, etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): void; replace_contents_finish(res: AsyncResult): [boolean, string | null]; replace_finish(res: AsyncResult): FileOutputStream; replace_readwrite( etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): FileIOStream; replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileIOStream>; replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; replace_readwrite_finish(res: AsyncResult): FileIOStream; resolve_relative_path(relative_path: string): File; set_attribute( attribute: string, type: FileAttributeType, value_p: any | null, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_byte_string( attribute: string, value: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_int32( attribute: string, value: number, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_int64( attribute: string, value: number, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_string( attribute: string, value: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_uint32( attribute: string, value: number, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attribute_uint64( attribute: string, value: number, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<[FileInfo]>; set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[FileInfo]> | void; set_attributes_finish(result: AsyncResult): [boolean, FileInfo]; set_attributes_from_info(info: FileInfo, flags: FileQueryInfoFlags, cancellable?: Cancellable | null): boolean; set_display_name(display_name: string, cancellable?: Cancellable | null): File; set_display_name_async(display_name: string, io_priority: number, cancellable?: Cancellable | null): Promise<File>; set_display_name_async( display_name: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; set_display_name_async( display_name: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<File> | void; set_display_name_finish(res: AsyncResult): File; start_mountable( flags: DriveStartFlags, start_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; start_mountable( flags: DriveStartFlags, start_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; start_mountable( flags: DriveStartFlags, start_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; start_mountable_finish(result: AsyncResult): boolean; stop_mountable( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; stop_mountable( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; stop_mountable( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; stop_mountable_finish(result: AsyncResult): boolean; supports_thread_contexts(): boolean; trash(cancellable?: Cancellable | null): boolean; trash_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; trash_async(io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; trash_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; trash_finish(result: AsyncResult): boolean; unmount_mountable(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; unmount_mountable( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; unmount_mountable( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; unmount_mountable_finish(result: AsyncResult): boolean; unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; unmount_mountable_with_operation_finish(result: AsyncResult): boolean; vfunc_append_to(flags: FileCreateFlags, cancellable?: Cancellable | null): FileOutputStream; vfunc_append_to_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; vfunc_append_to_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_append_to_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; vfunc_append_to_finish(res: AsyncResult): FileOutputStream; vfunc_copy( destination: File, flags: FileCopyFlags, cancellable?: Cancellable | null, progress_callback?: FileProgressCallback | null ): boolean; vfunc_copy_async( destination: File, flags: FileCopyFlags, io_priority: number, cancellable?: Cancellable | null ): void; vfunc_copy_finish(res: AsyncResult): boolean; vfunc_create(flags: FileCreateFlags, cancellable?: Cancellable | null): FileOutputStream; vfunc_create_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; vfunc_create_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_create_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; vfunc_create_finish(res: AsyncResult): FileOutputStream; vfunc_create_readwrite(flags: FileCreateFlags, cancellable?: Cancellable | null): FileIOStream; vfunc_create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileIOStream>; vfunc_create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_create_readwrite_async( flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; vfunc_create_readwrite_finish(res: AsyncResult): FileIOStream; vfunc_delete_file(cancellable?: Cancellable | null): boolean; vfunc_delete_file_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_delete_file_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_delete_file_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_delete_file_finish(result: AsyncResult): boolean; vfunc_dup(): File; vfunc_eject_mountable(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_eject_mountable( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject_mountable( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_mountable_finish(result: AsyncResult): boolean; vfunc_eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_mountable_with_operation_finish(result: AsyncResult): boolean; vfunc_enumerate_children( attributes: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): FileEnumerator; vfunc_enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileEnumerator>; vfunc_enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_enumerate_children_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileEnumerator> | void; vfunc_enumerate_children_finish(res: AsyncResult): FileEnumerator; vfunc_equal(file2: File): boolean; vfunc_find_enclosing_mount(cancellable?: Cancellable | null): Mount; vfunc_find_enclosing_mount_async(io_priority: number, cancellable?: Cancellable | null): Promise<Mount>; vfunc_find_enclosing_mount_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_find_enclosing_mount_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<Mount> | void; vfunc_find_enclosing_mount_finish(res: AsyncResult): Mount; vfunc_get_basename(): string; vfunc_get_child_for_display_name(display_name: string): File; vfunc_get_parent(): File | null; vfunc_get_parse_name(): string; vfunc_get_path(): string; vfunc_get_relative_path(descendant: File): string; vfunc_get_uri(): string; vfunc_get_uri_scheme(): string; vfunc_has_uri_scheme(uri_scheme: string): boolean; vfunc_hash(): number; vfunc_is_native(): boolean; vfunc_make_directory(cancellable?: Cancellable | null): boolean; vfunc_make_directory_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_make_directory_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_make_directory_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_make_directory_finish(result: AsyncResult): boolean; vfunc_make_symbolic_link(symlink_value: string, cancellable?: Cancellable | null): boolean; vfunc_measure_disk_usage_finish(result: AsyncResult): [boolean, number | null, number | null, number | null]; vfunc_monitor_dir(flags: FileMonitorFlags, cancellable?: Cancellable | null): FileMonitor; vfunc_monitor_file(flags: FileMonitorFlags, cancellable?: Cancellable | null): FileMonitor; vfunc_mount_enclosing_volume( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_mount_enclosing_volume( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_mount_enclosing_volume( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_mount_enclosing_volume_finish(result: AsyncResult): boolean; vfunc_mount_mountable( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<File>; vfunc_mount_mountable( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_mount_mountable( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<File> | void; vfunc_mount_mountable_finish(result: AsyncResult): File; vfunc_move( destination: File, flags: FileCopyFlags, cancellable?: Cancellable | null, progress_callback?: FileProgressCallback | null ): boolean; vfunc_open_readwrite(cancellable?: Cancellable | null): FileIOStream; vfunc_open_readwrite_async(io_priority: number, cancellable?: Cancellable | null): Promise<FileIOStream>; vfunc_open_readwrite_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_open_readwrite_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; vfunc_open_readwrite_finish(res: AsyncResult): FileIOStream; vfunc_poll_mountable(cancellable?: Cancellable | null): Promise<boolean>; vfunc_poll_mountable(cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_poll_mountable( cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_poll_mountable_finish(result: AsyncResult): boolean; vfunc_prefix_matches(file: File): boolean; vfunc_query_filesystem_info(attributes: string, cancellable?: Cancellable | null): FileInfo; vfunc_query_filesystem_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; vfunc_query_filesystem_info_async( attributes: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_query_filesystem_info_async( attributes: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; vfunc_query_filesystem_info_finish(res: AsyncResult): FileInfo; vfunc_query_info(attributes: string, flags: FileQueryInfoFlags, cancellable?: Cancellable | null): FileInfo; vfunc_query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileInfo>; vfunc_query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_query_info_async( attributes: string, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInfo> | void; vfunc_query_info_finish(res: AsyncResult): FileInfo; vfunc_query_settable_attributes(cancellable?: Cancellable | null): FileAttributeInfoList; vfunc_query_writable_namespaces(cancellable?: Cancellable | null): FileAttributeInfoList; vfunc_read_async(io_priority: number, cancellable?: Cancellable | null): Promise<FileInputStream>; vfunc_read_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_read_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileInputStream> | void; vfunc_read_finish(res: AsyncResult): FileInputStream; vfunc_read_fn(cancellable?: Cancellable | null): FileInputStream; vfunc_replace( etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): FileOutputStream; vfunc_replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileOutputStream>; vfunc_replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_replace_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileOutputStream> | void; vfunc_replace_finish(res: AsyncResult): FileOutputStream; vfunc_replace_readwrite( etag: string | null, make_backup: boolean, flags: FileCreateFlags, cancellable?: Cancellable | null ): FileIOStream; vfunc_replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<FileIOStream>; vfunc_replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_replace_readwrite_async( etag: string | null, make_backup: boolean, flags: FileCreateFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<FileIOStream> | void; vfunc_replace_readwrite_finish(res: AsyncResult): FileIOStream; vfunc_resolve_relative_path(relative_path: string): File; vfunc_set_attribute( attribute: string, type: FileAttributeType, value_p: any | null, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; vfunc_set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null ): Promise<[FileInfo]>; vfunc_set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_set_attributes_async( info: FileInfo, flags: FileQueryInfoFlags, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[FileInfo]> | void; vfunc_set_attributes_finish(result: AsyncResult): [boolean, FileInfo]; vfunc_set_attributes_from_info( info: FileInfo, flags: FileQueryInfoFlags, cancellable?: Cancellable | null ): boolean; vfunc_set_display_name(display_name: string, cancellable?: Cancellable | null): File; vfunc_set_display_name_async( display_name: string, io_priority: number, cancellable?: Cancellable | null ): Promise<File>; vfunc_set_display_name_async( display_name: string, io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_set_display_name_async( display_name: string, io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<File> | void; vfunc_set_display_name_finish(res: AsyncResult): File; vfunc_start_mountable( flags: DriveStartFlags, start_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_start_mountable( flags: DriveStartFlags, start_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_start_mountable( flags: DriveStartFlags, start_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_start_mountable_finish(result: AsyncResult): boolean; vfunc_stop_mountable( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_stop_mountable( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_stop_mountable( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_stop_mountable_finish(result: AsyncResult): boolean; vfunc_trash(cancellable?: Cancellable | null): boolean; vfunc_trash_async(io_priority: number, cancellable?: Cancellable | null): Promise<boolean>; vfunc_trash_async( io_priority: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_trash_async( io_priority: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_trash_finish(result: AsyncResult): boolean; vfunc_unmount_mountable(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_unmount_mountable( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_unmount_mountable( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_unmount_mountable_finish(result: AsyncResult): boolean; vfunc_unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_unmount_mountable_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_unmount_mountable_with_operation_finish(result: AsyncResult): boolean; } export const File: FileNamespace; export interface FileDescriptorBasedNamespace { $gtype: GObject.GType<FileDescriptorBased>; prototype: FileDescriptorBasedPrototype; } export type FileDescriptorBased = FileDescriptorBasedPrototype; export interface FileDescriptorBasedPrototype extends GObject.Object { // Members get_fd(): number; vfunc_get_fd(): number; } export const FileDescriptorBased: FileDescriptorBasedNamespace; export interface IconNamespace { $gtype: GObject.GType<Icon>; prototype: IconPrototype; deserialize(value: GLib.Variant): Icon; hash(icon: any): number; new_for_string(str: string): Icon; } export type Icon = IconPrototype; export interface IconPrototype extends GObject.Object { // Members equal(icon2?: Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; } export const Icon: IconNamespace; export interface InitableNamespace { $gtype: GObject.GType<Initable>; prototype: InitablePrototype; newv<T = GObject.Object>( object_type: GObject.GType, parameters: GObject.Parameter[], cancellable?: Cancellable | null ): T; newv(...args: never[]): never; } export type Initable = InitablePrototype; export interface InitablePrototype extends GObject.Object { // Members init(cancellable?: Cancellable | null): boolean; vfunc_init(cancellable?: Cancellable | null): boolean; } export const Initable: InitableNamespace; export interface ListModelNamespace { $gtype: GObject.GType<ListModel>; prototype: ListModelPrototype; } export type ListModel<A extends GObject.Object = GObject.Object> = ListModelPrototype<A>; export interface ListModelPrototype<A extends GObject.Object = GObject.Object> extends GObject.Object { // Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export const ListModel: ListModelNamespace; export interface LoadableIconNamespace { $gtype: GObject.GType<LoadableIcon>; prototype: LoadableIconPrototype; } export type LoadableIcon = LoadableIconPrototype; export interface LoadableIconPrototype extends Icon { // Members load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; load_finish(res: AsyncResult): [InputStream, string | null]; vfunc_load(size: number, cancellable?: Cancellable | null): [InputStream, string | null]; vfunc_load_async(size: number, cancellable?: Cancellable | null): Promise<[InputStream, string | null]>; vfunc_load_async(size: number, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_load_async( size: number, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<[InputStream, string | null]> | void; vfunc_load_finish(res: AsyncResult): [InputStream, string | null]; } export const LoadableIcon: LoadableIconNamespace; export interface MemoryMonitorNamespace { $gtype: GObject.GType<MemoryMonitor>; prototype: MemoryMonitorPrototype; dup_default(): MemoryMonitor; } export type MemoryMonitor = MemoryMonitorPrototype; export interface MemoryMonitorPrototype extends Initable { // Members vfunc_low_memory_warning(level: MemoryMonitorWarningLevel): void; } export const MemoryMonitor: MemoryMonitorNamespace; export interface MountNamespace { $gtype: GObject.GType<Mount>; prototype: MountPrototype; } export type Mount = MountPrototype; export interface MountPrototype extends GObject.Object { // Members can_eject(): boolean; can_unmount(): boolean; eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; eject(flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_finish(result: AsyncResult): boolean; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_with_operation_finish(result: AsyncResult): boolean; get_default_location(): File; get_drive(): Drive | null; get_icon(): Icon; get_name(): string; get_root(): File; get_sort_key(): string | null; get_symbolic_icon(): Icon; get_uuid(): string | null; get_volume(): Volume | null; guess_content_type(force_rescan: boolean, cancellable?: Cancellable | null): Promise<string[]>; guess_content_type( force_rescan: boolean, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; guess_content_type( force_rescan: boolean, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; guess_content_type_finish(result: AsyncResult): string[]; guess_content_type_sync(force_rescan: boolean, cancellable?: Cancellable | null): string[]; is_shadowed(): boolean; remount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; remount( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; remount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; remount_finish(result: AsyncResult): boolean; shadow(): void; unmount(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; unmount(flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; unmount( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; unmount_finish(result: AsyncResult): boolean; unmount_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; unmount_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; unmount_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; unmount_with_operation_finish(result: AsyncResult): boolean; unshadow(): void; vfunc_can_eject(): boolean; vfunc_can_unmount(): boolean; vfunc_changed(): void; vfunc_eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_eject( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_finish(result: AsyncResult): boolean; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_with_operation_finish(result: AsyncResult): boolean; vfunc_get_default_location(): File; vfunc_get_drive(): Drive | null; vfunc_get_icon(): Icon; vfunc_get_name(): string; vfunc_get_root(): File; vfunc_get_sort_key(): string | null; vfunc_get_symbolic_icon(): Icon; vfunc_get_uuid(): string | null; vfunc_get_volume(): Volume | null; vfunc_guess_content_type(force_rescan: boolean, cancellable?: Cancellable | null): Promise<string[]>; vfunc_guess_content_type( force_rescan: boolean, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_guess_content_type( force_rescan: boolean, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; vfunc_guess_content_type_finish(result: AsyncResult): string[]; vfunc_guess_content_type_sync(force_rescan: boolean, cancellable?: Cancellable | null): string[]; vfunc_pre_unmount(): void; vfunc_remount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_remount( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_remount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_remount_finish(result: AsyncResult): boolean; vfunc_unmount(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_unmount( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_unmount( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_unmount_finish(result: AsyncResult): boolean; vfunc_unmount_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_unmount_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_unmount_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_unmount_with_operation_finish(result: AsyncResult): boolean; vfunc_unmounted(): void; } export const Mount: MountNamespace; export interface NetworkMonitorNamespace { $gtype: GObject.GType<NetworkMonitor>; prototype: NetworkMonitorPrototype; get_default(): NetworkMonitor; } export type NetworkMonitor = NetworkMonitorPrototype; export interface NetworkMonitorPrototype extends Initable { // Properties connectivity: NetworkConnectivity; network_available: boolean; networkAvailable: boolean; network_metered: boolean; networkMetered: boolean; // Members can_reach(connectable: SocketConnectable, cancellable?: Cancellable | null): boolean; can_reach_async(connectable: SocketConnectable, cancellable?: Cancellable | null): Promise<boolean>; can_reach_async( connectable: SocketConnectable, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; can_reach_async( connectable: SocketConnectable, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; can_reach_finish(result: AsyncResult): boolean; get_connectivity(): NetworkConnectivity; get_network_available(): boolean; get_network_metered(): boolean; vfunc_can_reach(connectable: SocketConnectable, cancellable?: Cancellable | null): boolean; vfunc_can_reach_async(connectable: SocketConnectable, cancellable?: Cancellable | null): Promise<boolean>; vfunc_can_reach_async( connectable: SocketConnectable, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_can_reach_async( connectable: SocketConnectable, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_can_reach_finish(result: AsyncResult): boolean; vfunc_network_changed(network_available: boolean): void; } export const NetworkMonitor: NetworkMonitorNamespace; export interface PollableInputStreamNamespace { $gtype: GObject.GType<PollableInputStream>; prototype: PollableInputStreamPrototype; } export type PollableInputStream = PollableInputStreamPrototype; export interface PollableInputStreamPrototype extends InputStream { // Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_readable(): boolean; read_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_readable(): boolean; vfunc_read_nonblocking(buffer?: Uint8Array | null): number; } export const PollableInputStream: PollableInputStreamNamespace; export interface PollableOutputStreamNamespace { $gtype: GObject.GType<PollableOutputStream>; prototype: PollableOutputStreamPrototype; } export type PollableOutputStream = PollableOutputStreamPrototype; export interface PollableOutputStreamPrototype extends OutputStream { // Members can_poll(): boolean; create_source(cancellable?: Cancellable | null): GLib.Source; is_writable(): boolean; write_nonblocking(buffer: Uint8Array | string, cancellable?: Cancellable | null): number; writev_nonblocking(vectors: OutputVector[], cancellable?: Cancellable | null): [PollableReturn, number | null]; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Cancellable | null): GLib.Source; vfunc_is_writable(): boolean; vfunc_write_nonblocking(buffer?: Uint8Array | null): number; vfunc_writev_nonblocking(vectors: OutputVector[]): [PollableReturn, number | null]; } export const PollableOutputStream: PollableOutputStreamNamespace; export interface ProxyNamespace { $gtype: GObject.GType<Proxy>; prototype: ProxyPrototype; get_default_for_protocol(protocol: string): Proxy; } export type Proxy = ProxyPrototype; export interface ProxyPrototype extends GObject.Object { // Members connect(connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null): IOStream; connect(...args: never[]): never; connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null ): Promise<IOStream>; connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<IOStream> | void; connect_finish(result: AsyncResult): IOStream; supports_hostname(): boolean; vfunc_connect(connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null): IOStream; vfunc_connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null ): Promise<IOStream>; vfunc_connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_connect_async( connection: IOStream, proxy_address: ProxyAddress, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<IOStream> | void; vfunc_connect_finish(result: AsyncResult): IOStream; vfunc_supports_hostname(): boolean; } export const Proxy: ProxyNamespace; export interface ProxyResolverNamespace { $gtype: GObject.GType<ProxyResolver>; prototype: ProxyResolverPrototype; get_default(): ProxyResolver; } export type ProxyResolver = ProxyResolverPrototype; export interface ProxyResolverPrototype extends GObject.Object { // Members is_supported(): boolean; lookup(uri: string, cancellable?: Cancellable | null): string[]; lookup_async(uri: string, cancellable?: Cancellable | null): Promise<string[]>; lookup_async(uri: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; lookup_async( uri: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; lookup_finish(result: AsyncResult): string[]; vfunc_is_supported(): boolean; vfunc_lookup(uri: string, cancellable?: Cancellable | null): string[]; vfunc_lookup_async(uri: string, cancellable?: Cancellable | null): Promise<string[]>; vfunc_lookup_async(uri: string, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; vfunc_lookup_async( uri: string, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<string[]> | void; vfunc_lookup_finish(result: AsyncResult): string[]; } export const ProxyResolver: ProxyResolverNamespace; export interface RemoteActionGroupNamespace { $gtype: GObject.GType<RemoteActionGroup>; prototype: RemoteActionGroupPrototype; } export type RemoteActionGroup = RemoteActionGroupPrototype; export interface RemoteActionGroupPrototype extends ActionGroup { // Members activate_action_full(action_name: string, parameter: GLib.Variant | null, platform_data: GLib.Variant): void; change_action_state_full(action_name: string, value: GLib.Variant, platform_data: GLib.Variant): void; vfunc_activate_action_full(action_name: string, parameter: GLib.Variant | null, platform_data: GLib.Variant): void; vfunc_change_action_state_full(action_name: string, value: GLib.Variant, platform_data: GLib.Variant): void; } export const RemoteActionGroup: RemoteActionGroupNamespace; export interface SeekableNamespace { $gtype: GObject.GType<Seekable>; prototype: SeekablePrototype; } export type Seekable = SeekablePrototype; export interface SeekablePrototype extends GObject.Object { // Members can_seek(): boolean; can_truncate(): boolean; seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; tell(): number; truncate(offset: number, cancellable?: Cancellable | null): boolean; vfunc_can_seek(): boolean; vfunc_can_truncate(): boolean; vfunc_seek(offset: number, type: GLib.SeekType, cancellable?: Cancellable | null): boolean; vfunc_tell(): number; vfunc_truncate_fn(offset: number, cancellable?: Cancellable | null): boolean; } export const Seekable: SeekableNamespace; export interface SocketConnectableNamespace { $gtype: GObject.GType<SocketConnectable>; prototype: SocketConnectablePrototype; } export type SocketConnectable = SocketConnectablePrototype; export interface SocketConnectablePrototype extends GObject.Object { // Members enumerate(): SocketAddressEnumerator; proxy_enumerate(): SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): SocketAddressEnumerator; vfunc_proxy_enumerate(): SocketAddressEnumerator; vfunc_to_string(): string; } export const SocketConnectable: SocketConnectableNamespace; export interface TlsBackendNamespace { $gtype: GObject.GType<TlsBackend>; prototype: TlsBackendPrototype; get_default(): TlsBackend; } export type TlsBackend = TlsBackendPrototype; export interface TlsBackendPrototype extends GObject.Object { // Members get_certificate_type(): GObject.GType; get_client_connection_type(): GObject.GType; get_default_database(): TlsDatabase; get_dtls_client_connection_type(): GObject.GType; get_dtls_server_connection_type(): GObject.GType; get_file_database_type(): GObject.GType; get_server_connection_type(): GObject.GType; set_default_database(database?: TlsDatabase | null): void; supports_dtls(): boolean; supports_tls(): boolean; vfunc_get_default_database(): TlsDatabase; vfunc_supports_dtls(): boolean; vfunc_supports_tls(): boolean; } export const TlsBackend: TlsBackendNamespace; export interface TlsClientConnectionNamespace { $gtype: GObject.GType<TlsClientConnection>; prototype: TlsClientConnectionPrototype; ["new"](base_io_stream: IOStream, server_identity?: SocketConnectable | null): TlsClientConnection; } export type TlsClientConnection = TlsClientConnectionPrototype; export interface TlsClientConnectionPrototype extends TlsConnection { // Properties accepted_cas: any[]; acceptedCas: any[]; server_identity: SocketConnectable; serverIdentity: SocketConnectable; use_ssl3: boolean; useSsl3: boolean; validation_flags: TlsCertificateFlags; validationFlags: TlsCertificateFlags; // Members copy_session_state(source: TlsClientConnection): void; get_accepted_cas(): GLib.List; get_server_identity(): SocketConnectable; get_use_ssl3(): boolean; get_validation_flags(): TlsCertificateFlags; set_server_identity(identity: SocketConnectable): void; set_use_ssl3(use_ssl3: boolean): void; set_validation_flags(flags: TlsCertificateFlags): void; vfunc_copy_session_state(source: TlsClientConnection): void; } export const TlsClientConnection: TlsClientConnectionNamespace; export interface TlsFileDatabaseNamespace { $gtype: GObject.GType<TlsFileDatabase>; prototype: TlsFileDatabasePrototype; ["new"](anchors: string): TlsFileDatabase; } export type TlsFileDatabase = TlsFileDatabasePrototype; export interface TlsFileDatabasePrototype extends TlsDatabase { // Properties anchors: string; } export const TlsFileDatabase: TlsFileDatabaseNamespace; export interface TlsServerConnectionNamespace { $gtype: GObject.GType<TlsServerConnection>; prototype: TlsServerConnectionPrototype; ["new"](base_io_stream: IOStream, certificate?: TlsCertificate | null): TlsServerConnection; } export type TlsServerConnection = TlsServerConnectionPrototype; export interface TlsServerConnectionPrototype extends TlsConnection { // Properties authentication_mode: TlsAuthenticationMode; authenticationMode: TlsAuthenticationMode; } export const TlsServerConnection: TlsServerConnectionNamespace; export interface VolumeNamespace { $gtype: GObject.GType<Volume>; prototype: VolumePrototype; } export type Volume = VolumePrototype; export interface VolumePrototype extends GObject.Object { // Members can_eject(): boolean; can_mount(): boolean; eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; eject(flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null): void; eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_finish(result: AsyncResult): boolean; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; eject_with_operation_finish(result: AsyncResult): boolean; enumerate_identifiers(): string[]; get_activation_root(): File | null; get_drive(): Drive | null; get_icon(): Icon; get_identifier(kind: string): string | null; get_mount(): Mount | null; get_name(): string; get_sort_key(): string | null; get_symbolic_icon(): Icon; get_uuid(): string | null; mount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; mount( flags: MountMountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; mount( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; mount_finish(result: AsyncResult): boolean; should_automount(): boolean; vfunc_can_eject(): boolean; vfunc_can_mount(): boolean; vfunc_changed(): void; vfunc_eject(flags: MountUnmountFlags, cancellable?: Cancellable | null): Promise<boolean>; vfunc_eject( flags: MountUnmountFlags, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject( flags: MountUnmountFlags, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_finish(result: AsyncResult): boolean; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null ): Promise<boolean>; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation: MountOperation | null, cancellable: Cancellable | null, callback: AsyncReadyCallback<this> | null ): void; vfunc_eject_with_operation( flags: MountUnmountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_eject_with_operation_finish(result: AsyncResult): boolean; vfunc_enumerate_identifiers(): string[]; vfunc_get_activation_root(): File | null; vfunc_get_drive(): Drive | null; vfunc_get_icon(): Icon; vfunc_get_identifier(kind: string): string | null; vfunc_get_mount(): Mount | null; vfunc_get_name(): string; vfunc_get_sort_key(): string | null; vfunc_get_symbolic_icon(): Icon; vfunc_get_uuid(): string | null; vfunc_mount_finish(result: AsyncResult): boolean; vfunc_mount_fn( flags: MountMountFlags, mount_operation?: MountOperation | null, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<this> | null ): void; vfunc_removed(): void; vfunc_should_automount(): boolean; } export const Volume: VolumeNamespace; export interface DBusNamespace { prototype: DBusPrototype; readonly session: DBusConnection; readonly system: DBusConnection; get(bus_type: BusType, cancellable?: Cancellable | null): Promise<DBusConnection>; get(bus_type: BusType, cancellable: Cancellable | null, callback: AsyncReadyCallback<BusType> | null): void; get( bus_type: BusType, cancellable?: Cancellable | null, callback?: AsyncReadyCallback<BusType> | null ): Promise<DBusConnection> | void; get_finish(res: AsyncResult): DBusConnection; get_sync(bus_type: BusType, cancellable?: Cancellable | null): DBusConnection; own_name( bus_type: BusType, name: string, flags: BusNameOwnerFlags, bus_acquired_closure?: GObject.Closure | null, name_acquired_closure?: GObject.Closure | null, name_lost_closure?: GObject.Closure | null ): number; own_name_on_connection( connection: DBusConnection, name: string, flags: BusNameOwnerFlags, name_acquired_closure?: GObject.Closure | null, name_lost_closure?: GObject.Closure | null ): number; unown_name(owner_id: number): void; watch_name( bus_type: BusType, name: string, flags: BusNameWatcherFlags, name_appeared_closure?: GObject.Closure | null, name_vanished_closure?: GObject.Closure | null ): number; unwatch_name(watcher_id: number): void; watch_name_on_connection( connection: DBusConnection, name: string, flags: BusNameWatcherFlags, name_appeared_closure?: GObject.Closure | null, name_vanished_closure?: GObject.Closure | null ): number; } export type DBus = DBusPrototype; export interface DBusPrototype {} export const DBus: DBusNamespace; export module DBusExportedObject { export interface ConstructorProperties { [key: string]: any; } } export class DBusExportedObject { static $gtype: GObject.GType<DBusExportedObject>; constructor(properties?: Partial<DBusExportedObject.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DBusExportedObject.ConstructorProperties>, ...args: any[]): void; // Members static wrapJSObject(info: string, obj: any): DBusExportedObject; get_info(): DBusInterfaceInfo; get_connection(): DBusConnection; get_object_path(): string; unexport_from_connection(connection: DBusConnection): void; ["export"](busConnection: DBusConnection, objectPath: string): void; unexport(): void; flush(): void; emit_signal(name: string, variant: GLib.Variant): void; emit_property_changed(name: string, variant: GLib.Variant): void; }
the_stack
import React from 'react' import ReactDomServer from 'react-dom/server' import TypeWeibo, { TypeWeiboListByDay } from '~/src/type/namespace/weibo' import CommonUtil from '~/src/library/util/common' import moment from 'moment' import _ from 'lodash' import DATE_FORMAT from '~/src/constant/date_format' import Logger from '~/src/library/logger' class CommentCompontent extends React.Component< { agreeCount: number commentCount: number createAt: number updateAt: number }, {} > { render() { return ( <div className="comment"> <div className="info-flex-line"> <span className="float-left">赞同:{this.props.agreeCount}</span> <span className="float-right"> 创建时间:{moment.unix(this.props.createAt).format(DATE_FORMAT.DATABASE_BY_DAY)} </span> </div> <div className="clear-float" /> <div className="info-flex-line"> <span className="float-left">评论:{this.props.commentCount}</span> <span className="float-right"> 最后更新:{moment.unix(this.props.updateAt).format(DATE_FORMAT.DATABASE_BY_DAY)} </span> </div> </div> ) } } class Base { static renderIndex(bookname: string, recordList: Array<TypeWeiboListByDay>) { let indexList: Array<React.ReactElement<any>> = [] for (let record of recordList) { let indexItem = ( <li key={CommonUtil.getUuid()}> <a className="list-group-item" href={`./${record.title}.html`}> {record.title} </a> </li> ) indexList.push(indexItem) } const indexTableElement = ( <div className="panel panel-success center-block"> <div className="panel-heading">{bookname}</div> <div className="list-group"> <ol>{indexList}</ol> </div> </div> ) const pageElement = this.generatePageElement(bookname, [indexTableElement]) let content = this.renderToString(pageElement) return content } static generatePageElement(title: string, contentElementList: Array<React.ReactElement<any>>) { return ( <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charSet="utf-8" /> <title>{title}</title> <link rel="stylesheet" type="text/css" href="../css/normalize.css" /> <link rel="stylesheet" type="text/css" href="../css/markdown.css" /> <link rel="stylesheet" type="text/css" href="../css/customer.css" /> <link rel="stylesheet" type="text/css" href="../css/bootstrap.css" /> </head> <body> <div className="container">{contentElementList}</div> </body> </html> ) } /** * 生成单个微博的Element * @param mblog */ static generateSingleWeiboElement(mblog: TypeWeibo.TypeMblog) { if (_.isEmpty(mblog)) { return <div key={CommonUtil.getUuid()} /> } function generateMlogRecord(mblog: TypeWeibo.TypeMblog) { let mblogEle = null if (!mblog) { // blog记录不存在, 直接返回即可 return mblogEle } if (mblog.state === 7 || mblog.state === 8 || _.isEmpty(mblog.user) === true) { // 微博不可见(已被删除/半年内可见/主动隐藏/etc) mblogEle = ( <div className="weibo-rp"> <div className="weibo-text"> <span> <a>---</a>: </span> {/* <div>${mblog.text}</div> */} <span dangerouslySetInnerHTML={{ __html: `${mblog.text}` }} /> </div> <div> {/* 如果是图片的话, 需要展示九张图 */} <div className="weibo-media-wraps weibo-media media-b"> <ul className="m-auto-list" /> </div> </div> </div> ) return mblogEle } let articleRecord = mblog.article let articleElement = null if (articleRecord) { // 渲染文章元素 let isExistCoverImg = articleRecord?.cover_img?.image?.url let coverImgEle = isExistCoverImg ? ( <div className="main_toppic"> <div className="picbox"> <img node-type="articleHeaderPic" src={articleRecord?.cover_img?.image?.url} /> </div> </div> ) : null articleElement = ( <div className="WB_artical"> <div className="article-split-line"></div> {coverImgEle} <div className="main_editor " node-type="articleContent"> <div className="title" node-type="articleTitle"> {articleRecord.title} </div> <div className="art-line"></div> <div className="WB_editor_iframe_new" node-type="contentBody"> {/* 正文 */} <div className="article-content" dangerouslySetInnerHTML={{ __html: articleRecord.content }} /> <div className="DCI_v2 clearfix" /> </div> </div> </div> ) } // 正常微博 let mblogPictureList = [] if (mblog.pics) { // 是否有图片 let picIndex = 0 for (let picture of mblog.pics) { let picEle = ( <li key={picIndex} className="m-auto-box"> <div className="m-img-box m-imghold-square"> <img src={picture.large.url} /> </div> </li> ) mblogPictureList.push(picEle) } } let videoEle = null if (mblog?.page_info?.type === 'video') { let imgUrl = mblog?.page_info?.page_pic?.url || '' let during_s = mblog?.page_info?.media_info?.duration || 0 let during_str = CommonUtil.seconds2DuringStr(during_s) videoEle = ( <div className="weibo-video-container"> <div className="video-img-container"> <img src={imgUrl} className="video-img"></img> </div> <div className="video-info-container"> <div className="card-video_plusInfo"> {mblog?.page_info?.play_count} </div> <div className="card-video_during">{during_str}</div> </div> </div> ) } mblogEle = ( <div className="weibo-rp"> <div className="weibo-text"> <span> <a href={mblog.user.profile_url}>@{mblog.user.screen_name}</a>: </span> <div dangerouslySetInnerHTML={{ __html: `${mblog.text}` }} /> {/* <div>${mblog.text}</div> */} </div> <div className="weibo-img-list-container"> {/* 如果是图片的话, 需要展示九张图 */} <div className="weibo-media-wraps weibo-media media-b"> <ul className="m-auto-list">{mblogPictureList}</ul> </div> </div> {/* 视频内容 */} {videoEle} <div className="weibo-article-container"> {/* 文章内容 */} {articleElement} </div> </div> ) return mblogEle } let retweetEle = null if (_.isEmpty(mblog.retweeted_status) === false) { retweetEle = generateMlogRecord(mblog.retweeted_status!) } let articleRecord = mblog.article let articleElement = null if (articleRecord) { // 渲染文章元素 let isExistCoverImg = articleRecord?.cover_img?.image?.url let coverImgEle = isExistCoverImg ? ( <div className="main_toppic"> <div className="picbox"> <img node-type="articleHeaderPic" src={articleRecord?.cover_img?.image?.url} /> </div> </div> ) : null articleElement = ( <div className="WB_artical"> <div className="article-split-line"></div> {coverImgEle} <div className="main_editor " node-type="articleContent"> <div className="title" node-type="articleTitle"> {articleRecord.title} </div> <div className="art-line"></div> <div className="WB_editor_iframe_new" node-type="contentBody"> {/* 正文 */} <div className="article-content" dangerouslySetInnerHTML={{ __html: articleRecord.content }} /> <div className="DCI_v2 clearfix" /> </div> </div> </div> ) } // 正常微博 let mblogPictureList = [] if (mblog.pics) { // 是否有图片 let picIndex = 0 for (let picture of mblog.pics) { let picEle = ( <li key={picIndex} className="m-auto-box"> <div className="m-img-box m-imghold-square"> <img src={picture.large.url} /> </div> </li> ) mblogPictureList.push(picEle) } } let videoEle = null if (mblog?.page_info?.type === 'video') { let imgUrl = mblog?.page_info?.page_pic?.url || '' let during_s = mblog?.page_info?.media_info?.duration || 0 let during_str = CommonUtil.seconds2DuringStr(during_s) videoEle = ( <div className="weibo-video-container"> <div className="video-img-container"> <img src={imgUrl} className="video-img"></img> </div> <div className="video-info-container"> <div className="card-video_plusInfo"> {mblog?.page_info?.play_count} </div> <div className="card-video_during">{during_str}</div> </div> </div> ) } let mblogElement = ( <div key={CommonUtil.getUuid()} className="mblog-container"> <div className="card m-panel card9 weibo-member card-vip"> <div className="card-wrap"> <div className="card-main"> {/*以下html结构整理自微博m站*/} {/*用户头像*/} <header className="weibo-top m-box m-avatar-box"> <a className="m-img-box"> <img src={mblog.user.avatar_hd} /> <i className="m-icon m-icon-goldv-static" /> </a> <div className="m-box-col m-box-dir m-box-center"> <div className="m-text-box"> <a> <h3 className="m-text-cut"> {mblog.user.screen_name} <i className="m-icon m-icon-vipl7"></i> </h3> </a> <h4 className="m-text-cut"> <span className="time"> {moment.unix(mblog.created_timestamp_at as number).format(DATE_FORMAT.DISPLAY_BY_DAY)} </span> </h4> </div> </div> </header> {/*微博正文*/} {/*转发文字*/} <article className="weibo-main"> <div className="weibo-og"> <div className="weibo-text" dangerouslySetInnerHTML={{ __html: `${mblog.text}` }}> {/* 微博评论内容 */} </div> </div> {/* 所发布九图内容 */} <div className="weibo-img-list-container"> <div className="weibo-media-wraps weibo-media media-b"> <ul className="m-auto-list">{mblogPictureList}</ul> </div> </div> {/* 视频内容 */} {videoEle} {/* 所发布文章内容 */} <div className="weibo-article-container">{articleElement}</div> {/* 所转发的微博 */} {retweetEle} </article> <footer className="m-ctrl-box m-box-center-a"> <div className="m-diy-btn m-box-col m-box-center m-box-center-a m-box-center-retweet"> <i className="m-font m-font-forward lite-iconf lite-iconf-report" /> {/* 转发数 */} <h4>{mblog.reposts_count}</h4> </div> <span className="m-line-gradient" /> <div className="m-diy-btn m-box-col m-box-center m-box-center-a m-box-center-comment"> <i className="m-font m-font-comment lite-iconf lite-iconf-comments" /> {/* 评论数 */} <h4>{mblog.comments_count}</h4> </div> <span className="m-line-gradient" /> <div className="m-diy-btn m-box-col m-box-center m-box-center-a m-box-center-agree"> <i className="m-icon m-icon-like lite-iconf lite-iconf-like" /> {/* 点赞数 */} <h4>{mblog.attitudes_count}</h4> </div> </footer> </div> </div> </div> <hr /> </div> ) return mblogElement } /** * 生成页面底部的导航action * @returns */ static generateFooterGuideAction( param: { backUrl: string nextUrl: string indexUrl: string } = { backUrl: '#', nextUrl: '#', indexUrl: '#', }, ) { return ( <div key="footer-guide"> <div className="footer-container"> <div className={`action action-go-back ${param.backUrl === '#' ? 'action-disable' : ''}`}> <a href={param.backUrl || '#'}>上一页</a> </div> <span className="gradient"></span> <div className="action action-go-category"> <a href={param.indexUrl || '#'}>目录</a> </div> <span className="gradient"></span> <div className={`action action-go-next ${param.nextUrl === '#' ? 'action-disable' : ''}`}> <a href={param.nextUrl || '#'}>下一页</a> </div> </div> <div className="footer-container-placeholder"></div> </div> ) } static renderToString(contentElement: React.ReactElement<any>) { return ReactDomServer.renderToString(contentElement) } } export default Base
the_stack
import type { SimpleBBox } from '@antv/g-canvas'; import { CellBorderPosition, type CellTheme } from '@/common/interface'; import type { AreaRange } from '@/common/interface/scroll'; import { getContentArea, getMaxTextWidth, getTextAndFollowingIconPosition, getTextAreaRange, getBorderPositionAndStyle, } from '@/utils/cell/cell'; describe('Cell Content Test', () => { test('should return content area', () => { const cfg = { x: 0, y: 0, width: 100, height: 100, }; const padding = { top: 12, right: 12, bottom: 8, left: 8, }; const results = getContentArea(cfg, padding); expect(results).toEqual({ x: 8, y: 12, width: 80, height: 80, }); }); }); describe('Max Text Width Calculation Test', () => { test('should return max text width without icon', () => { expect(getMaxTextWidth(100)).toEqual(100); }); test('should return max text width with icon', () => { expect( getMaxTextWidth(100, { size: 10, margin: { left: 10, right: 8 }, }), ).toEqual(72); }); }); describe('Text and Icon area Test', () => { const content: SimpleBBox = { x: 0, y: 0, width: 100, height: 100, }; test('should return text when there is no icon cfg', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'left', textBaseline: 'top', }, 50, ), ).toEqual({ text: { x: 0, y: 0, }, icon: { x: 50, y: 0, }, }); }); test('should return text when text is right and icon is right', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'right', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 72, y: 0, }, icon: { x: 82, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'right', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 52, y: 0, }, icon: { x: 62, y: 0, }, }); }); test('should return text when text is right and icon is left', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'right', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 100, y: 0, }, icon: { x: 32, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'right', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 100, y: 0, }, icon: { x: 12, y: 0, }, }); }); test('should return text when text is center and icon is left', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'center', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 59, y: 0, }, icon: { x: 16, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'center', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 69, y: 0, }, icon: { x: 6, y: 0, }, }); }); test('should return text when text is center and icon is right', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'center', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 40, y: 0, }, icon: { x: 75, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'center', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 30, y: 0, }, icon: { x: 65, y: 0, }, }); }); test('should return text when text is left and icon is left', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'left', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 28, y: 0, }, icon: { x: 10, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'left', textBaseline: 'top', }, 50, { position: 'left', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 48, y: 0, }, icon: { x: 10, y: 0, }, }); }); test('should return text when text is left and icon is right', () => { expect( getTextAndFollowingIconPosition( content, { textAlign: 'left', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, ), ).toEqual({ text: { x: 0, y: 0, }, icon: { x: 60, y: 0, }, }); expect( getTextAndFollowingIconPosition( content, { textAlign: 'left', textBaseline: 'top', }, 50, { position: 'right', size: 10, margin: { left: 10, right: 8 }, }, 2, ), ).toEqual({ text: { x: 0, y: 0, }, icon: { x: 60, y: 0, }, }); }); }); describe('Horizontal Scrolling Text Position Test', () => { const content: AreaRange = { start: 0, width: 100, }; const textWidth = 20; test('should get center position when content is larger than viewport', () => { expect( getTextAreaRange( { start: 20, width: 50, }, content, textWidth, ).start, ).toEqual(45); }); test('should get center position when content is on the left of viewport', () => { // reset width is enough expect( getTextAreaRange( { start: 50, width: 100, }, content, textWidth, ).start, ).toEqual(75); // reset width isn't enough expect( getTextAreaRange( { start: 90, width: 100, }, content, textWidth, ).start, ).toEqual(90); }); test('should get center position when content is on the right of viewport', () => { // reset width is enough expect( getTextAreaRange( { start: -50, width: 100, }, content, textWidth, ).start, ).toEqual(25); // reset width isn't enough expect( getTextAreaRange( { start: -90, width: 100, }, content, textWidth, ).start, ).toEqual(10); }); test('should get center position when content is inside of viewport', () => { expect( getTextAreaRange( { start: -50, width: 200, }, content, textWidth, ).start, ).toEqual(50); }); test('should get border position', () => { const contentBox = { x: 0, y: 0, width: 200, height: 50, }; const style = { verticalBorderColorOpacity: 1, verticalBorderColor: '#000', verticalBorderWidth: 2, horizontalBorderColor: '#000', horizontalBorderColorOpacity: 1, horizontalBorderWidth: 2, }; expect( getBorderPositionAndStyle( CellBorderPosition.LEFT, contentBox, style as CellTheme, ).position, ).toEqual({ x1: 1, y1: 0, x2: 1, y2: 50, }); expect( getBorderPositionAndStyle( CellBorderPosition.RIGHT, contentBox, style as CellTheme, ).position, ).toEqual({ x1: 199, y1: 0, x2: 199, y2: 50, }); expect( getBorderPositionAndStyle( CellBorderPosition.TOP, contentBox, style as CellTheme, ).position, ).toEqual({ x1: 0, y1: 1, x2: 200, y2: 1, }); expect( getBorderPositionAndStyle( CellBorderPosition.BOTTOM, contentBox, style as CellTheme, ).position, ).toEqual({ x1: 0, y1: 49, x2: 200, y2: 49, }); }); });
the_stack
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, Input, NgZone, OnChanges, Output, ViewChild } from '@angular/core'; import { MatSliderChange } from '@angular/material'; import * as d3 from 'd3'; import { ZoomBehavior, ZoomTransform } from 'd3'; import { BrowseCloudFontSettings, CountingGridModel, IWordLabel } from '@browsecloud/models'; @Component({ selector: 'app-cloud-view', templateUrl: './cloud-view.component.html', styleUrls: ['./cloud-view.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CloudViewComponent implements OnChanges, AfterViewInit { @ViewChild('cloudView', { static: true }) public entryElement: ElementRef<HTMLCanvasElement>; @Input() public model: CountingGridModel; @Input() public searchWordIds: number[] = []; @Input() public zoomRange: [number, number] = [1, 13]; @Input() public maxLabels = 10000; @Input() public maxStartLabels = 500; @Input() public portionOfLabelsShownOnStart = 0.02; @Input() public pastBoundsTranslation = 300; @Input() public fontPolynomial: BrowseCloudFontSettings; @Input() public highlightPosition: [number, number]; @Input() public highlightLength = 150; @Input() public pinCircleRadius = 10; @Output() public readonly pinPlaced: EventEmitter<[number, number]> = new EventEmitter(); public currentTransform: ZoomTransform; private canvas: HTMLCanvasElement; private context: CanvasRenderingContext2D; private numberLabelsShownOnStart: number; private normalizedZoomFactor = 0; private pinCanvasCoordinates: [number, number]; private textWidthCache: { [name: string]: number } = {}; private zoomBehavior: ZoomBehavior<Element, {}>; constructor( private zone: NgZone, private changeDetectorRef: ChangeDetectorRef ) { } public ngOnChanges(): void { if (this.portionOfLabelsShownOnStart <= 0 || this.portionOfLabelsShownOnStart > 1) { throw new Error('portionOfLabelsShownOnStart must be between 0 and 1'); } // Reset textWidthCache. this.textWidthCache = {}; this.updateNumberLabelsShownOnStart(); this.render(); } public ngAfterViewInit(): void { this.canvas = this.entryElement.nativeElement; // Alpha is false below to enable the browser to make optimizations based on // the fact that we don't need the background of the canvas to be transparent. this.context = this.canvas.getContext('2d', { alpha: false }); this.updateNumberLabelsShownOnStart(); // Save for after view is visible. setTimeout(() => { this.makeBoundsUpdates(); this.render(); }, 0); } public resetVisualization(): void { this.pinCanvasCoordinates = null; d3.select(this.canvas).call(this.zoomBehavior.transform, d3.zoomIdentity); } public onCanvasClicked(event: MouseEvent) { this.pinCanvasCoordinates = [ ((event.offsetX - this.currentTransform.x) / this.currentTransform.k) * window.devicePixelRatio, ((event.offsetY - this.currentTransform.y) / this.currentTransform.k) * window.devicePixelRatio, ]; const colLength = this.canvas.width / this.model.topGrid.columnLength; const rowLength = this.canvas.height / this.model.topGrid.rowLength; let gridCol = Math.floor((this.pinCanvasCoordinates[0] + colLength / 2) / colLength) % this.model.topGrid.columnLength; let gridRow = Math.floor((this.pinCanvasCoordinates[1] + rowLength / 2) / rowLength) % this.model.topGrid.rowLength; gridCol = gridCol > 0 ? gridCol : gridCol + this.model.topGrid.columnLength; gridRow = gridRow > 0 ? gridRow : gridRow + this.model.topGrid.rowLength; this.pinPlaced.emit([gridRow, gridCol]); this.render(); } public render(): void { if (this.canvas == null || this.context == null) { return; } if (this.currentTransform == null) { this.currentTransform = d3.zoomIdentity; } // Start with a clean slate. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); // Fill black background. this.context.fillStyle = 'black'; this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); // Calculate bounds of the zoomed grid. const visualizationWidth = this.canvas.width * this.currentTransform.k; const visualizationHeight = this.canvas.height * this.currentTransform.k; // Place words. const scaledGridData = this.model.getScaledGridData( this.searchWordIds, visualizationWidth, visualizationHeight, this.currentTransform.x * window.devicePixelRatio, this.currentTransform.y * window.devicePixelRatio, this.currentTransform.k ); this.drawLabels(scaledGridData.wordLabels); if (this.pinCanvasCoordinates != null) { let pinActualX = ((this.pinCanvasCoordinates[0] * this.currentTransform.k) + (this.currentTransform.x * window.devicePixelRatio)) % visualizationWidth; let pinActualY = ((this.pinCanvasCoordinates[1] * this.currentTransform.k) + (this.currentTransform.y * window.devicePixelRatio)) % visualizationHeight; pinActualX = pinActualX > 0 ? pinActualX : pinActualX + visualizationWidth; pinActualY = pinActualY > 0 ? pinActualY : pinActualY + visualizationHeight; this.drawPinCircle(pinActualX, pinActualY); if (this.highlightPosition != null && this.highlightPosition[0] != null && this.highlightPosition[1]) { // Calculate highlight position nearest the pin. let highlightPossibleX = ((this.highlightPosition[0] * scaledGridData.colDistance) + (this.currentTransform.x * window.devicePixelRatio)) % visualizationWidth; let highlightPossibleY = ((this.highlightPosition[1] * scaledGridData.rowDistance) + (this.currentTransform.y * window.devicePixelRatio)) % visualizationHeight; highlightPossibleX = highlightPossibleX > 0 ? highlightPossibleX : highlightPossibleX + visualizationWidth; highlightPossibleY = highlightPossibleY > 0 ? highlightPossibleY : highlightPossibleY + visualizationHeight; const hightlightPossibleXs = [highlightPossibleX - visualizationWidth, highlightPossibleX, highlightPossibleX - visualizationWidth]; const hightlightPossibleYs = [highlightPossibleY - visualizationHeight, highlightPossibleY, highlightPossibleY - visualizationHeight]; this.drawHighlight( hightlightPossibleXs.sort((a, b) => (b - pinActualX) - (a - pinActualX))[0], hightlightPossibleYs.sort((a, b) => (b - pinActualY) - (a - pinActualY))[0] ); } } } private drawLabels(wordLabels: IWordLabel[]): void { const numberToShow = this.normalizedZoomFactor * (wordLabels.length - this.numberLabelsShownOnStart) + this.numberLabelsShownOnStart; const startIndex = Math.max(0, wordLabels.length - Math.min(numberToShow, this.maxLabels)); const numberOfWordsOnScreen = wordLabels.length - startIndex; // Global text settings. // Baseline at the top so the background rect will match the text. this.context.textBaseline = 'top'; wordLabels.slice(startIndex).forEach((wordLabel, index) => { // Font size is quadratic. const fontSize = this.quadraticResult( wordLabel.scaledWeight, this.fontPolynomial.quadraticWeight, 0, this.fontPolynomial.minimum ) * window.devicePixelRatio; // tslint:disable-next-line:max-line-length this.context.font = `${fontSize}px \"Segoe UI Web (West European)\", \"Segoe UI\", -apple-system, BlinkMacSystemFont, \"Roboto\", \"Helvetica Neue\", sans-serif`; // Calculate Alpha as a portion of the total items to show. const alpha = 1 - ((numberOfWordsOnScreen - index) / numberOfWordsOnScreen); // calculate text placement if (this.textWidthCache[`${wordLabel.wordId}${wordLabel.scaledWeight}}`] == null) { this.textWidthCache[`${wordLabel.wordId}${wordLabel.scaledWeight}}`] = this.context.measureText(wordLabel.word).width; } const textWidth = this.textWidthCache[`${wordLabel.wordId}${wordLabel.scaledWeight}}`]; const textX = wordLabel.point.x - textWidth / 2; const textY = wordLabel.point.y - fontSize / 2; // Display Background above threshold chosen for perf. if (alpha > 0.6) { // Background is black and half as transparent as the text so it can be seen through. this.context.fillStyle = `rgba(0, 0, 0, ${alpha * 0.5}`; this.context.fillRect(textX, textY, textWidth, fontSize); } // Text fill color setup. Alpha is also applied here. this.context.fillStyle = `rgba(${wordLabel.color.red}, ${wordLabel.color.green}, ${wordLabel.color.blue}, ${alpha})`; // Display word. this.context.fillText(wordLabel.word, textX, textY); }); } private drawPinCircle(x: number, y: number): void { this.context.beginPath(); this.context.arc(x - this.pinCircleRadius, y, this.pinCircleRadius * window.devicePixelRatio, 0, 2 * Math.PI, true); this.context.fillStyle = 'red'; this.context.fill(); } private drawHighlight(x: number, y: number): void { this.context.strokeStyle = 'yellow'; this.context.lineWidth = 5 * window.devicePixelRatio; const length = this.highlightLength * this.currentTransform.k * window.devicePixelRatio; this.context.strokeRect( x - length / 2, y - length / 2, length, length ); } @HostListener('window:resize', ['$event']) public onWindowResize(): void { // Update size and render. this.makeBoundsUpdates(); this.render(); } public onZoomSlider(change: MatSliderChange): void { this.zoomBehavior.scaleTo(d3.select(this.canvas), change.value); } private onZoom(): void { this.currentTransform = d3.event.transform; this.normalizedZoomFactor = (this.currentTransform.k - this.zoomRange[0]) / (this.zoomRange[1] - this.zoomRange[0]); this.changeDetectorRef.detectChanges(); this.render(); } private makeBoundsUpdates(): void { const oldWidth = this.canvas.width; const oldHeight = this.canvas.height; // Set initial size. this.canvas.width = this.canvas.offsetWidth * window.devicePixelRatio; this.canvas.height = this.canvas.offsetHeight * window.devicePixelRatio; // Setup d3 zoom. Outside NgZone so change detection is not constantly called. this.zone.runOutsideAngular(() => { this.zoomBehavior = d3.zoom() .scaleExtent(this.zoomRange) .on('zoom', () => this.onZoom()); d3.select(this.canvas).call(this.zoomBehavior); }); // Update pin location. if (this.pinCanvasCoordinates != null) { this.pinCanvasCoordinates[0] *= (this.canvas.width / oldWidth); this.pinCanvasCoordinates[1] *= (this.canvas.height / oldHeight); } } private updateNumberLabelsShownOnStart(): void { this.numberLabelsShownOnStart = Math.min( this.maxStartLabels, Math.floor(this.portionOfLabelsShownOnStart * this.model.topGrid.wordTags.length)); } private quadraticResult(x: number, a: number, b: number, c: number) { return a * x ** 2 + b * x + c; } }
the_stack
import assert from '../stub/assert'; import { newPromise, promiseRejectedWith, promiseResolvedWith, setPromiseIsHandledToTrue, uponPromise } from './helpers/webidl'; import { DequeueValue, EnqueueValueWithSize, PeekQueueValue, QueuePair, ResetQueue } from './abstract-ops/queue-with-sizes'; import { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy'; import { SimpleQueue } from './simple-queue'; import { typeIsObject } from './helpers/miscellaneous'; import { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods'; import { IsNonNegativeNumber } from './abstract-ops/miscellaneous'; import { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy'; import { convertQueuingStrategy } from './validators/queuing-strategy'; import { UnderlyingSink, UnderlyingSinkAbortCallback, UnderlyingSinkCloseCallback, UnderlyingSinkStartCallback, UnderlyingSinkWriteCallback, ValidatedUnderlyingSink } from './writable-stream/underlying-sink'; import { assertObject, assertRequiredArgument } from './validators/basic'; import { convertUnderlyingSink } from './validators/underlying-sink'; import { assertWritableStream } from './validators/writable-stream'; import { AbortController, AbortSignal, createAbortController } from './abort-signal'; type WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored'; interface WriteOrCloseRequest { _resolve: (value?: undefined) => void; _reject: (reason: any) => void; } type WriteRequest = WriteOrCloseRequest; type CloseRequest = WriteOrCloseRequest; interface PendingAbortRequest { _promise: Promise<undefined>; _resolve: (value?: undefined) => void; _reject: (reason: any) => void; _reason: any; _wasAlreadyErroring: boolean; } /** * A writable stream represents a destination for data, into which you can write. * * @public */ class WritableStream<W = any> { /** @internal */ _state!: WritableStreamState; /** @internal */ _storedError: any; /** @internal */ _writer: WritableStreamDefaultWriter<W> | undefined; /** @internal */ _writableStreamController!: WritableStreamDefaultController<W>; /** @internal */ _writeRequests!: SimpleQueue<WriteRequest>; /** @internal */ _inFlightWriteRequest: WriteRequest | undefined; /** @internal */ _closeRequest: CloseRequest | undefined; /** @internal */ _inFlightCloseRequest: CloseRequest | undefined; /** @internal */ _pendingAbortRequest: PendingAbortRequest | undefined; /** @internal */ _backpressure!: boolean; constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>); constructor(rawUnderlyingSink: UnderlyingSink<W> | null | undefined = {}, rawStrategy: QueuingStrategy<W> | null | undefined = {}) { if (rawUnderlyingSink === undefined) { rawUnderlyingSink = null; } else { assertObject(rawUnderlyingSink, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); InitializeWritableStream(this); const type = underlyingSink.type; if (type !== undefined) { throw new RangeError('Invalid type is specified'); } const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); } /** * Returns whether or not the writable stream is locked to a writer. */ get locked(): boolean { if (!IsWritableStream(this)) { throw streamBrandCheckException('locked'); } return IsWritableStreamLocked(this); } /** * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort * mechanism of the underlying sink. * * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel * the stream) if the stream is currently locked. */ abort(reason: any = undefined): Promise<void> { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException('abort')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); } return WritableStreamAbort(this, reason); } /** * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its * close behavior. During this time any further attempts to write will fail (without erroring the stream). * * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. */ close() { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException('close')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); } if (WritableStreamCloseQueuedOrInFlight(this)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamClose(this); } /** * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream * is locked, no other writer can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to write to a stream * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at * the same time, which would cause the resulting written data to be unpredictable and probably useless. */ getWriter(): WritableStreamDefaultWriter<W> { if (!IsWritableStream(this)) { throw streamBrandCheckException('getWriter'); } return AcquireWritableStreamDefaultWriter(this); } } Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { value: 'WritableStream', configurable: true }); } export { AcquireWritableStreamDefaultWriter, CreateWritableStream, IsWritableStream, IsWritableStreamLocked, WritableStream, WritableStreamAbort, WritableStreamDefaultControllerErrorIfNeeded, WritableStreamDefaultWriterCloseWithErrorPropagation, WritableStreamDefaultWriterRelease, WritableStreamDefaultWriterWrite, WritableStreamCloseQueuedOrInFlight, UnderlyingSink, UnderlyingSinkStartCallback, UnderlyingSinkWriteCallback, UnderlyingSinkCloseCallback, UnderlyingSinkAbortCallback }; // Abstract operations for the WritableStream. function AcquireWritableStreamDefaultWriter<W>(stream: WritableStream<W>): WritableStreamDefaultWriter<W> { return new WritableStreamDefaultWriter(stream); } // Throws if and only if startAlgorithm throws. function CreateWritableStream<W>(startAlgorithm: () => void | PromiseLike<void>, writeAlgorithm: (chunk: W) => Promise<void>, closeAlgorithm: () => Promise<void>, abortAlgorithm: (reason: any) => Promise<void>, highWaterMark = 1, sizeAlgorithm: QueuingStrategySizeCallback<W> = () => 1) { assert(IsNonNegativeNumber(highWaterMark)); const stream: WritableStream<W> = Object.create(WritableStream.prototype); InitializeWritableStream(stream); const controller: WritableStreamDefaultController<W> = Object.create(WritableStreamDefaultController.prototype); SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function InitializeWritableStream<W>(stream: WritableStream<W>) { stream._state = 'writable'; // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is // 'erroring' or 'errored'. May be set to an undefined value. stream._storedError = undefined; stream._writer = undefined; // Initialize to undefined first because the constructor of the controller checks this // variable to validate the caller. stream._writableStreamController = undefined!; // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data // producer without waiting for the queued writes to finish. stream._writeRequests = new SimpleQueue(); // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. stream._inFlightWriteRequest = undefined; // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer // has been detached. stream._closeRequest = undefined; // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. stream._inFlightCloseRequest = undefined; // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. stream._pendingAbortRequest = undefined; // The backpressure signal set by the controller. stream._backpressure = false; } function IsWritableStream(x: unknown): x is WritableStream { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { return false; } return x instanceof WritableStream; } function IsWritableStreamLocked(stream: WritableStream): boolean { assert(IsWritableStream(stream)); if (stream._writer === undefined) { return false; } return true; } function WritableStreamAbort(stream: WritableStream, reason: any): Promise<undefined> { if (stream._state === 'closed' || stream._state === 'errored') { return promiseResolvedWith(undefined); } stream._writableStreamController._abortReason = reason; stream._writableStreamController._abortController?.abort(); // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', // but it doesn't know that signaling abort runs author code that might have changed the state. // Widen the type again by casting to WritableStreamState. const state = stream._state as WritableStreamState; if (state === 'closed' || state === 'errored') { return promiseResolvedWith(undefined); } if (stream._pendingAbortRequest !== undefined) { return stream._pendingAbortRequest._promise; } assert(state === 'writable' || state === 'erroring'); let wasAlreadyErroring = false; if (state === 'erroring') { wasAlreadyErroring = true; // reason will not be used, so don't keep a reference to it. reason = undefined; } const promise = newPromise<undefined>((resolve, reject) => { stream._pendingAbortRequest = { _promise: undefined!, _resolve: resolve, _reject: reject, _reason: reason, _wasAlreadyErroring: wasAlreadyErroring }; }); stream._pendingAbortRequest!._promise = promise; if (!wasAlreadyErroring) { WritableStreamStartErroring(stream, reason); } return promise; } function WritableStreamClose(stream: WritableStream<any>): Promise<undefined> { const state = stream._state; if (state === 'closed' || state === 'errored') { return promiseRejectedWith(new TypeError( `The stream (in ${state} state) is not in the writable state and cannot be closed`)); } assert(state === 'writable' || state === 'erroring'); assert(!WritableStreamCloseQueuedOrInFlight(stream)); const promise = newPromise<undefined>((resolve, reject) => { const closeRequest: CloseRequest = { _resolve: resolve, _reject: reject }; stream._closeRequest = closeRequest; }); const writer = stream._writer; if (writer !== undefined && stream._backpressure && state === 'writable') { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } // WritableStream API exposed for controllers. function WritableStreamAddWriteRequest(stream: WritableStream): Promise<undefined> { assert(IsWritableStreamLocked(stream)); assert(stream._state === 'writable'); const promise = newPromise<undefined>((resolve, reject) => { const writeRequest: WriteRequest = { _resolve: resolve, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream: WritableStream, error: any) { const state = stream._state; if (state === 'writable') { WritableStreamStartErroring(stream, error); return; } assert(state === 'erroring'); WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream: WritableStream, reason: any) { assert(stream._storedError === undefined); assert(stream._state === 'writable'); const controller = stream._writableStreamController; assert(controller !== undefined); stream._state = 'erroring'; stream._storedError = reason; const writer = stream._writer; if (writer !== undefined) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream: WritableStream) { assert(stream._state === 'erroring'); assert(!WritableStreamHasOperationMarkedInFlight(stream)); stream._state = 'errored'; stream._writableStreamController[ErrorSteps](); const storedError = stream._storedError; stream._writeRequests.forEach(writeRequest => { writeRequest._reject(storedError); }); stream._writeRequests = new SimpleQueue(); if (stream._pendingAbortRequest === undefined) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = undefined; if (abortRequest._wasAlreadyErroring) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); uponPromise( promise, () => { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }, (reason: any) => { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }); } function WritableStreamFinishInFlightWrite(stream: WritableStream) { assert(stream._inFlightWriteRequest !== undefined); stream._inFlightWriteRequest!._resolve(undefined); stream._inFlightWriteRequest = undefined; } function WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) { assert(stream._inFlightWriteRequest !== undefined); stream._inFlightWriteRequest!._reject(error); stream._inFlightWriteRequest = undefined; assert(stream._state === 'writable' || stream._state === 'erroring'); WritableStreamDealWithRejection(stream, error); } function WritableStreamFinishInFlightClose(stream: WritableStream) { assert(stream._inFlightCloseRequest !== undefined); stream._inFlightCloseRequest!._resolve(undefined); stream._inFlightCloseRequest = undefined; const state = stream._state; assert(state === 'writable' || state === 'erroring'); if (state === 'erroring') { // The error was too late to do anything, so it is ignored. stream._storedError = undefined; if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = undefined; } } stream._state = 'closed'; const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseResolve(writer); } assert(stream._pendingAbortRequest === undefined); assert(stream._storedError === undefined); } function WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) { assert(stream._inFlightCloseRequest !== undefined); stream._inFlightCloseRequest!._reject(error); stream._inFlightCloseRequest = undefined; assert(stream._state === 'writable' || stream._state === 'erroring'); // Never execute sink abort() after sink close(). if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._reject(error); stream._pendingAbortRequest = undefined; } WritableStreamDealWithRejection(stream, error); } // TODO(ricea): Fix alphabetical order. function WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean { if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean { if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream: WritableStream) { assert(stream._inFlightCloseRequest === undefined); assert(stream._closeRequest !== undefined); stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = undefined; } function WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) { assert(stream._inFlightWriteRequest === undefined); assert(stream._writeRequests.length !== 0); stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) { assert(stream._state === 'errored'); if (stream._closeRequest !== undefined) { assert(stream._inFlightCloseRequest === undefined); stream._closeRequest._reject(stream._storedError); stream._closeRequest = undefined; } const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseReject(writer, stream._storedError); } } function WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) { assert(stream._state === 'writable'); assert(!WritableStreamCloseQueuedOrInFlight(stream)); const writer = stream._writer; if (writer !== undefined && backpressure !== stream._backpressure) { if (backpressure) { defaultWriterReadyPromiseReset(writer); } else { assert(!backpressure); defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } /** * A default writer vended by a {@link WritableStream}. * * @public */ export class WritableStreamDefaultWriter<W = any> { /** @internal */ _ownerWritableStream: WritableStream<W>; /** @internal */ _closedPromise!: Promise<undefined>; /** @internal */ _closedPromise_resolve?: (value?: undefined) => void; /** @internal */ _closedPromise_reject?: (reason: any) => void; /** @internal */ _closedPromiseState!: 'pending' | 'resolved' | 'rejected'; /** @internal */ _readyPromise!: Promise<undefined>; /** @internal */ _readyPromise_resolve?: (value?: undefined) => void; /** @internal */ _readyPromise_reject?: (reason: any) => void; /** @internal */ _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected'; constructor(stream: WritableStream<W>) { assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); assertWritableStream(stream, 'First parameter'); if (IsWritableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive writing by another writer'); } this._ownerWritableStream = stream; stream._writer = this; const state = stream._state; if (state === 'writable') { if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state === 'erroring') { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); defaultWriterClosedPromiseInitialize(this); } else if (state === 'closed') { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { assert(state === 'errored'); const storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the writer’s lock is released before the stream finishes closing. */ get closed(): Promise<undefined> { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('closed')); } return this._closedPromise; } /** * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. * A producer can use this information to determine the right amount of data to write. * * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when * the writer’s lock is released. */ get desiredSize(): number | null { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('desiredSize'); } if (this._ownerWritableStream === undefined) { throw defaultWriterLockException('desiredSize'); } return WritableStreamDefaultWriterGetDesiredSize(this); } /** * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips * back to zero or below, the getter will return a new promise that stays pending until the next transition. * * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become * rejected. */ get ready(): Promise<undefined> { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('ready')); } return this._readyPromise; } /** * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. */ abort(reason: any = undefined): Promise<void> { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('abort')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('abort')); } return WritableStreamDefaultWriterAbort(this, reason); } /** * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. */ close(): Promise<void> { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('close')); } const stream = this._ownerWritableStream; if (stream === undefined) { return promiseRejectedWith(defaultWriterLockException('close')); } if (WritableStreamCloseQueuedOrInFlight(stream)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamDefaultWriterClose(this); } /** * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from * now on; otherwise, the writer will appear closed. * * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents * other producers from writing in an interleaved manner. */ releaseLock(): void { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('releaseLock'); } const stream = this._ownerWritableStream; if (stream === undefined) { return; } assert(stream._writer !== undefined); WritableStreamDefaultWriterRelease(this); } /** * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes * errored before the writing process is initiated. * * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been * accepted, and not necessarily that it is safely saved to its ultimate destination. */ write(chunk: W): Promise<void>; write(chunk: W = undefined!): Promise<void> { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('write')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('write to')); } return WritableStreamDefaultWriterWrite(this, chunk); } } Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { value: 'WritableStreamDefaultWriter', configurable: true }); } // Abstract operations for the WritableStreamDefaultWriter. function IsWritableStreamDefaultWriter<W = any>(x: any): x is WritableStreamDefaultWriter<W> { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { return false; } return x instanceof WritableStreamDefaultWriter; } // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. function WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) { const stream = writer._ownerWritableStream; assert(stream !== undefined); return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise<undefined> { const stream = writer._ownerWritableStream; assert(stream !== undefined); return WritableStreamClose(stream); } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise<undefined> { const stream = writer._ownerWritableStream; assert(stream !== undefined); const state = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseResolvedWith(undefined); } if (state === 'errored') { return promiseRejectedWith(stream._storedError); } assert(state === 'writable' || state === 'erroring'); return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) { if (writer._closedPromiseState === 'pending') { defaultWriterClosedPromiseReject(writer, error); } else { defaultWriterClosedPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) { if (writer._readyPromiseState === 'pending') { defaultWriterReadyPromiseReject(writer, error); } else { defaultWriterReadyPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null { const stream = writer._ownerWritableStream; const state = stream._state; if (state === 'errored' || state === 'erroring') { return null; } if (state === 'closed') { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) { const stream = writer._ownerWritableStream; assert(stream !== undefined); assert(stream._writer === writer); const releasedError = new TypeError( `Writer was released and can no longer be used to monitor the stream's closedness`); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not // rejected until afterwards. This means that simply testing state will not work. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = undefined; writer._ownerWritableStream = undefined!; } function WritableStreamDefaultWriterWrite<W>(writer: WritableStreamDefaultWriter<W>, chunk: W): Promise<undefined> { const stream = writer._ownerWritableStream; assert(stream !== undefined); const controller = stream._writableStreamController; const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return promiseRejectedWith(defaultWriterLockException('write to')); } const state = stream._state; if (state === 'errored') { return promiseRejectedWith(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); } if (state === 'erroring') { return promiseRejectedWith(stream._storedError); } assert(state === 'writable'); const promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } const closeSentinel: unique symbol = {} as any; type QueueRecord<W> = W | typeof closeSentinel; /** * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. * * @public */ export class WritableStreamDefaultController<W = any> { /** @internal */ _controlledWritableStream!: WritableStream<W>; /** @internal */ _queue!: SimpleQueue<QueuePair<QueueRecord<W>>>; /** @internal */ _queueTotalSize!: number; /** @internal */ _abortReason: any; /** @internal */ _abortController: AbortController | undefined; /** @internal */ _started!: boolean; /** @internal */ _strategySizeAlgorithm!: QueuingStrategySizeCallback<W>; /** @internal */ _strategyHWM!: number; /** @internal */ _writeAlgorithm!: (chunk: W) => Promise<void>; /** @internal */ _closeAlgorithm!: () => Promise<void>; /** @internal */ _abortAlgorithm!: (reason: any) => Promise<void>; private constructor() { throw new TypeError('Illegal constructor'); } /** * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. */ get abortReason(): any { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException('abortReason'); } return this._abortReason; } /** * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. */ get signal(): AbortSignal { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException('signal'); } if (this._abortController === undefined) { // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, // so instead we only implement support for `signal` if we find a global `AbortController` constructor. throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); } return this._abortController.signal; } /** * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. * * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the * normal lifecycle of interactions with the underlying sink. */ error(e: any = undefined): void { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException('error'); } const state = this._controlledWritableStream._state; if (state !== 'writable') { // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so // just treat it as a no-op. return; } WritableStreamDefaultControllerError(this, e); } /** @internal */ [AbortSteps](reason: any): Promise<void> { const result = this._abortAlgorithm(reason); WritableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [ErrorSteps]() { ResetQueue(this); } } Object.defineProperties(WritableStreamDefaultController.prototype, { error: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { value: 'WritableStreamDefaultController', configurable: true }); } // Abstract operations implementing interface required by the WritableStream. function IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController<any> { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { return false; } return x instanceof WritableStreamDefaultController; } function SetUpWritableStreamDefaultController<W>(stream: WritableStream<W>, controller: WritableStreamDefaultController<W>, startAlgorithm: () => void | PromiseLike<void>, writeAlgorithm: (chunk: W) => Promise<void>, closeAlgorithm: () => Promise<void>, abortAlgorithm: (reason: any) => Promise<void>, highWaterMark: number, sizeAlgorithm: QueuingStrategySizeCallback<W>) { assert(IsWritableStream(stream)); assert(stream._writableStreamController === undefined); controller._controlledWritableStream = stream; stream._writableStreamController = controller; // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. controller._queue = undefined!; controller._queueTotalSize = undefined!; ResetQueue(controller); controller._abortReason = undefined; controller._abortController = createAbortController(); controller._started = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._writeAlgorithm = writeAlgorithm; controller._closeAlgorithm = closeAlgorithm; controller._abortAlgorithm = abortAlgorithm; const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); const startPromise = promiseResolvedWith(startResult); uponPromise( startPromise, () => { assert(stream._state === 'writable' || stream._state === 'erroring'); controller._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, r => { assert(stream._state === 'writable' || stream._state === 'erroring'); controller._started = true; WritableStreamDealWithRejection(stream, r); } ); } function SetUpWritableStreamDefaultControllerFromUnderlyingSink<W>(stream: WritableStream<W>, underlyingSink: ValidatedUnderlyingSink<W>, highWaterMark: number, sizeAlgorithm: QueuingStrategySizeCallback<W>) { const controller = Object.create(WritableStreamDefaultController.prototype); let startAlgorithm: () => void | PromiseLike<void> = () => undefined; let writeAlgorithm: (chunk: W) => Promise<void> = () => promiseResolvedWith(undefined); let closeAlgorithm: () => Promise<void> = () => promiseResolvedWith(undefined); let abortAlgorithm: (reason: any) => Promise<void> = () => promiseResolvedWith(undefined); if (underlyingSink.start !== undefined) { startAlgorithm = () => underlyingSink.start!(controller); } if (underlyingSink.write !== undefined) { writeAlgorithm = chunk => underlyingSink.write!(chunk, controller); } if (underlyingSink.close !== undefined) { closeAlgorithm = () => underlyingSink.close!(); } if (underlyingSink.abort !== undefined) { abortAlgorithm = reason => underlyingSink.abort!(reason); } SetUpWritableStreamDefaultController( stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm ); } // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. function WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController<any>) { controller._writeAlgorithm = undefined!; controller._closeAlgorithm = undefined!; controller._abortAlgorithm = undefined!; controller._strategySizeAlgorithm = undefined!; } function WritableStreamDefaultControllerClose<W>(controller: WritableStreamDefaultController<W>) { EnqueueValueWithSize(controller, closeSentinel, 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize<W>(controller: WritableStreamDefaultController<W>, chunk: W): number { try { return controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController<any>): number { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite<W>(controller: WritableStreamDefaultController<W>, chunk: W, chunkSize: number) { try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } const stream = controller._controlledWritableStream; if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } // Abstract operations for the WritableStreamDefaultController. function WritableStreamDefaultControllerAdvanceQueueIfNeeded<W>(controller: WritableStreamDefaultController<W>) { const stream = controller._controlledWritableStream; if (!controller._started) { return; } if (stream._inFlightWriteRequest !== undefined) { return; } const state = stream._state; assert(state !== 'closed' && state !== 'errored'); if (state === 'erroring') { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } const value = PeekQueueValue(controller); if (value === closeSentinel) { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, value); } } function WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController<any>, error: any) { if (controller._controlledWritableStream._state === 'writable') { WritableStreamDefaultControllerError(controller, error); } } function WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController<any>) { const stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); assert(controller._queue.length === 0); const sinkClosePromise = controller._closeAlgorithm(); WritableStreamDefaultControllerClearAlgorithms(controller); uponPromise( sinkClosePromise, () => { WritableStreamFinishInFlightClose(stream); }, reason => { WritableStreamFinishInFlightCloseWithError(stream, reason); } ); } function WritableStreamDefaultControllerProcessWrite<W>(controller: WritableStreamDefaultController<W>, chunk: W) { const stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); const sinkWritePromise = controller._writeAlgorithm(chunk); uponPromise( sinkWritePromise, () => { WritableStreamFinishInFlightWrite(stream); const state = stream._state; assert(state === 'writable' || state === 'erroring'); DequeueValue(controller); if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, reason => { if (stream._state === 'writable') { WritableStreamDefaultControllerClearAlgorithms(controller); } WritableStreamFinishInFlightWriteWithError(stream, reason); } ); } function WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController<any>): boolean { const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } // A client of WritableStreamDefaultController may use these functions directly to bypass state check. function WritableStreamDefaultControllerError(controller: WritableStreamDefaultController<any>, error: any) { const stream = controller._controlledWritableStream; assert(stream._state === 'writable'); WritableStreamDefaultControllerClearAlgorithms(controller); WritableStreamStartErroring(stream, error); } // Helper functions for the WritableStream. function streamBrandCheckException(name: string): TypeError { return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } // Helper functions for the WritableStreamDefaultController. function defaultControllerBrandCheckException(name: string): TypeError { return new TypeError( `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } // Helper functions for the WritableStreamDefaultWriter. function defaultWriterBrandCheckException(name: string): TypeError { return new TypeError( `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } function defaultWriterLockException(name: string): TypeError { return new TypeError('Cannot ' + name + ' a stream using a released writer'); } function defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) { writer._closedPromise = newPromise((resolve, reject) => { writer._closedPromise_resolve = resolve; writer._closedPromise_reject = reject; writer._closedPromiseState = 'pending'; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseReject(writer, reason); } function defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseResolve(writer); } function defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) { if (writer._closedPromise_reject === undefined) { return; } assert(writer._closedPromiseState === 'pending'); setPromiseIsHandledToTrue(writer._closedPromise); writer._closedPromise_reject(reason); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) { assert(writer._closedPromise_resolve === undefined); assert(writer._closedPromise_reject === undefined); assert(writer._closedPromiseState !== 'pending'); defaultWriterClosedPromiseInitializeAsRejected(writer, reason); } function defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) { if (writer._closedPromise_resolve === undefined) { return; } assert(writer._closedPromiseState === 'pending'); writer._closedPromise_resolve(undefined); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'resolved'; } function defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) { writer._readyPromise = newPromise((resolve, reject) => { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = 'pending'; } function defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseReject(writer, reason); } function defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseResolve(writer); } function defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) { if (writer._readyPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(writer._readyPromise); writer._readyPromise_reject(reason); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) { assert(writer._readyPromise_resolve === undefined); assert(writer._readyPromise_reject === undefined); defaultWriterReadyPromiseInitialize(writer); } function defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) { assert(writer._readyPromise_resolve === undefined); assert(writer._readyPromise_reject === undefined); defaultWriterReadyPromiseInitializeAsRejected(writer, reason); } function defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) { if (writer._readyPromise_resolve === undefined) { return; } writer._readyPromise_resolve(undefined); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'fulfilled'; }
the_stack
import { test_06_html } from "../parser/parser.test"; import parse from "../parser/parser"; import { PageContent, Color, StatePages } from "../pageModel"; import { SENTINEL_CONTENT } from "../contentTree/tree"; import { SENTINEL_INDEX } from "../tree/tree"; import { SENTINEL_STRUCTURE } from "./tree"; import { TagType } from "./structureModel"; import { SplitStructureAction, SPLIT_STRUCTURE_NODE } from "./actions"; import { splitStructureNode } from "./split"; import pageReducer from "../reducer"; import { splitStructureNode as splitStructureNodeActionCreator } from "./actions"; Date.now = jest.fn().mockReturnValue(1234567890); const expectedPage_1_2_1 = (): PageContent => ({ buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 102, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 4, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 16, parent: 4, right: SENTINEL_INDEX, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 3, leftSubTreeLength: 1, length: 0, parent: 2, right: 5, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 4, right: SENTINEL_INDEX, tag: "br", tagType: TagType.StartEndTag, }, ], root: 2, }, title: "This is the title", }); const expectedPage_1_2_2 = (): PageContent => ({ buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 102, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 3, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 5, leftSubTreeLength: 1, length: 16, parent: 2, right: 4, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "br", tagType: TagType.StartEndTag, }, ], root: 2, }, title: "This is the title", }); describe("Tests for splitting `StructureNode`s.", (): void => { test("1.1.1 Split the final `StructureNode`.", (): void => { const page = parse(test_06_html); const expectedPage: PageContent = { buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 102, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 4, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 13, parent: 4, right: SENTINEL_INDEX, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 3, leftSubTreeLength: 1, length: 0, parent: 2, right: 5, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Black, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 3, parent: 4, right: 6, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 6 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 5, right: SENTINEL_INDEX, tag: "p", tagType: TagType.EndTag, }, ], root: 2, }, title: "This is the title", }; const action: SplitStructureAction = { localOffset: 13, nodeIndex: 3, nodeOffset: 115, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage); }); test("1.1.2 Split the first `StructureNode`.", (): void => { const page = parse(test_06_html); const expectedPage: PageContent = { buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 19, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 3, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 5, leftSubTreeLength: 2, length: 16, parent: 2, right: 4, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Black, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 83, parent: 3, right: 6, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 6 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 5, right: SENTINEL_INDEX, tag: "p", tagType: TagType.EndTag, }, ], root: 2, }, title: "This is the title", }; const action: SplitStructureAction = { localOffset: 19, nodeIndex: 1, nodeOffset: 19, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage); }); test("1.2.1 Create a new `StructureNode` after the final `StructureNode`.", (): void => { const page = parse(test_06_html); const action: SplitStructureAction = { localOffset: 16, nodeIndex: 3, nodeOffset: 115, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage_1_2_1()); }); test("1.2.2 Create a new `StructureNode` after the first `StructureNode`.", (): void => { const page = parse(test_06_html); const action: SplitStructureAction = { localOffset: 102, nodeIndex: 1, nodeOffset: 0, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage_1_2_2()); }); test("1.3.1 Inserts an empty `<br />` tag after the existing `<br />` tag", (): void => { const page = expectedPage_1_2_1(); const expectedPage: PageContent = { buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 102, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 4, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 16, parent: 4, right: SENTINEL_INDEX, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 3, leftSubTreeLength: 1, length: 0, parent: 2, right: 5, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Black, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 4, right: 6, tag: "br", tagType: TagType.StartEndTag, }, { // 6 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 5, right: SENTINEL_INDEX, tag: "br", tagType: TagType.StartEndTag, }, ], root: 2, }, title: "This is the title", }; const action: SplitStructureAction = { localOffset: 0, nodeIndex: 5, nodeOffset: 118, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage); }); test("1.3.2 Inserts an empty `<br />` tag after the existing `<br />` tag", (): void => { const page = expectedPage_1_2_2(); const expectedPage: PageContent = { buffers: [ { content: "**Bold** text which has _italics_ and {text-decoration:underline}underlines{text-decoration:underline}{!cite} Citation", isReadOnly: true, lineStarts: [0], }, ], charset: "utf-8", content: { nodes: [ SENTINEL_CONTENT, { bufferIndex: 0, color: Color.Black, end: { column: 118, line: 0 }, left: SENTINEL_INDEX, leftCharCount: 0, leftLineFeedCount: 0, length: 118, lineFeedCount: 0, parent: SENTINEL_INDEX, right: SENTINEL_INDEX, start: { column: 0, line: 0 }, }, ], root: 1, }, created: "2018-09-03T14:08:00.0000000", dataAbsoluteEnabled: true, defaultStyle: { fontFamily: "Calibri", fontSize: "11pt", }, language: "en-NZ", previouslyInsertedContentNodeIndex: 1, previouslyInsertedContentNodeOffset: 0, structure: { nodes: [ SENTINEL_STRUCTURE, { // 1 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 102, parent: 2, right: SENTINEL_INDEX, style: { marginBottom: "0pt", marginTop: "0pt", }, tag: "p", tagType: TagType.StartTag, }, { // 2 color: Color.Black, id: "p:{6cb59116-8e61-03a9-39ef-edf64004790d}{62}", left: 1, leftSubTreeLength: 1, length: 0, parent: SENTINEL_INDEX, right: 3, tag: "p", tagType: TagType.EndTag, }, { // 3 color: Color.Red, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: 5, leftSubTreeLength: 2, length: 16, parent: 2, right: 4, style: { color: "#595959", fontSize: "9pt", marginBottom: "0pt", marginTop: "0pt", }, tag: "cite", tagType: TagType.StartTag, }, { // 4 color: Color.Black, id: "cite:{28216e73-1f0a-05fd-25c5-a04844147e70}{16}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: SENTINEL_INDEX, tag: "cite", tagType: TagType.EndTag, }, { // 5 color: Color.Black, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 3, right: 6, tag: "br", tagType: TagType.StartEndTag, }, { // 6 color: Color.Red, id: "local:p:{1234567890}", left: SENTINEL_INDEX, leftSubTreeLength: 0, length: 0, parent: 5, right: SENTINEL_INDEX, tag: "br", tagType: TagType.StartEndTag, }, ], root: 2, }, title: "This is the title", }; const action: SplitStructureAction = { localOffset: 0, nodeIndex: 5, nodeOffset: 102, pageId: "", type: SPLIT_STRUCTURE_NODE, }; splitStructureNode(page, action); expect(page).toStrictEqual(expectedPage); }); test("1.4 Reducer test", (): void => { const state: StatePages = { pageId: parse(test_06_html), }; const action = splitStructureNodeActionCreator("pageId", 3, 115, 16); const newState = pageReducer(state, action); expect(newState).toStrictEqual({ pageId: expectedPage_1_2_1(), }); }); });
the_stack
import BigNumber from 'bignumber.js'; import { getSolo } from '../helpers/Solo'; import { TestSolo } from '../modules/TestSolo'; import { snapshot, resetEVM, fastForward, mineAvgBlock } from '../helpers/EVM'; import { INTEGERS, ADDRESSES } from '../../src/lib/Constants'; import { address, BigNumberable, SendOptions } from '../../src/types'; import { expectThrow } from '../../src/lib/Expect'; const CURVE_FEE_DENOMINATOR = 10000000000; const DAI_DECIMALS = 18; const USDC_DECIMALS = 6; let solo: TestSolo; let accounts: address[]; let admin: address; let poker: address; let rando: address; let marketMaker: address; const defaultPrice = new BigNumber('1e18'); describe('DaiPriceOracle', () => { let snapshotId: string; beforeAll(async () => { const r = await getSolo(); solo = r.solo; accounts = r.accounts; admin = accounts[0]; marketMaker = accounts[6]; poker = accounts[9]; rando = accounts[8]; await resetEVM(); const tokenAmount = new BigNumber('1e19'); await Promise.all([ solo.oracle.daiPriceOracle.setPokerAddress(poker, { from: admin }), solo.testing.tokenB.issueTo(tokenAmount, marketMaker), solo.weth.wrap(marketMaker, tokenAmount), ]); snapshotId = await snapshot(); }); beforeEach(async () => { await resetEVM(snapshotId); }); describe('saiPriceOracle', () => { it('Returns the correct address', async () => { const saiPriceOracleAddress = ADDRESSES.TEST_SAI_PRICE_ORACLE; expect(solo.contracts.saiPriceOracle.options.address).toEqual(saiPriceOracleAddress); expect(solo.contracts.saiPriceOracle._address).toEqual(saiPriceOracleAddress); }); }); describe('getPrice', () => { it('Returns the default value', async () => { const price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).toEqual(defaultPrice); }); it('Can be set as the oracle for a market', async () => { await solo.admin.addMarket( solo.testing.tokenA.getAddress(), solo.contracts.daiPriceOracle.options.address, solo.contracts.testInterestSetter.options.address, INTEGERS.ZERO, INTEGERS.ZERO, { from: admin }, ); const price = await solo.getters.getMarketPrice(INTEGERS.ZERO); expect(price).toEqual(defaultPrice); }); it('Matches priceInfo', async () => { await Promise.all([ setCurvePrice('0.98'), setUniswapPrice('0.97'), ]); await updatePrice(); const priceInfo = await solo.oracle.daiPriceOracle.getPriceInfo(); const price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).toEqual(priceInfo.price); }); }); describe('ownerSetPriceOracle', () => { it('Fails for non-owner', async () => { await expectThrow( solo.oracle.daiPriceOracle.setPokerAddress(marketMaker, { from: rando }), ); }); it('Succeeds', async () => { const oldPoker = await solo.oracle.daiPriceOracle.getPoker(); await solo.oracle.daiPriceOracle.setPokerAddress(marketMaker, { from: admin }); const newPoker = await solo.oracle.daiPriceOracle.getPoker(); expect(newPoker).toEqual(marketMaker); expect(newPoker).not.toEqual(oldPoker); }); }); describe('updatePrice', () => { it('Does not update for non-poker', async () => { await Promise.all([ setCurvePrice('0.99'), setUniswapPrice('1.00'), ]); await expectThrow( updatePrice( null, null, { from: rando }, ), 'DaiPriceOracle: Only poker can call updatePrice', ); }); it('Updates timestamp correctly', async () => { await Promise.all([ setCurvePrice('0.99'), setUniswapPrice('1.00'), ]); const txResult = await updatePrice(); const { timestamp } = await solo.web3.eth.getBlock(txResult.blockNumber); const priceInfo = await solo.oracle.daiPriceOracle.getPriceInfo(); expect(priceInfo.lastUpdate).toEqual(new BigNumber(timestamp)); console.log(`\tUpdate Dai Price gas used: ${txResult.gasUsed}`); }); it('Emits an event', async () => { await Promise.all([ setCurvePrice('0.98'), setUniswapPrice('0.97'), ]); const txResult = await updatePrice(); const priceInfo = await solo.oracle.daiPriceOracle.getPriceInfo(); const log = txResult.events.PriceSet; expect(log).not.toBeUndefined(); expect(new BigNumber(log.returnValues.newPriceInfo.price)).toEqual(priceInfo.price); expect(new BigNumber(log.returnValues.newPriceInfo.lastUpdate)).toEqual(priceInfo.lastUpdate); }); it('Matches getBoundedTargetPrice', async () => { await Promise.all([ setCurvePrice('1.05'), setUniswapPrice('1.07'), ]); await fastForward(1000); const boundedPrice = await solo.oracle.daiPriceOracle.getBoundedTargetPrice(); await updatePrice(); const price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).toEqual(boundedPrice); }); it('Will migrate to the right price over many updates', async () => { await Promise.all([ setCurvePrice('1.025'), setUniswapPrice('1.04'), ]); let price: any; const targetPrice = await solo.oracle.daiPriceOracle.getTargetPrice(); await fastForward(1000); await updatePrice(); price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).not.toEqual(targetPrice); await fastForward(1000); await updatePrice(); price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).not.toEqual(targetPrice); await fastForward(1000); await updatePrice(); price = await solo.oracle.daiPriceOracle.getPrice(); expect(price).toEqual(targetPrice); }); it('Fails below minimum', async () => { await Promise.all([ setCurvePrice('0.97'), setUniswapPrice('0.96'), ]); await expectThrow( updatePrice( defaultPrice, null, ), 'DaiPriceOracle: newPrice below minimum', ); }); it('Fails above maximum', async () => { await Promise.all([ setCurvePrice('1.02'), setUniswapPrice('1.04'), ]); await expectThrow( updatePrice( null, defaultPrice, ), 'DaiPriceOracle: newPrice above maximum', ); }); }); describe('getTargetPrice', () => { it('Succeeds for price = dollar', async () => { let price: BigNumber; await Promise.all([ setCurvePrice('1.01'), setUniswapPrice('0.99'), ]); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(defaultPrice); await Promise.all([ setCurvePrice('0.99'), setUniswapPrice('1.01'), ]); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(defaultPrice); }); it('Succeeds for price < dollar', async () => { let price: BigNumber; await Promise.all([ setCurvePrice('0.95'), setUniswapPrice('0.98'), ]); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(defaultPrice.times('0.98')); await setUniswapPrice('0.50'); const curvePrice = await solo.oracle.daiPriceOracle.getCurvePrice(); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(curvePrice); }); it('Succeeds for price > dollar', async () => { let price: BigNumber; await Promise.all([ setCurvePrice('1.04'), setUniswapPrice('1.02'), ]); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(defaultPrice.times('1.02')); await setUniswapPrice('2.00'); const curvePrice = await solo.oracle.daiPriceOracle.getCurvePrice(); price = await solo.oracle.daiPriceOracle.getTargetPrice(); expect(price).toEqual(curvePrice); }); }); describe('getBoundedTargetPrice', () => { it('Upper-bounded by maximum absolute deviation', async () => { await fastForward(1000); await Promise.all([ setCurvePrice('1.10'), setUniswapPrice('1.10'), ]); const price = await solo.oracle.daiPriceOracle.getBoundedTargetPrice(); expect(price).toEqual(defaultPrice.times('1.01')); }); it('Lower-bounded by maximum absolute deviation', async () => { await fastForward(1000); await Promise.all([ setCurvePrice('0.90'), setUniswapPrice('0.90'), ]); const price = await solo.oracle.daiPriceOracle.getBoundedTargetPrice(); expect(price).toEqual(defaultPrice.times('0.99')); }); it('Upper-bounded by maximum deviation per second', async () => { await Promise.all([ setCurvePrice('1.10'), setUniswapPrice('1.10'), ]); await updatePrice(); await mineAvgBlock(); const price = await solo.oracle.daiPriceOracle.getPrice(); const boundedPrice = await solo.oracle.daiPriceOracle.getBoundedTargetPrice(); expect(boundedPrice.gt(price)).toEqual(true); expect(boundedPrice.lt(price.times('1.01'))).toEqual(true); }); it('Lower-bounded by maximum deviation per second', async () => { await Promise.all([ setCurvePrice('0.90'), setUniswapPrice('0.90'), ]); await updatePrice(); await mineAvgBlock(); const price = await solo.oracle.daiPriceOracle.getPrice(); const boundedPrice = await solo.oracle.daiPriceOracle.getBoundedTargetPrice(); expect(boundedPrice.lt(price)).toEqual(true); expect(boundedPrice.gt(price.times('0.99'))).toEqual(true); }); }); describe('getCurvePrice', () => { it('Returns the price, adjusting for the fee', async () => { await setCurvePrice('1.05'); const price = await solo.oracle.daiPriceOracle.getCurvePrice(); // Allow rounding error. const expectedPrice = new BigNumber('1.05').shiftedBy(18); expect(price.div(expectedPrice).minus(1).abs().toNumber()).toBeLessThan(1e-10); }); }); describe('getUniswapPrice', () => { it('Fails for zero liquidity', async () => { await expectThrow( solo.oracle.daiPriceOracle.getUniswapPrice(), ); }); it('Gets the right price for ETH-DAI = ETH-USDC', async () => { await setUniswapPrice(1); const price = await solo.oracle.daiPriceOracle.getUniswapPrice(); expect(price).toEqual(defaultPrice); }); it('Gets the right price for ETH-DAI > ETH-USDC', async () => { await setUniswapPrice(0.975); const price = await solo.oracle.daiPriceOracle.getUniswapPrice(); expect(price).toEqual(new BigNumber(0.975).shiftedBy(18)); }); it('Gets the right price for ETH-DAI < ETH-USDC', async () => { await setUniswapPrice(1.025); const price = await solo.oracle.daiPriceOracle.getUniswapPrice(); expect(price).toEqual(new BigNumber(1.025).shiftedBy(18)); }); it('Does not overflow when the pools hold on the order of $100B in value', async () => { await Promise.all([ // Suppose ETH has a price of $1. setUniswapEthDaiBalances( new BigNumber(100e9).shiftedBy(18), // ethAmt new BigNumber(100e9).shiftedBy(18), // daiAmt ), setUniswapEthUsdcBalances( new BigNumber(100e9).shiftedBy(18), // ethAmt new BigNumber(100e9).shiftedBy(6), // usdcAmt ), ]); const price = await solo.oracle.daiPriceOracle.getUniswapPrice(); expect(price).toEqual(defaultPrice); }); }); }); // ============ Helper Functions ============ async function setCurvePrice( price: BigNumberable, ) { // Add the fee. const fee = await solo.contracts.call( solo.contracts.testCurve.methods.fee(), ) as string; // dy is the amount of DAI received for 1 USDC, i.e. the reciprocal of the DAI-USDC price. const dy = new BigNumber(1).div(price); // Apply the fee which would be applied by the Curve contract. const feeAmount = dy.times(fee).div(CURVE_FEE_DENOMINATOR); const dyWithFee = dy.minus(feeAmount); await solo.contracts.send( solo.contracts.testCurve.methods.setDy( // Curve will treat dx and dy in terms of the base units of the currencies, so shift the value // to be returned by the difference between the decimals of DAI and USDC. dyWithFee.shiftedBy(DAI_DECIMALS - USDC_DECIMALS).toFixed(0), ), ); } async function setUniswapPrice( price: BigNumberable, ) { const ethPrice = new BigNumber(100); await Promise.all([ // Apply an arbitrary constant factor to the balances of each pool. setUniswapEthDaiBalances( new BigNumber(1).times(1.23).shiftedBy(18), // ethAmt ethPrice.times(1.23).shiftedBy(18), // daiAmt ), setUniswapEthUsdcBalances( new BigNumber(1).times(2.34).shiftedBy(18), // ethAmt ethPrice.times(price).times(2.34).shiftedBy(6), // usdcAmt ), ]); } async function setUniswapEthDaiBalances( ethAmt: BigNumberable, daiAmt: BigNumberable, ) { await solo.contracts.send( solo.contracts.testUniswapV2Pair.methods.setReserves( new BigNumber(daiAmt).toFixed(0), new BigNumber(ethAmt).toFixed(0), ), ); } async function setUniswapEthUsdcBalances( ethAmt: BigNumberable, usdcAmt: BigNumberable, ) { await solo.contracts.send( solo.contracts.testUniswapV2Pair2.methods.setReserves( new BigNumber(usdcAmt).toFixed(0), new BigNumber(ethAmt).toFixed(0), ), ); } async function updatePrice( minimum?: BigNumber, maximum?: BigNumber, options?: SendOptions, ) { return solo.oracle.daiPriceOracle.updatePrice(minimum, maximum, options || { from: poker }); }
the_stack
import * as angular from 'angular'; import { TableRowSelectModeEnum } from './tableRowSelectModeEnum'; import { TableTypeEnum } from './tableTypeEnum'; /** * @ngdoc interface * @name ITableScope * @module officeuifabric.components.table * * @description * Scope used by the table controller. * * @property {string} orderBy - Specifies the name of the property used to sort the table. Default null * @property {boolean} orderAsc - Specifies whether the data in the table should be sort ascending or descendiangular. * Default `true` (sorting ascending) * @property {string} rowSelectMode - Specifies the row selection mode used by the table * @property {ITableRowScope[]} rows - Contains the data rows (all except the header row) that belong to the table * @property {any} selectedItems - Contains an array with the selected items that belong to the table */ export interface ITableScope extends angular.IScope { orderBy?: string; orderAsc: boolean; rowSelectMode?: string; rows: ITableRowScope[]; tableType: string; tableTypeClass: string; selectedItems: any; } class TableController { public static $inject: string[] = ['$scope', '$log']; constructor(public $scope: ITableScope, public $log: angular.ILogService) { this.$scope.orderBy = null; this.$scope.orderAsc = true; this.$scope.rows = []; if (!this.$scope.selectedItems) { this.$scope.selectedItems = []; } } get orderBy(): string { return this.$scope.orderBy; } set orderBy(property: string) { this.$scope.orderBy = property; this.$scope.$digest(); } get orderAsc(): boolean { return this.$scope.orderAsc; } set orderAsc(orderAsc: boolean) { this.$scope.orderAsc = orderAsc; this.$scope.$digest(); } get rowSelectMode(): string { return this.$scope.rowSelectMode; } set rowSelectMode(rowSelectMode: string) { if (TableRowSelectModeEnum[rowSelectMode] === undefined) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' + '\'' + rowSelectMode + '\' is not a valid option for \'uif-row-select-mode\'. ' + 'Valid options are none|single|multiple.'); } this.$scope.rowSelectMode = rowSelectMode; this.$scope.$digest(); } get rows(): ITableRowScope[] { return this.$scope.rows; } set rows(rows: ITableRowScope[]) { this.$scope.rows = rows; } get selectedItems(): any[] { return this.$scope.selectedItems; } } /** * @ngdoc interface * @name ITableAttributes * @module officeuifabric.components.table * * @description * Attributes used by the table directive. * * @property {string} uifRowSelectMode - Specifies whether the table supports selecting rows. * Possible values: none - selecting rows is not possible; * single - only one row can be selected; * multiple - multiple rows can be selected; * @property {string} uifTableType - Specifies whether the table is rendered in fluid or fixed mode. * Possible values: fixed - the table is rendered in fixed style. * Added with Fabric 2.4. * fluid - the table style is fluid (Default) * @property {any} uifSelectedItems - Specifies the array which will be used to store the selected items * of the table */ export interface ITableAttributes extends angular.IAttributes { uifRowSelectMode?: string; uifTableType?: string; uifSelectedItems?: any; } /** * @ngdoc directive * @name uifTable * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table>` is a table directive. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table uif-selected-items="selectedItems"> * <uif-table-head> * <uif-table-row> * <uif-table-row-select></uif-table-row-select> * <uif-table-header>File name</uif-table-header> * <uif-table-header>Location</uif-table-header> * <uif-table-header>Modified</uif-table-header> * <uif-table-header>Type</uif-table-header> * </uif-table-row> * </uif-table-head> * <uif-table-body> * <uif-table-row ng-repeat="f in files" uif-selected="{{f.isSelected}}"> * <uif-table-row-select></uif-table-row-select> * <uif-table-cell>{{f.fileName}}</uif-table-cell> * <uif-table-cell>{{f.location}}</uif-table-cell> * <uif-table-cell>{{f.modified | date}}</uif-table-cell> * <uif-table-cell>{{f.type}}</uif-table-cell> * </uif-table-row> * </uif-table-body> * </uif-table> */ export class TableDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; // required for correct HTML rendering public template: string = '<table ng-class="[\'ms-Table\', tableTypeClass]" ng-transclude></table>'; public controller: any = TableController; public controllerAs: string = 'table'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableDirective(); return directive; } public link(scope: ITableScope, instanceElement: angular.IAugmentedJQuery, attrs: ITableAttributes, controller: TableController): void { // add support for selected items but due to not able to use isolate scope a workaround is used if (attrs.uifSelectedItems !== undefined && attrs.uifSelectedItems !== null) { let selectedItems: any = null; // check currentscope if it contains the selected item property selectedItems = scope.$eval(attrs.uifSelectedItems); // just to make sure it doesn't fail when not used if (selectedItems === undefined || selectedItems === null) { selectedItems = []; } scope.selectedItems = selectedItems; } if (attrs.uifRowSelectMode !== undefined && attrs.uifRowSelectMode !== null) { if (TableRowSelectModeEnum[attrs.uifRowSelectMode] === undefined) { controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' + '\'' + attrs.uifRowSelectMode + '\' is not a valid option for \'uif-row-select-mode\'. ' + 'Valid options are none|single|multiple.'); } else { scope.rowSelectMode = attrs.uifRowSelectMode; } } if (scope.rowSelectMode === undefined) { scope.rowSelectMode = TableRowSelectModeEnum[TableRowSelectModeEnum.none]; } if (attrs.uifTableType !== undefined && attrs.uifTableType !== null) { if (TableTypeEnum[attrs.uifTableType] === undefined) { controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' + '\'' + attrs.uifTableType + '\' is not a valid option for \'uif-table-type\'. ' + 'Valid options are fixed|fluid.'); } else { scope.tableType = attrs.uifTableType; } } if (scope.tableType === undefined) { scope.tableType = TableTypeEnum[TableTypeEnum.fluid]; } if (scope.tableType === TableTypeEnum[TableTypeEnum.fixed]) { scope.tableTypeClass = 'ms-Table--fixed'; } } } /** * @ngdoc interface * @name ITableRowScope * @module officeuifabric.components.table * * @description * Scope used by the table row controller. * * @property {any} item - Contains data item bound to the table row * @property {(ev: any) => void} rowClick - event handler for clicking the row * @property {boolean} selected - Specifies whether the particular row is selected or not */ export interface ITableRowScope extends angular.IScope { item: any; rowClick: (ev: any) => void; selected: boolean; } class TableRowController { public static $inject: string[] = ['$scope', '$log']; constructor(public $scope: ITableRowScope, public $log: angular.ILogService) { } get item(): any { return this.$scope.item; } set item(item: any) { this.$scope.item = item; this.$scope.$digest(); } get selected(): boolean { return this.$scope.selected; } set selected(selected: boolean) { this.$scope.selected = selected; this.$scope.$digest(); } } /** * @ngdoc interface * @name ITableRowAttributes * @module officeuifabric.components.table * * @description * Attributes used by the table row directive. * * @property {string} uifSelected - Specifies whether the particular row is selected or not * @property {any} uifItem - Data item bound to the row */ export interface ITableRowAttributes extends angular.IAttributes { uifSelected?: string; uifItem?: any; } /** * @ngdoc directive * @name uifTableRow * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-row>` is a table row directive. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table-row ng-repeat="f in files" uif-selected="{{f.isSelected}}"> * <uif-table-row-select></uif-table-row-select> * <uif-table-cell>{{f.fileName}}</uif-table-cell> * <uif-table-cell>{{f.location}}</uif-table-cell> * <uif-table-cell>{{f.modified | date}}</uif-table-cell> * <uif-table-cell>{{f.type}}</uif-table-cell> * </uif-table-row> */ export class TableRowDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; // required for correct HTML rendering public template: string = '<tr ng-transclude></tr>'; public require: string = '^uifTable'; public scope: {} = { item: '=uifItem' }; public controller: any = TableRowController; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableRowDirective(); return directive; } public link( scope: ITableRowScope, instanceElement: angular.IAugmentedJQuery, attrs: ITableRowAttributes, table: TableController): void { if (attrs.uifSelected !== undefined && attrs.uifSelected !== null) { let selectedString: string = attrs.uifSelected.toLowerCase(); if (selectedString !== 'true' && selectedString !== 'false') { table.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' + '\'' + attrs.uifSelected + '\' is not a valid boolean value. ' + 'Valid options are true|false.'); } else { if (selectedString === 'true') { scope.selected = true; } } } // don't treat header row as a table row if (scope.item !== undefined) { table.rows.push(scope); } scope.rowClick = (ev: any): void => { scope.selected = !scope.selected; scope.$apply(); }; scope.$watch('selected', (newValue: boolean, oldValue: boolean, tableRowScope: ITableRowScope): void => { if (newValue === true) { if (table.rowSelectMode === TableRowSelectModeEnum[TableRowSelectModeEnum.single]) { // unselect other items if (table.rows) { for (let i: number = 0; i < table.rows.length; i++) { if (table.rows[i] !== tableRowScope) { table.rows[i].selected = false; } } table.selectedItems.splice(0, table.selectedItems.length - 1); table.selectedItems.push(tableRowScope.item); } } // only add to the list if not yet exists. prevents conflicts // with preselected items let itemAlreadySelected: boolean = false; for (let i: number = 0; i < table.selectedItems.length; i++) { if (table.selectedItems[i] === tableRowScope.item) { itemAlreadySelected = true; break; } } if (!itemAlreadySelected) { table.selectedItems.push(tableRowScope.item); } instanceElement.addClass('is-selected'); } else { for (let i: number = 0; i < table.selectedItems.length; i++) { if (table.selectedItems[i] === tableRowScope.item) { table.selectedItems.splice(i, 1); break; } } instanceElement.removeClass('is-selected'); } }); if (table.rowSelectMode !== TableRowSelectModeEnum[TableRowSelectModeEnum.none] && scope.item !== undefined) { instanceElement.on('click', scope.rowClick); } if (table.rowSelectMode === TableRowSelectModeEnum[TableRowSelectModeEnum.none]) { instanceElement.css('cursor', 'default'); } } } /** * @ngdoc interface * @name ITableRowSelectScope * @module officeuifabric.components.table * * @description * Scope used by the table row select directive. * * @property {(ev: any) => void} rowSelectClick - event handler for clicking the row selector */ export interface ITableRowSelectScope extends angular.IScope { rowSelectClick: (ev: any) => void; tagName: string; } /** * @ngdoc directive * @name uifTableRowSelect * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-row-select>` is a directive for the control used to select table rows. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table-row ng-repeat="f in files" uif-selected="{{f.isSelected}}"> * <uif-table-row-select></uif-table-row-select> * <uif-table-cell>{{f.fileName}}</uif-table-cell> * <uif-table-cell>{{f.location}}</uif-table-cell> * <uif-table-cell>{{f.modified | date}}</uif-table-cell> * <uif-table-cell>{{f.type}}</uif-table-cell> * </uif-table-row> */ export class TableRowSelectDirective implements angular.IDirective { public restrict: string = 'E'; public template: string = '<td class="ms-Table-rowCheck"></td>'; public replace: boolean = true; // required for correct HTML rendering public require: string[] = ['^uifTable', '?^uifTableHead', '^uifTableRow']; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableRowSelectDirective(); return directive; } public link( scope: ITableRowSelectScope, instanceElement: angular.IAugmentedJQuery, attrs: angular.IAttributes, controllers: any[]): void { let thead: TableHeadController = controllers[1]; if (thead) { let newElem: angular.IAugmentedJQuery = angular.element('<th class="ms-Table-rowCheck"></th>'); instanceElement.replaceWith(newElem); instanceElement = newElem; } scope.rowSelectClick = (ev: any): void => { let table: TableController = controllers[0]; let row: TableRowController = controllers[2]; if (table.rowSelectMode !== TableRowSelectModeEnum[TableRowSelectModeEnum.multiple]) { return; } // clicking on regular rows which have data items bound to them is already // handled by row click event if (row.item === undefined || row.item === null) { // if set to true all rows will be selected. if set to false all rows will be unselected let shouldSelectAll: boolean = false; for (let i: number = 0; i < table.rows.length; i++) { if (table.rows[i].selected !== true) { shouldSelectAll = true; break; } } for (let i: number = 0; i < table.rows.length; i++) { if (table.rows[i].selected !== shouldSelectAll) { table.rows[i].selected = shouldSelectAll; } } scope.$apply(); } }; instanceElement.on('click', scope.rowSelectClick); } } /** * @ngdoc directive * @name uifTableCell * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-cell>` is a table cell directive. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table-cell>{{f.fileName}}</uif-table-cell> */ export class TableCellDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public template: string = '<td ng-transclude></td>'; public replace: boolean = true; // required for correct HTML rendering public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableCellDirective(); return directive; } } /** * @ngdoc interface * @name ITableHeaderScope * @module officeuifabric.components.table * * @description * Scope used by the table header directive. * * @property {(ev: any) => void} headerClick - event handler for clicking the header cell */ export interface ITableHeaderScope extends angular.IScope { headerClick: (ev: any) => void; } /** * @ngdoc interface * @name ITableHeaderAttributes * @module officeuifabric.components.table * * @description * Attributes used by the table header directive. * * @property {string} uifOrderBy - Specifies name of the property used to sort the table on */ export interface ITableHeaderAttributes extends angular.IAttributes { uifOrderBy: string; } /** * @ngdoc directive * @name uifTableHeader * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-header>` is a table header cell directive. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table-header>File name</uif-table-header> */ export class TableHeaderDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; // required for correct HTML rendering public template: string = '<th ng-transclude></th>'; public require: string = '^uifTable'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableHeaderDirective(); return directive; } public link( scope: ITableHeaderScope, instanceElement: angular.IAugmentedJQuery, attrs: ITableHeaderAttributes, table: TableController): void { scope.headerClick = (ev: any): void => { if (table.orderBy === attrs.uifOrderBy) { table.orderAsc = !table.orderAsc; } else { table.orderBy = attrs.uifOrderBy; table.orderAsc = true; } }; scope.$watch('table.orderBy', (newOrderBy: string, oldOrderBy: string, tableHeaderScope: ITableHeaderScope): void => { if (oldOrderBy !== newOrderBy && newOrderBy === attrs.uifOrderBy) { let cells: JQuery = instanceElement.parent().children(); for (let i: number = 0; i < cells.length; i++) { let _children: JQuery = cells.eq(i).children(); if (_children.length > 0) { let _sorter: JQuery = _children.eq(_children.length - 1); if (_sorter.hasClass('uif-sort-order')) { _sorter.remove(); } } } instanceElement.append('<span class="uif-sort-order">&nbsp;\ <i class="ms-Icon ms-Icon--caretDown" aria-hidden="true"></i></span>'); } }); scope.$watch('table.orderAsc', (newOrderAsc: boolean, oldOrderAsc: boolean, tableHeaderScope: ITableHeaderScope): void => { if (instanceElement.children().length > 0) { let _sorter: JQuery = instanceElement.children().eq(instanceElement.children().length - 1); if (_sorter.hasClass('uif-sort-order')) { let oldCssClass: string = oldOrderAsc ? 'ms-Icon--caretDown' : 'ms-Icon--caretUp'; let newCssClass: string = newOrderAsc ? 'ms-Icon--caretDown' : 'ms-Icon--caretUp'; _sorter.children().eq(0).removeClass(oldCssClass).addClass(newCssClass); } } }); if ('uifOrderBy' in attrs) { instanceElement.on('click', scope.headerClick); } } } class TableHeadController { } /** * @ngdoc directive * @name uifTableHead * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-head>` is a table head directive that denotes table head rows. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table> * <uif-table-head> * <uif-table-row>...</uif-table-row> * </uif-table-head> * </uif-table> */ export class TableHeadDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public template: string = '<thead ng-transclude></thead>'; public replace: boolean = true; // required for correct HTML rendering public controller: any = TableHeadController; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableHeadDirective(); return directive; } } /** * @ngdoc directive * @name uifTableBody * @module officeuifabric.components.table * * @restrict E * * @description * `<uif-table-body>` is a table body directive that denotes table body rows. * * @see {link http://dev.office.com/fabric/components/table} * * @usage * * <uif-table> * <uif-table-body> * <uif-table-row>...</uif-table-row> * </uif-table-body> * </uif-table> */ export class TableBodyDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public template: string = '<tbody ng-transclude></tbody>'; public replace: boolean = true; // required for correct HTML rendering public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new TableBodyDirective(); return directive; } } /** * @ngdoc module * @name officeuifabric.components.table * * @description * Table */ export let module: angular.IModule = angular.module('officeuifabric.components.table', ['officeuifabric.components']) .directive('uifTable', TableDirective.factory()) .directive('uifTableRow', TableRowDirective.factory()) .directive('uifTableRowSelect', TableRowSelectDirective.factory()) .directive('uifTableCell', TableCellDirective.factory()) .directive('uifTableHeader', TableHeaderDirective.factory()) .directive('uifTableHead', TableHeadDirective.factory()) .directive('uifTableBody', TableBodyDirective.factory());
the_stack