language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Exercises extends React.Component { constructor(props) { super(); this.state = { classes: props, log: { username: props.currentUser.username, exercise: props.currentWorkout.name, } }; } componentDidMount() { // this.props.toLogs(this.state.log) this.props.getExercises(this.props.currentUser.uid) // this.props.getUserLogs(this.props.currentUser.username) } render() { console.log("something5"); return ( <div className="App"> <Paper className={this.state.classes.root}> <Tables /> </Paper> <div className="profile"> <div className="leftcolumn"></div> <div className="mainColumn"></div> </div> </div> ); } }
JavaScript
class FocusAndDirectrixModel extends GQModel { /** * @param {Tandem} tandem */ constructor( tandem ) { // p const pProperty = new NumberProperty( P_RANGE.defaultValue, merge( { range: P_RANGE, isValidValue: value => ( value !== 0 ), // zero is not supported tandem: tandem.createTandem( 'pProperty' ), phetioDocumentation: StringUtils.fillIn( GQConstants.VALUE_DOC, { symbol: 'p' } ) }, { // Opt out of providing a slider in Studio. A generic slider will cause problems, since zero is not supported. // See https://github.com/phetsims/graphing-quadratics/issues/52 phetioStudioControl: false } ) ); phet.log && pProperty.link( p => { phet.log( `p=${p}` ); } ); // h const hProperty = new NumberProperty( H_RANGE.defaultValue, { range: H_RANGE, tandem: tandem.createTandem( 'hProperty' ), phetioDocumentation: StringUtils.fillIn( GQConstants.VALUE_DOC, { symbol: 'h' } ) } ); phet.log && hProperty.link( h => { phet.log( `h=${h}` ); } ); // k const kProperty = new NumberProperty( K_RANGE.defaultValue, { range: K_RANGE, tandem: tandem.createTandem( 'kProperty' ), phetioDocumentation: StringUtils.fillIn( GQConstants.VALUE_DOC, { symbol: 'k' } ) } ); phet.log && kProperty.link( k => { phet.log( `k=${k}` ); } ); // {DerivedProperty.<Quadratic>} const quadraticProperty = new DerivedProperty( [ pProperty, hProperty, kProperty ], ( p, h, k ) => Quadratic.createFromAlternateVertexForm( p, h, k, { color: GQColors.FOCUS_AND_DIRECTRIX_INTERACTIVE_CURVE } ), { tandem: tandem.createTandem( 'quadraticProperty' ), phetioDocumentation: 'the interactive quadratic, derived from p, h, and k', phetioType: DerivedProperty.DerivedPropertyIO( Quadratic.QuadraticIO ) } ); phet.log && quadraticProperty.link( quadratic => { phet.log( `quadratic: y = (1/(4(${quadratic.p})))(x - ${quadratic.h})^2 + ${quadratic.k}` ); } ); super( quadraticProperty, tandem ); // @public this.pProperty = pProperty; this.hProperty = hProperty; this.kProperty = kProperty; const initialPoint = new Vector2( POINT_X, this.quadraticProperty.value.solveY( POINT_X ) ); // @public this.pointOnParabolaProperty = new Vector2Property( initialPoint, { tandem: tandem.createTandem( 'pointOnParabolaProperty' ), phetioDocumentation: 'the interactive point on the parabola' } ); // update the point this.quadraticProperty.lazyLink( ( quadratic, oldQuadratic ) => { assert && assert( quadratic.vertex, `expected quadratic.vertex: ${quadratic.vertex}` ); assert && assert( oldQuadratic.vertex, `expected oldQuadratic.vertex: ${oldQuadratic.vertex}` ); if ( !phet.joist.sim.isSettingPhetioStateProperty.value ) { const dx = quadratic.vertex.x - oldQuadratic.vertex.x; const x = this.pointOnParabolaProperty.value.x + dx; this.pointOnParabolaProperty.value = quadratic.getClosestPointInRange( x, this.graph.xRange, this.graph.yRange ); } } ); } /** * @public * @override */ reset() { super.reset(); this.pProperty.reset(); this.hProperty.reset(); this.kProperty.reset(); this.pointOnParabolaProperty.reset(); } }
JavaScript
class CockroachDriver { // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(connection) { /** * Pool for slave databases. * Used in replication. */ this.slaves = []; /** * We store all created query runners because we need to release them. */ this.connectedQueryRunners = []; /** * Indicates if replication is enabled. */ this.isReplicated = false; /** * Indicates if tree tables are supported by this driver. */ this.treeSupport = true; /** * Represent transaction support by this driver */ this.transactionSupport = "nested"; /** * Gets list of supported column data types by a driver. * * @see https://www.cockroachlabs.com/docs/stable/data-types.html */ this.supportedDataTypes = [ "array", "bool", "boolean", "bytes", "bytea", "blob", "date", "numeric", "decimal", "dec", "float", "float4", "float8", "double precision", "real", "inet", "int", "int4", "integer", "int2", "int8", "int64", "smallint", "bigint", "interval", "string", "character varying", "character", "char", "char varying", "varchar", "text", "time", "time without time zone", "timestamp", "timestamptz", "timestamp without time zone", "timestamp with time zone", "json", "jsonb", "uuid", ]; /** * Returns type of upsert supported by driver if any */ this.supportedUpsertType = "on-conflict-do-update"; /** * Gets list of spatial column data types. */ this.spatialTypes = []; /** * Gets list of column data types that support length by a driver. */ this.withLengthColumnTypes = [ "character varying", "char varying", "varchar", "character", "char", "string", ]; /** * Gets list of column data types that support precision by a driver. */ this.withPrecisionColumnTypes = ["numeric", "decimal", "dec"]; /** * Gets list of column data types that support scale by a driver. */ this.withScaleColumnTypes = ["numeric", "decimal", "dec"]; /** * Orm has special columns and we need to know what database column types should be for those types. * Column types are driver dependant. */ this.mappedDataTypes = { createDate: "timestamptz", createDateDefault: "now()", updateDate: "timestamptz", updateDateDefault: "now()", deleteDate: "timestamptz", deleteDateNullable: true, version: Number, treeLevel: Number, migrationId: Number, migrationName: "varchar", migrationTimestamp: "int8", cacheId: Number, cacheIdentifier: "varchar", cacheTime: "int8", cacheDuration: Number, cacheQuery: "string", cacheResult: "string", metadataType: "varchar", metadataDatabase: "varchar", metadataSchema: "varchar", metadataTable: "varchar", metadataName: "varchar", metadataValue: "string", }; /** * Default values of length, precision and scale depends on column data type. * Used in the cases when length/precision/scale is not specified by user. */ this.dataTypeDefaults = { char: { length: 1 }, }; this.cteCapabilities = { enabled: true, writable: true, materializedHint: true, requiresRecursiveHint: true, }; this.connection = connection; this.options = connection.options; this.isReplicated = this.options.replication ? true : false; // load postgres package this.loadDependencies(); this.database = DriverUtils.buildDriverOptions(this.options.replication ? this.options.replication.master : this.options).database; this.schema = DriverUtils.buildDriverOptions(this.options).schema; // ObjectUtils.assign(this.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way // validate options to make sure everything is set // todo: revisit validation with replication in mind // if (!this.options.host) // throw new DriverOptionNotSetError("host"); // if (!this.options.username) // throw new DriverOptionNotSetError("username"); // if (!this.options.database) // throw new DriverOptionNotSetError("database"); } // ------------------------------------------------------------------------- // Public Implemented Methods // ------------------------------------------------------------------------- /** * Performs connection to the database. * Based on pooling options, it can either create connection immediately, * either create a pool and create connection when needed. */ async connect() { if (this.options.replication) { this.slaves = await Promise.all(this.options.replication.slaves.map((slave) => { return this.createPool(this.options, slave); })); this.master = await this.createPool(this.options, this.options.replication.master); } else { this.master = await this.createPool(this.options, this.options); } if (!this.database || !this.searchSchema) { const queryRunner = await this.createQueryRunner("master"); if (!this.database) { this.database = await queryRunner.getCurrentDatabase(); } if (!this.searchSchema) { this.searchSchema = await queryRunner.getCurrentSchema(); } await queryRunner.release(); } if (!this.schema) { this.schema = this.searchSchema; } } /** * Makes any action after connection (e.g. create extensions in Postgres driver). */ async afterConnect() { return Promise.resolve(); } /** * Closes connection with database. */ async disconnect() { if (!this.master) return Promise.reject(new ConnectionIsNotSetError("cockroachdb")); await this.closePool(this.master); await Promise.all(this.slaves.map((slave) => this.closePool(slave))); this.master = undefined; this.slaves = []; } /** * Creates a schema builder used to build and sync a schema. */ createSchemaBuilder() { return new RdbmsSchemaBuilder(this.connection); } /** * Creates a query runner used to execute database queries. */ createQueryRunner(mode) { return new CockroachQueryRunner(this, mode); } /** * Prepares given value to a value to be persisted, based on its column type and metadata. */ preparePersistentValue(value, columnMetadata) { if (columnMetadata.transformer) value = ApplyValueTransformers.transformTo(columnMetadata.transformer, value); if (value === null || value === undefined) return value; if (columnMetadata.type === Boolean) { return value === true ? 1 : 0; } else if (columnMetadata.type === "date") { return DateUtils.mixedDateToDateString(value); } else if (columnMetadata.type === "time") { return DateUtils.mixedDateToTimeString(value); } else if (columnMetadata.type === "datetime" || columnMetadata.type === Date || columnMetadata.type === "timestamp" || columnMetadata.type === "timestamptz" || columnMetadata.type === "timestamp with time zone" || columnMetadata.type === "timestamp without time zone") { return DateUtils.mixedDateToDate(value); } else if (["json", "jsonb", ...this.spatialTypes].indexOf(columnMetadata.type) >= 0) { return JSON.stringify(value); } else if (columnMetadata.type === "simple-array") { return DateUtils.simpleArrayToString(value); } else if (columnMetadata.type === "simple-json") { return DateUtils.simpleJsonToString(value); } return value; } /** * Prepares given value to a value to be persisted, based on its column type or metadata. */ prepareHydratedValue(value, columnMetadata) { if (value === null || value === undefined) return columnMetadata.transformer ? ApplyValueTransformers.transformFrom(columnMetadata.transformer, value) : value; // unique_rowid() generates bigint value and should not be converted to number if (([Number, "int4", "smallint", "int2"].some((v) => v === columnMetadata.type) && !columnMetadata.isArray) || columnMetadata.generationStrategy === "increment") { value = parseInt(value); } else if (columnMetadata.type === Boolean) { value = value ? true : false; } else if (columnMetadata.type === "datetime" || columnMetadata.type === Date || columnMetadata.type === "timestamp" || columnMetadata.type === "timestamptz" || columnMetadata.type === "timestamp with time zone" || columnMetadata.type === "timestamp without time zone") { value = DateUtils.normalizeHydratedDate(value); } else if (columnMetadata.type === "date") { value = DateUtils.mixedDateToDateString(value); } else if (columnMetadata.type === "time") { value = DateUtils.mixedTimeToString(value); } else if (columnMetadata.type === "simple-array") { value = DateUtils.stringToSimpleArray(value); } else if (columnMetadata.type === "simple-json") { value = DateUtils.stringToSimpleJson(value); } if (columnMetadata.transformer) value = ApplyValueTransformers.transformFrom(columnMetadata.transformer, value); return value; } /** * Replaces parameters in the given sql with special escaping character * and an array of parameter names to be passed to a query. */ escapeQueryWithParameters(sql, parameters, nativeParameters) { const escapedParameters = Object.keys(nativeParameters).map((key) => nativeParameters[key]); if (!parameters || !Object.keys(parameters).length) return [sql, escapedParameters]; sql = sql.replace(/:(\.\.\.)?([A-Za-z0-9_.]+)/g, (full, isArray, key) => { if (!parameters.hasOwnProperty(key)) { return full; } let value = parameters[key]; if (isArray) { return value .map((v) => { escapedParameters.push(v); return this.createParameter(key, escapedParameters.length - 1); }) .join(", "); } if (typeof value === "function") { return value(); } escapedParameters.push(value); return this.createParameter(key, escapedParameters.length - 1); }); // todo: make replace only in value statements, otherwise problems return [sql, escapedParameters]; } /** * Escapes a column name. */ escape(columnName) { return '"' + columnName + '"'; } /** * Build full table name with schema name and table name. * E.g. myDB.mySchema.myTable */ buildTableName(tableName, schema) { let tablePath = [tableName]; if (schema) { tablePath.unshift(schema); } return tablePath.join("."); } /** * Parse a target table name or other types and return a normalized table definition. */ parseTableName(target) { const driverDatabase = this.database; const driverSchema = this.schema; if (InstanceChecker.isTable(target) || InstanceChecker.isView(target)) { // name is sometimes a path const parsed = this.parseTableName(target.name); return { database: target.database || parsed.database || driverDatabase, schema: target.schema || parsed.schema || driverSchema, tableName: parsed.tableName, }; } if (InstanceChecker.isTableForeignKey(target)) { // referencedTableName is sometimes a path const parsed = this.parseTableName(target.referencedTableName); return { database: target.referencedDatabase || parsed.database || driverDatabase, schema: target.referencedSchema || parsed.schema || driverSchema, tableName: parsed.tableName, }; } if (InstanceChecker.isEntityMetadata(target)) { // EntityMetadata tableName is never a path return { database: target.database || driverDatabase, schema: target.schema || driverSchema, tableName: target.tableName, }; } const parts = target.split("."); return { database: driverDatabase, schema: (parts.length > 1 ? parts[0] : undefined) || driverSchema, tableName: parts.length > 1 ? parts[1] : parts[0], }; } /** * Creates a database type from a given column metadata. */ normalizeType(column) { if (column.type === Number || column.type === "integer" || column.type === "int" || column.type === "bigint" || column.type === "int64") { return "int8"; } else if (column.type === String || column.type === "character varying" || column.type === "char varying") { return "varchar"; } else if (column.type === Date || column.type === "timestamp without time zone") { return "timestamp"; } else if (column.type === "timestamp with time zone") { return "timestamptz"; } else if (column.type === "time without time zone") { return "time"; } else if (column.type === Boolean || column.type === "boolean") { return "bool"; } else if (column.type === "simple-array" || column.type === "simple-json" || column.type === "text") { return "string"; } else if (column.type === "bytea" || column.type === "blob") { return "bytes"; } else if (column.type === "smallint") { return "int2"; } else if (column.type === "numeric" || column.type === "dec") { return "decimal"; } else if (column.type === "double precision" || column.type === "float") { return "float8"; } else if (column.type === "real") { return "float4"; } else if (column.type === "character") { return "char"; } else if (column.type === "json") { return "jsonb"; } else { return column.type || ""; } } /** * Normalizes "default" value of the column. */ normalizeDefault(columnMetadata) { const defaultValue = columnMetadata.default; const arrayCast = columnMetadata.isArray ? `::${columnMetadata.type}[]` : ""; if (typeof defaultValue === "number") { return `(${defaultValue})`; } if (typeof defaultValue === "boolean") { return defaultValue ? "true" : "false"; } if (typeof defaultValue === "function") { const value = defaultValue(); if (value.toUpperCase() === "CURRENT_TIMESTAMP") { return "current_timestamp()"; } else if (value.toUpperCase() === "CURRENT_DATE") { return "current_date()"; } return value; } if (typeof defaultValue === "string") { return `'${defaultValue}'${arrayCast}`; } if (ObjectUtils.isObject(defaultValue) && defaultValue !== null) { return `'${JSON.stringify(defaultValue)}'`; } if (defaultValue === undefined || defaultValue === null) { return undefined; } return `${defaultValue}`; } /** * Normalizes "isUnique" value of the column. */ normalizeIsUnique(column) { return column.entityMetadata.uniques.some((uq) => uq.columns.length === 1 && uq.columns[0] === column); } /** * Returns default column lengths, which is required on column creation. */ getColumnLength(column) { return column.length ? column.length.toString() : ""; } /** * Creates column type definition including length, precision and scale */ createFullType(column) { let type = column.type; if (column.length) { type += "(" + column.length + ")"; } else if (column.precision !== null && column.precision !== undefined && column.scale !== null && column.scale !== undefined) { type += "(" + column.precision + "," + column.scale + ")"; } else if (column.precision !== null && column.precision !== undefined) { type += "(" + column.precision + ")"; } if (column.isArray) type += " array"; return type; } /** * Obtains a new database connection to a master server. * Used for replication. * If replication is not setup then returns default connection's database connection. */ async obtainMasterConnection() { if (!this.master) { throw new TypeORMError("Driver not Connected"); } return new Promise((ok, fail) => { this.master.connect((err, connection, release) => { err ? fail(err) : ok([connection, release]); }); }); } /** * Obtains a new database connection to a slave server. * Used for replication. * If replication is not setup then returns master (default) connection's database connection. */ async obtainSlaveConnection() { if (!this.slaves.length) return this.obtainMasterConnection(); const random = Math.floor(Math.random() * this.slaves.length); return new Promise((ok, fail) => { this.slaves[random].connect((err, connection, release) => { err ? fail(err) : ok([connection, release]); }); }); } /** * Creates generated map of values generated or returned by database after INSERT query. * * todo: slow. optimize Object.keys(), OrmUtils.mergeDeep and column.createValueMap parts */ createGeneratedMap(metadata, insertResult) { if (!insertResult) return undefined; return Object.keys(insertResult).reduce((map, key) => { const column = metadata.findColumnWithDatabaseName(key); if (column) { OrmUtils.mergeDeep(map, column.createValueMap(this.prepareHydratedValue(insertResult[key], column))); } return map; }, {}); } /** * Differentiate columns of this table and columns from the given column metadatas columns * and returns only changed. */ findChangedColumns(tableColumns, columnMetadatas) { return columnMetadatas.filter((columnMetadata) => { const tableColumn = tableColumns.find((c) => c.name === columnMetadata.databaseName); if (!tableColumn) return false; // we don't need new columns, we only need exist and changed // console.log("table:", columnMetadata.entityMetadata.tableName); // console.log("name:", tableColumn.name, columnMetadata.databaseName); // console.log("type:", tableColumn.type, this.normalizeType(columnMetadata)); // console.log("length:", tableColumn.length, columnMetadata.length); // console.log("width:", tableColumn.width, columnMetadata.width); // console.log("precision:", tableColumn.precision, columnMetadata.precision); // console.log("scale:", tableColumn.scale, columnMetadata.scale); // console.log("comment:", tableColumn.comment, this.escapeComment(columnMetadata.comment)); // console.log("default:", tableColumn.default, columnMetadata.default); // console.log("default changed:", !this.compareDefaultValues(this.normalizeDefault(columnMetadata), tableColumn.default)); // console.log("isPrimary:", tableColumn.isPrimary, columnMetadata.isPrimary); // console.log("isNullable:", tableColumn.isNullable, columnMetadata.isNullable); // console.log("isUnique:", tableColumn.isUnique, this.normalizeIsUnique(columnMetadata)); // console.log("isGenerated:", tableColumn.isGenerated, columnMetadata.isGenerated); // console.log("=========================================="); return (tableColumn.name !== columnMetadata.databaseName || tableColumn.type !== this.normalizeType(columnMetadata) || tableColumn.length !== columnMetadata.length || tableColumn.precision !== columnMetadata.precision || (columnMetadata.scale !== undefined && tableColumn.scale !== columnMetadata.scale) || tableColumn.comment !== this.escapeComment(columnMetadata.comment) || (!tableColumn.isGenerated && this.lowerDefaultValueIfNecessary(this.normalizeDefault(columnMetadata)) !== tableColumn.default) || // we included check for generated here, because generated columns already can have default values tableColumn.isPrimary !== columnMetadata.isPrimary || tableColumn.isNullable !== columnMetadata.isNullable || tableColumn.isUnique !== this.normalizeIsUnique(columnMetadata) || tableColumn.isGenerated !== columnMetadata.isGenerated); }); } lowerDefaultValueIfNecessary(value) { if (!value) { return value; } return value .split(`'`) .map((v, i) => { return i % 2 === 1 ? v : v.toLowerCase(); }) .join(`'`); } /** * Returns true if driver supports RETURNING / OUTPUT statement. */ isReturningSqlSupported() { return true; } /** * Returns true if driver supports uuid values generation on its own. */ isUUIDGenerationSupported() { return true; } /** * Returns true if driver supports fulltext indices. */ isFullTextColumnTypeSupported() { return false; } /** * Creates an escaped parameter. */ createParameter(parameterName, index) { return "$" + (index + 1); } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Loads postgres query stream package. */ loadStreamDependency() { try { return PlatformTools.load("pg-query-stream"); } catch (e) { // todo: better error for browser env throw new TypeORMError(`To use streams you should install pg-query-stream package. Please run npm i pg-query-stream --save command.`); } } // ------------------------------------------------------------------------- // Protected Methods // ------------------------------------------------------------------------- /** * If driver dependency is not given explicitly, then try to load it via "require". */ loadDependencies() { try { const postgres = this.options.driver || PlatformTools.load("pg"); this.postgres = postgres; try { const pgNative = this.options.nativeDriver || PlatformTools.load("pg-native"); if (pgNative && this.postgres.native) this.postgres = this.postgres.native; } catch (e) { } } catch (e) { // todo: better error for browser env throw new DriverPackageNotInstalledError("Postgres", "pg"); } } /** * Creates a new connection pool for a given database credentials. */ async createPool(options, credentials) { credentials = Object.assign({}, credentials, DriverUtils.buildDriverOptions(credentials)); // todo: do it better way // build connection options for the driver const connectionOptions = Object.assign({}, { host: credentials.host, user: credentials.username, password: credentials.password, database: credentials.database, port: credentials.port, ssl: credentials.ssl, application_name: options.applicationName, }, options.extra || {}); // create a connection pool const pool = new this.postgres.Pool(connectionOptions); const { logger } = this.connection; const poolErrorHandler = options.poolErrorHandler || ((error) => logger.log("warn", `Postgres pool raised an error. ${error}`)); /* Attaching an error handler to pool errors is essential, as, otherwise, errors raised will go unhandled and cause the hosting app to crash. */ pool.on("error", poolErrorHandler); return new Promise((ok, fail) => { pool.connect((err, connection, release) => { if (err) return fail(err); release(); ok(pool); }); }); } /** * Closes connection pool. */ async closePool(pool) { await Promise.all(this.connectedQueryRunners.map((queryRunner) => queryRunner.release())); return new Promise((ok, fail) => { pool.end((err) => (err ? fail(err) : ok())); }); } /** * Escapes a given comment. */ escapeComment(comment) { if (!comment) return comment; comment = comment.replace(/'/g, "''").replace(/\u0000/g, ""); // Null bytes aren't allowed in comments return comment; } }
JavaScript
class PreloadFile extends BaseFile { /** * Creates a file with the given path and, optionally, the given contents. Note * that, if contents is specified, it will be mutated by the file! * @param _fs The file system that created the file. * @param _path * @param _mode The mode that the file was opened using. * Dictates permissions and where the file pointer starts. * @param _stat The stats object for the given file. * PreloadFile will mutate this object. Note that this object must contain * the appropriate mode that the file was opened as. * @param contents A buffer containing the entire * contents of the file. PreloadFile will mutate this buffer. If not * specified, we assume it is a new file. */ constructor(_fs, _path, _flag, _stat, contents) { super(); this._pos = 0; this._dirty = false; this._fs = _fs; this._path = _path; this._flag = _flag; this._stat = _stat; this._buffer = contents ? contents : emptyBuffer(); // Note: This invariant is *not* maintained once the file starts getting // modified. // Note: Only actually matters if file is readable, as writeable modes may // truncate/append to file. if (this._stat.size !== this._buffer.length && this._flag.isReadable()) { throw new Error(`Invalid buffer: Buffer is ${this._buffer.length} long, yet Stats object specifies that file is ${this._stat.size} long.`); } } /** * NONSTANDARD: Get the underlying buffer for this file. !!DO NOT MUTATE!! Will mess up dirty tracking. */ getBuffer() { return this._buffer; } /** * NONSTANDARD: Get underlying stats for this file. !!DO NOT MUTATE!! */ getStats() { return this._stat; } getFlag() { return this._flag; } /** * Get the path to this file. * @return [String] The path to the file. */ getPath() { return this._path; } /** * Get the current file position. * * We emulate the following bug mentioned in the Node documentation: * > On Linux, positional writes don't work when the file is opened in append * mode. The kernel ignores the position argument and always appends the data * to the end of the file. * @return [Number] The current file position. */ getPos() { if (this._flag.isAppendable()) { return this._stat.size; } return this._pos; } /** * Advance the current file position by the indicated number of positions. * @param [Number] delta */ advancePos(delta) { return this._pos += delta; } /** * Set the file position. * @param [Number] newPos */ setPos(newPos) { return this._pos = newPos; } /** * **Core**: Asynchronous sync. Must be implemented by subclasses of this * class. * @param [Function(BrowserFS.ApiError)] cb */ sync(cb) { try { this.syncSync(); cb(); } catch (e) { cb(e); } } /** * **Core**: Synchronous sync. */ syncSync() { throw new ApiError(ErrorCode.ENOTSUP); } /** * **Core**: Asynchronous close. Must be implemented by subclasses of this * class. * @param [Function(BrowserFS.ApiError)] cb */ close(cb) { try { this.closeSync(); cb(); } catch (e) { cb(e); } } /** * **Core**: Synchronous close. */ closeSync() { throw new ApiError(ErrorCode.ENOTSUP); } /** * Asynchronous `stat`. * @param [Function(BrowserFS.ApiError, BrowserFS.node.fs.Stats)] cb */ stat(cb) { try { cb(null, Stats.clone(this._stat)); } catch (e) { cb(e); } } /** * Synchronous `stat`. */ statSync() { return Stats.clone(this._stat); } /** * Asynchronous truncate. * @param [Number] len * @param [Function(BrowserFS.ApiError)] cb */ truncate(len, cb) { try { this.truncateSync(len); if (this._flag.isSynchronous() && !fs.getRootFS().supportsSynch()) { this.sync(cb); } cb(); } catch (e) { return cb(e); } } /** * Synchronous truncate. * @param [Number] len */ truncateSync(len) { this._dirty = true; if (!this._flag.isWriteable()) { throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.'); } this._stat.mtimeMs = Date.now(); if (len > this._buffer.length) { const buf = Buffer.alloc(len - this._buffer.length, 0); // Write will set @_stat.size for us. this.writeSync(buf, 0, buf.length, this._buffer.length); if (this._flag.isSynchronous() && fs.getRootFS().supportsSynch()) { this.syncSync(); } return; } this._stat.size = len; // Truncate buffer to 'len'. const newBuff = Buffer.alloc(len); this._buffer.copy(newBuff, 0, 0, len); this._buffer = newBuff; if (this._flag.isSynchronous() && fs.getRootFS().supportsSynch()) { this.syncSync(); } } /** * Write buffer to the file. * Note that it is unsafe to use fs.write multiple times on the same file * without waiting for the callback. * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to * the file. * @param [Number] offset Offset in the buffer to start reading data from. * @param [Number] length The amount of bytes to write to the file. * @param [Number] position Offset from the beginning of the file where this * data should be written. If position is null, the data will be written at * the current position. * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)] * cb The number specifies the number of bytes written into the file. */ write(buffer, offset, length, position, cb) { try { cb(null, this.writeSync(buffer, offset, length, position), buffer); } catch (e) { cb(e); } } /** * Write buffer to the file. * Note that it is unsafe to use fs.writeSync multiple times on the same file * without waiting for the callback. * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to * the file. * @param [Number] offset Offset in the buffer to start reading data from. * @param [Number] length The amount of bytes to write to the file. * @param [Number] position Offset from the beginning of the file where this * data should be written. If position is null, the data will be written at * the current position. * @return [Number] */ writeSync(buffer, offset, length, position) { this._dirty = true; if (position === undefined || position === null) { position = this.getPos(); } if (!this._flag.isWriteable()) { throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.'); } const endFp = position + length; if (endFp > this._stat.size) { this._stat.size = endFp; if (endFp > this._buffer.length) { // Extend the buffer! const newBuff = Buffer.alloc(endFp); this._buffer.copy(newBuff); this._buffer = newBuff; } } const len = buffer.copy(this._buffer, position, offset, offset + length); this._stat.mtimeMs = Date.now(); if (this._flag.isSynchronous()) { this.syncSync(); return len; } this.setPos(position + len); return len; } /** * Read data from the file. * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be * written to. * @param [Number] offset The offset within the buffer where writing will * start. * @param [Number] length An integer specifying the number of bytes to read. * @param [Number] position An integer specifying where to begin reading from * in the file. If position is null, data will be read from the current file * position. * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)] cb The * number is the number of bytes read */ read(buffer, offset, length, position, cb) { try { cb(null, this.readSync(buffer, offset, length, position), buffer); } catch (e) { cb(e); } } /** * Read data from the file. * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be * written to. * @param [Number] offset The offset within the buffer where writing will * start. * @param [Number] length An integer specifying the number of bytes to read. * @param [Number] position An integer specifying where to begin reading from * in the file. If position is null, data will be read from the current file * position. * @return [Number] */ readSync(buffer, offset, length, position) { if (!this._flag.isReadable()) { throw new ApiError(ErrorCode.EPERM, 'File not opened with a readable mode.'); } if (position === undefined || position === null) { position = this.getPos(); } const endRead = position + length; if (endRead > this._stat.size) { length = this._stat.size - position; } const rv = this._buffer.copy(buffer, offset, position, position + length); this._stat.atimeMs = Date.now(); this._pos = position + length; return rv; } /** * Asynchronous `fchmod`. * @param [Number|String] mode * @param [Function(BrowserFS.ApiError)] cb */ chmod(mode, cb) { try { this.chmodSync(mode); cb(); } catch (e) { cb(e); } } /** * Asynchronous `fchmod`. * @param [Number] mode */ chmodSync(mode) { if (!this._fs.supportsProps()) { throw new ApiError(ErrorCode.ENOTSUP); } this._dirty = true; this._stat.chmod(mode); this.syncSync(); } isDirty() { return this._dirty; } /** * Resets the dirty bit. Should only be called after a sync has completed successfully. */ resetDirty() { this._dirty = false; } }
JavaScript
class NoSyncFile extends PreloadFile { constructor(_fs, _path, _flag, _stat, contents) { super(_fs, _path, _flag, _stat, contents); } /** * Asynchronous sync. Doesn't do anything, simply calls the cb. * @param [Function(BrowserFS.ApiError)] cb */ sync(cb) { cb(); } /** * Synchronous sync. Doesn't do anything. */ syncSync() { // NOP. } /** * Asynchronous close. Doesn't do anything, simply calls the cb. * @param [Function(BrowserFS.ApiError)] cb */ close(cb) { cb(); } /** * Synchronous close. Doesn't do anything. */ closeSync() { // NOP. } }
JavaScript
class PendingTransactionsByVideoIdsAndFromUserId extends CacheMultiBase { /** * Constructor to test cache management. * * @param {object} params * @param {Array} params.videoIds * @param {number} params.fromUserId * * @augments CacheMultiBase * * @constructor */ constructor(params) { super(params); } /** * Init Params in oThis * * @param params * @param {number} params.fromUserId * @param {Array} params.videoIds * @private */ _initParams(params) { const oThis = this; oThis.fromUserId = params.fromUserId; oThis.videoIds = params.videoIds; } /** * Set use object * * @sets oThis.useObject * * @private */ _setUseObject() { const oThis = this; oThis.useObject = false; } /** * Set cache type. * * @sets oThis.cacheType * * @returns {string} */ _setCacheType() { const oThis = this; oThis.cacheType = cacheManagementConst.memcached; } /** * set cache expiry in oThis.cacheExpiry and return it */ _setCacheExpiry() { const oThis = this; oThis.cacheExpiry = cacheManagementConst.largeExpiryTimeInterval; // 24 hours ; } /** * set cache keys */ _setCacheKeys() { const oThis = this; for (let i = 0; i < oThis.videoIds.length; i++) { oThis.cacheKeys[oThis._cacheKeyPrefix() + '_cmm_pt_fuid_' + oThis.fromUserId + '_vid_' + oThis.videoIds[i]] = oThis.videoIds[i]; } } /** * Set cache expiry in oThis.cacheExpiry and return it. * * @sets oThis.cacheExpiry * * @return {number} */ setCacheExpiry() { const oThis = this; oThis.cacheExpiry = cacheManagementConst.largeExpiryTimeInterval; return oThis.cacheExpiry; } /** * Fetch data from source for cache miss ids * * @param cacheMissIds * * @return {Promise<*>} */ async fetchDataFromSource(cacheMissIds) { const oThis = this; // This value is only returned if cache is not set. const pendingTransactionByToUserObjs = await new PendingTransactionModel().fetchPendingTransactionByFromUserIdAndVideoIds( cacheMissIds, oThis.fromUserId ); return responseHelper.successWithData(pendingTransactionByToUserObjs); } }
JavaScript
class DatabaseInstanceBase extends core_1.Resource { /** * Import an existing database instance. * * @stability stable */ static fromDatabaseInstanceAttributes(scope, id, attrs) { class Import extends DatabaseInstanceBase { constructor() { super(...arguments); this.defaultPort = ec2.Port.tcp(attrs.port); this.connections = new ec2.Connections({ securityGroups: attrs.securityGroups, defaultPort: this.defaultPort, }); this.instanceIdentifier = attrs.instanceIdentifier; this.dbInstanceEndpointAddress = attrs.instanceEndpointAddress; this.dbInstanceEndpointPort = attrs.port.toString(); this.instanceEndpoint = new endpoint_1.Endpoint(attrs.instanceEndpointAddress, attrs.port); this.engine = attrs.engine; this.enableIamAuthentication = true; } } return new Import(scope, id); } /** * Add a new db proxy to this instance. * * @stability stable */ addProxy(id, options) { return new proxy_1.DatabaseProxy(this, id, { proxyTarget: proxy_1.ProxyTarget.fromInstance(this), ...options, }); } /** * Grant the given identity connection access to the database. * * @stability stable */ grantConnect(grantee) { if (this.enableIamAuthentication === false) { throw new Error('Cannot grant connect when IAM authentication is disabled'); } this.enableIamAuthentication = true; return iam.Grant.addToPrincipal({ grantee, actions: ['rds-db:connect'], resourceArns: [this.instanceArn], }); } /** * Defines a CloudWatch event rule which triggers for instance events. * * Use * `rule.addEventPattern(pattern)` to specify a filter. * * @stability stable */ onEvent(id, options = {}) { const rule = new events.Rule(this, id, options); rule.addEventPattern({ source: ['aws.rds'], resources: [this.instanceArn], }); rule.addTarget(options.target); return rule; } /** * The instance arn. * * @stability stable */ get instanceArn() { return core_1.Stack.of(this).formatArn({ service: 'rds', resource: 'db', sep: ':', resourceName: this.instanceIdentifier, }); } /** * Renders the secret attachment target specifications. * * @stability stable */ asSecretAttachmentTarget() { return { targetId: this.instanceIdentifier, targetType: secretsmanager.AttachmentTargetType.RDS_DB_INSTANCE, }; } }
JavaScript
class DatabaseInstanceNew extends DatabaseInstanceBase { constructor(scope, id, props) { var _a, _b, _c, _d, _e, _f; super(scope, id); this.vpc = props.vpc; if (props.vpcSubnets && props.vpcPlacement) { throw new Error('Only one of `vpcSubnets` or `vpcPlacement` can be specified'); } this.vpcPlacement = (_a = props.vpcSubnets) !== null && _a !== void 0 ? _a : props.vpcPlacement; const subnetGroup = (_b = props.subnetGroup) !== null && _b !== void 0 ? _b : new subnet_group_1.SubnetGroup(this, 'SubnetGroup', { description: `Subnet group for ${this.node.id} database`, vpc: this.vpc, vpcSubnets: this.vpcPlacement, removalPolicy: props.removalPolicy === core_1.RemovalPolicy.RETAIN ? props.removalPolicy : undefined, }); const securityGroups = props.securityGroups || [new ec2.SecurityGroup(this, 'SecurityGroup', { description: `Security group for ${this.node.id} database`, vpc: props.vpc, })]; this.connections = new ec2.Connections({ securityGroups, defaultPort: ec2.Port.tcp(core_1.Lazy.number({ produce: () => this.instanceEndpoint.port })), }); let monitoringRole; if (props.monitoringInterval && props.monitoringInterval.toSeconds()) { monitoringRole = props.monitoringRole || new iam.Role(this, 'MonitoringRole', { assumedBy: new iam.ServicePrincipal('monitoring.rds.amazonaws.com'), managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonRDSEnhancedMonitoringRole')], }); } const storageType = props.storageType || StorageType.GP2; const iops = storageType === StorageType.IO1 ? (props.iops || 1000) : undefined; this.cloudwatchLogsExports = props.cloudwatchLogsExports; this.cloudwatchLogsRetention = props.cloudwatchLogsRetention; this.cloudwatchLogsRetentionRole = props.cloudwatchLogsRetentionRole; this.enableIamAuthentication = props.iamAuthentication; const enablePerformanceInsights = props.enablePerformanceInsights || props.performanceInsightRetention !== undefined || props.performanceInsightEncryptionKey !== undefined; if (enablePerformanceInsights && props.enablePerformanceInsights === false) { throw new Error('`enablePerformanceInsights` disabled, but `performanceInsightRetention` or `performanceInsightEncryptionKey` was set'); } if (props.domain) { this.domainId = props.domain; this.domainRole = props.domainRole || new iam.Role(this, 'RDSDirectoryServiceRole', { assumedBy: new iam.ServicePrincipal('rds.amazonaws.com'), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonRDSDirectoryServiceAccess'), ], }); } this.newCfnProps = { autoMinorVersionUpgrade: props.autoMinorVersionUpgrade, availabilityZone: props.multiAz ? undefined : props.availabilityZone, backupRetentionPeriod: props.backupRetention ? props.backupRetention.toDays() : undefined, copyTagsToSnapshot: props.copyTagsToSnapshot !== undefined ? props.copyTagsToSnapshot : true, dbInstanceClass: core_1.Lazy.string({ produce: () => `db.${this.instanceType}` }), dbInstanceIdentifier: props.instanceIdentifier, dbSubnetGroupName: subnetGroup.subnetGroupName, deleteAutomatedBackups: props.deleteAutomatedBackups, deletionProtection: util_1.defaultDeletionProtection(props.deletionProtection, props.removalPolicy), enableCloudwatchLogsExports: this.cloudwatchLogsExports, enableIamDatabaseAuthentication: core_1.Lazy.any({ produce: () => this.enableIamAuthentication }), enablePerformanceInsights: enablePerformanceInsights || props.enablePerformanceInsights, iops, monitoringInterval: props.monitoringInterval && props.monitoringInterval.toSeconds(), monitoringRoleArn: monitoringRole && monitoringRole.roleArn, multiAz: props.multiAz, optionGroupName: (_c = props.optionGroup) === null || _c === void 0 ? void 0 : _c.optionGroupName, performanceInsightsKmsKeyId: (_d = props.performanceInsightEncryptionKey) === null || _d === void 0 ? void 0 : _d.keyArn, performanceInsightsRetentionPeriod: enablePerformanceInsights ? (props.performanceInsightRetention || props_1.PerformanceInsightRetention.DEFAULT) : undefined, port: props.port ? props.port.toString() : undefined, preferredBackupWindow: props.preferredBackupWindow, preferredMaintenanceWindow: props.preferredMaintenanceWindow, processorFeatures: props.processorFeatures && renderProcessorFeatures(props.processorFeatures), publiclyAccessible: (_e = props.publiclyAccessible) !== null && _e !== void 0 ? _e : (this.vpcPlacement && this.vpcPlacement.subnetType === ec2.SubnetType.PUBLIC), storageType, vpcSecurityGroups: securityGroups.map(s => s.securityGroupId), maxAllocatedStorage: props.maxAllocatedStorage, domain: this.domainId, domainIamRoleName: (_f = this.domainRole) === null || _f === void 0 ? void 0 : _f.roleName, }; } /** * @stability stable */ setLogRetention() { if (this.cloudwatchLogsExports && this.cloudwatchLogsRetention) { for (const log of this.cloudwatchLogsExports) { new logs.LogRetention(this, `LogRetention${log}`, { logGroupName: `/aws/rds/instance/${this.instanceIdentifier}/${log}`, retention: this.cloudwatchLogsRetention, role: this.cloudwatchLogsRetentionRole, }); } } } }
JavaScript
class DatabaseInstanceSource extends DatabaseInstanceNew { constructor(scope, id, props) { var _a, _b, _c, _d; super(scope, id, props); this.singleUserRotationApplication = props.engine.singleUserRotationApplication; this.multiUserRotationApplication = props.engine.multiUserRotationApplication; this.engine = props.engine; let { s3ImportRole, s3ExportRole } = util_1.setupS3ImportExport(this, props, true); const engineConfig = props.engine.bindToInstance(this, { ...props, s3ImportRole, s3ExportRole, }); const instanceAssociatedRoles = []; const engineFeatures = engineConfig.features; if (s3ImportRole) { if (!(engineFeatures === null || engineFeatures === void 0 ? void 0 : engineFeatures.s3Import)) { throw new Error(`Engine '${util_1.engineDescription(props.engine)}' does not support S3 import`); } instanceAssociatedRoles.push({ roleArn: s3ImportRole.roleArn, featureName: engineFeatures === null || engineFeatures === void 0 ? void 0 : engineFeatures.s3Import }); } if (s3ExportRole) { if (!(engineFeatures === null || engineFeatures === void 0 ? void 0 : engineFeatures.s3Export)) { throw new Error(`Engine '${util_1.engineDescription(props.engine)}' does not support S3 export`); } // Only add the export role and feature if they are different from the import role & feature. if (s3ImportRole !== s3ExportRole || engineFeatures.s3Import !== (engineFeatures === null || engineFeatures === void 0 ? void 0 : engineFeatures.s3Export)) { instanceAssociatedRoles.push({ roleArn: s3ExportRole.roleArn, featureName: engineFeatures === null || engineFeatures === void 0 ? void 0 : engineFeatures.s3Export }); } } this.instanceType = (_a = props.instanceType) !== null && _a !== void 0 ? _a : ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE); const instanceParameterGroupConfig = (_b = props.parameterGroup) === null || _b === void 0 ? void 0 : _b.bindToInstance({}); this.sourceCfnProps = { ...this.newCfnProps, associatedRoles: instanceAssociatedRoles.length > 0 ? instanceAssociatedRoles : undefined, optionGroupName: (_c = engineConfig.optionGroup) === null || _c === void 0 ? void 0 : _c.optionGroupName, allocatedStorage: props.allocatedStorage ? props.allocatedStorage.toString() : '100', allowMajorVersionUpgrade: props.allowMajorVersionUpgrade, dbName: props.databaseName, dbParameterGroupName: instanceParameterGroupConfig === null || instanceParameterGroupConfig === void 0 ? void 0 : instanceParameterGroupConfig.parameterGroupName, engine: props.engine.engineType, engineVersion: (_d = props.engine.engineVersion) === null || _d === void 0 ? void 0 : _d.fullVersion, licenseModel: props.licenseModel, timezone: props.timezone, }; } /** * Adds the single user rotation of the master password to this instance. * * @param options the options for the rotation, if you want to override the defaults. * @stability stable */ addRotationSingleUser(options = {}) { var _a; if (!this.secret) { throw new Error('Cannot add single user rotation for an instance without secret.'); } const id = 'RotationSingleUser'; const existing = this.node.tryFindChild(id); if (existing) { throw new Error('A single user rotation was already added to this instance.'); } return new secretsmanager.SecretRotation(this, id, { secret: this.secret, application: this.singleUserRotationApplication, vpc: this.vpc, vpcSubnets: this.vpcPlacement, target: this, ...options, excludeCharacters: (_a = options.excludeCharacters) !== null && _a !== void 0 ? _a : util_1.DEFAULT_PASSWORD_EXCLUDE_CHARS, }); } /** * Adds the multi user rotation to this instance. * * @stability stable */ addRotationMultiUser(id, options) { var _a; if (!this.secret) { throw new Error('Cannot add multi user rotation for an instance without secret.'); } return new secretsmanager.SecretRotation(this, id, { ...options, excludeCharacters: (_a = options.excludeCharacters) !== null && _a !== void 0 ? _a : util_1.DEFAULT_PASSWORD_EXCLUDE_CHARS, masterSecret: this.secret, application: this.multiUserRotationApplication, vpc: this.vpc, vpcSubnets: this.vpcPlacement, target: this, }); } }
JavaScript
class DatabaseInstance extends DatabaseInstanceSource { /** * @stability stable */ constructor(scope, id, props) { var _a; super(scope, id, props); const credentials = util_1.renderCredentials(this, props.engine, props.credentials); const secret = credentials.secret; const instance = new rds_generated_1.CfnDBInstance(this, 'Resource', { ...this.sourceCfnProps, characterSetName: props.characterSetName, kmsKeyId: props.storageEncryptionKey && props.storageEncryptionKey.keyArn, masterUsername: credentials.username, masterUserPassword: (_a = credentials.password) === null || _a === void 0 ? void 0 : _a.toString(), storageEncrypted: props.storageEncryptionKey ? true : props.storageEncrypted, }); this.instanceIdentifier = instance.ref; this.dbInstanceEndpointAddress = instance.attrEndpointAddress; this.dbInstanceEndpointPort = instance.attrEndpointPort; // create a number token that represents the port of the instance const portAttribute = core_1.Token.asNumber(instance.attrEndpointPort); this.instanceEndpoint = new endpoint_1.Endpoint(instance.attrEndpointAddress, portAttribute); util_1.applyRemovalPolicy(instance, props.removalPolicy); if (secret) { this.secret = secret.attach(this); } this.setLogRetention(); } }
JavaScript
class DatabaseInstanceFromSnapshot extends DatabaseInstanceSource { /** * @stability stable */ constructor(scope, id, props) { var _a; super(scope, id, props); let credentials = props.credentials; let secret = credentials === null || credentials === void 0 ? void 0 : credentials.secret; if (!secret && (credentials === null || credentials === void 0 ? void 0 : credentials.generatePassword)) { if (!credentials.username) { throw new Error('`credentials` `username` must be specified when `generatePassword` is set to true'); } secret = new database_secret_1.DatabaseSecret(this, 'Secret', { username: credentials.username, encryptionKey: credentials.encryptionKey, excludeCharacters: credentials.excludeCharacters, replaceOnPasswordCriteriaChanges: credentials.replaceOnPasswordCriteriaChanges, }); } const instance = new rds_generated_1.CfnDBInstance(this, 'Resource', { ...this.sourceCfnProps, dbSnapshotIdentifier: props.snapshotIdentifier, masterUserPassword: secret ? secret.secretValueFromJson('password').toString() : (_a = credentials === null || credentials === void 0 ? void 0 : credentials.password) === null || _a === void 0 ? void 0 : _a.toString(), }); this.instanceIdentifier = instance.ref; this.dbInstanceEndpointAddress = instance.attrEndpointAddress; this.dbInstanceEndpointPort = instance.attrEndpointPort; // create a number token that represents the port of the instance const portAttribute = core_1.Token.asNumber(instance.attrEndpointPort); this.instanceEndpoint = new endpoint_1.Endpoint(instance.attrEndpointAddress, portAttribute); util_1.applyRemovalPolicy(instance, props.removalPolicy); if (secret) { this.secret = secret.attach(this); } this.setLogRetention(); } }
JavaScript
class DatabaseInstanceReadReplica extends DatabaseInstanceNew { /** * @stability stable */ constructor(scope, id, props) { super(scope, id, props); /** * The engine of this database Instance. * * May be not known for imported Instances if it wasn't provided explicitly, * or for read replicas. * * @stability stable */ this.engine = undefined; const instance = new rds_generated_1.CfnDBInstance(this, 'Resource', { ...this.newCfnProps, // this must be ARN, not ID, because of https://github.com/terraform-providers/terraform-provider-aws/issues/528#issuecomment-391169012 sourceDbInstanceIdentifier: props.sourceDatabaseInstance.instanceArn, kmsKeyId: props.storageEncryptionKey && props.storageEncryptionKey.keyArn, storageEncrypted: props.storageEncryptionKey ? true : props.storageEncrypted, }); this.instanceType = props.instanceType; this.instanceIdentifier = instance.ref; this.dbInstanceEndpointAddress = instance.attrEndpointAddress; this.dbInstanceEndpointPort = instance.attrEndpointPort; // create a number token that represents the port of the instance const portAttribute = core_1.Token.asNumber(instance.attrEndpointPort); this.instanceEndpoint = new endpoint_1.Endpoint(instance.attrEndpointAddress, portAttribute); util_1.applyRemovalPolicy(instance, props.removalPolicy); this.setLogRetention(); } }
JavaScript
class Article extends Component { constructor (props) { // Send what it gets to its parent object super(props); } render () { // Return HTML with the title, author, and text of this article // Use template literals for the variables return (` <Article> <Title>${this.props.title}</Title> <Author>${this.props.author}</Author> <Text>${this.props.text}</Text> </Article> ` ); } }
JavaScript
class _FPSControls { constructor(params) { this._cells = params.cells; this._Init(params); } _Init(params) { this._params = params; this._radius = 2; this._enabled = false; this._move = { forward: false, backward: false, left: false, right: false, up: false, down: false, }; this._standing = true; this._velocity = new THREE.Vector3(0, 0, 0); this._decceleration = new THREE.Vector3(-10, -10, -10); this._acceleration = new THREE.Vector3(5000, 5000, 5000); this._SetupPointerLock(); this._controls = new PointerLockControls( params.camera, document.body); params.scene.add(this._controls.getObject()); const controlObject = this._controls.getObject(); this._position = new THREE.Vector3(); this._rotation = new THREE.Quaternion(); this._position.copy(controlObject.position); this._rotation.copy(controlObject.quaternion); document.addEventListener('keydown', (e) => this._onKeyDown(e), false); document.addEventListener('keyup', (e) => this._onKeyUp(e), false); this._InitGUI(); } _InitGUI() { this._params.guiParams.camera = { acceleration_x: 5000, }; const rollup = this._params.gui.addFolder('Camera.FPS'); rollup.add(this._params.guiParams.camera, "acceleration_x", 50.0, 50000.0).onChange( () => { this._acceleration.set( this._params.guiParams.camera.acceleration_x, this._params.guiParams.camera.acceleration_x, this._params.guiParams.camera.acceleration_x); }); } _onKeyDown(event) { switch (event.keyCode) { case 38: // up case 87: // w this._move.forward = true; break; case 37: // left case 65: // a this._move.left = true; break; case 40: // down case 83: // s this._move.backward = true; break; case 39: // right case 68: // d this._move.right = true; break; case 33: // PG_UP this._move.up = true; break; case 34: // PG_DOWN this._move.down = true; break; } } _onKeyUp(event) { switch(event.keyCode) { case 38: // up case 87: // w this._move.forward = false; break; case 37: // left case 65: // a this._move.left = false; break; case 40: // down case 83: // s this._move.backward = false; break; case 39: // right case 68: // d this._move.right = false; break; case 33: // PG_UP this._move.up = false; break; case 34: // PG_DOWN this._move.down = false; break; } } _SetupPointerLock() { const hasPointerLock = ( 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document); if (hasPointerLock) { const lockChange = (event) => { if (document.pointerLockElement === document.body || document.mozPointerLockElement === document.body || document.webkitPointerLockElement === document.body ) { this._enabled = true; this._controls.enabled = true; } else { this._controls.enabled = false; } }; const lockError = (event) => { console.log(event); }; document.addEventListener('pointerlockchange', lockChange, false); document.addEventListener('webkitpointerlockchange', lockChange, false); document.addEventListener('mozpointerlockchange', lockChange, false); document.addEventListener('pointerlockerror', lockError, false); document.addEventListener('mozpointerlockerror', lockError, false); document.addEventListener('webkitpointerlockerror', lockError, false); document.getElementById('target').addEventListener('click', (event) => { document.body.requestPointerLock = ( document.body.requestPointerLock || document.body.mozRequestPointerLock || document.body.webkitRequestPointerLock); if (/Firefox/i.test(navigator.userAgent)) { const fullScreenChange = (event) => { if (document.fullscreenElement === document.body || document.mozFullscreenElement === document.body || document.mozFullScreenElement === document.body) { document.removeEventListener('fullscreenchange', fullScreenChange); document.removeEventListener('mozfullscreenchange', fullScreenChange); document.body.requestPointerLock(); } }; document.addEventListener( 'fullscreenchange', fullScreenChange, false); document.addEventListener( 'mozfullscreenchange', fullScreenChange, false); document.body.requestFullscreen = ( document.body.requestFullscreen || document.body.mozRequestFullscreen || document.body.mozRequestFullScreen || document.body.webkitRequestFullscreen); document.body.requestFullscreen(); } else { document.body.requestPointerLock(); } }, false); } } _FindIntersections(boxes, position) { const sphere = new THREE.Sphere(position, this._radius); const intersections = boxes.filter(b => { return sphere.intersectsBox(b); }); return intersections; } Update(timeInSeconds) { if (!this._enabled) { return; } const frameDecceleration = new THREE.Vector3( this._velocity.x * this._decceleration.x, this._velocity.y * this._decceleration.y, this._velocity.z * this._decceleration.z ); frameDecceleration.multiplyScalar(timeInSeconds); this._velocity.add(frameDecceleration); if (this._move.forward) { this._velocity.z -= this._acceleration.z * timeInSeconds; } if (this._move.backward) { this._velocity.z += this._acceleration.z * timeInSeconds; } if (this._move.left) { this._velocity.x -= this._acceleration.x * timeInSeconds; } if (this._move.right) { this._velocity.x += this._acceleration.x * timeInSeconds; } if (this._move.up) { this._velocity.y += this._acceleration.y * timeInSeconds; } if (this._move.down) { this._velocity.y -= this._acceleration.y * timeInSeconds; } const controlObject = this._controls.getObject(); const oldPosition = new THREE.Vector3(); oldPosition.copy(controlObject.position); const forward = new THREE.Vector3(0, 0, 1); forward.applyQuaternion(controlObject.quaternion); forward.normalize(); const updown = new THREE.Vector3(0, 1, 0); const sideways = new THREE.Vector3(1, 0, 0); sideways.applyQuaternion(controlObject.quaternion); sideways.normalize(); sideways.multiplyScalar(this._velocity.x * timeInSeconds); updown.multiplyScalar(this._velocity.y * timeInSeconds); forward.multiplyScalar(this._velocity.z * timeInSeconds); controlObject.position.add(forward); controlObject.position.add(sideways); controlObject.position.add(updown); // this._position.lerp(controlObject.position, 0.15); this._rotation.slerp(controlObject.quaternion, 0.15); // controlObject.position.copy(this._position); controlObject.quaternion.copy(this._rotation); } }
JavaScript
class StringBufferTerminalProvider { constructor(supportsColor = false) { this._standardBuffer = new StringBuilder_1.StringBuilder(); this._verboseBuffer = new StringBuilder_1.StringBuilder(); this._warningBuffer = new StringBuilder_1.StringBuilder(); this._errorBuffer = new StringBuilder_1.StringBuilder(); this._supportsColor = supportsColor; } /** * {@inheritDoc ITerminalProvider.write} */ write(data, severity) { switch (severity) { case ITerminalProvider_1.TerminalProviderSeverity.warning: { this._warningBuffer.append(data); break; } case ITerminalProvider_1.TerminalProviderSeverity.error: { this._errorBuffer.append(data); break; } case ITerminalProvider_1.TerminalProviderSeverity.verbose: { this._verboseBuffer.append(data); break; } case ITerminalProvider_1.TerminalProviderSeverity.log: default: { this._standardBuffer.append(data); break; } } } /** * {@inheritDoc ITerminalProvider.eolCharacter} */ get eolCharacter() { return '[n]'; } /** * {@inheritDoc ITerminalProvider.supportsColor} */ get supportsColor() { return this._supportsColor; } /** * Get everything that has been written at log-level severity. */ getOutput(options) { return this._normalizeOutput(this._standardBuffer.toString(), options); } /** * Get everything that has been written at verbose-level severity. */ getVerbose(options) { return this._normalizeOutput(this._verboseBuffer.toString(), options); } /** * Get everything that has been written at error-level severity. */ getErrorOutput(options) { return this._normalizeOutput(this._errorBuffer.toString(), options); } /** * Get everything that has been written at warning-level severity. */ getWarningOutput(options) { return this._normalizeOutput(this._warningBuffer.toString(), options); } _normalizeOutput(s, options) { options = Object.assign({ normalizeSpecialCharacters: true }, (options || {})); s = Text_1.Text.convertToLf(s); if (options.normalizeSpecialCharacters) { return AnsiEscape_1.AnsiEscape.formatForTests(s, { encodeNewlines: true }); } else { return s; } } }
JavaScript
class Help { constructor() { this.helpWidth = undefined; this.sortSubcommands = false; this.sortOptions = false; } /** * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. * * @param {Command} cmd * @returns {Command[]} */ visibleCommands(cmd) { const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden); if (cmd._hasImplicitHelpCommand()) { // Create a command matching the implicit help command. const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/); const helpCommand = cmd.createCommand(helpName) .helpOption(false); helpCommand.description(cmd._helpCommandDescription); if (helpArgs) helpCommand.arguments(helpArgs); visibleCommands.push(helpCommand); } if (this.sortSubcommands) { visibleCommands.sort((a, b) => { // @ts-ignore: overloaded return type return a.name().localeCompare(b.name()); }); } return visibleCommands; } /** * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. * * @param {Command} cmd * @returns {Option[]} */ visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); // Implicit help const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag); const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag); if (showShortHelpFlag || showLongHelpFlag) { let helpOption; if (!showShortHelpFlag) { helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription); } else if (!showLongHelpFlag) { helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription); } else { helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription); } visibleOptions.push(helpOption); } if (this.sortOptions) { const getSortKey = (option) => { // WYSIWYG for order displayed in help with short before long, no special handling for negated. return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); }; visibleOptions.sort((a, b) => { return getSortKey(a).localeCompare(getSortKey(b)); }); } return visibleOptions; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(cmd) { // Side effect! Apply the legacy descriptions before the arguments are displayed. if (cmd._argsDescription) { cmd._args.forEach(argument => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ''; }); } // If there are any arguments with a description then return all the arguments. if (cmd._args.find(argument => argument.description)) { return cmd._args; }; return []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(cmd) { // Legacy. Ignores custom usage string, and nested commands. const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); return cmd._name + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option (args ? ' ' + args : ''); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(option) { return option.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(argument) { return argument.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max(max, helper.subcommandTerm(command).length); }, 0); }; /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max(max, helper.optionTerm(option).length); }, 0); }; /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max(max, helper.argumentTerm(argument).length); }, 0); }; /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(cmd) { // Usage let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + '|' + cmd._aliases[0]; } let parentCmdNames = ''; for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; } return parentCmdNames + cmdName + ' ' + cmd.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.description(); } /** * Get the command description to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandDescription(cmd) { // @ts-ignore: overloaded return type return cmd.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(option) { if (option.negate) { return option.description; } const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (option.defaultValue !== undefined) { extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`); } if (extraInfo.length > 0) { return `${option.description} (${extraInfo.join(', ')})`; } return option.description; }; /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); } if (argument.defaultValue !== undefined) { extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`); } if (extraInfo.length > 0) { const extraDescripton = `(${extraInfo.join(', ')})`; if (argument.description) { return `${argument.description} ${extraDescripton}`; } return extraDescripton; } return argument.description; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth || 80; const itemIndentWidth = 2; const itemSeparatorWidth = 2; // between term and description function formatItem(term, description) { if (description) { const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth); } return term; }; function formatList(textArray) { return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); } // Usage let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; // Description const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([commandDescription, '']); } // Arguments const argumentList = helper.visibleArguments(cmd).map((argument) => { return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument)); }); if (argumentList.length > 0) { output = output.concat(['Arguments:', formatList(argumentList), '']); } // Options const optionList = helper.visibleOptions(cmd).map((option) => { return formatItem(helper.optionTerm(option), helper.optionDescription(option)); }); if (optionList.length > 0) { output = output.concat(['Options:', formatList(optionList), '']); } // Commands const commandList = helper.visibleCommands(cmd).map((cmd) => { return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd)); }); if (commandList.length > 0) { output = output.concat(['Commands:', formatList(commandList), '']); } return output.join('\n'); } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper) ); }; /** * Wrap the given string to width characters per line, with lines after the first indented. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. * * @param {string} str * @param {number} width * @param {number} indent * @param {number} [minColumnWidth=40] * @return {string} * */ wrap(str, width, indent, minColumnWidth = 40) { // Detect manually wrapped and indented strings by searching for line breaks // followed by multiple spaces/tabs. if (str.match(/[\n]\s+/)) return str; // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). const columnWidth = width - indent; if (columnWidth < minColumnWidth) return str; const leadingStr = str.substr(0, indent); const columnText = str.substr(indent); const indentString = ' '.repeat(indent); const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); const lines = columnText.match(regex) || []; return leadingStr + lines.map((line, i) => { if (line.slice(-1) === '\n') { line = line.slice(0, line.length - 1); } return ((i > 0) ? indentString : '') + line.trimRight(); }).join('\n'); } }
JavaScript
class App extends React.Component { // Here's what we will do step by step // 1. Add the text value in the textInput to the list todos which is in our state // 2. Render the FlatList! // 3. Make Todo items deletable by clicking on them // 4. Make things functional! state = { todos: [], text: "" } addTodo = () => { // 1. This function should add whatever is in this.state.text // to this.state.todos. Then clear text to allow a new todo // to be added let todosCopy = JSON.parse(JSON.stringify(this.state.todos)); todosCopy.push(this.state.text); this.setState({todos: todosCopy, text: ""}); } onChangeText = text => { this.setState({text}); } // 3.1 Add a function to delete an item from todos given its // index deleteTodo = index => { let todosCopy = JSON.parse(JSON.stringify(this.state.todos)); todosCopy.splice(index, 1); this.setState({ todos: todosCopy }); } render() { return ( <SafeAreaView style={styles.container}> <View style={styles.flatlist}> {/* // 2. Here, you will render your FlatList. To help you do // that, we have created a component for you to render the // items. Additionally, here are the props you will pass to // FlatList: // - style: Make sure your list takes all the white space // - data: What is the list of items we are trying to render? // - renderItem: Use the included ToDo to render items // ToDo component is called like this <ToDo text={"Hello"}/> // - keyExtractor: Write a one-line function to take // (item, index) in and returns index.toString() */} <FlatList data={this.state.todos} renderItem={( { item, index } ) => <ToDo id={index} text={item} onSelect={this.deleteTodo} /> } keyExtractor={(item, index) => { return index.toString() }} /> </View> <View style={{flexDirection: 'row'}}> <TextInput style={styles.textinput} onChangeText={text => this.onChangeText(text)} /*What method should be called here? */ value={this.state.text} /*What should be in place of the empty string? */ /> <Button style={styles.button} title="Add" onPress={this.addTodo} /*What should be called here? */ /> </View> </SafeAreaView> ); } }
JavaScript
class EditorUI { /** * Creates an instance of the editor UI class. * * @param {module:core/editor/editor~Editor} editor The editor instance. */ constructor( editor ) { /** * The editor that the UI belongs to. * * @readonly * @member {module:core/editor/editor~Editor} #editor */ this.editor = editor; /** * An instance of the {@link module:ui/componentfactory~ComponentFactory}, a registry used by plugins * to register factories of specific UI components. * * @readonly * @member {module:ui/componentfactory~ComponentFactory} #componentFactory */ this.componentFactory = new ComponentFactory( editor ); /** * Stores the information about the editor UI focus and propagates it so various plugins and components * are unified as a focus group. * * @readonly * @member {module:utils/focustracker~FocusTracker} #focusTracker */ this.focusTracker = new FocusTracker(); /** * Stores all editable elements used by the editor instance. * * @private * @member {Map.<String,HTMLElement>} */ this._editableElementsMap = new Map(); // Informs UI components that should be refreshed after layout change. this.listenTo( editor.editing.view.document, 'layoutChanged', () => this.update() ); } /** * The main (outermost) DOM element of the editor UI. * * For example, in {@link module:editor-classic/classiceditor~ClassicEditor} it is a `<div>` which * wraps the editable element and the toolbar. In {@link module:editor-inline/inlineeditor~InlineEditor} * it is the editable element itself (as there is no other wrapper). However, in * {@link module:editor-decoupled/decouplededitor~DecoupledEditor} it is set to `null` because this editor does not * come with a single "main" HTML element (its editable element and toolbar are separate). * * This property can be understood as a shorthand for retrieving the element that a specific editor integration * considers to be its main DOM element. * * @readonly * @member {HTMLElement|null} #element */ get element() { return null; } /** * Fires the {@link module:core/editor/editorui~EditorUI#event:update `update`} event. * * This method should be called when the editor UI (e.g. positions of its balloons) needs to be updated due to * some environmental change which CKEditor 5 is not aware of (e.g. resize of a container in which it is used). */ update() { this.fire( 'update' ); } /** * Destroys the UI. */ destroy() { this.stopListening(); this.focusTracker.destroy(); // Clean–up the references to the CKEditor instance stored in the native editable DOM elements. for ( const domElement of this._editableElementsMap.values() ) { domElement.ckeditorInstance = null; } this._editableElementsMap = new Map(); } /** * Store the native DOM editable element used by the editor under * a unique name. * * @param {String} rootName The unique name of the editable element. * @param {HTMLElement} domElement The native DOM editable element. */ setEditableElement( rootName, domElement ) { this._editableElementsMap.set( rootName, domElement ); // Put a reference to the CKEditor instance in the editable native DOM element. // It helps 3rd–party software (browser extensions, other libraries) access and recognize // CKEditor 5 instances (editing roots) and use their API (there is no global editor // instance registry). if ( !domElement.ckeditorInstance ) { domElement.ckeditorInstance = this.editor; } } /** * Returns the editable editor element with the given name or null if editable does not exist. * * @param {String} [rootName=main] The editable name. * @returns {HTMLElement|undefined} */ getEditableElement( rootName = 'main' ) { return this._editableElementsMap.get( rootName ); } /** * Returns array of names of all editor editable elements. * * @returns {Iterable.<String>} */ getEditableElementsNames() { return this._editableElementsMap.keys(); } /** * Stores all editable elements used by the editor instance. * * @protected * @deprecated * @member {Map.<String,HTMLElement>} */ get _editableElements() { /** * The {@link module:core/editor/editorui~EditorUI#_editableElements `EditorUI#_editableElements`} property has been * deprecated and will be removed in the near future. Please use {@link #setEditableElement `setEditableElement()`} and * {@link #getEditableElement `getEditableElement()`} methods instead. * * @error editor-ui-deprecated-editable-elements * @param {module:core/editor/editorui~EditorUI} editorUI Editor UI instance the deprecated property belongs to. */ console.warn( 'editor-ui-deprecated-editable-elements: ' + 'The EditorUI#_editableElements property has been deprecated and will be removed in the near future.', { editorUI: this } ); return this._editableElementsMap; } /** * Fired when the editor UI is ready. * * Fired before {@link module:engine/controller/datacontroller~DataController#event:ready}. * * @event ready */ /** * Fired whenever the UI (all related components) should be refreshed. * * **Note:**: The event is fired after each {@link module:engine/view/document~Document#event:layoutChanged}. * It can also be fired manually via the {@link module:core/editor/editorui~EditorUI#update} method. * * @event update */ }
JavaScript
class Vis extends Events { constructor($el, visConfigArgs) { super(arguments); this.el = $el.get ? $el.get(0) : $el; this.visConfigArgs = _.cloneDeep(visConfigArgs); } hasLegend() { return this.visConfigArgs.addLegend; } /** * Renders the visualization * * @method render * @param data {Object} Elasticsearch query results */ render(data, uiState) { if (!data) { throw new Error('No valid data!'); } if (this.handler) { this.data = null; this._runOnHandler('destroy'); } this.data = data; this.uiState = uiState; this.visConfig = new VisConfig(this.visConfigArgs, this.data, this.uiState, this.el); this.handler = new Handler(this, this.visConfig); this._runOnHandler('render'); } getLegendLabels() { return this.visConfig ? this.visConfig.get('legend.labels', null) : null; } getLegendColors() { return this.visConfig ? this.visConfig.get('legend.colors', null) : null; } _runOnHandler(method) { try { this.handler[method](); } catch (error) { if (error instanceof KbnError) { error.displayToScreen(this.handler); } else { throw error; } } } /** * Destroys the visualization * Removes chart and all elements associated with it. * Removes chart and all elements associated with it. * Remove event listeners and pass destroy call down to owned objects. * * @method destroy */ destroy() { const selection = d3.select(this.el).select('.vis-wrapper'); if (this.handler) this._runOnHandler('destroy'); selection.remove(); } /** * Sets attributes on the visualization * * @method set * @param name {String} An attribute name * @param val {*} Value to which the attribute name is set */ set(name, val) { this.visConfigArgs[name] = val; this.render(this.data, this.uiState); } /** * Gets attributes from the visualization * * @method get * @param name {String} An attribute name * @returns {*} The value of the attribute name */ get(name) { return this.visConfig.get(name); } /** * Turns on event listeners. * * @param event {String} * @param listener{Function} * @returns {*} */ on(event, listener) { const first = this.listenerCount(event) === 0; const ret = Events.prototype.on.call(this, event, listener); const added = this.listenerCount(event) > 0; // if this is the first listener added for the event // enable the event in the handler if (first && added && this.handler) this.handler.enable(event); return ret; } /** * Turns off event listeners. * * @param event {String} * @param listener{Function} * @returns {*} */ off(event, listener) { const last = this.listenerCount(event) === 1; const ret = Events.prototype.off.call(this, event, listener); const removed = this.listenerCount(event) === 0; // Once all listeners are removed, disable the events in the handler if (last && removed && this.handler) this.handler.disable(event); return ret; } }
JavaScript
class CsiBaseDriver { constructor(ctx, options) { this.ctx = ctx; this.options = options || {}; if (!this.options.hasOwnProperty("node")) { this.options.node = {}; } if (!this.options.node.hasOwnProperty("format")) { this.options.node.format = {}; } if (!this.options.node.hasOwnProperty("mount")) { this.options.node.mount = {}; } if (!this.options.node.mount.hasOwnProperty("checkFilesystem")) { this.options.node.mount.checkFilesystem = {}; } } /** * abstract way of retrieving values from parameters/secrets * in order of preference: * - democratic-csi.org/{instance_id}/{key} * - democratic-csi.org/{driver}/{key} * - {key} * * @param {*} parameters * @param {*} key */ getNormalizedParameterValue(parameters, key, driver, instance_id) { const normalized = this.getNormalizedParameters( parameters, driver, instance_id ); return normalized[key]; } getNormalizedParameters(parameters, driver, instance_id) { const normalized = JSON.parse(JSON.stringify(parameters)); const base_key = "democratic-csi.org"; driver = driver || this.options.driver; instance_id = instance_id || this.options.instance_id; for (const key in parameters) { let normalizedKey; let prefixLength; if (instance_id && key.startsWith(`${base_key}/${instance_id}/`)) { prefixLength = `${base_key}/${instance_id}/`.length; normalizedKey = key.slice(prefixLength); normalized[normalizedKey] = parameters[key]; delete normalized[key]; } if (driver && key.startsWith(`${base_key}/${driver}/`)) { prefixLength = `${base_key}/${driver}/`.length; normalizedKey = key.slice(prefixLength); normalized[normalizedKey] = parameters[key]; delete normalized[key]; } if (key.startsWith(`${base_key}/`)) { prefixLength = `${base_key}/`.length; normalizedKey = key.slice(prefixLength); normalized[normalizedKey] = parameters[key]; delete normalized[key]; } } return normalized; } /** * Get an instance of the Filesystem class * * @returns Filesystem */ getDefaultFilesystemInstance() { return registry.get( `${__REGISTRY_NS__}:default_filesystem_instance`, () => { return new Filesystem(); } ); } /** * Get an instance of the Mount class * * @returns Mount */ getDefaultMountInstance() { return registry.get(`${__REGISTRY_NS__}:default_mount_instance`, () => { const filesystem = this.getDefaultFilesystemInstance(); return new Mount({ filesystem }); }); } /** * Get an instance of the ISCSI class * * @returns ISCSI */ getDefaultISCSIInstance() { return registry.get(`${__REGISTRY_NS__}:default_iscsi_instance`, () => { return new ISCSI(); }); } getDefaultZetabyteInstance() { return registry.get(`${__REGISTRY_NS__}:default_zb_instance`, () => { return new Zetabyte({ idempotent: true, paths: { zfs: "zfs", zpool: "zpool", sudo: "sudo", chroot: "chroot", }, //logger: driver.ctx.logger, executor: { spawn: function () { const command = `${arguments[0]} ${arguments[1].join(" ")}`; return cp.exec(command); }, }, log_commands: true, }); }); } getDefaultOneClientInstance() { return registry.get(`${__REGISTRY_NS__}:default_oneclient_instance`, () => { return new OneClient(); }); } async GetPluginInfo(call) { return { name: this.ctx.args.csiName, vendor_version: this.ctx.args.version, }; } async GetPluginCapabilities(call) { let capabilities; const response = { capabilities: [], }; //UNKNOWN = 0; // CONTROLLER_SERVICE indicates that the Plugin provides RPCs for // the ControllerService. Plugins SHOULD provide this capability. // In rare cases certain plugins MAY wish to omit the // ControllerService entirely from their implementation, but such // SHOULD NOT be the common case. // The presence of this capability determines whether the CO will // attempt to invoke the REQUIRED ControllerService RPCs, as well // as specific RPCs as indicated by ControllerGetCapabilities. //CONTROLLER_SERVICE = 1; // VOLUME_ACCESSIBILITY_CONSTRAINTS indicates that the volumes for // this plugin MAY NOT be equally accessible by all nodes in the // cluster. The CO MUST use the topology information returned by // CreateVolumeRequest along with the topology information // returned by NodeGetInfo to ensure that a given volume is // accessible from a given node when scheduling workloads. //VOLUME_ACCESSIBILITY_CONSTRAINTS = 2; capabilities = this.options.service.identity.capabilities.service || [ "UNKNOWN", ]; capabilities.forEach((item) => { response.capabilities.push({ service: { type: item }, }); }); //UNKNOWN = 0; // ONLINE indicates that volumes may be expanded when published to // a node. When a Plugin implements this capability it MUST // implement either the EXPAND_VOLUME controller capability or the // EXPAND_VOLUME node capability or both. When a plugin supports // ONLINE volume expansion and also has the EXPAND_VOLUME // controller capability then the plugin MUST support expansion of // volumes currently published and available on a node. When a // plugin supports ONLINE volume expansion and also has the // EXPAND_VOLUME node capability then the plugin MAY support // expansion of node-published volume via NodeExpandVolume. // // Example 1: Given a shared filesystem volume (e.g. GlusterFs), // the Plugin may set the ONLINE volume expansion capability and // implement ControllerExpandVolume but not NodeExpandVolume. // // Example 2: Given a block storage volume type (e.g. EBS), the // Plugin may set the ONLINE volume expansion capability and // implement both ControllerExpandVolume and NodeExpandVolume. // // Example 3: Given a Plugin that supports volume expansion only // upon a node, the Plugin may set the ONLINE volume // expansion capability and implement NodeExpandVolume but not // ControllerExpandVolume. //ONLINE = 1; // OFFLINE indicates that volumes currently published and // available on a node SHALL NOT be expanded via // ControllerExpandVolume. When a plugin supports OFFLINE volume // expansion it MUST implement either the EXPAND_VOLUME controller // capability or both the EXPAND_VOLUME controller capability and // the EXPAND_VOLUME node capability. // // Example 1: Given a block storage volume type (e.g. Azure Disk) // that does not support expansion of "node-attached" (i.e. // controller-published) volumes, the Plugin may indicate // OFFLINE volume expansion support and implement both // ControllerExpandVolume and NodeExpandVolume. //OFFLINE = 2; capabilities = this.options.service.identity.capabilities .volume_expansion || ["UNKNOWN"]; capabilities.forEach((item) => { response.capabilities.push({ volume_expansion: { type: item }, }); }); return response; } async Probe(call) { return { ready: { value: true } }; } async ControllerGetCapabilities(call) { let capabilities; const response = { capabilities: [], }; //UNKNOWN = 0; //CREATE_DELETE_VOLUME = 1; //PUBLISH_UNPUBLISH_VOLUME = 2; //LIST_VOLUMES = 3; //GET_CAPACITY = 4; // Currently the only way to consume a snapshot is to create // a volume from it. Therefore plugins supporting // CREATE_DELETE_SNAPSHOT MUST support creating volume from // snapshot. //CREATE_DELETE_SNAPSHOT = 5; //LIST_SNAPSHOTS = 6; // Plugins supporting volume cloning at the storage level MAY // report this capability. The source volume MUST be managed by // the same plugin. Not all volume sources and parameters // combinations MAY work. //CLONE_VOLUME = 7; // Indicates the SP supports ControllerPublishVolume.readonly // field. //PUBLISH_READONLY = 8; // See VolumeExpansion for details. //EXPAND_VOLUME = 9; capabilities = this.options.service.controller.capabilities.rpc || [ "UNKNOWN", ]; capabilities.forEach((item) => { response.capabilities.push({ rpc: { type: item }, }); }); return response; } async NodeGetCapabilities(call) { let capabilities; const response = { capabilities: [], }; //UNKNOWN = 0; //STAGE_UNSTAGE_VOLUME = 1; // If Plugin implements GET_VOLUME_STATS capability // then it MUST implement NodeGetVolumeStats RPC // call for fetching volume statistics. //GET_VOLUME_STATS = 2; // See VolumeExpansion for details. //EXPAND_VOLUME = 3; capabilities = this.options.service.node.capabilities.rpc || ["UNKNOWN"]; capabilities.forEach((item) => { response.capabilities.push({ rpc: { type: item }, }); }); return response; } async NodeGetInfo(call) { return { node_id: process.env.CSI_NODE_ID || os.hostname(), max_volumes_per_node: 0, }; } /** * https://kubernetes-csi.github.io/docs/raw-block.html * --feature-gates=BlockVolume=true,CSIBlockVolume=true * * StagingTargetPath is always a directory even for block volumes * * NOTE: stage gets called every time publish does * * @param {*} call */ async NodeStageVolume(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); const iscsi = driver.getDefaultISCSIInstance(); let result; let device; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const staging_target_path = call.request.staging_target_path; if (!staging_target_path) { throw new GrpcError( grpc.status.INVALID_ARGUMENT, `missing staging_target_path` ); } const capability = call.request.volume_capability; if (!capability || Object.keys(capability).length === 0) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing capability`); } const access_type = capability.access_type || "mount"; const volume_context = call.request.volume_context; let fs_type; let mount_flags; let volume_mount_group; const node_attach_driver = volume_context.node_attach_driver; const block_path = staging_target_path + "/block_device"; const bind_mount_flags = []; bind_mount_flags.push("defaults"); const normalizedSecrets = this.getNormalizedParameters( call.request.secrets, call.request.volume_context.provisioner_driver, call.request.volume_context.provisioner_driver_instance_id ); /* let mount_options = await mount.getMountOptions(staging_target_path); console.log(mount_options); console.log(await mount.getMountOptionValue(mount_options, "stripe")); console.log(await mount.getMountOptionPresent(mount_options, "stripee")); throw new Error("foobar"); */ if (access_type == "mount") { fs_type = capability.mount.fs_type; mount_flags = capability.mount.mount_flags || []; // add secrets mount_flags if (normalizedSecrets.mount_flags) { mount_flags.push(normalizedSecrets.mount_flags); } switch (node_attach_driver) { case "oneclient": // move along break; default: mount_flags.push("defaults"); // https://github.com/karelzak/util-linux/issues/1429 //mount_flags.push("x-democratic-csi.managed"); //mount_flags.push("x-democratic-csi.staged"); break; } if ( semver.satisfies(driver.ctx.csiVersion, ">=1.5.0") && driver.options.service.node.capabilities.rpc.includes( "VOLUME_MOUNT_GROUP" ) ) { volume_mount_group = capability.mount.volume_mount_group; // in k8s this is derrived from the fsgroup in the pod security context } } if (call.request.volume_context.provisioner_driver == "node-manual") { result = await this.assertCapabilities([capability], node_attach_driver); if (!result.valid) { throw new GrpcError( grpc.status.INVALID_ARGUMENT, `invalid capability: ${result.message}` ); } } else { result = await this.assertCapabilities([capability]); if (!result.valid) { throw new GrpcError( grpc.status.INVALID_ARGUMENT, `invalid capability: ${result.message}` ); } } // csi spec stipulates that staging_target_path is a directory even for block mounts result = await filesystem.pathExists(staging_target_path); if (!result) { await filesystem.mkdir(staging_target_path, ["-p", "-m", "0750"]); } switch (node_attach_driver) { case "nfs": case "lustre": device = `${volume_context.server}:${volume_context.share}`; break; case "smb": device = `//${volume_context.server}/${volume_context.share}`; // if not present add guest let has_username = mount_flags.some((element) => { element = element.trim().toLowerCase(); return element.startsWith("username="); }); // prevents driver from hanging on stdin waiting for a password to be entered at the cli if (!has_username) { let has_guest = mount_flags.some((element) => { element = element.trim().toLowerCase(); return element === "guest"; }); if (!has_guest) { mount_flags.push("guest"); } } break; case "iscsi": let portals = []; if (volume_context.portal) { portals.push(volume_context.portal.trim()); } if (volume_context.portals) { volume_context.portals.split(",").forEach((portal) => { portals.push(portal.trim()); }); } // ensure full portal value portals = portals.map((value) => { if (!value.includes(":")) { value += ":3260"; } return value.trim(); }); // ensure unique entries only portals = [...new Set(portals)]; // stores actual device paths after iscsi login let iscsiDevices = []; // stores configuration of targets/iqn/luns to connect to let iscsiConnections = []; for (let portal of portals) { iscsiConnections.push({ portal, iqn: volume_context.iqn, lun: volume_context.lun, }); } /** * TODO: allow sending in iscsiConnection in a raw/manual format * TODO: allow option to determine if send_targets should be invoked * TODO: allow option to control whether nodedb entry should be created by driver * TODO: allow option to control whether nodedb entry should be deleted by driver */ for (let iscsiConnection of iscsiConnections) { // create DB entry // https://library.netapp.com/ecmdocs/ECMP1654943/html/GUID-8EC685B4-8CB6-40D8-A8D5-031A3899BCDC.html // put these options in place to force targets managed by csi to be explicitly attached (in the case of unclearn shutdown etc) let nodeDB = { "node.startup": "manual", //"node.session.scan": "manual", }; const nodeDBKeyPrefix = "node-db."; for (const key in normalizedSecrets) { if (key.startsWith(nodeDBKeyPrefix)) { nodeDB[key.substr(nodeDBKeyPrefix.length)] = normalizedSecrets[key]; } } // create 'DB' entry await iscsi.iscsiadm.createNodeDBEntry( iscsiConnection.iqn, iscsiConnection.portal, nodeDB ); // login await iscsi.iscsiadm.login( iscsiConnection.iqn, iscsiConnection.portal ); // get associated session let session = await iscsi.iscsiadm.getSession( iscsiConnection.iqn, iscsiConnection.portal ); // rescan in scenarios when login previously occurred but volumes never appeared await iscsi.iscsiadm.rescanSession(session); // find device name device = `/dev/disk/by-path/ip-${iscsiConnection.portal}-iscsi-${iscsiConnection.iqn}-lun-${iscsiConnection.lun}`; let deviceByPath = device; // can take some time for device to show up, loop for some period result = await filesystem.pathExists(device); let timer_start = Math.round(new Date().getTime() / 1000); let timer_max = 30; let deviceCreated = result; while (!result) { await sleep(2000); result = await filesystem.pathExists(device); if (result) { deviceCreated = true; break; } let current_time = Math.round(new Date().getTime() / 1000); if (!result && current_time - timer_start > timer_max) { driver.ctx.logger.warn( `hit timeout waiting for device node to appear: ${device}` ); break; } } if (deviceCreated) { device = await filesystem.realpath(device); iscsiDevices.push(device); driver.ctx.logger.info( `successfully logged into portal ${iscsiConnection.portal} and created device ${deviceByPath} with realpath ${device}` ); } } // let things settle // this will help in dm scenarios await sleep(2000); // filter duplicates iscsiDevices = iscsiDevices.filter((value, index, self) => { return self.indexOf(value) === index; }); // only throw an error if we were not able to attach to *any* devices if (iscsiDevices.length < 1) { throw new GrpcError( grpc.status.UNKNOWN, `unable to attach any iscsi devices` ); } if (iscsiDevices.length != iscsiConnections.length) { driver.ctx.logger.warn( `failed to attach all iscsi devices/targets/portals` ); // TODO: allow a parameter to control this behavior in some form if (false) { throw new GrpcError( grpc.status.UNKNOWN, `unable to attach all iscsi devices` ); } } // compare all device-mapper slaves with the newly created devices // if any of the new devices are device-mapper slaves treat this as a // multipath scenario let allDeviceMapperSlaves = await filesystem.getAllDeviceMapperSlaveDevices(); let commonDevices = allDeviceMapperSlaves.filter((value) => iscsiDevices.includes(value) ); const useMultipath = iscsiConnections.length > 1 || commonDevices.length > 0; // discover multipath device to use if (useMultipath) { device = await filesystem.getDeviceMapperDeviceFromSlaves( iscsiDevices, false ); if (!device) { throw new GrpcError( grpc.status.UNKNOWN, `failed to discover multipath device` ); } } break; case "hostpath": result = await mount.pathIsMounted(staging_target_path); // if not mounted, mount if (!result) { await mount.bindMount(volume_context.path, staging_target_path); return {}; } else { return {}; } break; case "oneclient": let oneclient = driver.getDefaultOneClientInstance(); device = "oneclient"; result = await mount.deviceIsMountedAtPath(device, staging_target_path); if (result) { return {}; } if (volume_context.space_names) { volume_context.space_names.split(",").forEach((space) => { mount_flags.push("--space", space); }); } if (volume_context.space_ids) { volume_context.space_ids.split(",").forEach((space) => { mount_flags.push("--space-id", space); }); } if (normalizedSecrets.token) { mount_flags.push("-t", normalizedSecrets.token); } else { if (volume_context.token) { mount_flags.push("-t", volume_context.token); } } result = await oneclient.mount( staging_target_path, ["-H", volume_context.server].concat(mount_flags) ); if (result) { return {}; } throw new GrpcError( grpc.status.UNKNOWN, `failed to mount oneclient: ${volume_context.server}` ); break; case "zfs-local": // TODO: make this a geneic zb instance (to ensure works with node-manual driver) const zb = driver.getDefaultZetabyteInstance(); result = await zb.zfs.get(`${volume_context.zfs_asset_name}`, [ "type", "mountpoint", ]); result = result[`${volume_context.zfs_asset_name}`]; switch (result.type.value) { case "filesystem": if (result.mountpoint.value != "legacy") { // zfs set mountpoint=legacy <dataset> // zfs inherit mountpoint <dataset> await zb.zfs.set(`${volume_context.zfs_asset_name}`, { mountpoint: "legacy", }); } device = `${volume_context.zfs_asset_name}`; if (!fs_type) { fs_type = "zfs"; } break; case "volume": device = `/dev/zvol/${volume_context.zfs_asset_name}`; break; default: throw new GrpcError( grpc.status.UNKNOWN, `unknown zfs asset type: ${result.type.value}` ); } break; default: throw new GrpcError( grpc.status.INVALID_ARGUMENT, `unknown/unsupported node_attach_driver: ${node_attach_driver}` ); } switch (access_type) { case "mount": let is_block = false; switch (node_attach_driver) { case "iscsi": is_block = true; break; case "zfs-local": is_block = device.startsWith("/dev/zvol/"); break; } if (is_block) { // block specific logic if (!fs_type) { fs_type = "ext4"; } if (await filesystem.isBlockDevice(device)) { // format result = await filesystem.deviceIsFormatted(device); if (!result) { let formatOptions = _.get( driver.options.node.format, [fs_type, "customOptions"], [] ); if (!Array.isArray(formatOptions)) { formatOptions = []; } await filesystem.formatDevice(device, fs_type, formatOptions); } let fs_info = await filesystem.getDeviceFilesystemInfo(device); fs_type = fs_info.type; // fsck result = await mount.deviceIsMountedAtPath( device, staging_target_path ); if (!result) { // https://github.com/democratic-csi/democratic-csi/issues/52#issuecomment-768463401 let checkFilesystem = driver.options.node.mount.checkFilesystem[fs_type] || {}; if (checkFilesystem.enabled) { await filesystem.checkFilesystem( device, fs_type, checkFilesystem.customOptions || [], checkFilesystem.customFilesystemOptions || [] ); } } } } result = await mount.deviceIsMountedAtPath(device, staging_target_path); if (!result) { if (!fs_type) { switch (node_attach_driver) { case "nfs": fs_type = "nfs"; break; case "lustre": fs_type = "lustre"; break; case "smb": fs_type = "cifs"; break; case "iscsi": fs_type = "ext4"; break; default: break; } } await mount.mount( device, staging_target_path, ["-t", fs_type].concat(["-o", mount_flags.join(",")]) ); } if (await filesystem.isBlockDevice(device)) { // go ahead and expand fs (this covers cloned setups where expand is not explicitly invoked) switch (fs_type) { case "ext4": case "ext3": case "ext4dev": //await filesystem.checkFilesystem(device, fs_info.type); try { await filesystem.expandFilesystem(device, fs_type); } catch (err) { // mount is clean and rw, but it will not expand until clean umount has been done // failed to execute filesystem command: resize2fs /dev/sda, response: {"code":1,"stdout":"Couldn't find valid filesystem superblock.\n","stderr":"resize2fs 1.44.5 (15-Dec-2018)\nresize2fs: Superblock checksum does not match superblock while trying to open /dev/sda\n"} // /dev/sda on /var/lib/kubelet/plugins/kubernetes.io/csi/pv/pvc-4a80757e-5e87-475d-826f-44fcc4719348/globalmount type ext4 (rw,relatime,stripe=256) if ( err.code == 1 && err.stdout.includes("find valid filesystem superblock") && err.stderr.includes("checksum does not match superblock") ) { driver.ctx.logger.warn( `successful mount, unsuccessful fs resize: attempting abnormal umount/mount/resize2fs to clear things up ${staging_target_path} (${device})` ); // try an unmount/mount/fsck cycle again just to clean things up await mount.umount(staging_target_path, []); await mount.mount( device, staging_target_path, ["-t", fs_type].concat(["-o", mount_flags.join(",")]) ); await filesystem.expandFilesystem(device, fs_type); } else { throw err; } } break; case "btrfs": case "xfs": //await filesystem.checkFilesystem(device, fs_info.type); await filesystem.expandFilesystem(staging_target_path, fs_type); break; default: // unsupported filesystem throw new GrpcError( grpc.status.FAILED_PRECONDITION, `unsupported/unknown filesystem ${fs_type}` ); } } break; case "block": //result = await mount.deviceIsMountedAtPath(device, block_path); result = await mount.deviceIsMountedAtPath("dev", block_path); if (!result) { result = await filesystem.pathExists(staging_target_path); if (!result) { await filesystem.mkdir(staging_target_path, ["-p", "-m", "0750"]); } result = await filesystem.pathExists(block_path); if (!result) { await filesystem.touch(block_path); } await mount.bindMount(device, block_path, [ "-o", bind_mount_flags.join(","), ]); } break; default: throw new GrpcError( grpc.status.INVALID_ARGUMENT, `unknown/unsupported access_type: ${access_type}` ); } return {}; } /** * NOTE: only gets called when the last pod on the node using the volume is removed * * 1. unmount fs * 2. logout of iscsi if neccessary * * @param {*} call */ async NodeUnstageVolume(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); const iscsi = driver.getDefaultISCSIInstance(); let result; let is_block = false; let is_device_mapper = false; let block_device_info; let access_type = "mount"; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const staging_target_path = call.request.staging_target_path; if (!staging_target_path) { throw new GrpcError( grpc.status.INVALID_ARGUMENT, `missing staging_target_path` ); } const block_path = staging_target_path + "/block_device"; let normalized_staging_path = staging_target_path; const umount_args = []; const umount_force_extra_args = ["--force", "--lazy"]; //result = await mount.pathIsMounted(block_path); //result = await mount.pathIsMounted(staging_target_path) // TODO: use the x-* mount options to detect if we should delete target try { result = await mount.pathIsMounted(block_path); } catch (err) { /** * on stalled fs such as nfs, even findmnt will return immediately for the base mount point * so in the case of timeout here (base mount point and then a file/folder beneath it) we almost certainly are not a block device * AND the fs is probably stalled */ if (err.timeout) { driver.ctx.logger.warn( `detected stale mount, attempting to force unmount: ${normalized_staging_path}` ); await mount.umount( normalized_staging_path, umount_args.concat(umount_force_extra_args) ); result = false; // assume we are *NOT* a block device at this point } else { throw err; } } if (result) { is_block = true; access_type = "block"; block_device_info = await filesystem.getBlockDevice(block_path); normalized_staging_path = block_path; } else { result = await mount.pathIsMounted(staging_target_path); if (result) { let device = await mount.getMountPointDevice(staging_target_path); result = await filesystem.isBlockDevice(device); if (result) { is_block = true; block_device_info = await filesystem.getBlockDevice(device); } } } result = await mount.pathIsMounted(normalized_staging_path); if (result) { try { result = await mount.umount(normalized_staging_path, umount_args); } catch (err) { if (err.timeout) { driver.ctx.logger.warn( `hit timeout waiting to unmount path: ${normalized_staging_path}` ); result = await mount.getMountDetails(normalized_staging_path); switch (result.fstype) { case "nfs": case "nfs4": driver.ctx.logger.warn( `detected stale nfs filesystem, attempting to force unmount: ${normalized_staging_path}` ); result = await mount.umount( normalized_staging_path, umount_args.concat(umount_force_extra_args) ); break; default: throw err; break; } } else { throw err; } } } if (is_block) { let realBlockDeviceInfos = []; // detect if is a multipath device is_device_mapper = await filesystem.isDeviceMapperDevice( block_device_info.path ); if (is_device_mapper) { let realBlockDevices = await filesystem.getDeviceMapperDeviceSlaves( block_device_info.path ); for (const realBlockDevice of realBlockDevices) { realBlockDeviceInfos.push( await filesystem.getBlockDevice(realBlockDevice) ); } } else { realBlockDeviceInfos = [block_device_info]; } // TODO: this could be made async to detach all simultaneously for (const block_device_info_i of realBlockDeviceInfos) { if (block_device_info_i.tran == "iscsi") { // figure out which iscsi session this belongs to and logout // scan /dev/disk/by-path/ip-*? // device = `/dev/disk/by-path/ip-${volume_context.portal}-iscsi-${volume_context.iqn}-lun-${volume_context.lun}`; // parse output from `iscsiadm -m session -P 3` let sessions = await iscsi.iscsiadm.getSessionsDetails(); for (let i = 0; i < sessions.length; i++) { let session = sessions[i]; let is_attached_to_session = false; if ( session.attached_scsi_devices && session.attached_scsi_devices.host && session.attached_scsi_devices.host.devices ) { is_attached_to_session = session.attached_scsi_devices.host.devices.some((device) => { if (device.attached_scsi_disk == block_device_info_i.name) { return true; } return false; }); } if (is_attached_to_session) { let timer_start; let timer_max; timer_start = Math.round(new Date().getTime() / 1000); timer_max = 30; let loggedOut = false; while (!loggedOut) { try { await iscsi.iscsiadm.logout(session.target, [ session.persistent_portal, ]); loggedOut = true; } catch (err) { await sleep(2000); let current_time = Math.round(new Date().getTime() / 1000); if (current_time - timer_start > timer_max) { // not throwing error for now as future invocations would not enter code path anyhow loggedOut = true; //throw new GrpcError( // grpc.status.UNKNOWN, // `hit timeout trying to logout of iscsi target: ${session.persistent_portal}` //); } } } timer_start = Math.round(new Date().getTime() / 1000); timer_max = 30; let deletedEntry = false; while (!deletedEntry) { try { await iscsi.iscsiadm.deleteNodeDBEntry( session.target, session.persistent_portal ); deletedEntry = true; } catch (err) { await sleep(2000); let current_time = Math.round(new Date().getTime() / 1000); if (current_time - timer_start > timer_max) { // not throwing error for now as future invocations would not enter code path anyhow deletedEntry = true; //throw new GrpcError( // grpc.status.UNKNOWN, // `hit timeout trying to delete iscsi node DB entry: ${session.target}, ${session.persistent_portal}` //); } } } } } } } } if (access_type == "block") { // remove touched file result = await filesystem.pathExists(block_path); if (result) { result = await filesystem.rm(block_path); } } result = await filesystem.pathExists(staging_target_path); if (result) { result = await filesystem.rmdir(staging_target_path); } return {}; } async NodePublishVolume(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); let result; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const staging_target_path = call.request.staging_target_path || ""; const target_path = call.request.target_path; if (!target_path) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing target_path`); } const capability = call.request.volume_capability; if (!capability || Object.keys(capability).length === 0) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing capability`); } const access_type = capability.access_type || "mount"; let mount_flags; let volume_mount_group; const readonly = call.request.readonly; const volume_context = call.request.volume_context; const bind_mount_flags = []; const node_attach_driver = volume_context.node_attach_driver; if (access_type == "mount") { mount_flags = capability.mount.mount_flags || []; bind_mount_flags.push(...mount_flags); if ( semver.satisfies(driver.ctx.csiVersion, ">=1.5.0") && driver.options.service.node.capabilities.rpc.includes( "VOLUME_MOUNT_GROUP" ) ) { volume_mount_group = capability.mount.volume_mount_group; // in k8s this is derrived from the fsgroup in the pod security context } } bind_mount_flags.push("defaults"); // https://github.com/karelzak/util-linux/issues/1429 //bind_mount_flags.push("x-democratic-csi.managed"); //bind_mount_flags.push("x-democratic-csi.published"); if (readonly) bind_mount_flags.push("ro"); // , "x-democratic-csi.ro" switch (node_attach_driver) { case "nfs": case "smb": case "lustre": case "oneclient": case "hostpath": case "iscsi": case "zfs-local": // ensure appropriate directories/files switch (access_type) { case "mount": // ensure directory exists result = await filesystem.pathExists(target_path); if (!result) { await filesystem.mkdir(target_path, ["-p", "-m", "0750"]); } break; case "block": // ensure target_path directory exists as target path should be a file let target_dir = await filesystem.dirname(target_path); result = await filesystem.pathExists(target_dir); if (!result) { await filesystem.mkdir(target_dir, ["-p", "-m", "0750"]); } // ensure target file exists result = await filesystem.pathExists(target_path); if (!result) { await filesystem.touch(target_path); } break; default: throw new GrpcError( grpc.status.INVALID_ARGUMENT, `unsupported/unknown access_type ${access_type}` ); } // ensure bind mount if (staging_target_path) { let normalized_staging_device; let normalized_staging_path; if (access_type == "block") { normalized_staging_path = staging_target_path + "/block_device"; } else { normalized_staging_path = staging_target_path; } // sanity check to ensure the staged path is actually mounted result = await mount.pathIsMounted(normalized_staging_path); if (!result) { throw new GrpcError( grpc.status.FAILED_PRECONDITION, `staging path is not mounted: ${normalized_staging_path}` ); } result = await mount.pathIsMounted(target_path); // if not mounted, mount if (!result) { await mount.bindMount(normalized_staging_path, target_path, [ "-o", bind_mount_flags.join(","), ]); } else { // if is mounted, ensure proper source if (access_type == "block") { normalized_staging_device = "dev"; // special syntax for single file bind mounts } else { normalized_staging_device = await mount.getMountPointDevice( staging_target_path ); } result = await mount.deviceIsMountedAtPath( normalized_staging_device, target_path ); if (!result) { throw new GrpcError( grpc.status.FAILED_PRECONDITION, `it appears something else is already mounted at ${target_path}` ); } } return {}; } // unsupported filesystem throw new GrpcError( grpc.status.FAILED_PRECONDITION, `only staged configurations are valid` ); default: throw new GrpcError( grpc.status.INVALID_ARGUMENT, `unknown/unsupported node_attach_driver: ${node_attach_driver}` ); } return {}; } async NodeUnpublishVolume(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); let result; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const target_path = call.request.target_path; if (!target_path) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing target_path`); } const umount_args = []; const umount_force_extra_args = ["--force", "--lazy"]; try { result = await mount.pathIsMounted(target_path); } catch (err) { // running findmnt on non-existant paths return immediately // the only time this should timeout is on a stale fs // so if timeout is hit we should be near certain it is indeed mounted if (err.timeout) { driver.ctx.logger.warn( `detected stale mount, attempting to force unmount: ${target_path}` ); await mount.umount( target_path, umount_args.concat(umount_force_extra_args) ); result = false; // assume we have fully unmounted } else { throw err; } } if (result) { try { result = await mount.umount(target_path, umount_args); } catch (err) { if (err.timeout) { driver.ctx.logger.warn( `hit timeout waiting to unmount path: ${target_path}` ); // bind mounts do show the 'real' fs details result = await mount.getMountDetails(target_path); switch (result.fstype) { case "nfs": case "nfs4": driver.ctx.logger.warn( `detected stale nfs filesystem, attempting to force unmount: ${target_path}` ); result = await mount.umount( target_path, umount_args.concat(umount_force_extra_args) ); break; default: throw err; break; } } else { throw err; } } } result = await filesystem.pathExists(target_path); if (result) { if (fs.lstatSync(target_path).isDirectory()) { result = await filesystem.rmdir(target_path); } else { result = await filesystem.rm([target_path]); } } return {}; } async NodeGetVolumeStats(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); let result; let device_path; let access_type; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const volume_path = call.request.volume_path; const block_path = volume_path + "/block_device"; if (!volume_path) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_path`); } let res = {}; //VOLUME_CONDITION if ( semver.satisfies(driver.ctx.csiVersion, ">=1.3.0") && driver.options.service.node.capabilities.rpc.includes("VOLUME_CONDITION") ) { // TODO: let drivers fill ths in let abnormal = false; let message = "OK"; res.volume_condition = { abnormal, message }; } if ( (await mount.isBindMountedBlockDevice(volume_path)) || (await mount.isBindMountedBlockDevice(block_path)) ) { device_path = block_path; access_type = "block"; } else { device_path = volume_path; access_type = "mount"; } switch (access_type) { case "mount": if (!(await mount.pathIsMounted(device_path))) { throw new GrpcError( grpc.status.NOT_FOUND, `nothing mounted at path: ${device_path}` ); } result = await mount.getMountDetails(device_path, [ "avail", "size", "used", ]); res.usage = [ { available: result.avail, total: result.size, used: result.used, unit: "BYTES", }, ]; break; case "block": if (!(await filesystem.pathExists(device_path))) { throw new GrpcError( grpc.status.NOT_FOUND, `nothing mounted at path: ${device_path}` ); } result = await filesystem.getBlockDevice(device_path); res.usage = [ { total: result.size, unit: "BYTES", }, ]; break; default: throw new GrpcError( grpc.status.INVALID_ARGUMENT, `unsupported/unknown access_type ${access_type}` ); } return res; } /** * https://kubernetes-csi.github.io/docs/volume-expansion.html * allowVolumeExpansion: true * --feature-gates=ExpandCSIVolumes=true * --feature-gates=ExpandInUsePersistentVolumes=true * * @param {*} call */ async NodeExpandVolume(call) { const driver = this; const mount = driver.getDefaultMountInstance(); const filesystem = driver.getDefaultFilesystemInstance(); let device; let fs_info; let device_path; let access_type; let is_block = false; let is_formatted; let fs_type; let is_device_mapper = false; const volume_id = call.request.volume_id; if (!volume_id) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_id`); } const volume_path = call.request.volume_path; if (!volume_path) { throw new GrpcError(grpc.status.INVALID_ARGUMENT, `missing volume_path`); } const block_path = volume_path + "/block_device"; const capacity_range = call.request.capacity_range; const volume_capability = call.request.volume_capability; if ( (await mount.isBindMountedBlockDevice(volume_path)) || (await mount.isBindMountedBlockDevice(block_path)) ) { access_type = "block"; device_path = block_path; } else { access_type = "mount"; device_path = volume_path; } try { device = await mount.getMountPointDevice(device_path); is_formatted = await filesystem.deviceIsFormatted(device); is_block = await filesystem.isBlockDevice(device); } catch (err) { if (err.code == 1) { throw new GrpcError( grpc.status.NOT_FOUND, `volume_path ${volume_path} is not currently mounted` ); } } if (is_block) { let rescan_devices = []; // detect if is a multipath device is_device_mapper = await filesystem.isDeviceMapperDevice(device); if (is_device_mapper) { // NOTE: want to make sure we scan the dm device *after* all the underlying slaves rescan_devices = await filesystem.getDeviceMapperDeviceSlaves(device); } rescan_devices.push(device); for (let sdevice of rescan_devices) { // TODO: technically rescan is only relevant/available for remote drives // such as iscsi etc, should probably limit this call as appropriate // for now crudely checking the scenario inside the method itself await filesystem.rescanDevice(sdevice); } // let things settle // it appears the dm devices can take a second to figure things out if (is_device_mapper || true) { await sleep(2000); } if (is_formatted && access_type == "mount") { fs_info = await filesystem.getDeviceFilesystemInfo(device); fs_type = fs_info.type; if (fs_type) { switch (fs_type) { case "ext4": case "ext3": case "ext4dev": //await filesystem.checkFilesystem(device, fs_info.type); await filesystem.expandFilesystem(device, fs_type); break; case "btrfs": case "xfs": let mount_info = await mount.getMountDetails(device_path); if (["btrfs", "xfs"].includes(mount_info.fstype)) { //await filesystem.checkFilesystem(device, fs_info.type); await filesystem.expandFilesystem(device_path, fs_type); } break; default: // unsupported filesystem throw new GrpcError( grpc.status.FAILED_PRECONDITION, `unsupported/unknown filesystem ${fs_type}` ); } } } else { //block device unformatted return {}; } } else { // not block device return {}; } return {}; } }
JavaScript
class Models { /** * Queries the database for all states in sorted order. * @param {object} db - A database client that can perform queries from the mysql2 module. * @return {Promise} Returns a promise that resolves with an array of rows from the states table. */ static getStates(db) { return db.execute('SELECT * FROM states ORDER BY title;') .then((result) => result[0]) .catch((err) => { console.error(err); }); } /** * Queries the database for all route segments with the given state ID. * * For longer column names, a shortened name is used to reduce bandwidth or for camel casing. * The queried rows are also sorted by the route number and ID, in that order. * Length in meters are queried to be from 15 to 3 decimal digits. * * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {number} stateId - The ID of the state to query route segments from. * @return {Promise} Returns a promise that resolves with an array of rows. Each row contains * a route segment's ID, route number, route signing type, order in the route, direction, * number of points, and total distance. */ static getRouteSegmentsBy(db, stateId) { const query = `SELECT id, route_num as routeNum, type, segment_num AS segNum, direction AS dir, len, TRUNCATE(len_m, 3) as len_m FROM segments WHERE state_key = ? ORDER BY route_num, id;`; return db.execute(query, [stateId]) .then((result) => result[0]) .catch((err) => { console.error(err); }); } /** * Queries all coordinates of a single route segment. * * The coordinates are truncated here because they cannot be easily truncated upon insertion. * This greatly reduces the size of the JSON response. * * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {number} routeSegmentId - The ID of the route segment. * @return {Promise} Returns a promise that resolves with an array of coodinate objects. */ static getPointsForRouteSegment(db, routeSegmentId) { const query = `SELECT TRUNCATE(lat, 7) as lat, TRUNCATE(lon, 7) as lon FROM points WHERE segment_key = ${routeSegmentId}`; return Models.processPointQueries(db, [query, ''], [{ id: routeSegmentId }]); } /** * Queries for all coordinates of a single route, type, and direction. * * This function supports highways in two directions and accounts for multiple routes that use * the same route number. * * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {number} stateId - The state ID for the route number. * @param {number} type - A routeEnum value of the HPMS route signing type. * @param {string} routeNum - The route number to get the points of. A few route numbers are alphanumeric (14U in California) so they are supported. * @param {string} dir - The direction of the route, either 'N', 'E', 'S', or 'W'. * @return {Promise} Returns a promise that resolves with an Array of objects, each containing * the data and an array of coordinates for each segment. */ static async getPointsForRoute(db, stateId, type, routeNum, dir) { const keyQuery = `SELECT id, direction as dir FROM segments WHERE route_num = ? AND state_key = ? AND type = ?${dir ? ' AND direction = ?' : ''};`; const args = dir ? [routeNum, stateId, type, dir] : [routeNum, stateId, type]; const keys = await db.query(keyQuery, args).then((result) => result[0]); if (keys.length === 0) { return []; } const routeSegments = keys.map( (key) => (dir !== undefined ? { id: key.id } : { dir: key.dir, id: key.id }), ); const combinedQuery = keys.map((key) => `SELECT TRUNCATE(lat, 7) as lat, TRUNCATE(lon, 7) as lon FROM points WHERE segment_key = ${key.id}`); return Models.processPointQueries(db, [...combinedQuery, ''], routeSegments); } /** * Queries for all concurrencies for a given route. * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {number} stateId - The state ID for the route number. * @param {string} routeNum - The route to get the points of that is concurrent with other routes. In some states, this is the route that gets the discontinuity. * @param {string} dir - The direction of the route, either 'N', 'E', 'S', or 'W'. * @return {Promise} Returns a promise that resolves with an Array of objects, each containing * the data and an array of coordinates for each route segment. * The route segments represented by the points could be from different routes. */ static async getPointsForConcurrencies(db, stateId, routeNum, dir) { const routeSegmentQuery = 'SELECT id FROM segments WHERE route_num = ? AND state_key = ? AND direction = ?'; const rte1Segments = await db.execute(routeSegmentQuery, [routeNum, stateId, dir]) .then((result) => result[0].map((routeSeg) => routeSeg.id)); if (rte1Segments.length === 0) { return []; } const concurrencies = await db.query('SELECT * FROM concurrencies WHERE first_seg IN (?)', [rte1Segments]) .then((result) => result[0]); if (concurrencies.length === 0) { return []; } const rte2Segments = await db.query('SELECT id, base FROM segments WHERE id IN (?)', [concurrencies.map((con) => con.rte2_seg)]) .then((result) => result[0]); const routeSegmentBaseMap = {}; rte2Segments.forEach((routeSeg) => { routeSegmentBaseMap[routeSeg.id] = routeSeg.base; }); const routeSegments = concurrencies.map((con) => ({ id: con.rte2_seg })); const combinedQuery = concurrencies.map((con) => `SELECT TRUNCATE(lat, 7) as lat, TRUNCATE(lon, 7) as lon FROM points WHERE segment_key = ${con.rte2_seg} AND id >= ${routeSegmentBaseMap[con.rte2_seg] + con.start_pt} AND id <= ${routeSegmentBaseMap[con.rte2_seg] + con.end_pt}`); return Models.processPointQueries(db, combinedQuery, routeSegments); } /** * Queries all existing users. * @param {object} db - A database client that can perform queries from the mysql2 module. * @return {Promise} A promise that resolves with all existing usernames and their IDs. */ static getUsers(db) { return db.execute('SELECT * FROM users;') .then((result) => result[0]) .catch((err) => { console.error(err); }); } /** * Queries all travel segments by username. * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {string} username - The username that the travel segments belong to. * @return {Promise} Returns a promise that resolves with an Array of objects, each containing * the data and an array of coordinates for each travel segment. */ static getTravelSegmentsBy(db, username) { return db.execute('SELECT * FROM users WHERE user = ?;', [username]) .then((result) => { if (result[0].length < 0) { return []; } return db.execute('SELECT segment_id as routeSegmentId, clinched, start_id as startId, end_id as endId FROM user_segments WHERE user_id = ?;', [result[0][0].id]) .then( (travelSegResult) => { const [travelSegmentData] = travelSegResult; if (travelSegmentData.length < 0) { return []; } return Models.getPointsByUser(db, travelSegmentData.map((travelSeg) => ({ ...travelSeg, clinched: travelSeg.clinched === 1, }))); }, ); }) .catch((err) => { console.error(err); }); } /** * Inserts a user into the database, if the username is not already taken. * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {string} username - The username to check and insert if not already taken. * @return {Promise} Returns a promise that resolves with whether the user creation was * successful. If so, the new user ID is also returned, otherwise the ID of * an existing user is returned. */ static createUser(db, username) { return db.execute('SELECT * FROM users WHERE user = ?;', [username]) .then((result) => { if (result[0].length) { return { success: false, userId: result[0][0].id }; } return db.query('INSERT INTO users (user) VALUES (?);', [username]) .then((insertResult) => ({ success: true, userId: insertResult[0].insertId })); }) .catch((err) => { console.error(err); }); } /** * Inserts travel segment data to the database, and calculates and inserts any travel segments * due to a highway concurrency. * * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {number} userId - The ID of the user the new travel segments are meant for. * @param {object[]} travelSegments - An array of travel segment data from the client. * @return {Promise} A promise that resolves with the result of the insert query. Used to obtain the number of travel segments inserted. */ static async createTravelSegment(db, userId, travelSegments) { const travelSegArgs = travelSegments.map( (travelSeg) => [ userId, travelSeg.routeSegmentId, travelSeg.clinched ? 1 : 0, travelSeg.startId, travelSeg.endId, ], ); const travelSegmentMap = travelSegments.reduce( (accum, travelSeg) => ({ ...accum, [travelSeg.routeSegmentId]: travelSeg }), {}, ); const routeSegmentDataMap = await db.query('SELECT * FROM segments WHERE id IN (?);', [Object.keys(travelSegmentMap)]) .then((result) => result[0]) .then((data) => data.reduce((accum, curr) => ({ ...accum, [curr.id]: curr }), {})); const concurrencyData = await db.query('SELECT * FROM concurrencies WHERE first_seg IN (?);', [Object.keys(travelSegmentMap)]) .then((result) => result[0]); const additionalTravelSegments = []; for (const concurrency of concurrencyData) { const isMainlineWithMainline = concurrency.first_seg < concurrency.last_seg; const routeSegmentId = isMainlineWithMainline ? concurrency.first_seg : concurrency.last_seg; const secondId = isMainlineWithMainline ? concurrency.last_seg : concurrency.first_seg; if ( travelSegmentMap[routeSegmentId].endId === routeSegmentDataMap[routeSegmentId].len && travelSegmentMap[secondId] && travelSegmentMap[secondId].startId === 0 ) { additionalTravelSegments.push( [userId, concurrency.rte2_seg, 0, concurrency.start_pt, concurrency.end_pt], ); } } return db.query('INSERT INTO user_segments (user_id, segment_id, clinched, start_id, end_id) VALUES ?;', [travelSegArgs.concat(additionalTravelSegments)]) .then((result) => result[0]) .catch((err) => { console.error(err); }); } /** * Helper function that executes queries on the points table and combines the result to a * single array. * * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {string[]} queries - Array that contains query strings, one for each route segment. * @param {object[]} routeSegments - Array of all data for each route segment being queried. * @return {Promise} Returns a promise that resolves with an Array of objects, each containing * the data and an array of coordinates for each route segment. */ static async processPointQueries(db, queries, routeSegments) { const pointArrays = await db.query(queries.join('; ')) .then((result) => result[0]) .then((result) => { if (Array.isArray(result[0])) { // Data Packet or array? return result.map((arr) => arr.map((point) => [point.lat, point.lon])); } return [result.map((point) => [point.lat, point.lon])]; // Always treat result as 2D array }) .catch((err) => { console.error(err); }); for (let i = 0; i < pointArrays.length; i += 1) { routeSegments[i].points = pointArrays[i]; } return routeSegments; } /** * Helper function that queries for all travel statistics and segments created by a given user. * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {object[]} travelSegData - Array of row objects from the travel segments table. * @return {Promise} Returns a promise that resolves with an object with an array of statistics * of a given route segment and an array of objects with segment and coordinate data. */ static async getPointsByUser(db, travelSegData) { if (travelSegData.length === 0) { return { travelSegments: [], travelStats: [], }; } const queries = []; for (const obj of travelSegData) { // Get the base point ID for the route segment, then calculate the start and end IDs const { endId, routeSegmentId, startId } = obj; const base = await db.execute('SELECT base FROM segments WHERE id = ?;', [routeSegmentId]).then((result) => result[0][0].base); const pointStartID = base + startId; const pointEndID = base + endId; const queryBase = `SELECT lat, lon FROM points WHERE segment_key = ${routeSegmentId}`; queries.push(`${queryBase} AND id >= ${pointStartID} AND id <= ${pointEndID}`); } const travelSegments = await Models.processPointQueries(db, [...queries, ''], travelSegData); const travelStats = await Models.calcStats(db, travelSegments); return { travelStats, travelSegments }; } /** * Helper function to calculate the travel statistics from travel segments. * @async * @param {object} db - A database client that can perform queries from the mysql2 module. * @param {object[]} travelSegments - Array of objects, each containing the data and an * array of coordinates for each route segment traveled by the user. * @return {Promise} Returns a promise that resolves with an array of objects representing * travel statistics. */ static async calcStats(db, travelSegments) { const stats = []; for (const travelSeg of travelSegments) { const routeSegment = await db.execute('SELECT * FROM segments WHERE id = ?', [travelSeg.routeSegmentId]).then((result) => result[0][0]); const { // eslint-disable-next-line @typescript-eslint/naming-convention len_m, state_key, route_num, segment_num, } = routeSegment; const state = await db.execute('SELECT * FROM states WHERE id = ?', [state_key]).then((result) => result[0][0].initials); let total = len_m; let metersTraveled = Utils.calcSegmentDistance(travelSeg.points); // Truncate to two decimal points metersTraveled = ~~(metersTraveled * 100) / 100; total = ~~(total * 100) / 100; const percentage = ~~((metersTraveled / total) * 10000) / 100; stats.push({ state, route: route_num, routeSegment: segment_num + 1, traveled: metersTraveled, total, percentage, }); } return stats; } }
JavaScript
class PromiseCache { constructor() { /** * Holds pending promises * * @type {Object.<string, Promise>} */ this.pending = {} } /** * Tries to find a pending promise corresponding to the result of keyFunc * - If not found, promiseFunc is executed and the resulting promise is stored while it's pending * - If found, it is immediately returned * * @template T * @param {function(): Promise<T>} promiseFunc - Not executed only if an "equal" promise is already pending. * @param {function(): string} keyFunc - Returns a key to find in cache to find a pending promise. * @returns {Promise<T>} */ async exec(promiseFunc, keyFunc) { const key = keyFunc() const already = this.pending[key] let prom if (already) { prom = already } else { prom = promiseFunc() this.pending[key] = prom } try { const response = await prom return response } finally { this.pending[key] = null } } /** * * @param {function(): string} keyFunc - Returns a key to find in cache to find a pending promise. * @returns {Promise | null} */ get(keyFunc) { const key = keyFunc() const already = this.pending[key] if (already) return already return null } }
JavaScript
class PageTitle extends React.Component { render() { return ( <div className="row text-center justify-content-center mb-5 zero-margin-btm" > <h2 className="cool-font phone-big-title"style={{marginBottom:10}}>{this.props.children}</h2> </div> ); } }
JavaScript
class DPSLTelemetryRequester { /** * Requests telemetry info specified in |category|. Then, parses the * response as response.$resultName.$infoName or throw error. * @param { !string } category * @param { !string } resultName * @param { !string } infoName * @return { !Promise<!dpsl.TelemetryInfoTypes> } * @suppress {checkTypes} * @throws { !Error } if the response is error/null/undefined/empty. * @private */ async _getSelectedTelemetryInfo(category, resultName, infoName) { const response = await getSelectedTelemetryInfo([category]); let result = null; if (response) { result = /** @type {Object} */ (response[resultName]); } if (result) { if ('error' in result) { throw new Error(JSON.stringify(result['error'])); } const info = /** @type {Object} */ (result[infoName]); if (info && info !== {}) { return /** @type {dpsl.TelemetryInfoTypes} */ (info); } } // The response or its inner fields are null/undefined/empty, throw error. throw new Error(JSON.stringify( {type: 'no-result-error', msg: 'Backend returned no result'})); } /** * Requests Backlight info. * @return { !Promise<!dpsl.BacklightInfo> } * @public */ async getBacklightInfo() { const result = await this._getSelectedTelemetryInfo( 'backlight', 'backlightResult', 'backlightInfo'); return /** @type {!dpsl.BacklightInfo} */ (result); } /** * Requests Battery info. * @return { !Promise<!dpsl.BatteryInfo> } * @public */ async getBatteryInfo() { const result = await this._getSelectedTelemetryInfo( 'battery', 'batteryResult', 'batteryInfo'); return /** @type {dpsl.BatteryInfo} */ (result); } /** * Requests Bluetooth info. * @return { !Promise<!dpsl.BluetoothInfo> } * @public */ async getBluetoothInfo() { const result = await this._getSelectedTelemetryInfo( 'bluetooth', 'bluetoothResult', 'bluetoothAdapterInfo'); return /** @type {dpsl.BluetoothInfo} */ (result); } /** * Requests CachedVpd info. * @return { !Promise<!dpsl.VpdInfo> } * @public */ async getCachedVpdInfo() { const result = await this._getSelectedTelemetryInfo( 'cached-vpd-data', 'vpdResult', 'vpdInfo'); return /** @type {dpsl.VpdInfo} */ (result); } /** * Requests CPU info. * @return { !Promise<!dpsl.CpuInfo> } * @public */ async getCpuInfo() { const result = await this._getSelectedTelemetryInfo('cpu', 'cpuResult', 'cpuInfo'); return /** @type {dpsl.CpuInfo} */ (result); } /** * Requests Fan info. * @return { !Promise<!dpsl.FanInfo> } * @public */ async getFanInfo() { const result = await this._getSelectedTelemetryInfo('fan', 'fanResult', 'fanInfo'); return /** @type {dpsl.FanInfo} */ (result); } /** * Requests Memory info. * @return { !Promise<!dpsl.MemoryInfo> } * @public */ async getMemoryInfo() { const result = await this._getSelectedTelemetryInfo( 'memory', 'memoryResult', 'memoryInfo'); return /** @type {dpsl.MemoryInfo} */ (result); } /** * Requests NonRemovableBlockDevice info. * @return { !Promise<!dpsl.BlockDeviceInfo> } * @public */ async getNonRemovableBlockDevicesInfo() { const result = await this._getSelectedTelemetryInfo( 'non-removable-block-devices', 'blockDeviceResult', 'blockDeviceInfo'); return /** @type {dpsl.BlockDeviceInfo} */ (result); } /** * Requests StatefulPartition info. * @return { !Promise<!dpsl.StatefulPartitionInfo> } * @public */ async getStatefulPartitionInfo() { const result = await this._getSelectedTelemetryInfo( 'stateful-partition', 'statefulPartitionResult', 'partitionInfo'); return /** @type {dpsl.StatefulPartitionInfo} */ (result); } /** * Requests Timezone info. * @return { !Promise<!dpsl.TimezoneInfo> } * @public */ async getTimezoneInfo() { const result = await this._getSelectedTelemetryInfo( 'timezone', 'timezoneResult', 'timezoneInfo'); return /** @type {dpsl.TimezoneInfo} */ (result); } }
JavaScript
class TelemetryRequester extends EventTarget { constructor() { super(); messagePipe.registerHandler( dpsl_internal.Message.SYSTEM_EVENTS_SERVICE_EVENTS, (message) => { const event = /** @type {!dpsl_internal.Event} */ (message); this.dispatchEvent(new Event(event.type)); }); } /** * Requests telemetry info. * @param { !Array<!string> } categories * @return { !Object } * @public */ async probeTelemetryInfo(categories) { console.warn( 'chromeos.telemetry.probeTelemetryInfo API is deprecated and will be', 'removed. Use dpsl.telemetry.get*, instead'); return getSelectedTelemetryInfo(categories); } }
JavaScript
class ConfirmRecovery extends Component { constructor(props) { super(props); this.state = { mnemonicPhrase: '', isLocked: true, modal: false, openIncorrectMnemonicsModal: false }; this.toggle = this.toggle.bind(this); this.toggleIncorrectMnemonicsModal = this.toggleIncorrectMnemonicsModal.bind( this ); } /** * isValidSeed() : This function is meant to check that captcha entered by user is valid or not. * If invalid then error message is displayed. */ isValidSeed(mnemonic) { const mnemonicKey = mnemonic.split(' '); if (mnemonicKey.length === 12) { return true; } return false; } /** * handleRecoverWallet() : this function is meant to generate the keys to recover wallet. * @param {*} mnemonic */ handleRecoverWallet(mnemonic) { const newMnemonic = mnemonic.trim(); if (!this.isValidSeed(newMnemonic)) { this.setState({ isLocked: true }); return; } this.setState({ isLocked: false }); const seed = Bip39.mnemonicToSeed(newMnemonic); // creates seed buffer this.walletSetup(seed); } /** * walletSetup() : This function verifies the user and generates a unique masterPrivateKey for that user. * Then navigate user to HomeScreen. */ walletSetup(seed) { const root = Hdkey.fromMasterSeed(seed); const masterPrivateKey = root.privateKey.toString('hex'); const addrNode = root.derive("m/44'/60'/0'/0/0"); // line 1 const pubKey = EthUtil.privateToPublic(addrNode._privateKey); //eslint-disable-line const addr = EthUtil.publicToAddress(pubKey).toString('hex'); const address = EthUtil.toChecksumAddress(addr); const hexPrivateKey = EthUtil.bufferToHex(addrNode._privateKey); //eslint-disable-line this.props.setKeys(masterPrivateKey, address, hexPrivateKey); const { onUnlockAccount, password } = this.props; if (onUnlockAccount) { onUnlockAccount(true, hexPrivateKey, password, address); } } onBack() { if (this.props.toggle) { this.setState({ isLocked: true }); this.props.toggle('1'); } } toggle() { const { isWaiting } = this.props; if (isWaiting) { return null; } this.setState({ modal: !this.state.modal }); } inputHandler = e => { this.setState({ mnemonicPhrase: e.target.value }); if (e.target.value !== '') { this.setState({ isLocked: false }); } else { this.setState({ isLocked: true }); } }; onUnlock() { const { mnemonicPhrase } = this.state; const { isLocked } = this.state; if (isLocked) { this.toggleIncorrectMnemonicsModal(); return; } if (mnemonicPhrase !== '') { this.handleRecoverWallet(mnemonicPhrase); } // onUnlockAccount(true, privateKey, password); } renderCancelAccountCreationModal() { const { openAccountManagement } = this.props; return ( <AccountCreationCancelModal toggle={() => this.toggle()} modal={this.state.modal} openAccountManagement={openAccountManagement} /> ); } /** * This method will toggle the Incorrect Mnemonics modal */ toggleIncorrectMnemonicsModal() { const { openIncorrectMnemonicsModal } = this.state; this.setState({ openIncorrectMnemonicsModal: !openIncorrectMnemonicsModal }); } render() { const { activeTab } = this.props; const { mnemonicPhrase, openIncorrectMnemonicsModal } = this.state; if (activeTab !== '2') { return null; } return ( <section className="bg-dark"> <Container> <Row> <Col> <div className="restore-confirm"> <div className="wallet-bar"> <h2 className="title"> <span>Restore Wallet</span> </h2> </div> <div className="vault-container bg-dark-light"> <FormGroup> <Label for="wallet-seed">Wallet Seed</Label> <Input type="textarea" name="wallet-seed" id="wallet-seed" placeholder="Separate each word with a single space" onChange={e => this.inputHandler(e)} value={mnemonicPhrase} /> </FormGroup> <div className="text-center"> <p className="text-white"> Enter your secret twelve word phrase here to restore your vault. </p> <p className="text-danger"> Separate each word with a single space </p> </div> </div> </div> <div className="mnemonic-btn"> <Button className="create-wallet" onClick={this.onUnlock.bind(this)} > Create Wallet </Button> <Button className="cancel" onClick={() => this.toggle()}> Cancel </Button> </div> </Col> {this.renderCancelAccountCreationModal()} <IncorrectMnemonicsModal openIncorrectMnemonicsModal={openIncorrectMnemonicsModal} toggleIncorrectMnemonicsModal={this.toggleIncorrectMnemonicsModal} /> </Row> </Container> </section> ); } }
JavaScript
class GitCorner extends LitElement { /* REQUIRED FOR TOOLING DO NOT TOUCH */ /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ static get tag() { return "git-corner"; } }
JavaScript
class FormatTicks extends expressionEvaluator_1.ExpressionEvaluator { /** * Initializes a new instance of the [FormatTicks](xref:adaptive-expressions.FormatTicks) class. */ constructor() { super(expressionType_1.ExpressionType.FormatTicks, FormatTicks.evaluator(), returnType_1.ReturnType.String, FormatTicks.validator); } /** * @private */ static evaluator() { return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { let error; let arg = args[0]; let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; if (functionUtils_1.FunctionUtils.isNumber(arg)) { arg = big_integer_1.default(arg); } if (typeof arg === 'string') { arg = big_integer_1.default(arg); } if (!big_integer_1.default.isInstance(arg)) { error = `formatTicks first argument ${arg} is not a number, numeric string or bigInt`; } else { // Convert to ms arg = arg .subtract(functionUtils_internal_1.InternalFunctionUtils.UnixMilliSecondToTicksConstant) .divide(functionUtils_internal_1.InternalFunctionUtils.MillisecondToTickConstant) .toJSNumber(); } let value; if (!error) { ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); if (functionUtils_1.FunctionUtils.isNumber(arg)) { const dateString = new Date(arg).toISOString(); value = dayjs_1.default(dateString).locale(locale).utc().format(format); } } return { value, error }; }); } /** * @param expression * @private */ static validator(expression) { functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.Number); } }
JavaScript
class ControllerPromise { /** * @param {function(function(?TYPE):void, function(*):void):void|!Promise<TYPE>} executorOrPromise * @param {function(TYPE,function(TYPE): ?TYPE): !Promise=} opt_waitForValue */ constructor(executorOrPromise, opt_waitForValue) { this.promise_ = typeof executorOrPromise == 'function' ? new Promise(executorOrPromise) : executorOrPromise; /** * Returns a Promise that resolves when the given expected value fulfills * the given condition. * @param {function(TYPE): ?TYPE} condition * @return {!Promise<?TYPE>} */ this.waitForValue = opt_waitForValue; } /** @override */ catch(onRejected) { return new ControllerPromise( this.promise_.catch(onRejected), this.waitForValue ); } /** @override */ finally(onFinally) { return new ControllerPromise( this.promise_.finally(onFinally), this.waitForValue ); } /** @override */ then(opt_onFulfilled, opt_onRejected) { opt_onFulfilled = opt_onFulfilled || ((x) => x); // Allow this and future `then`s to update the wait value. let wrappedWait = null; if (this.waitForValue) { wrappedWait = wrapWait(this.waitForValue, opt_onFulfilled); } return new ControllerPromise( this.promise_.then(opt_onFulfilled, opt_onRejected), wrappedWait ); } }
JavaScript
class TransactionStatus { /** * @param group * @param status * @param hash * @param deadline * @param height */ constructor( /** * The transaction status being the error name in case of failure and success otherwise. */ status, /** * The transaction status group "failed", "unconfirmed", "confirmed", etc... */ group, /** * The transaction hash. */ hash, /** * The transaction deadline. */ deadline, /** * The height of the block at which it was confirmed or rejected. */ height) { this.status = status; this.group = group; this.hash = hash; this.deadline = deadline; this.height = height; } }
JavaScript
class Accordion extends Component{ constructor(props) { super(props); this.onChangegame = this.onChangegame.bind(this); this.onChangegametype= this.onChangegametype.bind(this); this.onChangetablename = this.onChangetablename.bind(this); this.onChangetablenumber = this.onChangetablenumber.bind(this); this.onChangebet = this.onChangebet.bind(this); this.onChangevaluepoints = this.onChangevaluepoints.bind(this); this.onChangesittingcapacity = this.onChangesittingcapacity.bind(this); this.onChangetablestatus = this.onChangetablestatus.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { game:'', gametype:'', tablename: '', tablenumber: '', bet:'', valueponits:'', sittingcapacity:'', tablestatus:'', trainer:[] } } onChangegame(e) { this.setState({ game: e.target.value }) } onChangegametype(e) { this.setState({ gametype: e.target.value }) } onChangetablename(e) { this.setState({ tablename: e.target.value }) } onChangetablenumber(e) { this.setState({ tablenumber: e.target.value }) } onChangebet(e) { this.setState({ bet: e.target.value }) } onChangevaluepoints(e) { this.setState({ valueponits: e.target.value }) } onChangesittingcapacity(e) { this.setState({ sittingcapacity: e.target.value }) } onChangetablestatus(e) { this.setState({ tablestatus: e.target.value }) } onback(){ window.location='/#/components/alerts' } onSubmit(e) { e.preventDefault(); const customer = { game: this.state.game, gametype: this.state.gametype, tablename: this.state.tablename, tablenumber:this.state.tablenumber, bet:this.state.bet, valueponits:this.state.valueponits, sittingcapacity:this.state.sittingcapacity, tablestatus: this.state.tablestatus, } axios.post('https://arummynodejs.herokuapp.com/pointrummy/add', customer) .then(function(response){ if(response.data ==='Pointrummy added!'){ alert("Point Pokker Added") window.location.reload(true) } }) } render(){ return( <div style={{marginTop:"50px"}}> <Card border="light" className="bg-white shadow-sm mb-4"> <Card.Body> <h5 className="mb-4">Table Details</h5> <Form onSubmit={this.onSubmit}> <Row> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> Game:</Form.Label> <select class="form-control" id="calculator" name="game" onChange={this.onChangegame} value={this.state.game}> <option value="Crash Game">Crash Game</option> <option value="Free Game">Free Game</option> </select> </Form.Group> </Col> </Row> <Row className="align-items-center"> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> Game Type:</Form.Label> <select class="form-control" id="calculator" name="gametype" onChange={this.onChangegametype} value={this.state.gametype}> <option value="Point Rummy">Point Rummy</option> <option value="Pool Rummy">Pool Rummy</option> <option value="Deal Rummy">Deal Rummy</option> <option value="Papplu Rummy">Papplu Rammy</option> </select> </Form.Group> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="emal"> <Form.Label>Table Name:</Form.Label> <Form.Control required type="text" placeholder="" value={this.state.tablename} onChange={this.onChangetablename} name="password" /> </Form.Group> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="emal"> <Form.Label>Table no:</Form.Label> <Form.Control required type="number" placeholder="" value={this.state.tablenumber} onChange={this.onChangetablenumber} name="password" /> </Form.Group> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="phone"> <Form.Label>Beat/Entry:</Form.Label> <Form.Control required type="number" placeholder="" value={this.state.bet} onChange={this.onChangebet} name="password" /> </Form.Group> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="percenta"> <Form.Label>Value ponits(Rs):</Form.Label> <Form.Control required type="number" placeholder="" value={this.state.valueponits} onChange={this.onChangevaluepoints} max="100" name="role" /> </Form.Group> </Col> </Row> <Row className="align-items-center"> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> Sitting Capacity:</Form.Label> <select class="form-control" id="calculator" name="sittingcapacity" onChange={this.onChangesittingcapacity} value={this.state.sittingcapacity}> <option value="2 Seat">2 Seat</option> <option value="6 Seat">6 Seat</option> </select> </Form.Group> </Col> </Row> <Row className="align-items-center"> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> Table Status:</Form.Label> <select class="form-control" id="calculator" name="tablestatus" onChange={this.onChangetablestatus} value={this.state.tablestatus}> <option value="Live">Live</option> <option value="Stop">Stop</option> </select> </Form.Group> </Col> </Row> <Row> <Col md={3} className="mb-3"> <div className="mt-3"> <Button variant="primary" type="submit">Submit </Button> </div> </Col> </Row> </Form> </Card.Body> </Card> </div> ) } }
JavaScript
class SingleImageOpenlayers extends RasterLayerOpenlayers { static get className() { return 'vcs.vcm.layer.openlayers.SingleImageOpenlayers'; } /** * @param {import("@vcmap/core").Openlayers} map * @param {SingleImageImplementationOptions} options */ constructor(map, options) { super(map, options); /** @type {string} */ this.credit = options.credit; } /** * returns the ol Layer * @returns {import("ol/layer/Layer").default} */ getOLLayer() { const options = { attributions: this.credit, url: this.url, projection: 'EPSG:4326', imageExtent: this.extent.getCoordinatesInProjection(wgs84Projection), }; if (!isSameOrigin(this.url)) { options.crossOrigin = 'anonymous'; } return new ImageLayer({ source: new ImageStatic(options), opacity: this.opacity, }); } }
JavaScript
class Pokemon extends React.Component { constructor(props) { super(props); } // the render method that returns a <div> with the image of the pokemon, the name, and the pokemon id. render(){ return( <div> <img src={this.props.pData.sprites.front_default} /> <p>Name: {this.props.pData.name}</p> <p>Pokemon ID: {this.props.pData.id}</p> </div> ); } }
JavaScript
class Route { /** * Constructor for Route class. * * @param {workbox-routing~matchCallback} match * A callback function that determines whether the route matches a given * `fetch` event by returning a non-falsy value. * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resolving to a Response. * @param {string} [method='GET'] The HTTP method to match the Route * against. */ constructor(match, handler, method = defaultMethod) { { assert_js.assert.isType(match, 'function', { moduleName: 'workbox-routing', className: 'Route', funcName: 'constructor', paramName: 'match' }); if (method) { assert_js.assert.isOneOf(method, validMethods, { paramName: 'method' }); } } // These values are referenced directly by Router so cannot be // altered by minificaton. this.handler = normalizeHandler(handler); this.match = match; this.method = method; } /** * * @param {workbox-routing-handlerCallback} handler A callback * function that returns a Promise resolving to a Response */ setCatchHandler(handler) { this.catchHandler = normalizeHandler(handler); } }
JavaScript
class NavigationRoute extends Route { /** * If both `denylist` and `allowlist` are provided, the `denylist` will * take precedence and the request will not match this route. * * The regular expressions in `allowlist` and `denylist` * are matched against the concatenated * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} * portions of the requested URL. * * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. * @param {Object} options * @param {Array<RegExp>} [options.denylist] If any of these patterns match, * the route will not handle the request (even if a allowlist RegExp matches). * @param {Array<RegExp>} [options.allowlist=[/./]] If any of these patterns * match the URL's pathname and search parameter, the route will handle the * request (assuming the denylist doesn't match). */ constructor(handler, { allowlist = [/./], denylist = [] } = {}) { { assert_js.assert.isArrayOfClass(allowlist, RegExp, { moduleName: 'workbox-routing', className: 'NavigationRoute', funcName: 'constructor', paramName: 'options.allowlist' }); assert_js.assert.isArrayOfClass(denylist, RegExp, { moduleName: 'workbox-routing', className: 'NavigationRoute', funcName: 'constructor', paramName: 'options.denylist' }); } super(options => this._match(options), handler); this._allowlist = allowlist; this._denylist = denylist; } /** * Routes match handler. * * @param {Object} options * @param {URL} options.url * @param {Request} options.request * @return {boolean} * * @private */ _match({ url, request }) { if (request && request.mode !== 'navigate') { return false; } const pathnameAndSearch = url.pathname + url.search; for (const regExp of this._denylist) { if (regExp.test(pathnameAndSearch)) { { logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`); } return false; } } if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) { { logger_js.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`); } return true; } { logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`); } return false; } }
JavaScript
class RegExpRoute extends Route { /** * If the regular expression contains * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, * the captured values will be passed to the * {@link workbox-routing~handlerCallback} `params` * argument. * * @param {RegExp} regExp The regular expression to match against URLs. * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. * @param {string} [method='GET'] The HTTP method to match the Route * against. */ constructor(regExp, handler, method) { { assert_js.assert.isInstance(regExp, RegExp, { moduleName: 'workbox-routing', className: 'RegExpRoute', funcName: 'constructor', paramName: 'pattern' }); } const match = ({ url }) => { const result = regExp.exec(url.href); // Return immediately if there's no match. if (!result) { return; } // Require that the match start at the first character in the URL string // if it's a cross-origin request. // See https://github.com/GoogleChrome/workbox/issues/281 for the context // behind this behavior. if (url.origin !== location.origin && result.index !== 0) { { logger_js.logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`); } return; } // If the route matches, but there aren't any capture groups defined, then // this will return [], which is truthy and therefore sufficient to // indicate a match. // If there are capture groups, then it will return their values. return result.slice(1); }; super(match, handler, method); } }
JavaScript
class Router { /** * Initializes a new Router. */ constructor() { this._routes = new Map(); this._defaultHandlerMap = new Map(); } /** * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP * method name ('GET', etc.) to an array of all the corresponding `Route` * instances that are registered. */ get routes() { return this._routes; } /** * Adds a fetch event listener to respond to events when a route matches * the event's request. */ addFetchListener() { // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 self.addEventListener('fetch', event => { const { request } = event; const responsePromise = this.handleRequest({ request, event }); if (responsePromise) { event.respondWith(responsePromise); } }); } /** * Adds a message event listener for URLs to cache from the window. * This is useful to cache resources loaded on the page prior to when the * service worker started controlling it. * * The format of the message data sent from the window should be as follows. * Where the `urlsToCache` array may consist of URL strings or an array of * URL string + `requestInit` object (the same as you'd pass to `fetch()`). * * ``` * { * type: 'CACHE_URLS', * payload: { * urlsToCache: [ * './script1.js', * './script2.js', * ['./script3.js', {mode: 'no-cors'}], * ], * }, * } * ``` */ addCacheListener() { // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 self.addEventListener('message', event => { // event.data is type 'any' // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (event.data && event.data.type === 'CACHE_URLS') { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const { payload } = event.data; { logger_js.logger.debug(`Caching URLs from the window`, payload.urlsToCache); } const requestPromises = Promise.all(payload.urlsToCache.map(entry => { if (typeof entry === 'string') { entry = [entry]; } const request = new Request(...entry); return this.handleRequest({ request, event }); // TODO(philipwalton): TypeScript errors without this typecast for // some reason (probably a bug). The real type here should work but // doesn't: `Array<Promise<Response> | undefined>`. })); // TypeScript event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success. if (event.ports && event.ports[0]) { void requestPromises.then(() => event.ports[0].postMessage(true)); } } }); } /** * Apply the routing rules to a FetchEvent object to get a Response from an * appropriate Route's handler. * * @param {Object} options * @param {Request} options.request The request to handle. * @param {ExtendableEvent} options.event The event that triggered the * request. * @return {Promise<Response>|undefined} A promise is returned if a * registered route can handle the request. If there is no matching * route and there's no `defaultHandler`, `undefined` is returned. */ handleRequest({ request, event }) { { assert_js.assert.isInstance(request, Request, { moduleName: 'workbox-routing', className: 'Router', funcName: 'handleRequest', paramName: 'options.request' }); } const url = new URL(request.url, location.href); if (!url.protocol.startsWith('http')) { { logger_js.logger.debug(`Workbox Router only supports URLs that start with 'http'.`); } return; } const sameOrigin = url.origin === location.origin; const { params, route } = this.findMatchingRoute({ event, request, sameOrigin, url }); let handler = route && route.handler; const debugMessages = []; { if (handler) { debugMessages.push([`Found a route to handle this request:`, route]); if (params) { debugMessages.push([`Passing the following params to the route's handler:`, params]); } } } // If we don't have a handler because there was no matching route, then // fall back to defaultHandler if that's defined. const method = request.method; if (!handler && this._defaultHandlerMap.has(method)) { { debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`); } handler = this._defaultHandlerMap.get(method); } if (!handler) { { // No handler so Workbox will do nothing. If logs is set of debug // i.e. verbose, we should print out this information. logger_js.logger.debug(`No route found for: ${getFriendlyURL_js.getFriendlyURL(url)}`); } return; } { // We have a handler, meaning Workbox is going to handle the route. // print the routing details to the console. logger_js.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_js.getFriendlyURL(url)}`); debugMessages.forEach(msg => { if (Array.isArray(msg)) { logger_js.logger.log(...msg); } else { logger_js.logger.log(msg); } }); logger_js.logger.groupEnd(); } // Wrap in try and catch in case the handle method throws a synchronous // error. It should still callback to the catch handler. let responsePromise; try { responsePromise = handler.handle({ url, request, event, params }); } catch (err) { responsePromise = Promise.reject(err); } // Get route's catch handler, if it exists const catchHandler = route && route.catchHandler; if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { responsePromise = responsePromise.catch(async err => { // If there's a route catch handler, process that first if (catchHandler) { { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to route's Catch Handler.`); logger_js.logger.error(`Error thrown by:`, route); logger_js.logger.error(err); logger_js.logger.groupEnd(); } try { return await catchHandler.handle({ url, request, event, params }); } catch (catchErr) { if (catchErr instanceof Error) { err = catchErr; } } } if (this._catchHandler) { { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to global Catch Handler.`); logger_js.logger.error(`Error thrown by:`, route); logger_js.logger.error(err); logger_js.logger.groupEnd(); } return this._catchHandler.handle({ url, request, event }); } throw err; }); } return responsePromise; } /** * Checks a request and URL (and optionally an event) against the list of * registered routes, and if there's a match, returns the corresponding * route along with any params generated by the match. * * @param {Object} options * @param {URL} options.url * @param {boolean} options.sameOrigin The result of comparing `url.origin` * against the current origin. * @param {Request} options.request The request to match. * @param {Event} options.event The corresponding event. * @return {Object} An object with `route` and `params` properties. * They are populated if a matching route was found or `undefined` * otherwise. */ findMatchingRoute({ url, sameOrigin, request, event }) { const routes = this._routes.get(request.method) || []; for (const route of routes) { let params; // route.match returns type any, not possible to change right now. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const matchResult = route.match({ url, sameOrigin, request, event }); if (matchResult) { { // Warn developers that using an async matchCallback is almost always // not the right thing to do. if (matchResult instanceof Promise) { logger_js.logger.warn(`While routing ${getFriendlyURL_js.getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route); } } // See https://github.com/GoogleChrome/workbox/issues/2079 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment params = matchResult; if (Array.isArray(params) && params.length === 0) { // Instead of passing an empty array in as params, use undefined. params = undefined; } else if (matchResult.constructor === Object && // eslint-disable-line Object.keys(matchResult).length === 0) { // Instead of passing an empty object in as params, use undefined. params = undefined; } else if (typeof matchResult === 'boolean') { // For the boolean value true (rather than just something truth-y), // don't set params. // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 params = undefined; } // Return early if have a match. return { route, params }; } } // If no match was found above, return and empty object. return {}; } /** * Define a default `handler` that's called when no routes explicitly * match the incoming request. * * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. * * Without a default handler, unmatched requests will go against the * network as if there were no service worker present. * * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. * @param {string} [method='GET'] The HTTP method to associate with this * default handler. Each method has its own default. */ setDefaultHandler(handler, method = defaultMethod) { this._defaultHandlerMap.set(method, normalizeHandler(handler)); } /** * If a Route throws an error while handling a request, this `handler` * will be called and given a chance to provide a response. * * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. */ setCatchHandler(handler) { this._catchHandler = normalizeHandler(handler); } /** * Registers a route with the router. * * @param {workbox-routing.Route} route The route to register. */ registerRoute(route) { { assert_js.assert.isType(route, 'object', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route' }); assert_js.assert.hasMethod(route, 'match', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route' }); assert_js.assert.isType(route.handler, 'object', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route' }); assert_js.assert.hasMethod(route.handler, 'handle', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route.handler' }); assert_js.assert.isType(route.method, 'string', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route.method' }); } if (!this._routes.has(route.method)) { this._routes.set(route.method, []); } // Give precedence to all of the earlier routes by adding this additional // route to the end of the array. this._routes.get(route.method).push(route); } /** * Unregisters a route with the router. * * @param {workbox-routing.Route} route The route to unregister. */ unregisterRoute(route) { if (!this._routes.has(route.method)) { throw new WorkboxError_js.WorkboxError('unregister-route-but-not-found-with-method', { method: route.method }); } const routeIndex = this._routes.get(route.method).indexOf(route); if (routeIndex > -1) { this._routes.get(route.method).splice(routeIndex, 1); } else { throw new WorkboxError_js.WorkboxError('unregister-route-route-not-registered'); } } }
JavaScript
class AzureIaaSVMJobExtendedInfo { /** * Create a AzureIaaSVMJobExtendedInfo. * @member {array} [tasksList] List of tasks associated with this job. * @member {object} [propertyBag] Job properties. * @member {number} [progressPercentage] Indicates progress of the job. Null * if it has not started or completed. * @member {string} [dynamicErrorMessage] Non localized error message on job * execution. */ constructor() { } /** * Defines the metadata of AzureIaaSVMJobExtendedInfo * * @returns {object} metadata of AzureIaaSVMJobExtendedInfo * */ mapper() { return { required: false, serializedName: 'AzureIaaSVMJobExtendedInfo', type: { name: 'Composite', className: 'AzureIaaSVMJobExtendedInfo', modelProperties: { tasksList: { required: false, serializedName: 'tasksList', type: { name: 'Sequence', element: { required: false, serializedName: 'AzureIaaSVMJobTaskDetailsElementType', type: { name: 'Composite', className: 'AzureIaaSVMJobTaskDetails' } } } }, propertyBag: { required: false, serializedName: 'propertyBag', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, progressPercentage: { required: false, serializedName: 'progressPercentage', type: { name: 'Number' } }, dynamicErrorMessage: { required: false, serializedName: 'dynamicErrorMessage', type: { name: 'String' } } } } }; } }
JavaScript
class LocApiProvider extends BaseProvider { /** * @private */ _setup() { this.has.schemes = true this.has.top = false this.has.data = true this.has.concepts = true this.has.narrower = true this.has.ancestors = false this.has.suggest = true this.has.search = true } /** * Used by `registryForScheme` (see src/lib/CocodaSDK.js) to determine a provider config for a concept schceme. * * @param {Object} options * @param {Object} options.scheme scheme for which the config is requested * @returns {Object} provider configuration */ static _registryConfigForBartocApiConfig({ scheme } = {}) { // Check if scheme is supported if (!scheme || !supportedSchemes.find(s => jskos.compare(s, scheme))) { return null } // We don't need any API endpoints because they are hardcoded. return { schemes: [scheme], } } /** * Returns all concept schemes. * * @returns {Object[]} array of JSKOS concept scheme objects */ async getSchemes() { const schemes = [] for (let scheme of await Promise.all( supportedSchemes.filter(s => !this.schemes || !this.schemes.length || this.schemes.find(s2 => jskos.compare(s, s2))).map(s => axios({ method: "get", url: `${s.uri.replace("http:", "https:")}.json`, }).then(({ status, data }) => { if (status === 200) { let scheme = data.find(d => s.uri === d["@id"]) if (scheme) { scheme = jskos.merge(madsToJskosScheme(scheme), s) scheme.topConcepts = (scheme.topConcepts || []).filter(c => c) return scheme } } return null })))) { if (scheme) { schemes.push(scheme) } } return schemes } /** * TODO: Possibly reenable for LCC * Returns top concepts for a concept scheme. * * @param {Object} config * @param {Object} config.scheme concept scheme object * @returns {Object[]} array of JSKOS concept objects */ // async getTop({ scheme }) { // if (scheme.topConcepts && !scheme.topConcepts.includes(null)) { // return scheme.topConcepts // } // const schemes = await this.getSchemes() // scheme = schemes.find(s => jskos.compare(s, scheme)) // return scheme && scheme.topConcepts || [] // } /** * Returns details for a list of concepts. * * @param {Object} config * @param {Object[]} config.concepts list of concept objects to load * @returns {Object[]} array of JSKOS concept objects */ async getConcepts({ concepts }) { if (!Array.isArray(concepts)) { concepts = [concepts] } const resultConcepts = [] for (let concept of await Promise.all(concepts.map(c => axios({ method: "get", url: `${c.uri.replace("http:", "https:")}.json`, }).then(({ status, data }) => { if (status === 200) { let concept = data.find(d => c.uri === d["@id"]) if (concept) { return madsToJskosConcept(concept, { scheme: c.inScheme && c.inScheme[0] }) } return null } })))) { if (concept) { resultConcepts.push(concept) } } return resultConcepts } /** * Returns suggestion result in OpenSearch Suggest Format. * * @param {Object} config * @param {string} config.search search string * @param {Object} config.scheme concept scheme to search in * @param {number} [config.limit=100] maximum number of search results (default might be overridden by registry) * @param {number} [config.offset=0] offset * @returns {Array} result in OpenSearch Suggest Format */ async suggest(config) { const results = await this.search(config) return [ config.search, results.map(c => { return jskos.prefLabel(c, { fallbackToUri: true }) }), [], results.map(c => c.uri), ] } /** * Returns search results in JSKOS Format. * * @param {Object} config * @param {string} config.search search string * @param {Object} config.scheme concept scheme to search in * @param {number} [config.limit=100] maximum number of search results (default might be overridden by registry) * @param {number} [config.offset=0] offset * @returns {Array} result in JSKOS Format */ async search({ search, scheme, limit, offset }) { const schemeUri = jskos.getAllUris(scheme).find(uri => uri.startsWith(locUriPrefix)) if (!schemeUri || !supportedSchemes.find(s => jskos.compare(s, { uri: schemeUri }))) { throw new errors.InvalidOrMissingParameterError({ parameter: "scheme", message: "provided scheme is not supported (yet)" }) } if (!search) { throw new errors.InvalidOrMissingParameterError({ parameter: "search", message: "parameter is empty or missing" }) } limit = limit || this._jskos.suggestResultLimit || 100 offset = offset || 0 const { data } = await axios({ method: "get", url: `${schemeUri}/suggest2`.replace("http:", "https:"), params: { q: search, count: limit || 100, offset, searchtype: "keyword", }, }) return (data.hits || []).map(d => ({ uri: d.uri, notation: [d.token], prefLabel: { en: d.aLabel }, inScheme: [scheme], })).filter(schemeNamespaceFilter(scheme)) } }
JavaScript
class AtomicTransactionComposer { constructor() { this.status = AtomicTransactionComposerStatus.BUILDING; this.transactions = []; this.methodCalls = new Map(); this.signedTxns = []; this.txIDs = []; } /** * Get the status of this composer's transaction group. */ getStatus() { return this.status; } /** * Get the number of transactions currently in this atomic group. */ count() { return this.transactions.length; } /** * Create a new composer with the same underlying transactions. The new composer's status will be * BUILDING, so additional transactions may be added to it. */ clone() { const theClone = new AtomicTransactionComposer(); theClone.transactions = this.transactions.map(({ txn, signer }) => ({ // not quite a deep copy, but good enough for our purposes (modifying txn.group in buildGroup) txn: transaction_1.Transaction.from_obj_for_encoding({ ...txn.get_obj_for_encoding(), // erase the group ID grp: undefined, }), signer, })); theClone.methodCalls = new Map(this.methodCalls); return theClone; } /** * Add a transaction to this atomic group. * * An error will be thrown if the transaction has a nonzero group ID, the composer's status is * not BUILDING, or if adding this transaction causes the current group to exceed MAX_GROUP_SIZE. */ addTransaction(txnAndSigner) { if (this.status !== AtomicTransactionComposerStatus.BUILDING) { throw new Error('Cannot add transactions when composer status is not BUILDING'); } if (this.transactions.length === AtomicTransactionComposer.MAX_GROUP_SIZE) { throw new Error(`Adding an additional transaction exceeds the maximum atomic group size of ${AtomicTransactionComposer.MAX_GROUP_SIZE}`); } if (txnAndSigner.txn.group && txnAndSigner.txn.group.some((v) => v !== 0)) { throw new Error('Cannot add a transaction with nonzero group ID'); } this.transactions.push(txnAndSigner); } /** * Add a smart contract method call to this atomic group. * * An error will be thrown if the composer's status is not BUILDING, if adding this transaction * causes the current group to exceed MAX_GROUP_SIZE, or if the provided arguments are invalid * for the given method. */ addMethodCall({ appID, method, methodArgs, sender, suggestedParams, onComplete, approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages, note, lease, rekeyTo, signer, }) { if (this.status !== AtomicTransactionComposerStatus.BUILDING) { throw new Error('Cannot add transactions when composer status is not BUILDING'); } if (this.transactions.length + method.txnCount() > AtomicTransactionComposer.MAX_GROUP_SIZE) { throw new Error(`Adding additional transactions exceeds the maximum atomic group size of ${AtomicTransactionComposer.MAX_GROUP_SIZE}`); } if (appID === 0) { if (approvalProgram == null || clearProgram == null || numGlobalInts == null || numGlobalByteSlices == null || numLocalInts == null || numLocalByteSlices == null) { throw new Error('One of the following required parameters for application creation is missing: approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices'); } } else if (onComplete === base_1.OnApplicationComplete.UpdateApplicationOC) { if (approvalProgram == null || clearProgram == null) { throw new Error('One of the following required parameters for OnApplicationComplete.UpdateApplicationOC is missing: approvalProgram, clearProgram'); } if (numGlobalInts != null || numGlobalByteSlices != null || numLocalInts != null || numLocalByteSlices != null || extraPages != null) { throw new Error('One of the following application creation parameters were set on a non-creation call: numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages'); } } else if (approvalProgram != null || clearProgram != null || numGlobalInts != null || numGlobalByteSlices != null || numLocalInts != null || numLocalByteSlices != null || extraPages != null) { throw new Error('One of the following application creation parameters were set on a non-creation call: approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages'); } if (methodArgs == null) { // eslint-disable-next-line no-param-reassign methodArgs = []; } if (methodArgs.length !== method.args.length) { throw new Error(`Incorrect number of method arguments. Expected ${method.args.length}, got ${methodArgs.length}`); } let basicArgTypes = []; let basicArgValues = []; const txnArgs = []; const refArgTypes = []; const refArgValues = []; const refArgIndexToBasicArgIndex = new Map(); for (let i = 0; i < methodArgs.length; i++) { let argType = method.args[i].type; const argValue = methodArgs[i]; if (abi_1.abiTypeIsTransaction(argType)) { if (!signer_1.isTransactionWithSigner(argValue) || !abi_1.abiCheckTransactionType(argType, argValue.txn)) { throw new Error(`Expected ${argType} transaction for argument at index ${i}`); } if (argValue.txn.group && argValue.txn.group.some((v) => v !== 0)) { throw new Error('Cannot add a transaction with nonzero group ID'); } txnArgs.push(argValue); continue; } if (signer_1.isTransactionWithSigner(argValue)) { throw new Error(`Expected non-transaction value for argument at index ${i}`); } if (abi_1.abiTypeIsReference(argType)) { refArgIndexToBasicArgIndex.set(refArgTypes.length, basicArgTypes.length); refArgTypes.push(argType); refArgValues.push(argValue); // treat the reference as a uint8 for encoding purposes argType = new abi_1.ABIUintType(8); } if (typeof argType === 'string') { throw new Error(`Unknown ABI type: ${argType}`); } basicArgTypes.push(argType); basicArgValues.push(argValue); } const resolvedRefIndexes = []; const foreignAccounts = []; const foreignApps = []; const foreignAssets = []; for (let i = 0; i < refArgTypes.length; i++) { const refType = refArgTypes[i]; const refValue = refArgValues[i]; let resolved = 0; switch (refType) { case abi_1.ABIReferenceType.account: { const addressType = new abi_1.ABIAddressType(); const address = addressType.decode(addressType.encode(refValue)); resolved = populateForeignArray(address, foreignAccounts, sender); break; } case abi_1.ABIReferenceType.application: { const uint64Type = new abi_1.ABIUintType(64); const refAppID = uint64Type.decode(uint64Type.encode(refValue)); if (refAppID > Number.MAX_SAFE_INTEGER) { throw new Error(`Expected safe integer for application value, got ${refAppID}`); } resolved = populateForeignArray(Number(refAppID), foreignApps, appID); break; } case abi_1.ABIReferenceType.asset: { const uint64Type = new abi_1.ABIUintType(64); const refAssetID = uint64Type.decode(uint64Type.encode(refValue)); if (refAssetID > Number.MAX_SAFE_INTEGER) { throw new Error(`Expected safe integer for asset value, got ${refAssetID}`); } resolved = populateForeignArray(Number(refAssetID), foreignAssets); break; } default: throw new Error(`Unknown reference type: ${refType}`); } resolvedRefIndexes.push(resolved); } for (let i = 0; i < resolvedRefIndexes.length; i++) { const basicArgIndex = refArgIndexToBasicArgIndex.get(i); basicArgValues[basicArgIndex] = resolvedRefIndexes[i]; } if (basicArgTypes.length > MAX_APP_ARGS - 1) { const lastArgTupleTypes = basicArgTypes.slice(MAX_APP_ARGS - 2); const lastArgTupleValues = basicArgValues.slice(MAX_APP_ARGS - 2); basicArgTypes = basicArgTypes.slice(0, MAX_APP_ARGS - 2); basicArgValues = basicArgValues.slice(0, MAX_APP_ARGS - 2); basicArgTypes.push(new abi_1.ABITupleType(lastArgTupleTypes)); basicArgValues.push(lastArgTupleValues); } const appArgsEncoded = [method.getSelector()]; for (let i = 0; i < basicArgTypes.length; i++) { appArgsEncoded.push(basicArgTypes[i].encode(basicArgValues[i])); } const appCall = { txn: makeTxn_1.makeApplicationCallTxnFromObject({ from: sender, appIndex: appID, appArgs: appArgsEncoded, accounts: foreignAccounts, foreignApps, foreignAssets, onComplete: onComplete == null ? base_1.OnApplicationComplete.NoOpOC : onComplete, approvalProgram, clearProgram, numGlobalInts, numGlobalByteSlices, numLocalInts, numLocalByteSlices, extraPages, lease, note, rekeyTo, suggestedParams, }), signer, }; this.transactions.push(...txnArgs, appCall); this.methodCalls.set(this.transactions.length - 1, method); } /** * Finalize the transaction group and returned the finalized transactions. * * The composer's status will be at least BUILT after executing this method. */ buildGroup() { if (this.status === AtomicTransactionComposerStatus.BUILDING) { if (this.transactions.length === 0) { throw new Error('Cannot build a group with 0 transactions'); } if (this.transactions.length > 1) { group_1.assignGroupID(this.transactions.map((txnWithSigner) => txnWithSigner.txn)); } this.status = AtomicTransactionComposerStatus.BUILT; } return this.transactions; } /** * Obtain signatures for each transaction in this group. If signatures have already been obtained, * this method will return cached versions of the signatures. * * The composer's status will be at least SIGNED after executing this method. * * An error will be thrown if signing any of the transactions fails. * * @returns A promise that resolves to an array of signed transactions. */ async gatherSignatures() { if (this.status >= AtomicTransactionComposerStatus.SIGNED) { return this.signedTxns; } // retrieve built transactions and verify status is BUILT const txnsWithSigners = this.buildGroup(); const txnGroup = txnsWithSigners.map((txnWithSigner) => txnWithSigner.txn); const indexesPerSigner = new Map(); for (let i = 0; i < txnsWithSigners.length; i++) { const { signer } = txnsWithSigners[i]; if (!indexesPerSigner.has(signer)) { indexesPerSigner.set(signer, []); } indexesPerSigner.get(signer).push(i); } const orderedSigners = Array.from(indexesPerSigner); const batchedSigs = await Promise.all(orderedSigners.map(([signer, indexes]) => signer(txnGroup, indexes))); const signedTxns = txnsWithSigners.map(() => null); for (let signerIndex = 0; signerIndex < orderedSigners.length; signerIndex++) { const indexes = orderedSigners[signerIndex][1]; const sigs = batchedSigs[signerIndex]; for (let i = 0; i < indexes.length; i++) { signedTxns[indexes[i]] = sigs[i]; } } if (!signedTxns.every((sig) => sig != null)) { throw new Error(`Missing signatures. Got ${signedTxns}`); } const txIDs = signedTxns.map((stxn, index) => { try { return transaction_1.decodeSignedTransaction(stxn).txn.txID(); } catch (err) { throw new Error(`Cannot decode signed transaction at index ${index}. ${err}`); } }); this.signedTxns = signedTxns; this.txIDs = txIDs; this.status = AtomicTransactionComposerStatus.SIGNED; return signedTxns; } /** * Send the transaction group to the network, but don't wait for it to be committed to a block. An * error will be thrown if submission fails. * * The composer's status must be SUBMITTED or lower before calling this method. If submission is * successful, this composer's status will update to SUBMITTED. * * Note: a group can only be submitted again if it fails. * * @param client - An Algodv2 client * * @returns A promise that, upon success, resolves to a list of TxIDs of the submitted transactions. */ async submit(client) { if (this.status > AtomicTransactionComposerStatus.SUBMITTED) { throw new Error('Transaction group cannot be resubmitted'); } const stxns = await this.gatherSignatures(); await client.sendRawTransaction(stxns).do(); this.status = AtomicTransactionComposerStatus.SUBMITTED; return this.txIDs; } /** * Send the transaction group to the network and wait until it's committed to a block. An error * will be thrown if submission or execution fails. * * The composer's status must be SUBMITTED or lower before calling this method, since execution is * only allowed once. If submission is successful, this composer's status will update to SUBMITTED. * If the execution is also successful, this composer's status will update to COMMITTED. * * Note: a group can only be submitted again if it fails. * * @param client - An Algodv2 client * @param waitRounds - The maximum number of rounds to wait for transaction confirmation * * @returns A promise that, upon success, resolves to an object containing the confirmed round for * this transaction, the txIDs of the submitted transactions, and an array of results containing * one element for each method call transaction in this group. */ async execute(client, waitRounds) { if (this.status === AtomicTransactionComposerStatus.COMMITTED) { throw new Error('Transaction group has already been executed successfully'); } const txIDs = await this.submit(client); this.status = AtomicTransactionComposerStatus.SUBMITTED; const firstMethodCallIndex = this.transactions.findIndex((_, index) => this.methodCalls.has(index)); const indexToWaitFor = firstMethodCallIndex === -1 ? 0 : firstMethodCallIndex; const confirmedTxnInfo = await wait_1.waitForConfirmation(client, txIDs[indexToWaitFor], waitRounds); this.status = AtomicTransactionComposerStatus.COMMITTED; const confirmedRound = confirmedTxnInfo['confirmed-round']; const methodResults = []; for (const [txnIndex, method] of this.methodCalls) { const txID = txIDs[txnIndex]; const methodResult = { txID, rawReturnValue: new Uint8Array(), }; try { const pendingInfo = txnIndex === firstMethodCallIndex ? confirmedTxnInfo : // eslint-disable-next-line no-await-in-loop await client.pendingTransactionInformation(txID).do(); methodResult.txInfo = pendingInfo; if (method.returns.type !== 'void') { const logs = pendingInfo.logs || []; if (logs.length === 0) { throw new Error('App call transaction did not log a return value'); } const lastLog = Buffer.from(logs[logs.length - 1], 'base64'); if (lastLog.byteLength < 4 || !lastLog.slice(0, 4).equals(RETURN_PREFIX)) { throw new Error('App call transaction did not log a return value'); } methodResult.rawReturnValue = new Uint8Array(lastLog.slice(4)); methodResult.returnValue = method.returns.type.decode(methodResult.rawReturnValue); } } catch (err) { methodResult.decodeError = err; } methodResults.push(methodResult); } return { confirmedRound, txIDs, methodResults, }; } }
JavaScript
class ToggleSwitch extends Component { state = { checked: this.props.defaultChecked }; onChange = e => { this.setState({ checked: e.target.checked }); if (typeof this.props.onChange === "function") this.props.onChange(); if(e.target.checked) { console.log("Dark Mode"); this.props.modeChange('bodyDark'); }else { console.log("Normal Mode"); this.props.modeChange('bodyLight'); } }; render() { return ( <div className={"toggle-switch" + (this.props.Small ? " small-switch" : "")} > <input type="checkbox" name={this.props.Name} className="toggle-switch-checkbox" id={this.props.id} checked={this.props.currentValue} defaultChecked={this.props.defaultChecked} onChange={this.onChange} disabled={this.props.disabled} /> {this.props.id ? ( <label className="toggle-switch-label" htmlFor={this.props.id}> <span className={ this.props.disabled ? "toggle-switch-inner toggle-switch-disabled" : "toggle-switch-inner" } data-yes={this.props.Text[0]} data-no={this.props.Text[1]} /> <span className={ this.props.disabled ? "toggle-switch-switch toggle-switch-disabled" : "toggle-switch-switch" } /> </label> ) : null} </div> ); } // Set text for rendering. static defaultProps = { Text: ["Yes", "No"] }; }
JavaScript
class CloudServices extends Plugin { /** * @inheritdoc */ static get pluginName() { return 'CloudServices'; } /** * @inheritDoc */ init() { const editor = this.editor; const config = editor.config; const options = config.get( 'cloudServices' ) || {}; for ( const optionName in options ) { this[ optionName ] = options[ optionName ]; } /** * The authentication token URL for CKEditor Cloud Services or a callback to the token value promise. See the * {@link module:cloud-services/cloudservices~CloudServicesConfig#tokenUrl} for more details. * * @readonly * @member {String|Function|undefined} #tokenUrl */ /** * The URL to which the files should be uploaded. * * @readonly * @member {String} #uploadUrl */ /** * Other plugins use this token for the authorization process. It handles token requesting and refreshing. * Its value is `null` when {@link module:cloud-services/cloudservices~CloudServicesConfig#tokenUrl} is not provided. * * @readonly * @member {Object|null} #token */ if ( !this.tokenUrl ) { this.token = null; return; } this.token = new CloudServices.Token( this.tokenUrl ); return this.token.init(); } }
JavaScript
class ChromeHeadlessDriver extends Driver { /** * Instantiate the object */ constructor() { super(); } /** * Build the driver with capabilities * @returns {WebDriver} Driver object */ build() { return new webdriver .Builder() .forBrowser('chrome') .setChromeOptions(new chrome.Options().headless()) .build(); } }
JavaScript
class ReactionCollector extends Collector { /** * @param {Message} message The message upon which to collect reactions * @param {CollectorFilter} filter The filter to apply to this collector * @param {ReactionCollectorOptions} [options={}] The options to apply to this collector */ constructor(message, filter, options = {}) { super(message.client, filter, options); /** * The message * @type {Message} */ this.message = message; /** * The users which have reacted * @type {Collection} */ this.users = new Collection(); /** * The total number of reactions collected * @type {number} */ this.total = 0; this.client.on('messageReactionAdd', this.listener); } /** * Handle an incoming reaction for possible collection. * @param {MessageReaction} reaction The reaction to possibly collect * @returns {?{key: Snowflake, value: MessageReaction}} Reaction data to collect * @private */ handle(reaction) { if (reaction.message.id !== this.message.id) return null; return { key: reaction.emoji.id || reaction.emoji.name, value: reaction, }; } /** * Check after collection to see if the collector is done. * @param {MessageReaction} reaction The reaction that was collected * @param {User} user The user that reacted * @returns {?string} Reason to end the collector, if any * @private */ postCheck(reaction, user) { this.users.set(user.id, user); if (this.options.max && ++this.total >= this.options.max) return 'limit'; if (this.options.maxEmojis && this.collected.size >= this.options.maxEmojis) return 'emojiLimit'; if (this.options.maxUsers && this.users.size >= this.options.maxUsers) return 'userLimit'; return null; } /** * Remove event listeners. * @private */ cleanup() { this.client.removeListener('messageReactionAdd', this.listener); } }
JavaScript
class HtmlAttr { /** * Creates a new setter functor for HTML Attributes * @param {string} key - the attribute name. * @param {string} value - the value to set for the attribute. * @param {...string} tags - the HTML tags that support this attribute. */ constructor(key, value, ...tags) { this.key = key; this.value = value; this.tags = tags.map(t => t.toLocaleUpperCase()); Object.freeze(this); } /** * Set the attribute value on an HTMLElement * @param {HTMLElement} elem - the element on which to set the attribute. */ apply(elem) { const isValid = this.tags.length === 0 || this.tags.indexOf(elem.tagName) > -1; if (!isValid) { console.warn(`Element ${elem.tagName} does not support Attribute ${this.key}`); } else if (this.key === "style") { Object.assign(elem[this.key], this.value); } else if (!(typeof value === "boolean" || value instanceof Boolean) || this.key === "muted") { elem[this.key] = this.value; } else if (this.value) { elem.setAttribute(this.key, ""); } else { elem.removeAttribute(this.key); } } }
JavaScript
class CommunicationsModuleTypeSearchBuilder extends SearchBuilder { /** * @param {!InternalOpenGateAPI} parent - Instance of our InternalOpenGateAPI */ constructor(parent) { super(parent, {}); this._url = '/communicationsModuleType'; this.customFilters = {}; } /** * Build a instance of StaticSearch * * @example * ogapi.administrativeStateSearchBuilder().filter({and:[]}).build() * @throws {SearchBuilderError} Throw error on url build * @return {StaticSearch} */ build() { return new StaticSearch(this._parent, this._buildUrl(), this._buildFilter(), this._builderParams.timeout, 'communicationsModuleType', this.customFilters); } /** * Sets id to search * * @description * The list of types of communication modules is as follows: * "GENERIC", "WIFI", "EHTERNET", "BLUETOOTH", "MESH", "LOWPAN", "LTE_M", PLC", "ZIGBEE", "ADSL", "MOBILE", "NARROWBAND", "GSM", "UMTS", "CAN", "I2C", "RS232", "RS422", "RS485" * @example * ogapi.communicationsModuleTypeSearchBuilder().withType('GENERIC').build() * @param {!string} communicationsModuleType - specific type * @throws {Error} throw error when type is not typeof string * @return {CommunicationsModuleTypeSearchBuilder} */ withType(communicationsModuleType) { if (typeof communicationsModuleType !== 'string') { throw new Error('Parameter type must be a string'); } this.customFilters.type = communicationsModuleType; return this; } }
JavaScript
class Operation { /** * Create a Operation. * @property {string} [operationState] Operation state. Possible values * include: 'Failed', 'NotStarted', 'Running', 'Succeeded' * @property {string} [createdTimestamp] Timestamp when the operation was * created. * @property {string} [lastActionTimestamp] Timestamp when the current state * was entered. * @property {string} [resourceLocation] Relative URI to the target resource * location for completed resources. * @property {string} [userId] User Id * @property {string} [operationId] Operation Id. * @property {object} [errorResponse] Error details in case of failures. * @property {object} [errorResponse.error] The error object. */ constructor() { } /** * Defines the metadata of Operation * * @returns {object} metadata of Operation * */ mapper() { return { required: false, serializedName: 'Operation', type: { name: 'Composite', className: 'Operation', modelProperties: { operationState: { required: false, serializedName: 'operationState', type: { name: 'String' } }, createdTimestamp: { required: false, serializedName: 'createdTimestamp', type: { name: 'String' } }, lastActionTimestamp: { required: false, serializedName: 'lastActionTimestamp', type: { name: 'String' } }, resourceLocation: { required: false, serializedName: 'resourceLocation', type: { name: 'String' } }, userId: { required: false, serializedName: 'userId', type: { name: 'String' } }, operationId: { required: false, serializedName: 'operationId', type: { name: 'String' } }, errorResponse: { required: false, serializedName: 'errorResponse', type: { name: 'Composite', className: 'ErrorResponse' } } } } }; } }
JavaScript
class Approve extends PureComponent { static navigationOptions = ({ navigation }) => getApproveNavbar('approve.title', navigation); static propTypes = { /** * List of accounts from the AccountTrackerController */ accounts: PropTypes.object, /** * Transaction state */ transaction: PropTypes.object.isRequired, /** * Action that sets transaction attributes from object to a transaction */ setTransactionObject: PropTypes.func.isRequired, /** * List of transactions */ transactions: PropTypes.array, /** * Number of tokens */ tokensLength: PropTypes.number, /** * Number of accounts */ accountsLength: PropTypes.number, /** * A string representing the network name */ providerType: PropTypes.string, /** * Whether the modal is visible */ modalVisible: PropTypes.bool, /** /* Token approve modal visible or not */ toggleApproveModal: PropTypes.func, /** * Current selected ticker */ ticker: PropTypes.string }; state = { approved: false, gasError: undefined, warningGasPriceHigh: undefined, ready: false, mode: REVIEW, over: false, analyticsParams: {} }; componentDidMount = () => { if (!this.props?.transaction?.id) { this.props.toggleApproveModal(false); return null; } this.handleFetchBasicEstimates(); AppState.addEventListener('change', this.handleAppStateChange); }; componentWillUnmount = () => { const { approved } = this.state; const { transaction } = this.props; AppState.removeEventListener('change', this.handleAppStateChange); if (!approved) Engine.context.TransactionController.cancelTransaction(transaction.id); }; handleAppStateChange = appState => { if (appState !== 'active') { const { transaction } = this.props; transaction && transaction.id && Engine.context.TransactionController.cancelTransaction(transaction.id); this.props.toggleApproveModal(false); } }; handleFetchBasicEstimates = async () => { this.setState({ ready: false }); const basicGasEstimates = await getBasicGasEstimatesByChainId(); if (basicGasEstimates) { this.handleSetGasFee(this.props.transaction.gas, apiEstimateModifiedToWEI(basicGasEstimates.averageGwei)); } return this.setState({ basicGasEstimates, ready: true }); }; trackApproveEvent = event => { const { transaction, tokensLength, accountsLength, providerType } = this.props; InteractionManager.runAfterInteractions(() => { Analytics.trackEventWithParameters(event, { view: transaction.origin, numberOfTokens: tokensLength, numberOfAccounts: accountsLength, network: providerType }); }); }; handleSetGasFee = (customGas, customGasPrice, warningGasPriceHigh) => { const { setTransactionObject } = this.props; this.setState({ gasEstimationReady: false }); this.setState({ warningGasPriceHigh }); setTransactionObject({ gas: customGas, gasPrice: customGasPrice }); setTimeout(() => { this.setState({ gasEstimationReady: true, errorMessage: undefined }); }, 100); }; validateGas = () => { let error; const { ticker, transaction: { value, gas, gasPrice, from }, accounts } = this.props; const fromAccount = accounts[safeToChecksumAddress(from)]; const total = value.add(gas.mul(gasPrice)); if (!gas) error = strings('transaction.invalid_gas'); else if (!gasPrice) error = strings('transaction.invalid_gas_price'); else if (fromAccount && isBN(gas) && isBN(gasPrice) && hexToBN(fromAccount.balance).lt(gas.mul(gasPrice))) { this.setState({ over: true }); const amount = renderFromWei(total.sub(value)); const tokenSymbol = getTicker(ticker); error = strings('transaction.insufficient_amount', { amount, tokenSymbol }); } this.setState({ gasError: error }); return error; }; prepareTransaction = transaction => ({ ...transaction, gas: BNToHex(transaction.gas), gasPrice: BNToHex(transaction.gasPrice), value: BNToHex(transaction.value), to: safeToChecksumAddress(transaction.to), from: safeToChecksumAddress(transaction.from) }); onConfirm = async () => { if (this.validateGas()) return; const { TransactionController } = Engine.context; const { transactions } = this.props; try { const transaction = this.prepareTransaction(this.props.transaction); TransactionController.hub.once(`${transaction.id}:finished`, transactionMeta => { if (transactionMeta.status === 'submitted') { this.setState({ approved: true }); this.props.toggleApproveModal(); NotificationManager.watchSubmittedTransaction({ ...transactionMeta, assetType: 'ETH' }); } else { throw transactionMeta.error; } }); const fullTx = transactions.find(({ id }) => id === transaction.id); const updatedTx = { ...fullTx, transaction }; await TransactionController.updateTransaction(updatedTx); await TransactionController.approveTransaction(transaction.id); AnalyticsV2.trackEvent(AnalyticsV2.ANALYTICS_EVENTS.APPROVAL_COMPLETED, this.state.analyticsParams); } catch (error) { Alert.alert(strings('transactions.transaction_error'), error && error.message, [{ text: 'OK' }]); Logger.error(error, 'error while trying to send transaction (Approve)'); this.setState({ transactionHandled: false }); } }; onCancel = () => { AnalyticsV2.trackEvent(AnalyticsV2.ANALYTICS_EVENTS.APPROVAL_CANCELLED, this.state.analyticsParams); this.props.toggleApproveModal(false); }; review = () => { this.onModeChange(REVIEW); }; onModeChange = mode => { this.setState({ mode }); if (mode === EDIT) { InteractionManager.runAfterInteractions(() => { Analytics.trackEvent(ANALYTICS_EVENT_OPTS.SEND_FLOW_ADJUSTS_TRANSACTION_FEE); }); } }; setAnalyticsParams = analyticsParams => { this.setState({ analyticsParams }); }; getGasAnalyticsParams = () => { const { analyticsParams } = this.state; return { dapp_host_name: analyticsParams?.dapp_host_name, dapp_url: analyticsParams?.dapp_url, active_currency: { value: analyticsParams?.active_currency, anonymous: true } }; }; render = () => { const { gasError, basicGasEstimates, mode, ready, over, warningGasPriceHigh } = this.state; const { transaction } = this.props; if (!transaction.id) return null; return ( <Modal isVisible={this.props.modalVisible} animationIn="slideInUp" animationOut="slideOutDown" style={styles.bottomModal} backdropOpacity={0.7} animationInTiming={600} animationOutTiming={600} onBackdropPress={this.onCancel} onBackButtonPress={this.onCancel} onSwipeComplete={this.onCancel} swipeDirection={'down'} propagateSwipe > <KeyboardAwareScrollView contentContainerStyle={styles.keyboardAwareWrapper}> <AnimatedTransactionModal onModeChange={this.onModeChange} ready={ready} review={this.review}> <ApproveTransactionReview gasError={gasError} warningGasPriceHigh={warningGasPriceHigh} onCancel={this.onCancel} onConfirm={this.onConfirm} over={over} onSetAnalyticsParams={this.setAnalyticsParams} /> <CustomGas handleGasFeeSelection={this.handleSetGasFee} basicGasEstimates={basicGasEstimates} gas={transaction.gas} gasPrice={transaction.gasPrice} gasError={gasError} mode={mode} view={'Approve'} analyticsParams={this.getGasAnalyticsParams()} /> </AnimatedTransactionModal> </KeyboardAwareScrollView> </Modal> ); }; }
JavaScript
class ParquetCursor { /** * Create a new parquet reader from the file metadata and an envelope reader. * It is usually not recommended to call this constructor directly except for * advanced and internal use cases. Consider using getCursor() on the * ParquetReader instead */ constructor(metadata, envelopeReader, schema, columnList) { this.metadata = metadata; this.envelopeReader = envelopeReader; this.schema = schema; this.columnList = columnList; this.rowGroup = []; this.rowGroupIndex = 0; } /** * Retrieve the next row from the cursor. Returns a row or NULL if the end * of the file was reached */ async next() { if (this.rowGroup.length === 0) { if (this.rowGroupIndex >= this.metadata.row_groups.length) { return null; } let rowBuffer = await this.envelopeReader.readRowGroup( this.schema, this.metadata.row_groups[this.rowGroupIndex], this.columnList); this.rowGroup = parquet_shredder.materializeRecords(this.schema, rowBuffer); this.rowGroupIndex++; } return this.rowGroup.shift(); } /** * Rewind the cursor the the beginning of the file */ rewind() { this.rowGroup = []; this.rowGroupIndex = 0; } }
JavaScript
class ParquetReader { /** * Open the parquet file pointed to by the specified path and return a new * parquet reader */ static async openFile(filePath, options) { let envelopeReader = await ParquetEnvelopeReader.openFile(filePath, options); return this.openEnvelopeReader(envelopeReader, options); } static async openBuffer(buffer, options) { let envelopeReader = await ParquetEnvelopeReader.openBuffer(buffer, options); return this.openEnvelopeReader(envelopeReader, options); } /** * Open the parquet file from S3 using the supplied aws client and params * The params have to include `Bucket` and `Key` to the file requested * This function returns a new parquet reader */ static async openS3(client, params, options) { let envelopeReader = await ParquetEnvelopeReader.openS3(client, params, options); return this.openEnvelopeReader(envelopeReader, options); } /** * Open the parquet file from a url using the supplied request module * params should either be a string (url) or an object that includes * a `url` property. * This function returns a new parquet reader */ static async openUrl(request, params, options) { let envelopeReader = await ParquetEnvelopeReader.openUrl(request, params, options); return this.openEnvelopeReader(envelopeReader, options); } static async openEnvelopeReader(envelopeReader, opts) { if (opts && opts.metadata) { return new ParquetReader(opts.metadata, envelopeReader, opts); } try { await envelopeReader.readHeader(); let metadata = await envelopeReader.readFooter(); return new ParquetReader(metadata, envelopeReader, opts); } catch (err) { await envelopeReader.close(); throw err; } } /** * Create a new parquet reader from the file metadata and an envelope reader. * It is not recommended to call this constructor directly except for advanced * and internal use cases. Consider using one of the open{File,Buffer} methods * instead */ constructor(metadata, envelopeReader, opts) { opts = opts || {}; if (metadata.version != PARQUET_VERSION) { throw 'invalid parquet version'; } // If metadata is a json file then we need to convert INT64 and CTIME if (metadata.json) { const convert = (o) => { if (o && typeof o === 'object') { Object.keys(o).forEach(key => o[key] = convert(o[key])); if (o.parquetType === 'CTIME') { return new Date(o.value); } else if (o.parquetType === 'INT64') { return new Int64(Buffer.from(o.value)); } } return o; }; // Go through all PageLocation objects and set the proper prototype metadata.row_groups.forEach(rowGroup => { rowGroup.columns.forEach(column => { if (column.offsetIndex) { column.offsetIndex.page_locations.forEach(d => { if (Array.isArray(d)) { Object.setPrototypeOf(d,parquet_thrift.PageLocation.prototype); } }); } }); }); convert(metadata); } this.metadata = envelopeReader.metadata = metadata; this.envelopeReader = envelopeReader; this.schema = envelopeReader.schema = new parquet_schema.ParquetSchema( decodeSchema( this.metadata.schema.slice(1))); /* decode any statistics values */ if (this.metadata.row_groups && !this.metadata.json && !opts.rawStatistics) { this.metadata.row_groups.forEach(row => row.columns.forEach( col => { const stats = col.meta_data.statistics; if (stats) { const field = this.schema.findField(col.meta_data.path_in_schema); stats.max_value = decodeStatisticsValue(stats.max_value, field); stats.min_value = decodeStatisticsValue(stats.min_value, field); stats.min = decodeStatisticsValue(stats.min, field); stats.max = decodeStatisticsValue(stats.max, field); } })); } } /** * Return a cursor to the file. You may open more than one cursor and use * them concurrently. All cursors become invalid once close() is called on * the reader object. * * The required_columns parameter controls which columns are actually read * from disk. An empty array or no value implies all columns. A list of column * names means that only those columns should be loaded from disk. */ getCursor(columnList) { if (!columnList) { columnList = []; } columnList = columnList.map((x) => x.constructor === Array ? x : [x]); return new ParquetCursor( this.metadata, this.envelopeReader, this.schema, columnList); } /** * Return the number of rows in this file. Note that the number of rows is * not neccessarily equal to the number of rows in each column. */ getRowCount() { return this.metadata.num_rows; } /** * Returns the ParquetSchema for this file */ getSchema() { return this.schema; } /** * Returns the user (key/value) metadata for this file */ getMetadata() { let md = {}; for (let kv of this.metadata.key_value_metadata) { md[kv.key] = kv.value; } return md; } exportMetadata(indent) { function replacer(key, value) { if (value instanceof parquet_thrift.PageLocation) { return [value[0], value[1], value[2]]; } if (typeof value === 'object') { for (let k in value) { if (value[k] instanceof Date) { value[k].toJSON = () => ({ parquetType: 'CTIME', value: value[k].valueOf() }); } } } if (typeof value === 'bigint') { return value.toString(); } if (value instanceof Int64) { if (isFinite(value)) { return Number(value); } else { return { parquetType: 'INT64', value: [...value.buffer] }; } } else { return value; } } const metadata = Object.assign({}, this.metadata, {json: true}); return JSON.stringify(metadata,replacer,indent); } /** * Close this parquet reader. You MUST call this method once you're finished * reading rows */ async close() { await this.envelopeReader.close(); this.envelopeReader = null; this.metadata = null; } decodePages(buffer, opts) { return decodePages(buffer,opts); } }
JavaScript
class RatingIndicator extends UI5Element { static get metadata() { return metadata; } static get render() { return litRender; } static get styles() { return RatingIndicatorCss; } static get template() { return RatingIndicatorTemplate; } static async onDefine() { await fetchI18nBundle("@ui5/webcomponents"); } constructor() { super(); this._liveValue = null; // stores the value to determine when to fire change this.i18nBundle = getI18nBundle("@ui5/webcomponents"); } onBeforeRendering() { this.calcState(); } calcState() { this._stars = []; for (let i = 1; i < this.max + 1; i++) { const remainder = Math.round((this.value - Math.floor(this.value)) * 10); let halfStar = false, tempValue = this.value; if (Math.floor(this.value) + 1 === i && remainder > 2 && remainder < 8) { halfStar = true; } else if (remainder <= 2) { tempValue = Math.floor(this.value); } else if (remainder >= 8) { tempValue = Math.ceil(this.value); } this._stars.push({ selected: i <= tempValue, index: i, halfStar, }); } } _onclick(event) { if (this.disabled || this.readonly) { return; } this.value = parseInt(event.target.getAttribute("data-value")); if (this.value === 1 && this._liveValue === 1) { this.value = 0; } if (this._liveValue !== this.value) { this.fireEvent("change"); this._liveValue = this.value; } } _onkeydown(event) { if (this.disabled || this.readonly) { return; } const down = isDown(event) || isLeft(event); const up = isRight(event) || isUp(event) || isSpace(event) || isEnter(event); if (down || up) { event.preventDefault(); if (down && this.value > 0) { this.value = Math.round(this.value - 1); this.fireEvent("change"); } else if (up && this.value < this.max) { this.value = Math.round(this.value + 1); this.fireEvent("change"); } } } _onfocusin() { if (this.disabled) { return; } this._focused = true; this._liveValue = this.value; } _onfocusout() { this._focused = false; } get tabIndex() { return this.disabled ? "-1" : "0"; } get tooltip() { return this.getAttribute("title") || this.defaultTooltip; } get defaultTooltip() { return this.i18nBundle.getText(RATING_INDICATOR_TOOLTIP_TEXT); } get _ariaRoleDescription() { return this.i18nBundle.getText(RATING_INDICATOR_TEXT); } get _ariaDisabled() { return this.disabled || undefined; } get ariaReadonly() { return this.readonly ? "true" : undefined; } }
JavaScript
class Store { constructor () { this._store = {} } /** * Set a value in the context store. * * @param {string} key nested keys are seperated by dots * @param {*} value * @throws {RuntimeException} */ set (key, value) { const path = this._path(key) const lastProp = path.pop() let store = this._store for (let prop of path) { if (store[prop] == null) { store[prop] = {} } else if (typeof store[prop] !== 'object') { throw RuntimeException.setPropNonObject(prop) } store = store[prop] } store[lastProp] = value } /** * Get the value of a key form the context store. * * @param {string} key nested keys are seperated by dots * @param {*} [fallback] the value to return if the key is not set * @return {*} */ get (key, fallback = null) { return this._get(key) || fallback } /** * @private * @param {string} key * @return {*} */ _get (key) { const path = this._path(key) let value = this._store for (let prop of path) { if (value[prop] == null) { return null } value = value[prop] } return value } /** * @private * @param {string} key * @return {string[]} */ _path (key) { return key.split('.') } }
JavaScript
class OwnersActive extends Component { constructor(props) { super(props); this.state = { showActive: false, }; this.toggleActive = this.toggleActive.bind(this); } toggleActive() { let isActive = this.state.showActive; isActive = !isActive; this.setState({showActive: isActive}); } render() { const boldStyle = { textAlign: "center", fontWeight: "bold" }; owners = []; i = 1; this.props.sorteo.owners.forEach((o)=>{ this.props.users.forEach((u)=>{ if(u.userId !== Meteor.user()._id && o === u.userId && u.online){ owners.push(<MenuItem primaryText={u.username} key={i}/>); i++; return; } }); }); return ( <div> <MenuItem primaryText={"Active Owners ("+owners.length+")"} leftIcon={<People/>} style={boldStyle} onClick={this.toggleActive}/> { this.state.showActive ? <div className="center-items"> {owners} </div> : null } </div> ); } }
JavaScript
class CreateRepo extends Component { constructor() { super(); this.createRepository = this.createRepository.bind(this); } state = {}; createRepository(event) { event.preventDefault(); //const data = new FormData(event.target); } render() { return ( <div className="wrapper-container"> <p className="title">CREATE REPOSITORY</p> <div className="body-sec create-repo-container "> <div className="row"> <div className="col"> <Alert className="alert-custom" variant="warning"> <i className="fas fa-code"></i> command to execute <CopyToClipboard text="command to execute"> <button className="btn-invisible"> <i className="far fa-copy"></i> </button> </CopyToClipboard> </Alert> <Form onSubmit={this.createRepository}> <Form.Group controlId=""> <Form.Label>Repository Name</Form.Label> <Form.Control name="repo" type="text" placeholder="Enter repository name" /> </Form.Group> <Form.Group controlId=""> <Form.Label>Description</Form.Label> <Form.Control type="text" placeholder="Enter description" /> </Form.Group> <Form.Group controlId=""> <Form.Label>Username</Form.Label> <Form.Control type="text" placeholder="Enter username" /> </Form.Group> <Form.Group controlId=""> <Form.Label>Email</Form.Label> <Form.Control type="email" placeholder="Enter email" /> </Form.Group> <Button variant="primary" type="submit"> Create Repository </Button> </Form> </div> </div> </div> </div> ); } }
JavaScript
class Config { constructor() { this.domainName = "https://explore.fastdna.net"; this.appName = "FASTDNA"; this.siteName = "Component explorer"; } /** * Retrieves the Git Branch for the local user account */ branchName() { return spawn('git', ['rev-parse', '--abbrev-ref', 'HEAD']).output[1].toString().trim(); } }
JavaScript
class Run { constructor(eyes, driver, website) { console.log("Starting tests on: %s", website); driver.get(website); // Note: There are many ways to navigate/find/select elements on a page. // Not all are cross-browser compliant and for example, we can't // use xpath in all browser drivers. As a result, we're using // navigation though not necessarily most performant but effective. // Iterate each components documentation driver.navigate().to(`${website}/components/button/`); eyes.checkWindow("button"); driver.navigate().to(`${website}/components/caption/`); eyes.checkWindow("caption"); driver.navigate().to(`${website}/components/checkbox/`); eyes.checkWindow("checkbox"); driver.navigate().to(`${website}/components/dialog/`); eyes.checkWindow("dialog"); driver.navigate().to(`${website}/components/divider/`); eyes.checkWindow("divider"); driver.navigate().to(`${website}/components/flipper/`); eyes.checkWindow("flipper"); driver.navigate().to(`${website}/components/heading/`); eyes.checkWindow("heading"); driver.navigate().to(`${website}/components/hypertext/`); eyes.checkWindow("hypertext"); driver.navigate().to(`${website}/components/image/`); eyes.checkWindow("image"); driver.navigate().to(`${website}/components/label/`); eyes.checkWindow("label"); driver.navigate().to(`${website}/components/metatext/`); eyes.checkWindow("metatext"); driver.navigate().to(`${website}/components/paragraph/`); eyes.checkWindow("paragraph"); driver.navigate().to(`${website}/components/subheading/`); eyes.checkWindow("subheading"); driver.navigate().to(`${website}/components/text-field/`); eyes.checkWindow("text-field"); driver.navigate().to(`${website}/components/toggle/`); eyes.checkWindow("toggle"); driver.navigate().to(`${website}/components/typography/`); eyes.checkWindow("typography"); // Turn on Developer tools and iterate each component // Xpath selectors do not work in Internet Explorer // driver.findElement(By.xpath("//button[text()='dev tools']")).click(); // one possible solution would be to inject data attributes for each component we can bind to. // For example, data-test="friendly name" // driver.findElement(By.cssSelector('[data-element="city"]')) // Navigate to example views for each component driver.navigate().to(`${website}/components/button/examples`); eyes.checkWindow("button example"); driver.navigate().to(`${website}/components/caption/examples`); eyes.checkWindow("caption example"); driver.navigate().to(`${website}/components/checkbox/examples`); eyes.checkWindow("checkbox example"); driver.navigate().to(`${website}/components/dialog/examples`); eyes.checkWindow("dialog example"); driver.navigate().to(`${website}/components/divider/examples`); eyes.checkWindow("divider example"); driver.navigate().to(`${website}/components/flipper/examples`); eyes.checkWindow("flipper example"); driver.navigate().to(`${website}/components/heading/examples`); eyes.checkWindow("heading example"); driver.navigate().to(`${website}/components/hypertext/examples`); eyes.checkWindow("hypertext example"); driver.navigate().to(`${website}/components/image/examples`); eyes.checkWindow("image example"); driver.navigate().to(`${website}/components/label/examples`); eyes.checkWindow("label example"); driver.navigate().to(`${website}/components/metatext/examples`); eyes.checkWindow("metatext example"); driver.navigate().to(`${website}/components/paragraph/examples`); eyes.checkWindow("paragraph example"); driver.navigate().to(`${website}/components/subheading/examples`); eyes.checkWindow("subheading example"); driver.navigate().to(`${website}/components/text-field/examples`); eyes.checkWindow("text-field example"); driver.navigate().to(`${website}/components/toggle/examples`); eyes.checkWindow("toggle example"); driver.navigate().to(`${website}/components/typography/examples`); eyes.checkWindow("typography example"); } }
JavaScript
class FadeView extends PureComponent { static propTypes = { /** * Determines to show / hide the children components */ visible: PropTypes.bool, /** * Children components of the FadeView * it can be a text node, an image, or an icon * or an Array with a combination of them */ children: PropTypes.any, /** * Styles to be applied to the FadeView */ style: ViewPropTypes.style }; constructor(props) { super(props); this.state = { visible: props.visible }; this.visibility = new Animated.Value(props.visible ? 1 : 0); } componentDidMount() { this.mounted = true; } componentWillUnmount() { this.mounted = false; } componentDidUpdate() { Animated.timing(this.visibility, { toValue: this.props.visible ? 1 : 0, duration: 300, useNativeDriver: true, isInteraction: false }).start(() => { if (this.props.visible !== this.state.visible) { setTimeout(() => { this.mounted && this.setState({ visible: this.props.visible }); }, 500); } }); } render = () => { const { style, children, ...rest } = this.props; const containerStyle = { opacity: this.visibility.interpolate({ inputRange: [0, 1], outputRange: [0, 1] }) }; const combinedStyle = [containerStyle, style]; return ( <Animated.View style={this.state.visible ? combinedStyle : containerStyle} {...rest}> {this.state.visible ? children : null} </Animated.View> ); }; }
JavaScript
class Find extends Component { state = { projects: [] }; //Display all projects. User can search by category if desired. componentDidMount() { //Console logging the category from URL ("/find/:category") // console.log(this.props); if (this.props.match.params.categoryId) { this.searchCategory() } else { this.getAllProjects() } } //This method runs as soon as page loads. It shows ALL projects. getAllProjects = () => { API.getProjects() .then(res => // console.log(res.data.date) this.setState({ projects: res.data }) ) .catch(() => this.setState({ projects: [], message: 'Uh oh our search is going wrong' }) ); }; //This function runs on button click. It searches by the category in URL. searchCategory = () => { API.searchCategory(this.props.match.params.categoryId) .then(res => { this.setState({ projects: res.data }) // console.log("this is res.data" + res.data[0].Category.name); }) }; render() { return ( <div className='bg-color' style={{ backgroundColor: '#D8D3C8' }}> <Jumbotron> <h1> This page loads all projects. Search by a category (in url) if desired. </h1> {/* <FormBtn onClick={this.searchCategory} type="success" className="input-lg body-btn">Search By Category</FormBtn> */} {/* <Dropdown /> */} </Jumbotron> {/* aria-haspopup="true" aria-expanded="false" */} {/* aria-labelledby="dropdownMenuLink" */} <Container> <Row> <div className="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Category Filter </button> <div className="dropdown-menu" ariaLabelledby="dropdownMenuLink"> <a className="dropdown-item" href="/find/all">None</a> <a className="dropdown-item" href="/find/category/1">Environmental</a> <a className="dropdown-item" href="/find/category/2">Hunger and Food Security</a> <a className="dropdown-item" href="/find/category/3">Education and Literacy</a> <a className="dropdown-item" href="/find/category/4">Crisis Support and Disaster Relief</a> <a className="dropdown-item" href="/find/category/5">Elder Care</a> <a className="dropdown-item" href="/find/category/6">Vulnerable Groups</a> <a className="dropdown-item" href="/find/category/7">Animal Welfare</a> <a className="dropdown-item" href="/find/category/8">Housing and Shelter</a> <a className="dropdown-item" href="/find/category/9">Community Projects</a> <a className="dropdown-item" href="/find/category/10">Children and Youth</a> </div> </div> </Row> <Row> {this.state.projects.map(project => ( <Col size='md-4'> <TestTile id={project.id} title={project.title} date={project.date} photo_url={project.photo_url} category={project.Category.name} /> </Col> ))} </Row> </Container> </div> ) } }
JavaScript
class MyWS { /** * WebSocket Pool * @type {Object} */ static wsPool = {}; /** * Class Instance of WebSocket * @type {WebSocket} */ ws = null; /** * Class Instance of current WebSocket full path * @type {string} */ fullPath = ""; /** * Constructor of class MyWS * Use WebSocket Pool to manage a number of WebSockets * @param {string} path relative path of websocket server to host * @param {string} host host of Websocket Server * @param {string | number} port port of WebSocket Server */ constructor(path, host = window.location.hostname, port = window.location.port) { let protocol; if (window.location.protocol === "https:") { protocol = "wss:"; } else { protocol = "ws:"; } this.fullPath = `${protocol}//${host}:${port}${path}`; let ws = MyWS.wsPool[this.fullPath]; if (!(ws && ws.readyState === WebSocket.OPEN)) { ws = new WebSocket(this.fullPath); MyWS.wsPool[this.fullPath] = ws; } this.ws = ws; } /** * Send Message via current WebSocket * @param {JSON} message * @returns {Promise<void|*>} */ async send(message) { if (!this.ws) { return Promise.reject(new Error("WebSocket 连接不存在!")); } switch (this.ws.readyState) { case WebSocket.OPEN: this.ws.send(JSON.stringify(message)); return Promise.resolve(); case WebSocket.CONNECTING: await Other.sleep(50); return this.send(message); case WebSocket.CLOSING: case WebSocket.CLOSED: return Promise.reject(new Error("连接已关闭")); default: return Promise.reject(new Error("未知错误")); } } /** * Close Current WebSocket Connection * And remove from WebSocket Pool */ close() { console.log("CLOSING WS"); this.ws.close(); console.log(`CLOSED WS: ${this.ws.readyState}`); this.ws.onmessage = null; this.ws.onerror = null; this.ws.onopen = null; this.ws = null; MyWS.wsPool[this.fullPath] = null; this.fullPath = null; } /** * addAction * @param { Function } handler * @param {"message" | "error" | "open" | "close"} type * @returns {boolean|undefined} */ addAction(handler, type) { if (!this.ws) { return undefined; } this.ws.addEventListener(type, handler); return true; } /** * removeAction * @param {Function} handler * @param {"message" | "error" | "open" | "close"} type * @returns {boolean|undefined} */ removeAction(handler, type) { if (!this.ws) { return undefined; } this.ws.removeEventListener(type, handler); return true; } }
JavaScript
class InsertValuesMissingError extends TypeORMError_1.TypeORMError { constructor() { super(`Cannot perform insert query because values are not defined. ` + `Call "qb.values(...)" method to specify inserted values.`); } }
JavaScript
class Render { constructor() { this.viewAngle = 55; this.near = 1; this.far = 10000; this.frame = 0; this.floor = -45; this.background = 0xDDDDDD; this.zRotation = -180 * Math.PI / 180; this.xRotation = -33 * Math.PI / 180; this.start = Date.now(); this.fog = this.background; this.generator = new Generator(10); window.addEventListener('resize', this.resize, true); window.addEventListener('click', this.stats, true); // this.createGUI(); this.setViewport(); this.init(); this.renderLoop(); } init = () => { this.setRender(); this.setCamera(); this.setControls(); this.setSkyBox(); this.setLights(); this.setScene(); }; stats = () => { console.log(this.camera.position); }; setRender = () => { // Set Render and Scene // this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(this.width, this.height); this.renderer.setPixelRatio(this.devicePixelRatio); this.renderer.shadowMapEnabled = true; document.body.appendChild(this.renderer.domElement); // Root Scene Element // this.scene = new THREE.Scene(); }; setCamera = () => { this.camera = new THREE.PerspectiveCamera( this.viewAngle, this.aspect, this.near, this.far ); this.scene.add(this.camera); this.camera.position.set(0, 12, 24); this.camera.lookAt(this.scene.position); }; setControls = () => { this.controls = new THREE.OrbitControls(this.camera); this.controls.maxDistance = 3000; this.controls.minDistance = 0.1; }; setLights = () => { // Set AmbientLight // this.ambient = new THREE.AmbientLight(0xAAAAAA); this.ambient.position.set(0, 45, 0); this.scene.add(this.ambient); this.spotLight = new THREE.DirectionalLight(0x0666666); this.spotLight.position.set(-6, 30, 80); this.spotLight.castShadow = true; this.scene.add(this.spotLight); }; setSkyBox = () => { const urls = [xpos, xneg, ypos, yneg, zpos, zneg]; this.skybox = new THREE.CubeTextureLoader().load(urls); this.skybox.format = THREE.RGBFormat; this.skybox.mapping = THREE.CubeReflectionMapping; // CubeReflectionMapping || CubeRefractionMapping this.scene.background = this.skybox; }; setScene = () => { this.meshMaterial = new THREE.ShaderMaterial({ uniforms: { tExplosion: { type: 't', value: THREE.ImageUtils.loadTexture(explosion), }, time: { type: 'f', value: 0.0, }, timeScale: { type: 'f', value: 2.0, } }, vertexShader, fragmentShader, }); this.fireball = new THREE.Mesh( new THREE.IcosahedronGeometry(7, 4), this.meshMaterial ); this.scene.add(this.fireball); // const objectLoader = new THREE.ObjectLoader(); // this.skullObject = objectLoader.parse(skullModel); // this.skullObject.children[0].geometry.dynamic = true; // this.skullObject.children[0].rotation.set(105 * Math.PI / 180, 0, 0); // this.skullObject.children[0].material = this.meshMaterial; // this.scene.add(this.skullObject); }; checkObjects = () => { const timeStop = this.frame * 0.2; const angleRotate = timeStop * Math.PI / 180; const timeScale = 1 - Math.sin(angleRotate) * 0.1; // this.skullObject.children[0].rotation.y = angleRotate; // this.fireball.scale.set(timeScale, timeScale, timeScale); this.meshMaterial.uniforms.timeScale.value = timeScale; }; setViewport = () => { this.width = window.innerWidth; this.height = window.innerHeight; this.aspect = this.width / this.height; this.devicePixelRatio = window.devicePixelRatio; }; resize = () => { this.setViewport(); this.camera.updateProjectionMatrix(); this.renderer.setSize(this.width, this.height); }; rgbToHex = (r, g, b) => { const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); return `0x${hex}`; }; renderScene = () => { this.renderer.render(this.scene, this.camera); }; renderLoop = () => { this.frame ++; this.meshMaterial.uniforms.time.value = 0.00025 * (Date.now() - this.start); this.checkObjects(); this.renderScene(); window.requestAnimationFrame(this.renderLoop.bind(this)); }; // DATGUI STUFF HERE // createGUI = () => { }; }
JavaScript
class Block extends Component { getSpacings(type) { const { margin, marginTop, marginRight, marginBottom, marginLeft, marginVertical, marginHorizontal, padding, paddingTop, paddingRight, paddingBottom, paddingLeft, paddingVertical, paddingHorizontal, theme } = this.props; const { SIZES } = mergeTheme(expoTheme, theme); if (type === "margin") { return [ margin && spacing(type, margin, SIZES.base), marginTop && parseSpacing("marginTop", marginTop, SIZES.base), marginRight && parseSpacing("marginRight", marginRight, SIZES.base), marginBottom && parseSpacing("marginBottom", marginBottom, SIZES.base), marginLeft && parseSpacing("marginLeft", marginLeft, SIZES.base), marginVertical && parseSpacing("marginVertical", marginVertical, SIZES.base), marginHorizontal && parseSpacing("marginHorizontal", marginHorizontal, SIZES.base) ]; } if (type === "padding") { return [ padding && spacing(type, padding, SIZES.base), paddingTop && parseSpacing("paddingTop", paddingTop, SIZES.base), paddingRight && parseSpacing("paddingRight", paddingRight, SIZES.base), paddingBottom && parseSpacing("paddingBottom", paddingBottom, SIZES.base), paddingLeft && parseSpacing("paddingLeft", paddingLeft, SIZES.base), paddingVertical && parseSpacing("paddingVertical", paddingVertical, SIZES.base), paddingHorizontal && parseSpacing("paddingHorizontal", paddingHorizontal, SIZES.base) ]; } } render() { const { flex, noflex, row, column, center, middle, left, right, top, bottom, card, shadow, elevation, // colors color, primary, secondary, tertiary, black, white, gray, error, warning, success, info, // positioning space, radius, wrap, animated, theme, safe, style, children, ...props } = this.props; const excludeProps = [ "margin", "marginTop", "marginRight", "marginBottom", "marginLeft", "marginVertical", "marginHorizontal", "padding", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", "paddingVertical", "paddingHorizontal" ]; const extraProps = Object.keys(props).reduce((prop, key) => { if (!excludeProps.includes(`${key}`)) { prop[key] = props[key]; } return prop; }, {}); const { SIZES, COLORS } = mergeTheme(expoTheme, theme); const marginSpacing = this.getSpacings("margin"); const paddingSpacing = this.getSpacings("padding"); const blockStyles = StyleSheet.flatten([ styles.block, flex && { flex: flex === true ? 1 : flex }, (!flex || noflex) && { flex: 0 }, row && styles.row, column && styles.column, center && styles.center, middle && styles.middle, left && styles.left, right && styles.right, top && styles.top, bottom && styles.bottom, marginSpacing, paddingSpacing, wrap && styles.wrap, shadow && { elevation, shadowColor: COLORS.black, shadowOffset: { width: 0, height: elevation - 1 }, shadowOpacity: 0.1, shadowRadius: elevation }, space && { justifyContent: `space-${space}` }, card && { borderRadius: SIZES.border }, radius && { borderRadius: radius }, // color shortcuts primary && { backgroundColor: COLORS.primary }, secondary && { backgroundColor: COLORS.secondary }, tertiary && { backgroundColor: COLORS.tertiary }, black && { backgroundColor: COLORS.black }, white && { backgroundColor: COLORS.white }, gray && { backgroundColor: COLORS.gray }, error && { backgroundColor: COLORS.error }, warning && { backgroundColor: COLORS.warning }, success && { backgroundColor: COLORS.success }, info && { backgroundColor: COLORS.info }, color && { backgroundColor: color }, // custom backgroundColor style // rewrite predefined styles ]); if (animated) { return ( <Animated.View style={blockStyles} {...extraProps}> {children} </Animated.View> ); } if (safe) { return ( <SafeAreaView style={blockStyles} {...extraProps}> {children} </SafeAreaView> ); } return ( <View style={blockStyles} {...extraProps}> {children} </View> ); } }
JavaScript
class MergeContext { /** * @param {NodeGit.Repository} repo * @param {NodeGit.Commit|null} ourCommit * @param {NodeGit.Commit} theirCommit * @param {MergeCommon.MODE} mode * @param {Open.SUB_OPEN_OPTION} openOption * @param {[String]} doNotRecurse * @param {String|null} commitMessage * @param {() -> Promise(String)} editMessage */ constructor(metaRepo, ourCommit, theirCommit, mode, openOption, doNotRecurse, commitMessage, editMessage, authorName, authorEmail, committerName, committerEmail) { assert.instanceOf(metaRepo, NodeGit.Repository); if (null !== ourCommit) { assert.instanceOf(ourCommit, NodeGit.Commit); } assert.instanceOf(theirCommit, NodeGit.Commit); assert.isNumber(mode); assert.isNumber(openOption); if (null !== commitMessage) { assert.isString(commitMessage); } assert.isFunction(editMessage); this.d_metaRepo = metaRepo; this.d_ourCommit = ourCommit; this.d_theirCommit = theirCommit; this.d_mode = mode; this.d_openOption = openOption; this.d_doNotRecurse = doNotRecurse; this.d_commitMessage = commitMessage; this.d_editMessage = editMessage; this.d_opener = new Open.Opener(metaRepo, ourCommit); this.d_changeIndex = null; this.d_changes = null; this.d_conflictsMessage = ""; this.d_authorName = authorName; this.d_authorEmail = authorEmail; this.d_committerName = committerName; this.d_committerEmail = committerEmail; } /** * @property {Boolean} forceBare if working directory is disabled */ get forceBare() { return Open.SUB_OPEN_OPTION.FORCE_BARE === this.d_openOption; } /** * @property {NodeGit.Repository} */ get metaRepo() { return this.d_metaRepo; } /** * @property {Opener} */ get opener() { return this.d_opener; } /** * @property {NodeGit.Commit} */ get theirCommit() { return this.d_theirCommit; } /** * @property {Open.SUB_OPEN_OPTION} */ get openOption() { return this.d_openOption; } /** * @property {[String]} */ get doNotRecurse() { return this.d_doNotRecurse; } /** * @property {MODE} */ get mode() { return this.d_mode; } /** * Reference to update when creating the merge commit * @property {String | null} */ get refToUpdate() { return this.forceBare ? null : "HEAD"; } }
JavaScript
class MergeStepResult { /** * @param {String | null} infoMessage message to display to user * @param {String | null} errorMessage message signifies a fatal error * @param {String | null} finishSha commit sha indicating end of merge * @param {Object} submoduleCommits map from submodule to commit */ constructor(infoMessage, errorMessage, finishSha, submoduleCommits) { this.d_infoMessage = infoMessage; this.d_errorMessage = errorMessage; this.d_finishSha = finishSha; this.d_submoduleCommits = submoduleCommits; } /** * @property {String|null} */ get errorMessage() { return this.d_errorMessage; } /** * @property {String|null} */ get infoMessage() { return this.d_infoMessage; } /** * @property {String|null} */ get finishSha() { return this.d_finishSha; } /** * @property {Object} map from submodule to commit */ get submoduleCommits() { if (null === this.d_submoduleCommits) { return {}; } return this.d_submoduleCommits; } /** * @static * @return {MergeStepResult} empty result object */ static empty() { return new MergeStepResult(null, null, null, {}); } /** * A merge result that signifies we need to abort current merging process. * * @static * @param {MergeStepResult} msg error message */ static error(msg) { return new MergeStepResult(null, msg, null, {}); } /** * A merge result that does not have any submodule commit. Only a finishing * sha at the meta repo level will be returned. * * @static * @param {String} infoMessage * @param {String} finishSha meta repo commit sha */ static justMeta(infoMessage, finishSha) { return new MergeStepResult(infoMessage, null, finishSha, {}); } }
JavaScript
class SourceTrigger { /** * Create a SourceTrigger. * @member {object} sourceRepository The properties that describes the * source(code) for the task. * @member {string} [sourceRepository.sourceControlType] The type of source * control service. Possible values include: 'Github', * 'VisualStudioTeamService' * @member {string} [sourceRepository.repositoryUrl] The full URL to the * source code respository * @member {string} [sourceRepository.branch] The branch name of the source * code. * @member {object} [sourceRepository.sourceControlAuthProperties] The * authorization properties for accessing the source code repository and to * set up * webhooks for notifications. * @member {string} [sourceRepository.sourceControlAuthProperties.tokenType] * The type of Auth token. Possible values include: 'PAT', 'OAuth' * @member {string} [sourceRepository.sourceControlAuthProperties.token] The * access token used to access the source control provider. * @member {string} * [sourceRepository.sourceControlAuthProperties.refreshToken] The refresh * token used to refresh the access token. * @member {string} [sourceRepository.sourceControlAuthProperties.scope] The * scope of the access token. * @member {number} [sourceRepository.sourceControlAuthProperties.expiresIn] * Time in seconds that the token remains valid * @member {array} sourceTriggerEvents The source event corresponding to the * trigger. * @member {string} [status] The current status of build trigger. Possible * values include: 'Disabled', 'Enabled' * @member {string} name The name of the trigger. */ constructor() { } /** * Defines the metadata of SourceTrigger * * @returns {object} metadata of SourceTrigger * */ mapper() { return { required: false, serializedName: 'SourceTrigger', type: { name: 'Composite', className: 'SourceTrigger', modelProperties: { sourceRepository: { required: true, serializedName: 'sourceRepository', type: { name: 'Composite', className: 'SourceProperties' } }, sourceTriggerEvents: { required: true, serializedName: 'sourceTriggerEvents', type: { name: 'Sequence', element: { required: false, serializedName: 'SourceTriggerEventElementType', type: { name: 'String' } } } }, status: { required: false, serializedName: 'status', type: { name: 'String' } }, name: { required: true, serializedName: 'name', type: { name: 'String' } } } } }; } }
JavaScript
class Frame { /** * Create a new frame. * * @param {Object} dims * Dimensions of the new image. * * @param {Number} dims.x * Image width, in pixels. * * @param {Number} dims.y * Image height, in pixels. * * @param {Uint8Array} content * Optional image content to use, in 8bpp linear format. If omitted, a new * empty buffer is allocated and filled with palette index 0. * * @param {Palette} palette * Colour palette to use for this frame only. Omit or specify null to use * the palette from the parent Image instance. Don't specify this property * unless the file format has multiple frames, and supports each frame * having a different palette. * * @param {Object} hotspot * Pixel coordinate within the image that should appear at the location the * image is drawn. If the hotspot is (10,20) then drawing the image at * (100,100) will cause the top-left of the image (0,0) to be drawn at * (90,80), so that the hotspot is at the (100,100) coordinate. * * @param {Number} hotspotX * Horizontal hotspot point, in pixels from the left of the frame. May be * negative. * * @param {Number} hotspotY * Vertical hotspot point, in pixels from the top of the frame. May be * negative. * * @param {Number} offsetX * Number of pixels this frame is moved horizontally relative to the * overall image. This is so a frame in an animation may only update a * small section of the overall image. May NOT be negative or cause the * frame to extend beyond the bounding box defined by the parent image. * Defaults to `0`. * * @param {Number} offsetY * Number of pixels this frame is moved vertically. Same conditions apply * as for `offsetX`. Defaults to `0`. * * @param {Number} postDelay * Number of milliseconds to wait after drawing the image, if the image is * a frame in an animation sequence. Ignored if not part of an animation. * Do not set (or set to `undefined`) unless this is an animation, as the * presence of this value is used to distinguish between tilesets and * animations. */ constructor(params) { this.width = params.width || undefined; this.height = params.height || undefined; this.pixels = params.pixels || new Uint8Array(this.width * this.height); this.palette = params.palette || undefined; this.hotspotX = params.hotspotX || undefined; this.hotspotY = params.hotspotY || undefined; this.offsetX = params.offsetX || 0; this.offsetY = params.offsetY || 0; } /** * Return a new frame identical to the original, but with a duplicated buffer * so that changes to the copy do not affect the original. */ clone() { return new Frame({ width: this.width, height: this.height, pixels: new Uint8Array(this.pixels), palette: this.palette && this.palette.clone(), hotspotX: this.hotspotX, hotspotY: this.hotspotY, offsetX: this.offsetX, offsetY: this.offsetY, }); } }
JavaScript
class SocketConnection { // Statuses start. get createdStatus() { return 'CREATED'; } get connectedStatus() { return 'CONNECTED'; } get expiredStatus() { return 'EXPIRED'; } // Statuses end. get statuses() { const oThis = this; return { '1': oThis.createdStatus, '2': oThis.connectedStatus, '3': oThis.expiredStatus }; } get invertedStatuses() { const oThis = this; invertedStatuses = invertedStatuses || util.invert(oThis.statuses); return invertedStatuses; } /** * Get socket RMQ topic name. * * @param {string} socketIdentifier * * @returns {string} */ getSocketRmqTopic(socketIdentifier) { return 'socket.' + socketIdentifier; } /** * Get socket identifier from topic. * * @param {string} topic * * @returns {string} */ getSocketIdentifierFromTopic(topic) { const topicElements = topic.split('.'); return topicElements[topicElements.length - 1]; } }
JavaScript
class CanvasHandler extends React.Component { constructor(props) { super(props); this.lastImage = ""; this.x = 0; // canvas position in x this.y = 0; // canvas position in y (with scrollbar) this.clickPressed = false; // canvas envent handlers this.handlers = {}; this.headers = null; this.state = { size: { width: 640, height: 360, }, }; this.canvas = React.createRef(); } getHeaders() { return this.headers; } // get the value getValue() { return ""; } setImage(image) { this.lastImage = image; } componentDidMount() { this.ctx = this.canvas.current.getContext("2d"); } setCanvasSize({width, height}) { this.setState((prev) => { if (width) { prev.size.width = width; } if (height) { prev.size.height = height; } }); } repaintCanvas(callbackOnImageLoaded) { var image = new Image(); image.onload = () => callbackOnImageLoaded(); image.src = "data:image/jpg;base64," + this.lastImage; } updateCanvasPosition() { var bounds = this.canvas.current.getBoundingClientRect(); this.x = bounds.left; this.y = bounds.top; } /* render() { return ; }*/ }
JavaScript
class DataRowGenerator { /** * Receives the table data. * Especific the value of your table in db-structure. * * @param dataGen the table data mapped in db-structure * @example * dbStructure = (id) => { * 't_customer' => { 'field' : {type:'...', val: '...'}} //the object of t_customer is what this class expects. * } */ constructor(dataGen){ this.dataGen = dataGen; } /** * Generates your data. * @param extraData object optional - in case you want to add something to the object * @return object * @example * { * simpleResult: { id: 3, name: 'John', ...}, //used as the return of insert.add(...) * completeResult: { id: { column: 'customer_id', val: 'John', type: 'string'}} // used as param of GenericSQLBuilder * } * */ generateData(extraData) { let result = {}; let completeResult = {} for(const prop in this.dataGen) { let value = this.dataGen[prop].val; let type = this.dataGen[prop].type; let column = this.dataGen[prop].column ? this.dataGen[prop].column : prop; if(_.isFunction(value)){ value = value(); } if(_.isObject(extraData) && !_.isUndefined(extraData[prop])) { value = typeof extraData[prop] == 'function' ? extraData[prop]() : extraData[prop]; } result[prop] = value; completeResult[column] = { type, val: value, column } } return { simpleResult: result, completeResult: completeResult } ; } }
JavaScript
class RestHandler extends RequestHandler { constructor(method, path, resolver) { super({ info: { header: `${method} ${path}`, path, method, }, ctx: restContext, resolver, }); this.checkRedundantQueryParameters(); } checkRedundantQueryParameters() { const { method, path } = this.info; if (path instanceof RegExp) { return; } const url = cleanUrl(path); // Bypass request handler URLs that have no redundant characters. if (url === path) { return; } const searchParams = getSearchParams(path); const queryParams = []; searchParams.forEach((_, paramName) => { queryParams.push(paramName); }); devUtils.warn(`\ Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead, and access query parameters in the response resolver function: rest.${method.toLowerCase()}("${url}", (req, res, ctx) => { const query = req.url.searchParams ${queryParams .map((paramName) => `\ const ${paramName} = query.get("${paramName}")`) .join('\n')} })\ `); } parse(request, resolutionContext) { return matchRequestUrl(request.url, this.info.path, resolutionContext === null || resolutionContext === void 0 ? void 0 : resolutionContext.baseUrl); } getPublicRequest(request, parsedResult) { return Object.assign(Object.assign({}, request), { params: parsedResult.params || {} }); } predicate(request, parsedResult) { return (isStringEqual(this.info.method, request.method) && parsedResult.matches); } log(request, response) { const publicUrl = getPublicUrlFromRequest(request); const loggedRequest = prepareRequest(request); const loggedResponse = prepareResponse(response); const statusColor = getStatusCodeColor(response.status); console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit'); console.log('Request', loggedRequest); console.log('Handler:', { mask: this.info.path, resolver: this.resolver, }); console.log('Response', loggedResponse); console.groupEnd(); } }
JavaScript
class SpreadsheetLabelMappingDeleteHistoryHashToken extends SpreadsheetLabelMappingHistoryHashToken { /** * Singleton instance. */ static INSTANCE = new SpreadsheetLabelMappingDeleteHistoryHashToken(); toHistoryHashToken() { return SpreadsheetHistoryHash.DELETE; } labelMappingWidget(widget) { widget.deleteLabelMapping(); } equals(other) { return this === other || (other instanceof SpreadsheetLabelMappingDeleteHistoryHashToken); } }
JavaScript
class Shootout extends Phase { constructor(game, phase, leader, mark, options = { isJob: false }) { super(game, 'Shootout'); this.highNoonPhase = phase; this.options = options; this.leader = leader; this.mark = mark; this.leader.shootoutStatus = ShootoutStatuses.LeaderPosse; this.leaderPlayerName = this.leader.controller.name; this.leaderPosse = new ShootoutPosse(this, this.leaderPlayer, true); if(!this.isJob()) { this.mark.shootoutStatus = ShootoutStatuses.MarkPosse; this.opposingPlayerName = this.mark.controller.name; this.opposingPosse = new ShootoutPosse(this, this.opposingPlayer, false); } this.loserCasualtiesMod = 0; this.jobSuccessful = null; this.headlineUsed = false; this.shootoutLoseWinOrder = []; this.remainingSteps = []; this.moveOptions = {}; this.initialise([ new SimpleStep(this.game, () => this.initialiseLeaderPosse()), new SimpleStep(this.game, () => this.initialiseOpposingPosse()), new SimpleStep(this.game, () => this.gatherPosses()), new SimpleStep(this.game, () => this.breakinAndEnterin()), new SimpleStep(this.game, () => this.beginShootoutRound()) ]); } initialiseLeaderPosse() { this.queueStep(new ShootoutPossePrompt(this.game, this, this.leaderPlayer)); } initialiseOpposingPosse() { if(!this.isJob()) { this.queueStep(new ShootoutPossePrompt(this.game, this, this.opposingPlayer)); } else { let opponent = this.leaderPlayer.getOpponent(); if(this.game.getNumberOfPlayers() < 2) { this.endJob(); } else { this.opposingPlayerName = opponent.name; this.game.queueStep(new ChooseYesNoPrompt(this.game, opponent, { title: 'Do you want to oppose?', onYes: () => { this.opposingPosse = new ShootoutPosse(this, this.opposingPlayer); this.queueStep(new ShootoutPossePrompt(this.game, this, this.opposingPlayer)); }, onNo: () => { this.endJob(); } })); } } this.leaderOpponentOrder = [this.leader.controller.name, this.opposingPlayerName]; } get leaderPlayer() { if(!this.game || !this.leaderPlayerName) { return null; } return this.game.getPlayerByName(this.leaderPlayerName); } get opposingPlayer() { if(!this.game || !this.opposingPlayerName) { return null; } return this.game.getPlayerByName(this.opposingPlayerName); } get shootoutLocation() { return this.game.findLocation(this.mark.gamelocation); } isJob() { return this.options.isJob; } resetForTheRound() { this.winner = null; this.looser = null; this.leaderPlayer.rankModifier = 0; this.leaderPlayer.casualties = 0; this.opposingPlayer.rankModifier = 0; this.opposingPlayer.casualties = 0; } beginShootoutRound() { if(this.checkEndCondition()) { return; } this.game.raiseEvent('onShootoutSlinginLeadStarted'); this.remainingSteps = [ new SimpleStep(this.game, () => this.resetForTheRound()), new SimpleStep(this.game, () => this.shootoutPlays()), new SimpleStep(this.game, () => this.pickYerShooterStep()), new SimpleStep(this.game, () => this.draw()), new SimpleStep(this.game, () => this.game.revealHands()), new SimpleStep(this.game, () => this.resolutionPlays()), new SimpleStep(this.game, () => this.determineWinner()), new SimpleStep(this.game, () => this.casualtiesAndRunOrGun()) ]; this.game.raiseEvent('onBeginShootoutRound'); this.queueStep(new SimpleStep(this.game, () => { if(!this.checkEndCondition()) { if(this.remainingSteps.length !== 0) { let step = this.remainingSteps.shift(); this.queueStep(step); return false; } } else { return true; } })); this.queueStep(new SimpleStep(this, () => this.chamberAnotherRound())); } startPhase() { for(const player of this.game.getPlayers()) { player.phase = this.name; } this.game.raiseEvent('onShootoutPhaseStarted'); let phaseName = this.isJob() ? 'Job' : 'Shootout'; this.game.addAlert('phasestart', phaseName + ' started!'); } endPhase(isCancel = false) { this.game.raiseEvent('onShootoutPhaseFinished', { phase: this.name }); this.game.currentPhase = this.highNoonPhase; var attackingPlayer = this.leaderPlayer; var defendingPlayer = this.opposingPlayer; attackingPlayer.phase = this.highNoonPhase; if(defendingPlayer) { defendingPlayer.phase = this.highNoonPhase; } this.actOnAllParticipants(dude => dude.shootoutStatus = ShootoutStatuses.None); this.game.endShootout(isCancel); if(this.isJob()) { this.options.jobAbility.setResult(this.jobSuccessful, this); this.options.jobAbility.reset(); } let phaseName = this.isJob() ? 'Job' : 'Shootout'; this.game.addAlert('phasestart', phaseName + ' ended!'); } endJob(recordStatus = true) { if(!this.isJob()) { return; } if(recordStatus) { this.recordJobStatus(); } this.actOnLeaderPosse(card => this.sendHome(card, { isCardEffect: false })); } queueStep(step) { this.pipeline.queueStep(step); } getPosseByPlayer(player) { if(player === this.leaderPlayer) { return this.leaderPosse; } if(player === this.opposingPlayer) { return this.opposingPosse; } } isInLeaderPosse(card) { return this.leaderPosse.isInPosse(card); } isInOpposingPosse(card) { return this.opposingPosse.isInPosse(card); } isInShootout(card) { return this.isInLeaderPosse(card) || this.isInOpposingPosse(card); } belongsToLeaderPlayer(dude) { return dude.controller.name === this.leaderPlayerName; } belongsToOpposingPlayer(dude) { return dude.controller.name === this.opposingPlayerName; } checkEndCondition() { return !this.leaderPosse || !this.opposingPosse || this.leaderPosse.isEmpty() || this.opposingPosse.isEmpty(); } getLeaderDrawCount() { return { player: this.leaderPlayer, number: 5 + this.leaderPosse.getStudBonus(), redraw: this.leaderPosse.getDrawBonus() }; } getOpposingDrawCount() { return { player: this.opposingPlayer, number: 5 + this.opposingPosse.getStudBonus(), redraw: this.opposingPosse.getDrawBonus() }; } sendHome(card, options) { this.removeFromPosse(card); return this.game.resolveGameAction(GameActions.sendHome({ card: card, options: options })); } addToPosse(dude) { if(this.belongsToLeaderPlayer(dude)) { this.leaderPosse.addToPosse(dude); } else if(this.belongsToOpposingPlayer(dude)) { this.opposingPosse.addToPosse(dude); } } removeFromPosse(dude) { this.game.raiseEvent('onDudeLeftPosse', { card: dude, shootout: this }, event => { if(event.shootout.belongsToLeaderPlayer(event.card) && event.shootout.leaderPosse) { event.shootout.leaderPosse.removeFromPosse(event.card); } else if(event.shootout.belongsToOpposingPlayer(event.card) && event.shootout.opposingPosse) { event.shootout.opposingPosse.removeFromPosse(event.card); } if(this.jobSuccessful === null) { this.recordJobStatus(); } }); } gatherPosses() { if(!this.checkEndCondition()) { this.actOnAllParticipants(dude => { let dudeMoveOptions = this.moveOptions[dude.uuid] || { moveToPosse: true, needToBoot: true, allowBooted: false }; if(dudeMoveOptions.moveToPosse) { dude.moveToShootoutLocation(dudeMoveOptions); } }); } } shootoutPlays() { this.queueStep(new PlayWindow(this.game, 'shootout plays', 'Make Shootout plays')); } pickYerShooterStep() { this.queueStep(new PickYerShooterPrompt(this.game, this.leaderOpponentOrder)); } pickShooter(dude) { if(this.isInLeaderPosse(dude)) { this.leaderPosse.pickShooter(dude); return; } if(this.isInOpposingPosse(dude)) { this.opposingPosse.pickShooter(dude); } } actOnLeaderPosse(action, exception) { if(this.leaderPosse) { this.leaderPosse.actOnPosse(action, exception); } } actOnOpposingPosse(action, exception) { if(this.opposingPosse) { this.opposingPosse.actOnPosse(action, exception); } } actOnPlayerPosse(player, action, exception) { if(this.leaderPlayer === player) { this.actOnLeaderPosse(action, exception); } else if(this.opposingPlayer === player) { this.actOnOpposingPosse(action, exception); } } actOnAllParticipants(action) { this.actOnLeaderPosse(action); this.actOnOpposingPosse(action); } breakinAndEnterin() { if(this.checkEndCondition() || this.shootoutLocation.isTownSquare()) { return; } let locationCard = this.shootoutLocation.locationCard; if(locationCard && (locationCard.getType() === 'outfit' || locationCard.hasKeyword('private'))) { if(locationCard.owner !== this.leaderPlayer) { this.actOnLeaderPosse(dude => dude.increaseBounty(), dude => dude.shootoutOptions.contains('doesNotGetBountyOnJoin')); } else { this.actOnOpposingPosse(dude => dude.increaseBounty(), dude => dude.shootoutOptions.contains('doesNotGetBountyOnJoin')); } } } draw() { this.queueStep(new DrawHandPrompt(this.game, [this.getLeaderDrawCount(), this.getOpposingDrawCount()])); } resolutionPlays() { this.queueStep(new PlayWindow(this.game, 'shootout resolution', 'Make Resolution plays')); } determineWinner() { this.shootoutLoseWinOrder = []; let opposingRank = this.opposingPlayer.getTotalRank(); let leaderRank = this.leaderPlayer.getTotalRank(); this.winner = this.opposingPlayer; this.loser = this.leaderPlayer; if(leaderRank === opposingRank) { let tiebreakResult = this.game.resolveTiebreaker(this.leaderPlayer, this.opposingPlayer); this.leaderPlayer.casualties = this.opposingPlayer.casualties = 1; if(tiebreakResult.decision === 'exact tie') { this.game.addMessage('Shootout ended in an exact tie, there is no winner or loser.'); this.shootoutLoseWinOrder = [this.leaderPlayer.name, this.opposingPlayer.name]; this.winner = null; this.loser = null; return; } this.winner = tiebreakResult.winner; this.loser = tiebreakResult.loser; this.game.addMessage('Shootout ended in a tie, but {0} wins on {1}.', this.winner, tiebreakResult.decision); } else { if(leaderRank > opposingRank) { this.winner = this.leaderPlayer; this.loser = this.opposingPlayer; } this.loser.casualties = Math.abs(leaderRank - opposingRank); this.game.addMessage('{0} is the winner of this shootout by {1} ranks.', this.winner, Math.abs(leaderRank - opposingRank)); } this.loser.casualties += this.loserCasualtiesMod; this.shootoutLoseWinOrder = [this.loser.name, this.winner.name]; } casualtiesAndRunOrGun() { this.queueStep(new TakeYerLumpsPrompt(this.game, this.shootoutLoseWinOrder)); this.queueStep(new RunOrGunPrompt(this.game, this.shootoutLoseWinOrder)); } chamberAnotherRound() { this.queueStep(new SimpleStep(this.game, () => this.game.discardDrawHands())); if(!this.checkEndCondition()) { this.game.addAlert('info', 'Both players Chamber another round and go to next round of shootout.'); this.queueStep(new SimpleStep(this.game, () => this.beginShootoutRound())); } else { this.endJob(false); } } addMoveOptions(dude, options) { this.moveOptions[dude.uuid] = options; } recordJobStatus() { if(!this.isJob()) { return; } if(!this.opposingPosse || this.opposingPosse.isEmpty()) { this.jobSuccessful = true; } if(!this.leaderPosse || this.leaderPosse.isEmpty()) { this.jobSuccessful = false; } } getGameElementType() { return 'shootout'; } }
JavaScript
class c{constructor(t,e){this.name=t,this.container=e,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(t){const n=this.normalizeInstanceIdentifier(t);if(!this.instancesDeferred.has(n)){const t=new e;if(this.instancesDeferred.set(n,t),this.isInitialized(n)||this.shouldAutoInitialize())try{const e=this.getOrInitializeService({instanceIdentifier:n});e&&t.resolve(e)}catch(t){}}return this.instancesDeferred.get(n).promise}getImmediate(t){var e;const n=this.normalizeInstanceIdentifier(null==t?void 0:t.identifier),r=null!==(e=null==t?void 0:t.optional)&&void 0!==e&&e;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(t){if(r)return null;throw t}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,this.shouldAutoInitialize()){if(function(t){return"EAGER"===t.instantiationMode} /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */(t))try{this.getOrInitializeService({instanceIdentifier:a})}catch(t){}for(const[t,e]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(t);try{const t=this.getOrInitializeService({instanceIdentifier:n});e.resolve(t)}catch(t){}}}}clearInstance(t="[DEFAULT]"){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter((t=>"INTERNAL"in t)).map((t=>t.INTERNAL.delete())),...t.filter((t=>"_delete"in t)).map((t=>t._delete()))])}isComponentSet(){return null!=this.component}isInitialized(t="[DEFAULT]"){return this.instances.has(t)}getOptions(t="[DEFAULT]"){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,n=this.normalizeInstanceIdentifier(t.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:e});for(const[t,e]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(t)&&e.resolve(r)}return r}onInit(t,e){var n;const r=this.normalizeInstanceIdentifier(e),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(t),this.onInitCallbacks.set(r,i);const o=this.instances.get(r);return o&&t(o,r),()=>{i.delete(t)}}invokeOnInitCallbacks(t,e){const n=this.onInitCallbacks.get(e);if(n)for(const r of n)try{r(t,e)}catch(t){}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let n=this.instances.get(t);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=t,r===a?void 0:r),options:e}),this.instances.set(t,n),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(n,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,n)}catch(t){}var r;return n||null}normalizeInstanceIdentifier(t="[DEFAULT]"){return this.component?this.component.multipleInstances?t:a:t}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}
JavaScript
class T{constructor(t){this.container=t}getPlatformInfoString(){return this.container.getProviders().map((t=>{if(function(t){const e=t.getComponent();return"VERSION"===(null==e?void 0:e.type)} /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */(t)){const e=t.getImmediate();return`${e.library}/${e.version}`}return null})).filter((t=>t)).join(" ")}}
JavaScript
class Container extends React.Component { constructor(props) { super(props); this.composeState = this.composeState.bind(this); this.updateInput = this.updateInput.bind(this); this.selectSource = this.selectSource.bind(this); this.selectDestination = this.selectDestination.bind(this); this.state = { amount: 1.0, displayedAmount: 1.0, srcCurrency: undefined, dstCurrency: undefined }; } updateInput(newAmount) { const _this = this; //console.log('newAmount', newAmount); this.composeState(newAmount,this.state.srcCurrency, this.state.dstCurrency) .then((s) => { _this.setState(s); }) } selectSource(target) { const _this = this; //console.log('selectSrc', target); this.composeState(this.state.amount,target, this.state.dstCurrency) .then((s) => { _this.setState(s); }); } selectDestination(target) { const _this = this; //console.log('selectDst', target); this.composeState(this.state.amount,this.state.srcCurrency, target) .then((s) => { _this.setState(s); }) } composeState(amount, src, dst) { if (src && dst) { return fetchCurrency(src.currencyCode, dst.currencyCode) .then((values) => { let srcAmountInEur = values.src * amount; let convertedAmount = values.dst * srcAmountInEur; let displayAmount = src.symbol + ' ' + Number(amount).toLocaleString('en'); let displayConverted = dst.symbol + ' ' + Number(convertedAmount).toLocaleString('en'); //console.log("convertedAmount, displayConverted", convertedAmount, displayConverted); let results = { amount: amount, convertedAmount : convertedAmount, displayedAmount: displayAmount, displayConverted: displayConverted, srcCurrency: src, dstCurrency: dst }; return results; }); } else { return Promise.resolve({ amount: amount, srcCurrency: src, dstCurrency: dst } ); } } render() { var amount = this.state.amount; var displayConverted = this.state.displayConverted; var srcCurrency = this.state.srcCurrency; // TODO improve the CSS layout. Add space between elements. // TODO Improve look and feel. Improve instructions. // TODO Select some countries to be at the top of the list. Like CAD, USD, etc. return <div> <div className="Q1"> <header className="Q1-header"> <h1 className="Q1-title">Currencies</h1> </header> <p className="Q1-intro"> Ready to get currency exchange rates? Select the starting and ending country and enter an amount. </p> </div> <Amount amount={amount} srcCurrency={srcCurrency} callbackFromParent={this.updateInput}/> <AmountOutput amount={displayConverted} srcCurrency={srcCurrency}/> <CountryList id="src" title="Convert From" countryCodes={this.props.countryCodes} callbackFromParent={this.selectSource}/> <CountryList id="dst" title="Convert To" countryCodes={this.props.countryCodes} callbackFromParent={this.selectDestination}/> </div> } }
JavaScript
class DeliverymanDeliveryController { async index(req, res) { // buscando id do entregador / looking for deliveryman man id const { id: deliveryman_id } = req.params; // buscando id da entrega nas query / looking for delivery id in the query const { delivered, page = 1 } = req.query; const deliveryman = await Deliveryman.findByPk(deliveryman_id, { attributes: ['id', 'name'], include: [ { model: File_avatar, as: 'avatar', attributes: ['id', 'path', 'url'], }, ], }); if (!deliveryman) { return res .status(400) .json({ Erro: 'Entregador não localizado, verifique o ID informado!' }); } // se existir a query delivered e for igual a true, só vai trazer entregas realizadas // if there is a query delivered and it is equal to true, it will only bring deliveries made if (delivered && delivered === 'true') { const deliveries = await Delivery.findAll({ where: { deliveryman_id, signature_id: { [Op.not]: null }, canceled_at: null, }, order: ['id'], limit: 5, offset: (page - 1) * 5, attributes: [ // pegando os dados que queremos trabalhar da tabela deliveryman // getting the data we want to work with from the deliveryman table 'id', 'deliveryman_id', 'product', 'status', 'start_date', 'end_date', 'canceled_at', ], include: [ { model: File_signature, as: 'signature', attributes: ['id', 'path', 'url'], }, { model: Recipient, as: 'recipient', paranoid: false, attributes: [ 'id', 'name', 'street', 'number', 'city', 'uf', 'zip_code', ], }, ], }); const deliverymanDeliveries = []; deliverymanDeliveries.push(deliveryman); deliverymanDeliveries.push(deliveries); return res.json(deliverymanDeliveries); } // trazendo para entregador todas entregas ainda não finalizadas // bringing to delivery person all deliveries not yet completed const deliveries = await Delivery.findAll({ where: { deliveryman_id, signature_id: null, canceled_at: null, }, order: ['id'], limit: 5, offset: (page - 1) * 5, attributes: [ 'id', 'deliveryman_id', 'product', 'status', 'start_date', 'end_date', 'canceled_at', ], include: [ { model: File_signature, as: 'signature', attributes: ['id', 'path', 'url'], }, { model: Recipient, as: 'recipient', paranoid: false, attributes: [ 'id', 'name', 'street', 'number', 'city', 'uf', 'zip_code', ], }, ], }); const deliverymanDeliveries = []; deliverymanDeliveries.push(deliveryman); deliverymanDeliveries.push(deliveries); return res.json(deliverymanDeliveries); } // método atualizar entrega para status retirado e informando a data de retirada // update delivery method to withdrawn status and informing the withdrawal date async update(req, res) { const schema = Yup.object().shape({ id: Yup.number().required(), start_date: Yup.date().required(), }); if (!(await schema.isValid(req.body))) { return res.status(400).json({ Erro: 'Erro na validação!' }); } // buscando do body o id da entrega e a data inicial // searching from the body the delivery id and the start date const { id: delivery_id, start_date } = req.body; // buscando o id do entregador do params // fetching the delivery id from params const { id: deliveryman_id } = req.params; const deliveryman = await Deliveryman.findByPk(deliveryman_id); // verificando se o deliveryman existe // checking if deliveryman exists if (!deliveryman) { return res .status(400) .json({ Erro: 'Entregador não localizado, verifique o ID informado!' }); } // ajustando o formato das datas / adjusting date format const startDateISO = startOfHour(parseISO(start_date)); const delivery = await Delivery.findByPk(delivery_id, { attributes: [ 'id', 'product', 'status', 'start_date', 'end_date', 'canceled_at', 'deleted_at', ], paranoid: false, include: [ { model: File_signature, as: 'signature', attributes: ['id', 'path', 'url'], }, { model: Deliveryman, as: 'deliveryman', attributes: ['id', 'name'], include: [ { model: File_avatar, as: 'avatar', attributes: ['id', 'path', 'url'], }, ], }, { model: Recipient, as: 'recipient', paranoid: true, attributes: [ 'id', 'name', 'street', 'number', 'city', 'uf', 'zip_code', ], }, ], }); // Verificar se a a entrega existe / Check if delivery exists if (!delivery) { return res .status(400) .json({ Erro: 'Entrega não localizada, verifique o ID!' }); } // verificando se a entrega esta cadastrada para o entregador informado // checking if the delivery is registered for the informed delivery person // eslint-disable-next-line eqeqeq if (delivery.deliveryman.id != deliveryman_id) { return res.status(400).json({ Erro: 'Entrega não cadastrada para o ID do entregador informado!', }); } // verificando se entrega já foi finalizada // checking if delivery has already been completed if (delivery.status === 'Entregue' && delivery.end_date != null) { return res.status(400).json({ Erro: 'Entrega já finalizadas!' }); } // verificando se entrega foi cancelado // checking if delivery has been canceled if ( delivery.status === 'Cancelado' && delivery.canceled_at != null && delivery.deleted_at != null ) { return res.status(400).json({ Erro: 'Entrega canceladas, precisam ser postadas para retirada!', }); } // verificando se a retirada já foi realizado / checking if the withdrawal has already been carried out if (delivery.status === 'Retirado' && delivery.start_date != null) { return res.status(400).json({ Erro: 'Entrega já retirada!' }); } // Verificando se o entregador já retirou o máximo permitido // Checking if the delivery person has already withdrawn the maximum allowed const { count } = await Delivery.findAndCountAll({ where: { deliveryman_id, status: 'Retirado', signature_id: null, }, }); if (count === 5) { return res.status(400).json({ Erro: 'Cada entregador pode retirar no máximo de 5 entregas!', }); } // verificando se a hora informada esta dentro do horarios estipulados para retirada // checking if the time informed is within the stipulated hours for withdrawal if ( isBefore(startDateISO, setHours(startDateISO, 7)) || isAfter(startDateISO, setHours(startDateISO, 17)) ) { return res.status(400).json({ Erro: 'Informe uma data de retirada, entre as 08:00 até as 19:59!', }); } await delivery.update({ status: 'Retirado', start_date: startDateISO, }); return res.json([{ Info: 'Entrega retirada!' }, delivery]); } }
JavaScript
class RoutingType extends EventEmitter { constructor(obj) { super(); this.route = _.defaults(obj.route, {value: null, extensions: {}}); this.config = obj.config; } getRoute() { return this.route; } getPermalinks() { return false; } getType() { return this.config.type; } getFilter() { return this.config.options && this.config.options.filter; } toString() { return `Type: ${this.getType()}, Route: ${this.getRoute().value}`; } }
JavaScript
class TableOfContents extends BaseStateElement { static get properties() { return { opened: {type: Boolean, reflect: true}, }; } constructor() { super(); this.scrollSpy = this.scrollSpy.bind(this); this.tocActiveClass = 'w-toc__active'; this.tocBorderClass = 'w-toc__border'; this.tocVisibleClass = 'w-toc__visible'; } connectedCallback() { // This sets initial global state before subscribing to the store. // If we didn't do this then `this.opened` would always be set to false // because onStateChanged runs synchronously after we call // super.connectedCallback(); if (this.hasAttribute('opened')) { openToC(); } super.connectedCallback(); this.tocHTML = this.innerHTML; this.articleContent = this.closest('main'); if (!this.articleContent) { console.warn(`Article container not found.`); return; } this.headings = this.articleContent.querySelectorAll( 'h1[id], h2[id], h3[id]', ); this.observer = new IntersectionObserver(this.scrollSpy, { rootMargin: '0px 0px -80% 0px', }); this.headings.forEach((heading) => this.observer.observe(heading)); } render() { const content = /** @type TemplateStringsArray */ ( /** @type ReadonlyArray<string> */ ([this.tocHTML]) ); return html` <div class="w-toc__label"> <span>In this article</span> <button class="w-button w-button--secondary w-button--icon" data-icon="close" aria-close="Close Table of Contents" @click="${closeToC}" ></button> </div> <div class="w-toc__content"> ${html(content)} </div> `; } disconnectedCallback() { super.disconnectedCallback(); closeToC(); this.observer.disconnect(); } onStateChanged({isTocOpened}) { this.opened = isTocOpened; } scrollSpy(headings) { const links = new Map( [...this.querySelectorAll('a')].map((l) => [l.getAttribute('href'), l]), ); for (const heading of headings) { const href = `#${heading.target.getAttribute('id')}`; const link = links.get(href); if (link) { if (heading.intersectionRatio > 0) { link.classList.add(this.tocVisibleClass); this.previouslyActiveHeading = heading.target.getAttribute('id'); } else { link.classList.remove(this.tocVisibleClass); } } const firstVisibleLink = this.querySelector(`.${this.tocVisibleClass}`); links.forEach((link) => { link.classList.remove(this.tocActiveClass, this.tocVisibleClass); link.parentElement.classList.remove(this.tocBorderClass); }); if (firstVisibleLink) { firstVisibleLink.classList.add(this.tocActiveClass); firstVisibleLink.parentElement.classList.add(this.tocBorderClass); } if (!firstVisibleLink && this.previouslyActiveHeading) { const last = this.querySelector( `a[href="#${this.previouslyActiveHeading}"]`, ); last.classList.add(this.tocActiveClass); last.parentElement.classList.add(this.tocBorderClass); } } } }
JavaScript
class VisibleLicense { /** * Constructor. * * @param {array} uiRights * @param {object} right * @param {int} index */ constructor(uiRights, right, index) { this.index = index; this.type = right.id ? 'standard' : 'custom'; this.key = right.id || right.title; this.initial = this.type === 'custom' ? right : null; let uiRight = _find( uiRights, right.id ? (o) => o.id === right.id : (o) => o.title === right.title ) || {}; this.description = uiRight.description_l10n || right.description || ""; this.title = uiRight.title_l10n || right.title || ""; this.link = ( uiRight.props && uiRight.props.url || uiRight.link || right.props && right.props.url || right.link || "" ); } }
JavaScript
class Sandbox { constructor() { // Wrapper for boxed `Shovel` this._shovel = shovelNew(); } /** * Evaluate arbitrary source code. */ eval(source, callback) { return shovelEval.call(this._shovel, source, function (err, res) { try { callback.call(undefined, err, res); } catch (e) { console.error("Uncaught %O", e); throw e; } }); } }
JavaScript
class InboundNatRule extends models['SubResource'] { /** * Create a InboundNatRule. * @member {object} [frontendIPConfiguration] A reference to frontend IP * addresses. * @member {string} [frontendIPConfiguration.id] Resource ID. * @member {object} [backendIPConfiguration] A reference to a private IP * address defined on a network interface of a VM. Traffic sent to the * frontend port of each of the frontend IP configurations is forwarded to * the backend IP. * @member {array} * [backendIPConfiguration.applicationGatewayBackendAddressPools] The * reference of ApplicationGatewayBackendAddressPool resource. * @member {array} [backendIPConfiguration.loadBalancerBackendAddressPools] * The reference of LoadBalancerBackendAddressPool resource. * @member {array} [backendIPConfiguration.loadBalancerInboundNatRules] A * list of references of LoadBalancerInboundNatRules. * @member {string} [backendIPConfiguration.privateIPAddress] Private IP * address of the IP configuration. * @member {string} [backendIPConfiguration.privateIPAllocationMethod] * Defines how a private IP address is assigned. Possible values are: * 'Static' and 'Dynamic'. Possible values include: 'Static', 'Dynamic' * @member {string} [backendIPConfiguration.privateIPAddressVersion] * Available from Api-Version 2016-03-30 onwards, it represents whether the * specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. * Possible values are: 'IPv4' and 'IPv6'. Possible values include: 'IPv4', * 'IPv6' * @member {object} [backendIPConfiguration.subnet] Subnet bound to the IP * configuration. * @member {string} [backendIPConfiguration.subnet.addressPrefix] The address * prefix for the subnet. * @member {object} [backendIPConfiguration.subnet.networkSecurityGroup] The * reference of the NetworkSecurityGroup resource. * @member {array} * [backendIPConfiguration.subnet.networkSecurityGroup.securityRules] A * collection of security rules of the network security group. * @member {array} * [backendIPConfiguration.subnet.networkSecurityGroup.defaultSecurityRules] * The default security rules of network security group. * @member {array} * [backendIPConfiguration.subnet.networkSecurityGroup.networkInterfaces] A * collection of references to network interfaces. * @member {array} * [backendIPConfiguration.subnet.networkSecurityGroup.subnets] A collection * of references to subnets. * @member {string} * [backendIPConfiguration.subnet.networkSecurityGroup.resourceGuid] The * resource GUID property of the network security group resource. * @member {string} * [backendIPConfiguration.subnet.networkSecurityGroup.provisioningState] The * provisioning state of the public IP resource. Possible values are: * 'Updating', 'Deleting', and 'Failed'. * @member {string} [backendIPConfiguration.subnet.networkSecurityGroup.etag] * A unique read-only string that changes whenever the resource is updated. * @member {object} [backendIPConfiguration.subnet.routeTable] The reference * of the RouteTable resource. * @member {array} [backendIPConfiguration.subnet.routeTable.routes] * Collection of routes contained within a route table. * @member {array} [backendIPConfiguration.subnet.routeTable.subnets] A * collection of references to subnets. * @member {boolean} * [backendIPConfiguration.subnet.routeTable.disableBgpRoutePropagation] Gets * or sets whether to disable the routes learned by BGP on that route table. * True means disable. * @member {string} * [backendIPConfiguration.subnet.routeTable.provisioningState] The * provisioning state of the resource. Possible values are: 'Updating', * 'Deleting', and 'Failed'. * @member {string} [backendIPConfiguration.subnet.routeTable.etag] Gets a * unique read-only string that changes whenever the resource is updated. * @member {array} [backendIPConfiguration.subnet.serviceEndpoints] An array * of service endpoints. * @member {array} [backendIPConfiguration.subnet.ipConfigurations] Gets an * array of references to the network interface IP configurations using * subnet. * @member {array} [backendIPConfiguration.subnet.resourceNavigationLinks] * Gets an array of references to the external resources using subnet. * @member {string} [backendIPConfiguration.subnet.provisioningState] The * provisioning state of the resource. * @member {string} [backendIPConfiguration.subnet.name] The name of the * resource that is unique within a resource group. This name can be used to * access the resource. * @member {string} [backendIPConfiguration.subnet.etag] A unique read-only * string that changes whenever the resource is updated. * @member {boolean} [backendIPConfiguration.primary] Gets whether this is a * primary customer address on the network interface. * @member {object} [backendIPConfiguration.publicIPAddress] Public IP * address bound to the IP configuration. * @member {object} [backendIPConfiguration.publicIPAddress.sku] The public * IP address SKU. * @member {string} [backendIPConfiguration.publicIPAddress.sku.name] Name of * a public IP address SKU. Possible values include: 'Basic', 'Standard' * @member {string} * [backendIPConfiguration.publicIPAddress.publicIPAllocationMethod] The * public IP allocation method. Possible values are: 'Static' and 'Dynamic'. * Possible values include: 'Static', 'Dynamic' * @member {string} * [backendIPConfiguration.publicIPAddress.publicIPAddressVersion] The public * IP address version. Possible values are: 'IPv4' and 'IPv6'. Possible * values include: 'IPv4', 'IPv6' * @member {object} [backendIPConfiguration.publicIPAddress.ipConfiguration] * The IP configuration associated with the public IP address. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.privateIPAddress] * The private IP address of the IP configuration. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.privateIPAllocationMethod] * The private IP allocation method. Possible values are 'Static' and * 'Dynamic'. Possible values include: 'Static', 'Dynamic' * @member {object} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet] The * reference of the subnet resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.addressPrefix] * The address prefix for the subnet. * @member {object} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup] * The reference of the NetworkSecurityGroup resource. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.securityRules] * A collection of security rules of the network security group. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.defaultSecurityRules] * The default security rules of network security group. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.networkInterfaces] * A collection of references to network interfaces. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.subnets] * A collection of references to subnets. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.resourceGuid] * The resource GUID property of the network security group resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.provisioningState] * The provisioning state of the public IP resource. Possible values are: * 'Updating', 'Deleting', and 'Failed'. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.networkSecurityGroup.etag] * A unique read-only string that changes whenever the resource is updated. * @member {object} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable] * The reference of the RouteTable resource. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable.routes] * Collection of routes contained within a route table. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable.subnets] * A collection of references to subnets. * @member {boolean} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable.disableBgpRoutePropagation] * Gets or sets whether to disable the routes learned by BGP on that route * table. True means disable. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable.provisioningState] * The provisioning state of the resource. Possible values are: 'Updating', * 'Deleting', and 'Failed'. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.routeTable.etag] * Gets a unique read-only string that changes whenever the resource is * updated. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.serviceEndpoints] * An array of service endpoints. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.ipConfigurations] * Gets an array of references to the network interface IP configurations * using subnet. * @member {array} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.resourceNavigationLinks] * Gets an array of references to the external resources using subnet. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.provisioningState] * The provisioning state of the resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.name] The * name of the resource that is unique within a resource group. This name can * be used to access the resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.subnet.etag] A * unique read-only string that changes whenever the resource is updated. * @member {object} * [backendIPConfiguration.publicIPAddress.ipConfiguration.publicIPAddress] * The reference of the public IP resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.provisioningState] * Gets the provisioning state of the public IP resource. Possible values * are: 'Updating', 'Deleting', and 'Failed'. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.name] The name of * the resource that is unique within a resource group. This name can be used * to access the resource. * @member {string} * [backendIPConfiguration.publicIPAddress.ipConfiguration.etag] A unique * read-only string that changes whenever the resource is updated. * @member {object} [backendIPConfiguration.publicIPAddress.dnsSettings] The * FQDN of the DNS record associated with the public IP address. * @member {string} * [backendIPConfiguration.publicIPAddress.dnsSettings.domainNameLabel] Gets * or sets the Domain name label.The concatenation of the domain name label * and the regionalized DNS zone make up the fully qualified domain name * associated with the public IP address. If a domain name label is * specified, an A DNS record is created for the public IP in the Microsoft * Azure DNS system. * @member {string} [backendIPConfiguration.publicIPAddress.dnsSettings.fqdn] * Gets the FQDN, Fully qualified domain name of the A DNS record associated * with the public IP. This is the concatenation of the domainNameLabel and * the regionalized DNS zone. * @member {string} * [backendIPConfiguration.publicIPAddress.dnsSettings.reverseFqdn] Gets or * Sets the Reverse FQDN. A user-visible, fully qualified domain name that * resolves to this public IP address. If the reverseFqdn is specified, then * a PTR DNS record is created pointing from the IP address in the * in-addr.arpa domain to the reverse FQDN. * @member {string} [backendIPConfiguration.publicIPAddress.ipAddress] The IP * address associated with the public IP address resource. * @member {number} * [backendIPConfiguration.publicIPAddress.idleTimeoutInMinutes] The idle * timeout of the public IP address. * @member {string} [backendIPConfiguration.publicIPAddress.resourceGuid] The * resource GUID property of the public IP resource. * @member {string} * [backendIPConfiguration.publicIPAddress.provisioningState] The * provisioning state of the PublicIP resource. Possible values are: * 'Updating', 'Deleting', and 'Failed'. * @member {string} [backendIPConfiguration.publicIPAddress.etag] A unique * read-only string that changes whenever the resource is updated. * @member {array} [backendIPConfiguration.publicIPAddress.zones] A list of * availability zones denoting the IP allocated for the resource needs to * come from. * @member {array} [backendIPConfiguration.applicationSecurityGroups] * Application security groups in which the IP configuration is included. * @member {string} [backendIPConfiguration.provisioningState] The * provisioning state of the network interface IP configuration. Possible * values are: 'Updating', 'Deleting', and 'Failed'. * @member {string} [backendIPConfiguration.name] The name of the resource * that is unique within a resource group. This name can be used to access * the resource. * @member {string} [backendIPConfiguration.etag] A unique read-only string * that changes whenever the resource is updated. * @member {string} [protocol] Possible values include: 'Udp', 'Tcp', 'All' * @member {number} [frontendPort] The port for the external endpoint. Port * numbers for each rule must be unique within the Load Balancer. Acceptable * values range from 1 to 65534. * @member {number} [backendPort] The port used for the internal endpoint. * Acceptable values range from 1 to 65535. * @member {number} [idleTimeoutInMinutes] The timeout for the TCP idle * connection. The value can be set between 4 and 30 minutes. The default * value is 4 minutes. This element is only used when the protocol is set to * TCP. * @member {boolean} [enableFloatingIP] Configures a virtual machine's * endpoint for the floating IP capability required to configure a SQL * AlwaysOn Availability Group. This setting is required when using the SQL * AlwaysOn Availability Groups in SQL server. This setting can't be changed * after you create the endpoint. * @member {string} [provisioningState] Gets the provisioning state of the * public IP resource. Possible values are: 'Updating', 'Deleting', and * 'Failed'. * @member {string} [name] Gets name of the resource that is unique within a * resource group. This name can be used to access the resource. * @member {string} [etag] A unique read-only string that changes whenever * the resource is updated. */ constructor() { super(); } /** * Defines the metadata of InboundNatRule * * @returns {object} metadata of InboundNatRule * */ mapper() { return { required: false, serializedName: 'InboundNatRule', type: { name: 'Composite', className: 'InboundNatRule', modelProperties: { id: { required: false, serializedName: 'id', type: { name: 'String' } }, frontendIPConfiguration: { required: false, serializedName: 'properties.frontendIPConfiguration', type: { name: 'Composite', className: 'SubResource' } }, backendIPConfiguration: { required: false, readOnly: true, serializedName: 'properties.backendIPConfiguration', type: { name: 'Composite', className: 'NetworkInterfaceIPConfiguration' } }, protocol: { required: false, serializedName: 'properties.protocol', type: { name: 'String' } }, frontendPort: { required: false, serializedName: 'properties.frontendPort', type: { name: 'Number' } }, backendPort: { required: false, serializedName: 'properties.backendPort', type: { name: 'Number' } }, idleTimeoutInMinutes: { required: false, serializedName: 'properties.idleTimeoutInMinutes', type: { name: 'Number' } }, enableFloatingIP: { required: false, serializedName: 'properties.enableFloatingIP', type: { name: 'Boolean' } }, provisioningState: { required: false, serializedName: 'properties.provisioningState', type: { name: 'String' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, etag: { required: false, serializedName: 'etag', type: { name: 'String' } } } } }; } }
JavaScript
class Input extends UI5Element { static get metadata() { return metadata; } static get render() { return litRender; } static get template() { return InputTemplate; } static get staticAreaTemplate() { return InputPopoverTemplate; } static get styles() { return styles; } static get staticAreaStyles() { return [ResponsivePopoverCommonCss, ValueStateMessageCss, SuggestionsCss]; } constructor() { super(); // Indicates if there is selected suggestionItem. this.hasSuggestionItemSelected = false; // Represents the value before user moves selection from suggestion item to another // and its value is updated after each move. // Note: Used to register and fire "input" event upon [SPACE] or [ENTER]. // Note: The property "value" is updated upon selection move and can`t be used. this.valueBeforeItemSelection = ""; // Represents the value before user moves selection between the suggestion items // and its value remains the same when the user navigates up or down the list. // Note: Used to cancel selection upon [ESC]. this.valueBeforeItemPreview = ""; // Indicates if the user selection has been canceled with [ESC]. this.suggestionSelectionCanceled = false; // Indicates if the change event has already been fired this._changeFiredValue = null; // tracks the value between focus in and focus out to detect that change event should be fired. this.previousValue = undefined; // Indicates, if the component is rendering for first time. this.firstRendering = true; // The value that should be highlited. this.highlightValue = ""; // The last value confirmed by the user with "ENTER" this.lastConfirmedValue = ""; // Indicates, if the user pressed the BACKSPACE key. this._backspaceKeyDown = false; // all sementic events this.EVENT_CHANGE = "change"; this.EVENT_INPUT = "input"; this.EVENT_SUGGESTION_ITEM_SELECT = "suggestion-item-select"; // all user interactions this.ACTION_ENTER = "enter"; this.ACTION_USER_INPUT = "input"; // Suggestions array initialization this.suggestionsTexts = []; this._handleResizeBound = this._handleResize.bind(this); } onEnterDOM() { ResizeHandler.register(this, this._handleResizeBound); } onExitDOM() { ResizeHandler.deregister(this, this._handleResizeBound); } onBeforeRendering() { if (this.showSuggestions) { this.enableSuggestions(); this.suggestionsTexts = this.Suggestions.defaultSlotProperties(this.highlightValue); } this.open = this.open && (!!this.suggestionItems.length || this._isPhone); const FormSupport = getFeature("FormSupport"); if (FormSupport) { FormSupport.syncNativeHiddenInput(this); } else if (this.name) { console.warn(`In order for the "name" property to have effect, you should also: import "@ui5/webcomponents/dist/features/InputElementsFormSupport.js";`); // eslint-disable-line } } async onAfterRendering() { if (this.Suggestions) { this.Suggestions.toggle(this.open, { preventFocusRestore: true, }); this._listWidth = await this.Suggestions._getListWidth(); } if (this.shouldDisplayOnlyValueStateMessage) { this.openPopover(); } else { this.closePopover(); } } _onkeydown(event) { if (isUp(event)) { return this._handleUp(event); } if (isDown(event)) { return this._handleDown(event); } if (isSpace(event)) { return this._handleSpace(event); } if (isTabNext(event)) { return this._handleTab(event); } if (isEnter(event)) { return this._handleEnter(event); } if (isPageUp(event)) { return this._handlePageUp(event); } if (isPageDown(event)) { return this._handlePageDown(event); } if (isHome(event)) { return this._handleHome(event); } if (isEnd(event)) { return this._handleEnd(event); } if (isEscape(event)) { return this._handleEscape(event); } if (isBackSpace(event)) { this._backspaceKeyDown = true; this._selectedText = window.getSelection().toString(); } if (this.showSuggestions) { this._clearPopoverFocusAndSelection(); } this._keyDown = true; } _onkeyup(event) { // The native Delete event does not update the value property "on time". So, the (native) change event is always fired with the old value if (isDelete(event)) { this.value = event.target.value; } this._keyDown = false; this._backspaceKeyDown = false; } /* Event handling */ _handleUp(event) { if (this.Suggestions && this.Suggestions.isOpened()) { this.Suggestions.onUp(event); } } _handleDown(event) { if (this.Suggestions && this.Suggestions.isOpened()) { this.Suggestions.onDown(event); } } _handleSpace(event) { if (this.Suggestions) { this.Suggestions.onSpace(event); } } _handleTab(event) { if (this.Suggestions && (this.previousValue !== this.value)) { this.Suggestions.onTab(event); } } _handleEnter(event) { const itemPressed = !!(this.Suggestions && this.Suggestions.onEnter(event)); if (!itemPressed) { this.fireEventByAction(this.ACTION_ENTER); this.lastConfirmedValue = this.value; return; } this.focused = true; } _handlePageUp(event) { if (this._isSuggestionsFocused) { this.Suggestions.onPageUp(event); } else { event.preventDefault(); } } _handlePageDown(event) { if (this._isSuggestionsFocused) { this.Suggestions.onPageDown(event); } else { event.preventDefault(); } } _handleHome(event) { if (this._isSuggestionsFocused) { this.Suggestions.onHome(event); } } _handleEnd(event) { if (this._isSuggestionsFocused) { this.Suggestions.onEnd(event); } } _handleEscape() { const hasSuggestions = this.showSuggestions && !!this.Suggestions; const isOpen = hasSuggestions && this.open; if (!isOpen) { this.value = this.lastConfirmedValue ? this.lastConfirmedValue : this.previousValue; return; } if (hasSuggestions && isOpen && this.Suggestions._isItemOnTarget()) { // Restore the value. this.value = this.valueBeforeItemPreview; // Mark that the selection has been canceled, so the popover can close // and not reopen, due to receiving focus. this.suggestionSelectionCanceled = true; this.focused = true; } if (this._isValueStateFocused) { this._isValueStateFocused = false; this.focused = true; } this.open = false; } async _onfocusin(event) { await this.getInputDOMRef(); this.focused = true; // invalidating property this.previousValue = this.value; this.valueBeforeItemPreview = this.value; this._inputIconFocused = event.target && event.target === this.querySelector("[ui5-icon]"); } _onfocusout(event) { const focusedOutToSuggestions = this.Suggestions && event.relatedTarget && event.relatedTarget.shadowRoot && event.relatedTarget.shadowRoot.contains(this.Suggestions.responsivePopover); const focusedOutToValueStateMessage = event.relatedTarget && event.relatedTarget.shadowRoot && event.relatedTarget.shadowRoot.querySelector(".ui5-valuestatemessage-root"); // if focusout is triggered by pressing on suggestion item or value state message popover, skip invalidation, because re-rendering // will happen before "itemPress" event, which will make item "active" state not visualized if (focusedOutToSuggestions || focusedOutToValueStateMessage) { event.stopImmediatePropagation(); return; } const toBeFocused = event.relatedTarget; if (toBeFocused && toBeFocused.classList.contains(this._id)) { return; } this.closePopover(); this._clearPopoverFocusAndSelection(); this.previousValue = ""; this.lastConfirmedValue = ""; this.focused = false; // invalidating property this.open = false; } _clearPopoverFocusAndSelection() { if (!this.showSuggestions || !this.Suggestions) { return; } this._isValueStateFocused = false; this.hasSuggestionItemSelected = false; this.Suggestions._deselectItems(); this.Suggestions._clearItemFocus(); } _click(event) { if (isPhone() && !this.readonly && this.Suggestions) { this.blur(); this.open = true; } } _handleNativeInputChange() { // The native change sometimes fires too early and getting input's value in the listener would return // the previous value instead of the most recent one. This would make things consistent. clearTimeout(this._nativeChangeDebounce); this._nativeChangeDebounce = setTimeout(() => this._handleChange(), 100); } _handleChange() { if (this._changeFiredValue !== this.value) { this._changeFiredValue = this.value; this.fireEvent(this.EVENT_CHANGE); } } _scroll(event) { const detail = event.detail; this.fireEvent("suggestion-scroll", { scrollTop: detail.scrollTop, scrollContainer: detail.targetRef, }); } _handleInput(event) { const inputDomRef = this.getInputDOMRefSync(); const emptyValueFiredOnNumberInput = this.value && this.isTypeNumber && !inputDomRef.value; this.suggestionSelectionCanceled = false; if (emptyValueFiredOnNumberInput && !this._backspaceKeyDown) { // For input with type="Number", if the delimiter is entered second time, // the inner input is firing event with empty value return; } if (emptyValueFiredOnNumberInput && this._backspaceKeyDown) { // Issue: when the user removes the character(s) after the delimeter of numeric Input, // the native input is firing event with an empty value and we have to manually handle this case, // otherwise the entire input will be cleared as we sync the "value". // There are tree scenarios: // Example: type "123.4" and press BACKSPACE - the native input is firing event with empty value. // Example: type "123.456", select/mark "456" and press BACKSPACE - the native input is firing event with empty value. // Example: type "123.456", select/mark "123.456" and press BACKSPACE - the native input is firing event with empty value, // but this time that's really the case. // Perform manual handling in case of floating number // and if the user did not select the entire input value if (rgxFloat.test(this.value) && this._selectedText !== this.value) { const newValue = this.removeFractionalPart(this.value); // update state this.value = newValue; this.highlightValue = newValue; this.valueBeforeItemPreview = newValue; // fire events this.fireEvent(this.EVENT_INPUT); this.fireEvent("value-changed"); return; } } if (event.target === inputDomRef) { this.focused = true; // stop the native event, as the semantic "input" would be fired. event.stopImmediatePropagation(); } /* skip calling change event when an input with a placeholder is focused on IE - value of the host and the internal input should be differnt in case of actual input - input is called when a key is pressed => keyup should not be called yet */ const skipFiring = (inputDomRef.value === this.value) && isIE() && !this._keyDown && !!this.placeholder; !skipFiring && this.fireEventByAction(this.ACTION_USER_INPUT); this.hasSuggestionItemSelected = false; this._isValueStateFocused = false; if (this.Suggestions) { this.Suggestions.updateSelectedItemPosition(null); if (!this._isPhone) { this.open = !!inputDomRef.value; } } } _handleResize() { this._inputWidth = this.offsetWidth; } _closeRespPopover(preventFocusRestore) { this.Suggestions.close(preventFocusRestore); } async _afterOpenPopover() { // Set initial focus to the native input if (isPhone()) { (await this.getInputDOMRef()).focus(); } } _afterClosePopover() { this.announceSelectedItem(); // close device's keyboard and prevent further typing if (isPhone()) { this.blur(); this.focused = false; } } /** * Checks if the value state popover is open. * @returns {boolean} true if the value state popover is open, false otherwise */ isValueStateOpened() { return !!this._isPopoverOpen; } async openPopover() { const popover = await this._getPopover(); if (popover) { this._isPopoverOpen = true; popover.showAt(this); } } async closePopover() { const popover = await this._getPopover(); popover && popover.close(); } async _getPopover() { const staticAreaItem = await this.getStaticAreaItemDomRef(); return staticAreaItem && staticAreaItem.querySelector("[ui5-popover]"); } enableSuggestions() { if (this.Suggestions) { return; } const Suggestions = getFeature("InputSuggestions"); if (Suggestions) { this.Suggestions = new Suggestions(this, "suggestionItems", true); } else { throw new Error(`You have to import "@ui5/webcomponents/dist/features/InputSuggestions.js" module to use ui5-input suggestions`); } } selectSuggestion(item, keyboardUsed) { if (item.group) { return; } const itemText = item.text || item.textContent; // keep textContent for compatibility const fireInput = keyboardUsed ? this.valueBeforeItemSelection !== itemText : this.value !== itemText; this.hasSuggestionItemSelected = true; if (fireInput) { this.value = itemText; this.valueBeforeItemSelection = itemText; this.lastConfirmedValue = itemText; this.fireEvent(this.EVENT_INPUT); this._handleChange(); } this.valueBeforeItemPreview = ""; this.suggestionSelectionCanceled = false; this.fireEvent(this.EVENT_SUGGESTION_ITEM_SELECT, { item }); } previewSuggestion(item) { this.valueBeforeItemSelection = this.value; this.updateValueOnPreview(item); this.announceSelectedItem(); this._previewItem = item; } /** * Updates the input value on item preview. * @param {Object} item The item that is on preview */ updateValueOnPreview(item) { const noPreview = item.type === "Inactive" || item.group; const itemValue = noPreview ? this.valueBeforeItemPreview : (item.effectiveTitle || item.textContent); this.value = itemValue; } /** * The suggestion item on preview. * @type { sap.ui.webcomponents.main.IInputSuggestionItem } * @readonly * @public */ get previewItem() { if (!this._previewItem) { return null; } return this.getSuggestionByListItem(this._previewItem); } async fireEventByAction(action) { await this.getInputDOMRef(); if (this.disabled || this.readonly) { return; } const inputValue = await this.getInputValue(); const isUserInput = action === this.ACTION_USER_INPUT; const input = await this.getInputDOMRef(); const cursorPosition = input.selectionStart; this.value = inputValue; this.highlightValue = inputValue; this.valueBeforeItemPreview = inputValue; if (isSafari()) { // When setting the value by hand, Safari moves the cursor when typing in the middle of the text (See #1761) setTimeout(() => { input.selectionStart = cursorPosition; input.selectionEnd = cursorPosition; }, 0); } if (isUserInput) { // input this.fireEvent(this.EVENT_INPUT); // Angular two way data binding this.fireEvent("value-changed"); return; } // In IE, pressing the ENTER does not fire change const valueChanged = (this.previousValue !== undefined) && (this.previousValue !== this.value); if (isIE() && action === this.ACTION_ENTER && valueChanged) { this._handleChange(); } } async getInputValue() { const domRef = this.getDomRef(); if (domRef) { return (await this.getInputDOMRef()).value; } return ""; } async getInputDOMRef() { if (isPhone() && this.Suggestions) { await this.Suggestions._getSuggestionPopover(); return this.Suggestions && this.Suggestions.responsivePopover.querySelector(".ui5-input-inner-phone"); } return this.nativeInput; } getInputDOMRefSync() { if (isPhone() && this.Suggestions) { return this.Suggestions && this.Suggestions.responsivePopover.querySelector(".ui5-input-inner-phone"); } return this.nativeInput; } /** * Returns a reference to the native input element * @protected */ get nativeInput() { return this.getDomRef() && this.getDomRef().querySelector(`input`); } get nativeInputWidth() { return this.nativeInput && this.nativeInput.offsetWidth; } getLabelableElementId() { return this.getInputId(); } getSuggestionByListItem(item) { const key = parseInt(item.getAttribute("data-ui5-key")); return this.suggestionItems[key]; } /** * Returns if the suggestions popover is scrollable. * The method returns <code>Promise</code> that resolves to true, * if the popup is scrollable and false otherwise. * @returns {Promise} */ isSuggestionsScrollable() { if (!this.Suggestions) { return Promise.resolve(false); } return this.Suggestions._isScrollable(); } getInputId() { return `${this._id}-inner`; } /* Suggestions interface */ onItemFocused() {} onItemMouseOver(event) { const item = event.target; const suggestion = this.getSuggestionByListItem(item); suggestion && suggestion.fireEvent("mouseover", { item: suggestion, targetRef: item, }); } onItemMouseOut(event) { const item = event.target; const suggestion = this.getSuggestionByListItem(item); suggestion && suggestion.fireEvent("mouseout", { item: suggestion, targetRef: item, }); } onItemMouseDown(event) { event.preventDefault(); } onItemSelected(item, keyboardUsed) { this.selectSuggestion(item, keyboardUsed); } onItemPreviewed(item) { this.previewSuggestion(item); this.fireEvent("suggestion-item-preview", { item: this.getSuggestionByListItem(item), targetRef: item, }); } onOpen() {} onClose() {} valueStateTextMappings() { return { "Success": Input.i18nBundle.getText(VALUE_STATE_SUCCESS), "Information": Input.i18nBundle.getText(VALUE_STATE_INFORMATION), "Error": Input.i18nBundle.getText(VALUE_STATE_ERROR), "Warning": Input.i18nBundle.getText(VALUE_STATE_WARNING), }; } announceSelectedItem() { const invisibleText = this.shadowRoot.querySelector(`#${this._id}-selectionText`); if (this.Suggestions && this.Suggestions._isItemOnTarget()) { invisibleText.textContent = this.itemSelectionAnnounce; } else { invisibleText.textContent = ""; } } get _readonly() { return this.readonly && !this.disabled; } get _headerTitleText() { return Input.i18nBundle.getText(INPUT_SUGGESTIONS_TITLE); } get inputType() { return this.type.toLowerCase(); } get isTypeNumber() { return this.type === InputType.Number; } get suggestionsTextId() { return this.showSuggestions ? `${this._id}-suggestionsText` : ""; } get valueStateTextId() { return this.hasValueState ? `${this._id}-valueStateDesc` : ""; } get accInfo() { const ariaHasPopupDefault = this.showSuggestions ? "true" : undefined; const ariaAutoCompleteDefault = this.showSuggestions ? "list" : undefined; const ariaDescribedBy = this._inputAccInfo.ariaDescribedBy ? `${this.suggestionsTextId} ${this.valueStateTextId} ${this._inputAccInfo.ariaDescribedBy}`.trim() : `${this.suggestionsTextId} ${this.valueStateTextId}`.trim(); return { "input": { "ariaRoledescription": this._inputAccInfo && (this._inputAccInfo.ariaRoledescription || undefined), "ariaDescribedBy": ariaDescribedBy || undefined, "ariaInvalid": this.valueState === ValueState.Error ? "true" : undefined, "ariaHasPopup": this._inputAccInfo.ariaHasPopup ? this._inputAccInfo.ariaHasPopup : ariaHasPopupDefault, "ariaAutoComplete": this._inputAccInfo.ariaAutoComplete ? this._inputAccInfo.ariaAutoComplete : ariaAutoCompleteDefault, "role": this._inputAccInfo && this._inputAccInfo.role, "ariaControls": this._inputAccInfo && this._inputAccInfo.ariaControls, "ariaExpanded": this._inputAccInfo && this._inputAccInfo.ariaExpanded, "ariaDescription": this._inputAccInfo && this._inputAccInfo.ariaDescription, "ariaLabel": (this._inputAccInfo && this._inputAccInfo.ariaLabel) || getEffectiveAriaLabelText(this), }, }; } get nativeInputAttributes() { return { "min": this.isTypeNumber ? this._nativeInputAttributes.min : undefined, "max": this.isTypeNumber ? this._nativeInputAttributes.max : undefined, "step": this.isTypeNumber ? (this._nativeInputAttributes.step || "any") : undefined, }; } get ariaValueStateHiddenText() { if (!this.hasValueStateMessage) { return; } if (this.shouldDisplayDefaultValueStateMessage) { return this.valueStateText; } return this.valueStateMessageText.map(el => el.textContent).join(" "); } get itemSelectionAnnounce() { return this.Suggestions ? this.Suggestions.itemSelectionAnnounce : undefined; } get classes() { return { popover: { "ui5-suggestions-popover": !this.isPhone && this.showSuggestions, "ui5-suggestions-popover-with-value-state-header": !this.isPhone && this.showSuggestions && this.hasValueStateMessage, }, popoverValueState: { "ui5-valuestatemessage-root": true, "ui5-valuestatemessage-header": true, "ui5-valuestatemessage--success": this.valueState === ValueState.Success, "ui5-valuestatemessage--error": this.valueState === ValueState.Error, "ui5-valuestatemessage--warning": this.valueState === ValueState.Warning, "ui5-valuestatemessage--information": this.valueState === ValueState.Information, }, }; } get styles() { const remSizeIxPx = parseInt(getComputedStyle(document.documentElement).fontSize); const stylesObject = { popoverHeader: { "max-width": `${this._inputWidth}px`, }, suggestionPopoverHeader: { "display": this._listWidth === 0 ? "none" : "inline-block", "width": `${this._listWidth}px`, }, suggestionsPopover: { "min-width": `${this._inputWidth}px`, "max-width": (this._inputWidth / remSizeIxPx) > 40 ? `${this._inputWidth}px` : "40rem", }, innerInput: {}, }; if (this.nativeInputWidth < 48) { stylesObject.innerInput.padding = "0"; } return stylesObject; } get suggestionSeparators() { return "None"; } get valueStateMessageText() { return this.getSlottedNodes("valueStateMessage").map(el => el.cloneNode(true)); } get shouldDisplayOnlyValueStateMessage() { return this.hasValueStateMessage && !this.readonly && !this.open && this.focused; } get shouldDisplayDefaultValueStateMessage() { return !this.valueStateMessage.length && this.hasValueStateMessage; } get hasValueState() { return this.valueState !== ValueState.None; } get hasValueStateMessage() { return this.hasValueState && this.valueState !== ValueState.Success && (!this._inputIconFocused // Handles the cases when valueStateMessage is forwarded (from datepicker e.g.) || (this._isPhone && this.Suggestions)); // Handles Input with suggestions on mobile } get valueStateText() { return this.valueStateTextMappings()[this.valueState]; } get suggestionsText() { return Input.i18nBundle.getText(INPUT_SUGGESTIONS); } get availableSuggestionsCount() { if (this.showSuggestions && (this.value || this.Suggestions.isOpened())) { switch (this.suggestionsTexts.length) { case 0: return Input.i18nBundle.getText(INPUT_SUGGESTIONS_NO_HIT); case 1: return Input.i18nBundle.getText(INPUT_SUGGESTIONS_ONE_HIT); default: return Input.i18nBundle.getText(INPUT_SUGGESTIONS_MORE_HITS, this.suggestionsTexts.length); } } return undefined; } get step() { return this.isTypeNumber ? "any" : undefined; } get _isPhone() { return isPhone(); } get _isSuggestionsFocused() { return !this.focused && this.Suggestions && this.Suggestions.isOpened(); } /** * Returns the placeholder value. * @protected */ get _placeholder() { return this.placeholder; } /** * This method is relevant for sap_horizon theme only */ get _valueStateInputIcon() { const iconPerValueState = { Error: `<path xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" d="M10 20C4.47715 20 0 15.5228 0 10C0 4.47715 4.47715 0 10 0C15.5228 0 20 4.47715 20 10C20 15.5228 15.5228 20 10 20ZM7.70711 13.7071C7.31658 14.0976 6.68342 14.0976 6.29289 13.7071C5.90237 13.3166 5.90237 12.6834 6.29289 12.2929L8.58579 10L6.29289 7.70711C5.90237 7.31658 5.90237 6.68342 6.29289 6.29289C6.68342 5.90237 7.31658 5.90237 7.70711 6.29289L10 8.58579L12.2929 6.29289C12.6834 5.90237 13.3166 5.90237 13.7071 6.29289C14.0976 6.68342 14.0976 7.31658 13.7071 7.70711L11.4142 10L13.7071 12.2929C14.0976 12.6834 14.0976 13.3166 13.7071 13.7071C13.3166 14.0976 12.6834 14.0976 12.2929 13.7071L10 11.4142L7.70711 13.7071Z" fill="#EE3939"/>`, Warning: `<path xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" d="M11.8619 0.49298C11.6823 0.187541 11.3544 0 11 0C10.6456 0 10.3177 0.187541 10.1381 0.49298L0.138066 17.493C-0.0438112 17.8022 -0.0461447 18.1851 0.13195 18.4965C0.310046 18.8079 0.641283 19 1 19H21C21.3587 19 21.69 18.8079 21.868 18.4965C22.0461 18.1851 22.0438 17.8022 21.8619 17.493L11.8619 0.49298ZM11 6C11.5523 6 12 6.44772 12 7V10C12 10.5523 11.5523 11 11 11C10.4477 11 10 10.5523 10 10V7C10 6.44772 10.4477 6 11 6ZM11 16C11.8284 16 12.5 15.3284 12.5 14.5C12.5 13.6716 11.8284 13 11 13C10.1716 13 9.5 13.6716 9.5 14.5C9.5 15.3284 10.1716 16 11 16Z" fill="#F58B00"/>`, Success: `<path xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" d="M0 10C0 15.5228 4.47715 20 10 20C15.5228 20 20 15.5228 20 10C20 4.47715 15.5228 0 10 0C4.47715 0 0 4.47715 0 10ZM14.7071 6.29289C14.3166 5.90237 13.6834 5.90237 13.2929 6.29289L8 11.5858L6.70711 10.2929C6.31658 9.90237 5.68342 9.90237 5.29289 10.2929C4.90237 10.6834 4.90237 11.3166 5.29289 11.7071L7.29289 13.7071C7.68342 14.0976 8.31658 14.0976 8.70711 13.7071L14.7071 7.70711C15.0976 7.31658 15.0976 6.68342 14.7071 6.29289Z" fill="#36A41D"/>`, Information: `<path xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" d="M3 0C1.34315 0 0 1.34315 0 3V15C0 16.6569 1.34315 18 3 18H15C16.6569 18 18 16.6569 18 15V3C18 1.34315 16.6569 0 15 0H3ZM9 6.5C9.82843 6.5 10.5 5.82843 10.5 5C10.5 4.17157 9.82843 3.5 9 3.5C8.17157 3.5 7.5 4.17157 7.5 5C7.5 5.82843 8.17157 6.5 9 6.5ZM9 8.5C9.55228 8.5 10 8.94772 10 9.5V13.5C10 14.0523 9.55228 14.5 9 14.5C8.44771 14.5 8 14.0523 8 13.5V9.5C8 8.94772 8.44771 8.5 9 8.5Z" fill="#1B90FF"/>`, }; const result = ` <svg xmlns="http://www.w3.org/2000/svg" width="24" height="20" viewBox="0 0 20 20" fill="none"> ${iconPerValueState[this.valueState]}; </svg> `; return this.valueState !== ValueState.None ? result : ""; } get _valueStatePopoverHorizontalAlign() { return this.effectiveDir !== "rtl" ? "Left" : "Right"; } /** * This method is relevant for sap_horizon theme only */ get _valueStateMessageInputIcon() { const iconPerValueState = { Error: "error", Warning: "alert", Success: "sys-enter-2", Information: "information", }; return this.valueState !== ValueState.None ? iconPerValueState[this.valueState] : ""; } /** * Returns the caret position inside the native input * @protected */ getCaretPosition() { return getCaretPosition(this.nativeInput); } /** * Sets the caret to a certain position inside the native input * @protected * @param pos */ setCaretPosition(pos) { setCaretPosition(this.nativeInput, pos); } /** * Removes the fractional part of floating-point number. * @param {String} value the numeric value of Input of type "Number" */ removeFractionalPart(value) { if (value.includes(".")) { return value.slice(0, value.indexOf(".")); } if (value.includes(",")) { return value.slice(0, value.indexOf(",")); } return value; } static get dependencies() { const Suggestions = getFeature("InputSuggestions"); return [Popover].concat(Suggestions ? Suggestions.dependencies : []); } static async onDefine() { const Suggestions = getFeature("InputSuggestions"); [Input.i18nBundle] = await Promise.all([ getI18nBundle("@ui5/webcomponents"), Suggestions ? Suggestions.init() : Promise.resolve(), ]); } }
JavaScript
class ReuseTabContextMenuComponent { /** * @param {?} i18nSrv */ constructor(i18nSrv) { this.i18nSrv = i18nSrv; this.close = new EventEmitter(); } /** * @param {?} value * @return {?} */ set i18n(value) { this._i18n = Object.assign({}, this.i18nSrv.getData('reuseTab'), value); } /** * @return {?} */ get i18n() { return this._i18n; } /** * @return {?} */ get includeNonCloseable() { return this.event.ctrlKey; } /** * @param {?} type * @param {?} item * @return {?} */ notify(type, item) { this.close.next({ type, item: this.item, includeNonCloseable: this.includeNonCloseable, }); } /** * @return {?} */ ngOnInit() { if (this.includeNonCloseable) this.item.closable = true; } /** * @param {?} e * @param {?} type * @return {?} */ click(e, type) { e.preventDefault(); e.stopPropagation(); if (type === 'close' && !this.item.closable) return; if (type === 'closeRight' && this.item.last) return; this.notify(type, this.item); } /** * @param {?} event * @return {?} */ closeMenu(event) { if (event.type === 'click' && event.button === 2) return; this.notify(null, null); } }
JavaScript
class ReuseTabContextService { /** * @param {?} overlay */ constructor(overlay) { this.overlay = overlay; this.show = new Subject(); this.close = new Subject(); } /** * @return {?} */ remove() { if (!this.ref) return; this.ref.detach(); this.ref.dispose(); this.ref = null; } /** * @param {?} context * @return {?} */ open(context) { this.remove(); const { event, item } = context; /** @type {?} */ const fakeElement = new ElementRef({ getBoundingClientRect: () => ({ bottom: event.clientY, height: 0, left: event.clientX, right: event.clientX, top: event.clientY, width: 0, }), }); /** @type {?} */ const positions = [ new ConnectionPositionPair({ originX: 'start', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' }), new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'bottom' }), ]; /** @type {?} */ const positionStrategy = this.overlay .position() .flexibleConnectedTo(fakeElement) .withPositions(positions); this.ref = this.overlay.create({ positionStrategy, panelClass: 'reuse-tab__cm', scrollStrategy: this.overlay.scrollStrategies.close(), }); /** @type {?} */ const comp = this.ref.attach(new ComponentPortal(ReuseTabContextMenuComponent)); /** @type {?} */ const instance = comp.instance; instance.i18n = this.i18n; instance.item = Object.assign({}, item); instance.event = event; /** @type {?} */ const sub$ = new Subscription(); sub$.add(instance.close.subscribe((res) => { this.close.next(res); this.remove(); })); comp.onDestroy(() => sub$.unsubscribe()); } }
JavaScript
class ReuseTabContextComponent { /** * @param {?} srv */ constructor(srv) { this.srv = srv; this.sub$ = new Subscription(); this.change = new EventEmitter(); this.sub$.add(srv.show.subscribe(context => this.srv.open(context))); this.sub$.add(srv.close.subscribe(res => this.change.emit(res))); } /** * @param {?} value * @return {?} */ set i18n(value) { this.srv.i18n = value; } /** * @return {?} */ ngOnDestroy() { this.sub$.unsubscribe(); } }
JavaScript
class ReuseTabContextDirective { /** * @param {?} srv */ constructor(srv) { this.srv = srv; } /** * @param {?} event * @return {?} */ onContextMenu(event) { this.srv.show.next({ event, item: this.item, }); event.preventDefault(); event.stopPropagation(); } }
JavaScript
class ReuseTabComponent { /** * @param {?} el * @param {?} srv * @param {?} cd * @param {?} router * @param {?} route * @param {?} render * @param {?} i18nSrv */ constructor(el, srv, cd, router, route, render, i18nSrv) { this.srv = srv; this.cd = cd; this.router = router; this.route = route; this.render = render; this.i18nSrv = i18nSrv; this.list = []; this.pos = 0; /** * 设置匹配模式 */ this.mode = ReuseTabMatchMode.Menu; /** * 是否Debug模式 */ this.debug = false; /** * 允许关闭 */ this.allowClose = true; /** * 总是显示当前页 */ this.showCurrent = true; /** * 切换时回调 */ this.change = new EventEmitter(); /** * 关闭回调 */ this.close = new EventEmitter(); this.el = el.nativeElement; /** @type {?} */ const route$ = this.router.events.pipe(filter(evt => evt instanceof NavigationEnd)); this.sub$ = combineLatest(this.srv.change, route$).subscribe(([res, e]) => this.genList(/** @type {?} */ (res))); if (this.i18nSrv) { this.i18n$ = this.i18nSrv.change .pipe(debounceTime(100)) .subscribe(() => this.genList()); } } /** * @param {?} title * @return {?} */ genTit(title) { return title.i18n && this.i18nSrv ? this.i18nSrv.fanyi(title.i18n) : title.text; } /** * @param {?=} notify * @return {?} */ genList(notify) { /** @type {?} */ const isClosed = notify && notify.active === 'close'; /** @type {?} */ const beforeClosePos = isClosed ? this.list.findIndex(w => w.url === notify["url"]) : -1; /** @type {?} */ const ls = this.srv.items.map((item, index) => { return /** @type {?} */ ({ url: item.url, title: this.genTit(item.title), closable: this.allowClose && item.closable && this.srv.count > 0, index, active: false, last: false, }); }); if (this.showCurrent) { /** @type {?} */ const snapshot = this.route.snapshot; /** @type {?} */ const url = this.srv.getUrl(snapshot); /** @type {?} */ const idx = ls.findIndex(w => w.url === url); // jump directly when the current exists in the list // or create a new current item and jump if (idx !== -1 || (isClosed && notify["url"] === url)) { this.pos = isClosed ? idx >= beforeClosePos ? this.pos - 1 : this.pos : idx; } else { /** @type {?} */ const snapshotTrue = this.srv.getTruthRoute(snapshot); ls.push(/** @type {?} */ ({ url, title: this.genTit(this.srv.getTitle(url, snapshotTrue)), closable: this.allowClose && this.srv.count > 0 && this.srv.getClosable(url, snapshotTrue), index: ls.length, active: false, last: false, })); this.pos = ls.length - 1; } // fix unabled close last item if (ls.length <= 1) ls[0].closable = false; } this.list = ls; if (ls.length && isClosed) { this.to(null, this.pos); } this.refStatus(false); this.visibility(); this.cd.detectChanges(); } /** * @return {?} */ visibility() { if (this.showCurrent) return; this.render.setStyle(this.el, 'display', this.list.length === 0 ? 'none' : 'block'); } /** * @param {?} res * @return {?} */ cmChange(res) { switch (res.type) { case 'close': this._close(null, res.item.index, res.includeNonCloseable); break; case 'closeRight': this.srv.closeRight(res.item.url, res.includeNonCloseable); this.close.emit(null); break; case 'clear': case 'closeOther': this.srv.clear(res.includeNonCloseable); this.close.emit(null); break; } } /** * @param {?=} dc * @return {?} */ refStatus(dc = true) { if (this.list.length) { this.list[this.list.length - 1].last = true; this.list.forEach((i, idx) => (i.active = this.pos === idx)); } if (dc) this.cd.detectChanges(); } /** * @param {?} e * @param {?} index * @return {?} */ to(e, index) { if (e) { e.preventDefault(); e.stopPropagation(); } index = Math.max(0, Math.min(index, this.list.length - 1)); /** @type {?} */ const item = this.list[index]; this.router.navigateByUrl(item.url).then(res => { if (!res) return; this.pos = index; this.item = item; this.refStatus(); this.change.emit(item); }); } /** * @param {?} e * @param {?} idx * @param {?} includeNonCloseable * @return {?} */ _close(e, idx, includeNonCloseable) { if (e) { e.preventDefault(); e.stopPropagation(); } /** @type {?} */ const item = this.list[idx]; this.srv.close(item.url, includeNonCloseable); this.close.emit(item); this.cd.detectChanges(); return false; } /** * @return {?} */ ngOnInit() { this.genList(); } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { if (changes.max) this.srv.max = this.max; if (changes.excludes) this.srv.excludes = this.excludes; if (changes.mode) this.srv.mode = this.mode; this.srv.debug = this.debug; this.cd.detectChanges(); } /** * @return {?} */ ngOnDestroy() { const { i18n$, sub$ } = this; sub$.unsubscribe(); if (i18n$) i18n$.unsubscribe(); } }
JavaScript
class ReuseTabStrategy { /** * @param {?} srv */ constructor(srv) { this.srv = srv; } /** * @param {?} route * @return {?} */ shouldDetach(route) { return this.srv.shouldDetach(route); } /** * @param {?} route * @param {?} handle * @return {?} */ store(route, handle) { this.srv.store(route, handle); } /** * @param {?} route * @return {?} */ shouldAttach(route) { return this.srv.shouldAttach(route); } /** * @param {?} route * @return {?} */ retrieve(route) { return this.srv.retrieve(route); } /** * @param {?} future * @param {?} curr * @return {?} */ shouldReuseRoute(future, curr) { return this.srv.shouldReuseRoute(future, curr); } }
JavaScript
class DanglingResolver { constructor (_id, _resolve, _reject) { this.id = _id this.resolve = _resolve this.reject = _reject } }
JavaScript
class CircleStyle extends RegularShape { /** * @param {Options} [opt_options] Options. */ constructor(opt_options) { const options = opt_options ? opt_options : {}; super({ points: Infinity, fill: options.fill, radius: options.radius, stroke: options.stroke, scale: options.scale !== undefined ? options.scale : 1, rotation: options.rotation !== undefined ? options.rotation : 0, rotateWithView: options.rotateWithView !== undefined ? options.rotateWithView : false, displacement: options.displacement !== undefined ? options.displacement : [0, 0], }); } /** * Clones the style. * @return {CircleStyle} The cloned style. * @api */ clone() { const scale = this.getScale(); const style = new CircleStyle({ fill: this.getFill() ? this.getFill().clone() : undefined, stroke: this.getStroke() ? this.getStroke().clone() : undefined, radius: this.getRadius(), scale: Array.isArray(scale) ? scale.slice() : scale, rotation: this.getRotation(), rotateWithView: this.getRotateWithView(), displacement: this.getDisplacement().slice(), }); style.setOpacity(this.getOpacity()); return style; } /** * Set the circle radius. * * @param {number} radius Circle radius. * @api */ setRadius(radius) { this.radius_ = radius; this.render(); } }
JavaScript
class Program { constructor(name, material) { /** * Shader progarm name. * @public * @type {string} */ this.name = name; this.attributes = {}; this.uniforms = {}; /** * Attributes. * @public * @type {Object} */ this._attributes = {}; for (let t in material.attributes) { if (typeof (material.attributes[t]) === "string" || typeof (material.attributes[t]) === "number") { this._attributes[t] = { 'type': material.attributes[t] }; } else { this._attributes[t] = material.attributes[t]; } } /** * Uniforms. * @public * @type {Object} */ this._uniforms = {}; for (let t in material.uniforms) { if (typeof (material.uniforms[t]) === "string" || typeof (material.uniforms[t]) === "number") { this._uniforms[t] = { 'type': material.uniforms[t] }; } else { this._uniforms[t] = material.uniforms[t]; } } /** * Vertex shader. * @public * @type {string} */ this.vertexShader = material.vertexShader; /** * Fragment shader. * @public * @type {string} */ this.fragmentShader = material.fragmentShader; /** * Webgl context. * @public * @type {Object} */ this.gl = null; /** * All program variables. * @private * @type {Object} */ this._variables = {}; /** * Program pointer. * @private * @type {Object} */ this._p = null; /** * Texture counter. * @prvate * @type {number} */ this._textureID = 0; /** * Program attributes array. * @private * @type {Array.<Object>} */ this._attribArrays = []; } /** * Sets the current program frame. * @public */ use() { this.gl.useProgram(this._p); } /** * Sets program variables. * @public * @param {Object} material - Variables and values object. */ set(material) { this._textureID = 0; for (var i in material) { this._variables[i].value = material[i]; this._variables[i]._callback(this, this._variables[i]); } } /** * Apply current variables. * @public */ apply() { this._textureID = 0; var v = this._variables; for (var i in v) { v[i]._callback(this, v[i]); } } /** * Calls drawElements index buffer function. * @public * @param {number} mode - Draw mode(GL_TRIANGLES, GL_LINESTRING etc.). * @param {Object} buffer - Index buffer. */ drawIndexBuffer(mode, buffer) { this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, buffer); this.gl.drawElements(mode, buffer.numItems, this.gl.UNSIGNED_SHORT, 0); } /** * Calls drawArrays function. * @public * @param {number} mode - Draw mode(GL_TRIANGLES, GL_LINESTRING etc.). * @param {number} numItems - Curent binded buffer drawing items count. */ drawArrays(mode, numItems) { this.gl.drawArrays(mode, 0, numItems); } /** * Check and log for an shader compile errors and warnings. Returns True - if no errors otherwise returns False. * @private * @param {Object} shader - WebGl shader program. * @param {string} src - Shader program source. * @returns {boolean} - */ _getShaderCompileStatus(shader, src) { this.gl.shaderSource(shader, src); this.gl.compileShader(shader); if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { cons.logErr("og/Program/Program:" + this.name + " - " + this.gl.getShaderInfoLog(shader) + "."); return false; } return true; } /** * Returns compiled vertex shader program pointer. * @private * @param {string} src - Vertex shader source code. * @returns {Object} - */ _createVertexShader(src) { var shader = this.gl.createShader(this.gl.VERTEX_SHADER); if (!this._getShaderCompileStatus(shader, src)) { return null; } return shader; } /** * Returns compiled fragment shader program pointer. * @private * @param {string} src - Vertex shader source code. * @returns {Object} - */ _createFragmentShader(src) { var shader = this.gl.createShader(this.gl.FRAGMENT_SHADER); if (!this._getShaderCompileStatus(shader, src)) { return null; } return shader; } /** * Disable current program vertexAttribArrays. * @public */ disableAttribArrays() { var gl = this.gl; var a = this._attribArrays; var i = a.length; while (i--) { gl.disableVertexAttribArray(a[i]); } } /** * Enable current program vertexAttribArrays. * @public */ enableAttribArrays() { var gl = this.gl; var a = this._attribArrays; var i = a.length; while (i--) { gl.enableVertexAttribArray(a[i]); } } /** * Delete program. * @public */ delete() { this.gl.deleteProgram(this._p); } /** * Creates program. * @public * @param {Object} gl - WebGl context. */ createProgram(gl) { this.gl = gl; this._p = this.gl.createProgram(); var fs = this._createFragmentShader(this.fragmentShader); var vs = this._createVertexShader(this.vertexShader); gl.attachShader(this._p, fs); gl.attachShader(this._p, vs); gl.linkProgram(this._p); if (!gl.getProgramParameter(this._p, gl.LINK_STATUS)) { cons.logErr("og/Program/Program:" + this.name + " - couldn't initialise shaders. " + gl.getProgramInfoLog(this._p) + "."); gl.deleteProgram(this._p); return; } this.use(); for (var a in this._attributes) { //this.attributes[a]._name = a; this._variables[a] = this._attributes[a]; //Maybe, it will be better to remove enableArray option... this._attributes[a].enableArray = (this._attributes[a].enableArray != undefined ? this._attributes[a].enableArray : true); if (this._attributes[a].enableArray) this._attributes[a]._callback = Program.bindBuffer; else { if (typeof (this._attributes[a].type) === "string") { this._attributes[a]._callback = callbacks.a[typeStr[this._attributes[a].type.trim().toLowerCase()]]; } else { this._attributes[a]._callback = callbacks.a[this._attributes[a].type]; } } this._p[a] = gl.getAttribLocation(this._p, a); if (this._p[a] == undefined) { cons.logErr("og/Program/Program:" + this.name + " - attribute '" + a + "' is not exists."); gl.deleteProgram(this._p); return; } if (this._attributes[a].enableArray) { this._attribArrays.push(this._p[a]); gl.enableVertexAttribArray(this._p[a]); } this._attributes[a]._pName = this._p[a]; this.attributes[a] = this._p[a]; } for (var u in this._uniforms) { //this.uniforms[u]._name = u; if (typeof (this._uniforms[u].type) === "string") { this._uniforms[u]._callback = callbacks.u[typeStr[this._uniforms[u].type.trim().toLowerCase()]]; } else { this._uniforms[u]._callback = callbacks.u[this._uniforms[u].type]; } this._variables[u] = this._uniforms[u]; this._p[u] = gl.getUniformLocation(this._p, u); if (this._p[u] == undefined) { cons.logErr("og/Program/Program:" + this.name + " - uniform '" + u + "' is not exists."); gl.deleteProgram(this._p); return; } this._uniforms[u]._pName = this._p[u]; this.uniforms[u] = this._p[u]; } gl.detachShader(this._p, fs); gl.detachShader(this._p, vs); gl.deleteShader(fs); gl.deleteShader(vs); } /** * Bind program buffer. * @function * @param {og.webgl.Program} program - Used program. * @param {Object} variable - Variable represents buffer data. */ static bindBuffer(program, variable) { var gl = program.gl; gl.bindBuffer(gl.ARRAY_BUFFER, variable.value); gl.vertexAttribPointer(variable._pName, variable.value.itemSize, gl.FLOAT, false, 0, 0); } }
JavaScript
class Patreon extends ClickableComponent { constructor(player, options) { super(player, options); } createEl() { let el = super.createEl('input', {className: 'qa-input-checkbox', defaultChecked: JSON.parse(window.localStorage.getItem('patreon')) || false}, {type:'checkbox', id: 'patreon-toggle'}); return el; } buildCSSClass() { return `qa-input-checkbox ${super.buildCSSClass()}`; } /** * Handle click for button * * @method handleClick */ handleClick(event) { super.handleClick(event); const target = event.target; if(target.checked) { window.localStorage.setItem('patreon', true); this.player().trigger('patreon'); } else { window.localStorage.setItem('patreon', false); this.player().trigger('public'); } } }
JavaScript
class Autoplay { /** @param {!../ampdoc-impl.AmpDoc} ampdoc */ constructor(ampdoc) { /** @private @const {!../ampdoc-impl.AmpDoc} */ this.ampdoc_ = ampdoc; /** * @return {!../position-observer/position-observer-impl.PositionObserver} * @private */ this.getPositionObserver_ = once(() => this.installPositionObserver_()); /** @private @const {!Array<!AutoplayEntry>} */ this.entries_ = []; /** * @return {!Promise<boolean>} * @private */ this.isSupported_ = once(() => { // Can't destructure as the compiler expects direct member access for // `getMode`. const {win} = this.ampdoc_; const isLite = getMode(win).lite; return VideoUtils.isAutoplaySupported(win, /* isLiteMode */ isLite); }); } /** @private */ installPositionObserver_() { installPositionObserverServiceForDoc(this.ampdoc_); // No getter in services.js. return ( /** @type { * !../position-observer/position-observer-impl.PositionObserver * } */ (getServiceForDoc(this.ampdoc_, 'position-observer'))); } /** * @param {!../../video-interface.VideoOrBaseElementDef} video * @return {!Promise<?AutoplayEntry>} `null` when unsupported. */ register(video) { // Controls are hidden before support is determined to prevent visual jump // for the common case where autoplay is supported. if (video.isInteractive()) { video.hideControls(); } return this.isSupported_().then(isSupported => { if (!isSupported) { // Disable autoplay if (video.isInteractive()) { video.showControls(); } return null; } const entry = new AutoplayEntry(this.ampdoc_, this.getPositionObserver_(), video); this.entries_.push(entry); return entry; }); } /** * @param {!Element} element */ delegate(element) { const entry = this.getEntryFor_(element); if (!entry) { return; } entry.delegate(); } /** * @param {!Element} element * @return {?AutoplayEntry} * @private */ getEntryFor_(element) { for (let i = 0; i < this.entries_.length; i++) { const entry = this.entries_[i]; if (entry.video.element == element) { return entry; } } return null; } }
JavaScript
class Urls { constructor() { this.urls = {}; } /** * @description Add a url to the system. * @param {Object} options */ add(options) { const url = options.url; const generatorId = options.generatorId; const resource = options.resource; debug('cache', url); if (this.urls[resource.data.id]) { logging.error(new errors.InternalServerError({ message: 'This should not happen.', code: 'URLSERVICE_RESOURCE_DUPLICATE' })); this.removeResourceId(resource.data.id); } this.urls[resource.data.id] = { url: url, generatorId: generatorId, resource: resource }; // @NOTE: Notify the whole system. Currently used for sitemaps service. events.emit('url.added', { url: { relative: url, absolute: urlUtils.createUrl(url, true) }, resource: resource }); } /** * @description Get url by resource id. * @param {String} id * @returns {Object} */ getByResourceId(id) { return this.urls[id]; } /** * @description Get all urls by generator id. * @param {String} generatorId * @returns {Array} */ getByGeneratorId(generatorId) { return _.reduce(Object.keys(this.urls), (toReturn, resourceId) => { if (this.urls[resourceId].generatorId === generatorId) { toReturn.push(this.urls[resourceId]); } return toReturn; }, []); } /** * @description Get by url. * * @NOTE: * It's is in theory possible that: * * - resource1 -> /welcome/ * - resource2 -> /welcome/ * * But depending on the routing registration, you will always serve e.g. resource1, * because the router it belongs to was registered first. */ getByUrl(url) { return _.reduce(Object.keys(this.urls), (toReturn, resourceId) => { if (this.urls[resourceId].url === url) { toReturn.push(this.urls[resourceId]); } return toReturn; }, []); } /** * @description Remove url. * @param id */ removeResourceId(id) { if (!this.urls[id]) { return; } debug('removed', this.urls[id].url, this.urls[id].generatorId); events.emit('url.removed', { url: this.urls[id].url, resource: this.urls[id].resource }); delete this.urls[id]; } /** * @description Reset instance. */ reset() { this.urls = {}; } /** * @description Soft reset instance. */ softReset() { this.urls = {}; } }
JavaScript
class TagImages extends React.Component { constructor(props) { super(props); this.state = { files: [], images_src: [], messageType: null, message: null, showAgreement: false, license: null, sending: false, defaultID: null }; this.loadLicense = this.loadLicense.bind(this); this.onChangeShowAgreement = this.onChangeShowAgreement.bind(this); this.onInputChange = this.onInputChange.bind(this); this.onInputValueChange = this.onInputValueChange.bind(this); this.getInputValue = this.getInputValue.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.getAttachedFiles = this.getAttachedFiles.bind(this); this.removeFile = this.removeFile.bind(this); this.errorMessage = this.errorMessage.bind(this); this.onCloseMessage = this.onCloseMessage.bind(this); this.setDefaultID = this.setDefaultID.bind(this); this.launchFileMonitor = this.launchFileMonitor.bind(this); this.onLocationChange = this.onLocationChange.bind(this); this.setDefaultCities = this.setDefaultCities.bind(this); } setDefaultCities() { if (this.state.defaultID !== null) { const defaultCity = this.state[`location_${this.state.defaultID}`]; if (defaultCity) { const cities = {}; for (let i = 0; i < this.state.files.length; ++i) { cities[`location_${this.state.files[i].id}`] = defaultCity; } this.setState(cities); } } } setDefaultID(defaultID) { this.setState({defaultID}, this.setDefaultCities); } errorMessage(message) { this.setState({messageType: 'error', message: message}); } loadLicense() { if (this.state.license) return; const url = `${parseUrlFolder()}/LICENSE.txt`; console.log(`Loading license from ${url}`); axios({ method: 'get', url: url, responseType: 'text' }) .then(reponse => { // Is this possible? if (!reponse) throw new Error(`No image available for address ${url}`); this.setState({license: reponse.data}); }) .catch(error => { console.error(error); }); } onChangeShowAgreement(value) { this.setState({showAgreement: value}); } onCloseMessage() { this.setState({ messageType: null, message: null, sending: false }) } /** When there is a change in the input attached to an images, see the event and attach the data entered to the state object * **/ onInputChange(event) { this.setState({[event.target.name]: event.target.value}); }; onInputValueChange(name, value) { this.setState({[name]: value}); } onLocationChange(name, value) { this.setState({ [name]: value, defaultID: null }) } getInputValue(name) { return this.state[name] || ''; } launchFileMonitor() { scrollToElement('home'); const metadata = this.state.files.map((file) => { let file_location = this.state["location_" + file.id]; let file_category = this.state["category_" + file.id]; if (file_location === undefined) file_location = ''; if (file_category === undefined || file_category === '') file_category = CATEGORIES[0]; return { file_location: file_location, file_category: file_category }; }); const fileMonitor = new FileMonitor( this.state.files.map(file => file.file), metadata, this.props.loadThanks, this.errorMessage ); fileMonitor.start(); } handleSubmit(e) { /** Method called after hitting finish uploading. Using * current files in this.state.files and the input name tags send image and their meta data to the * uploadDropfile method Note, we are currently uploading one image at a time to avoid large data uploads. **/ e.preventDefault(); //Upload Files One by One this.setState({sending: true}, this.launchFileMonitor); }; getAttachedFiles(files) { const all_files = this.state.files.concat(files.map(file => new FileWithID(file))); // To display image files we need to create a URL object that can be passed to the src of img html element. const images_src = all_files.map(file => URL.createObjectURL(file.file)); this.setState({ files: all_files, images_src: images_src }, this.setDefaultCities); }; removeFile(fileIndex) { if (fileIndex >= 0 && fileIndex < this.state.files.length) { const files = this.state.files.slice(); const images_src = this.state.images_src.slice(); const removedID = files[fileIndex].id; files.splice(fileIndex, 1); images_src.splice(fileIndex, 1); this.setState({ files: files, images_src: images_src, defaultID: this.state.defaultID === removedID ? null : this.state.defaultID }); } } renderImageForms() { let forms_html = []; for (let i = 0; i < this.state.files.length; ++i) { const imageSrc = this.state.images_src[i]; const id = this.state.files[i].id; const categoryId = `category_${id}`; const locationId = `location_${id}`; const fileIndex = i; forms_html.push(<div className="form-col" key={i}> <form className="image-form"> <div className="form-group"> <div className="image-wrapper" style={{backgroundImage: `url(${imageSrc})`}}> <div className="progress" style={{display: 'none'}}> <div className="progress-bar bg-info" id={`progress-${fileIndex}`} role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"/> </div> <div className="window-close-button"> <button onClick={(event) => { event.preventDefault(); this.removeFile(fileIndex); }}> <span><FontAwesomeIcon icon={faTrashAlt}/></span> </button> </div> </div> </div> <div className="form-group"> <label className="sr-only" htmlFor={categoryId}>Category</label> <div className="input-group"> <div className="input-group-prepend"> <span className="input-group-text input-text">Category</span> </div> <select name={categoryId} id={categoryId} onChange={this.onInputChange} value={this.getInputValue(categoryId)} className="form-control custom-select input"> {CATEGORIES.map((category, index) => ( <option key={index} value={category}>{category}</option> ))} </select> </div> </div> <div className="form-group"> <label className="sr-only" htmlFor={locationId}>City</label> <div className="input-group autocomplete"> <div className="input-group-prepend"> <span className="input-group-text input-text">City</span> </div> <LocationInput id={locationId} setAddress={this.onLocationChange} getAddress={this.getInputValue}/> </div> </div> {i === 0 ? ( <div className="custom-control custom-checkbox apply-city-all"> <input type="checkbox" className="custom-control-input" id="use-default-id" checked={this.state.defaultID === id} onChange={(event) => this.setDefaultID(event.target.checked ? id : null)}/> <label className="custom-control-label" htmlFor="use-default-id"> &nbsp;&nbsp;Use this city for all images </label> </div> ) : ''} </form> </div>); } return forms_html; } render() { /** * Each image section behvaes like a form of it's own. Currently we upload * one image with each request. **/ const agreement = this.context; const forms_html = this.renderImageForms(); return ( <div className="upload-form flex-grow-1 d-flex flex-column"> <Helmet> <title>Upload and describe your pictures</title> </Helmet> <h3>Upload pictures and tell us more about them.</h3> <div className="upload-form-content px-4 py-5 flex-grow-1 d-flex flex-column justify-content-center"> {/** If there is a message from the api request show this underneath the header **/} <div className={`d-flex flex-row flex-wrap ${forms_html.length ? '' : 'justify-content-center'}`}> {/** Add forms and image previews to the DOM **/} {forms_html} <div className={`form-col ${forms_html.length ? 'with-files' : 'no-files'}`}> {/** Another dropzone component to allow users to add more images while adding the metadata **/} {/** Show the upload section if the add images flag is set to true. This flag is toggled by the addMoreImages method **/} <div className="drop-zone-container"> <Dropzone ref={dropzoneRef} accept="image/*" onDrop={this.getAttachedFiles} noClick noKeyboard> {({getRootProps, getInputProps, acceptedFiles}) => { return ( <div {...getRootProps({className: 'dropzone'})}> <input {...getInputProps()} /> {forms_html.length ? ( <div> <div className="upload-more" onClick={openDialog}>+</div> <div>Add more photos</div> </div> ) : ( <div> <div> <img alt="Upload your photos" className="img-fluid upload-icon" src={uploadIcon}/> </div> <div className="py-4">Drag and drop your photos here</div> <div> <span className="button btn btn-danger btn-lg" onClick={openDialog}> UPLOAD YOUR PHOTOS </span> </div> </div> )} </div> ); }} </Dropzone> </div> {forms_html.length ? '' : ( <div className="mt-5 mb-4"> You can upload multiple files at once (only common image formats will be accepted). </div> )} </div> </div> {/** On click on finish uploading start submitting images to the server **/} {this.state.files.length && !this.state.sending ? ( <div className="upload-form-wrapper pt-5"> <form> <div className="custom-control custom-checkbox"> <input type="checkbox" className="custom-control-input" id="agree-license" checked={agreement.getAgreement()} onChange={(event) => agreement.setAgreement(event.target.checked)}/> <label className="custom-control-label" htmlFor="agree-license"> &nbsp;&nbsp;I agree with the&nbsp; </label> <span className="link-license" onClick={() => this.onChangeShowAgreement(true)}> license </span>. </div> </form> <button className="finish-uploading btn btn-info btn-lg mt-3" disabled={!agreement.getAgreement()} onClick={this.handleSubmit}> DONE UPLOADING </button> </div> ) : ''} {this.state.showAgreement && ( <FancyBox title={'LICENSE'} onClose={() => this.onChangeShowAgreement(false)}> <pre className="license"> {this.state.license ? this.state.license : `Loading agreement ...`} </pre> </FancyBox> )} {this.state.message && ( <FancyBox title={`${this.state.messageType.charAt(0).toUpperCase()}${this.state.messageType.substr(1)}`} onClose={this.onCloseMessage}> <div className={`message ${this.state.messageType}`}> {this.state.message} </div> </FancyBox> )} </div> </div> ); } componentDidMount() { this.loadLicense(); } }
JavaScript
class Imap { constructor (host, port, options = {}) { this.timeoutEnterIdle = TIMEOUT_ENTER_IDLE this.timeoutSocketLowerBound = TIMEOUT_SOCKET_LOWER_BOUND this.timeoutSocketMultiplier = TIMEOUT_SOCKET_MULTIPLIER this.options = options this.port = port || (this.options.useSecureTransport ? 993 : 143) this.host = host || 'localhost' // Use a TLS connection. Port 993 also forces TLS. this.options.useSecureTransport = 'useSecureTransport' in this.options ? !!this.options.useSecureTransport : this.port === 993 this.secureMode = !!this.options.useSecureTransport // Does the connection use SSL/TLS this._connectionReady = false // Is the conection established and greeting is received from the server this._globalAcceptUntagged = {} // Global handlers for unrelated responses (EXPUNGE, EXISTS etc.) this._clientQueue = [] // Queue of outgoing commands this._canSend = false // Is it OK to send something to the server this._tagCounter = 0 // Counter to allow uniqueue imap tags this._currentCommand = false // Current command that is waiting for response from the server this._idleTimer = false // Timer waiting to enter idle this._socketTimeoutTimer = false // Timer waiting to declare the socket dead starting from the last write this.compressed = false // Is the connection compressed and needs inflating/deflating // // HELPERS // // As the server sends data in chunks, it needs to be split into separate lines. Helps parsing the input. this._incomingBuffers = [] this._bufferState = BUFFER_STATE_DEFAULT this._literalRemaining = 0 // // Event placeholders, may be overriden with callback functions // this.oncert = null this.onerror = null // Irrecoverable error occurred. Connection to the server will be closed automatically. this.onready = null // The connection to the server has been established and greeting is received this.onidle = null // There are no more commands to process } // PUBLIC METHODS /** * Initiate a connection to the server. Wait for onready event * * @param {Object} Socket * TESTING ONLY! The TCPSocket has a pretty nonsensical convenience constructor, * which makes it hard to mock. For dependency-injection purposes, we use the * Socket parameter to pass in a mock Socket implementation. Should be left blank * in production use! * @returns {Promise} Resolves when socket is opened */ connect (Socket = TCPSocket) { return new Promise((resolve, reject) => { this.socket = Socket.open(this.host, this.port, { binaryType: 'arraybuffer', useSecureTransport: this.secureMode, ca: this.options.ca, ws: this.options.ws }); // allows certificate handling for platform w/o native tls support // oncert is non standard so setting it might throw if the socket object is immutable try { this.socket.oncert = (cert) => { this.oncert && this.oncert(cert) } } catch (E) { } // Connection closing unexpected is an error this.socket.onclose = () => this._onError(new Error('Socket closed unexpectedly!')) this.socket.ondata = (evt) => { try { this._onData(evt) } catch (err) { this._onError(err) } } // if an error happens during create time, reject the promise this.socket.onerror = (e) => { reject(new Error('Could not open socket: ' + e.data.message)) } this.socket.onopen = () => { // use proper "irrecoverable error, tear down everything"-handler only after socket is open this.socket.onerror = (e) => this._onError(e) resolve() } }) } /** * Closes the connection to the server * * @returns {Promise} Resolves when the socket is closed */ close (error) { return new Promise((resolve) => { var tearDown = () => { // fulfill pending promises this._clientQueue.forEach(cmd => cmd.callback(error)) if (this._currentCommand) { this._currentCommand.callback(error) } this._clientQueue = [] this._currentCommand = false clearTimeout(this._idleTimer) this._idleTimer = null clearTimeout(this._socketTimeoutTimer) this._socketTimeoutTimer = null if (this.socket) { // remove all listeners this.socket.onopen = null this.socket.onclose = null this.socket.ondata = null this.socket.onerror = null try { this.socket.oncert = null } catch (E) { } this.socket = null } resolve() } this._disableCompression() if (!this.socket || this.socket.readyState !== 'open') { return tearDown() } this.socket.onclose = this.socket.onerror = tearDown // we don't really care about the error here this.socket.close() }) } /** * Send LOGOUT to the server. * * Use is discouraged! * * @returns {Promise} Resolves when connection is closed by server. */ logout () { return new Promise((resolve, reject) => { this.socket.onclose = this.socket.onerror = () => { this.close('Client logging out').then(resolve).catch(reject) } this.enqueueCommand('LOGOUT') }) } /** * Initiates TLS handshake */ upgrade () { this.secureMode = true this.socket.upgradeToSecure() } /** * Schedules a command to be sent to the server. * See https://github.com/emailjs/emailjs-imap-handler for request structure. * Do not provide a tag property, it will be set by the queue manager. * * To catch untagged responses use acceptUntagged property. For example, if * the value for it is 'FETCH' then the reponse includes 'payload.FETCH' property * that is an array including all listed * FETCH responses. * * @param {Object} request Structured request object * @param {Array} acceptUntagged a list of untagged responses that will be included in 'payload' property * @param {Object} [options] Optional data for the command payload * @returns {Promise} Promise that resolves when the corresponding response was received */ enqueueCommand (request, acceptUntagged, options) { if (typeof request === 'string') { request = { command: request } } acceptUntagged = [].concat(acceptUntagged || []).map((untagged) => (untagged || '').toString().toUpperCase().trim()) var tag = 'W' + (++this._tagCounter) request.tag = tag return new Promise((resolve, reject) => { var data = { tag: tag, request: request, payload: acceptUntagged.length ? {} : undefined, callback: (response) => { if (this.isError(response)) { return reject(response) } else if (['NO', 'BAD'].indexOf(propOr('', 'command', response).toUpperCase().trim()) >= 0) { var error = new Error(response.humanReadable || 'Error') if (response.code) { error.code = response.code } return reject(error) } resolve(response) } } // apply any additional options to the command Object.keys(options || {}).forEach((key) => { data[key] = options[key] }) acceptUntagged.forEach((command) => { data.payload[command] = [] }) // if we're in priority mode (i.e. we ran commands in a precheck), // queue any commands BEFORE the command that contianed the precheck, // otherwise just queue command as usual var index = data.ctx ? this._clientQueue.indexOf(data.ctx) : -1 if (index >= 0) { data.tag += '.p' data.request.tag += '.p' this._clientQueue.splice(index, 0, data) } else { this._clientQueue.push(data) } if (this._canSend) { this._sendRequest() } }) } /** * * @param commands * @param ctx * @returns {*} */ getPreviouslyQueued (commands, ctx) { const startIndex = this._clientQueue.indexOf(ctx) - 1 // search backwards for the commands and return the first found for (let i = startIndex; i >= 0; i--) { if (isMatch(this._clientQueue[i])) { return this._clientQueue[i] } } // also check current command if no SELECT is queued if (isMatch(this._currentCommand)) { return this._currentCommand } return false function isMatch (data) { return data && data.request && commands.indexOf(data.request.command) >= 0 } } /** * Send data to the TCP socket * Arms a timeout waiting for a response from the server. * * @param {String} str Payload */ send (str) { const buffer = toTypedArray(str).buffer const timeout = this.timeoutSocketLowerBound + Math.floor(buffer.byteLength * this.timeoutSocketMultiplier) clearTimeout(this._socketTimeoutTimer) // clear pending timeouts this._socketTimeoutTimer = setTimeout(() => this._onError(new Error(' Socket timed out!')), timeout) // arm the next timeout if (this.compressed) { this._sendCompressed(buffer) } else { this.socket.send(buffer) } } /** * Set a global handler for an untagged response. If currently processed command * has not listed untagged command it is forwarded to the global handler. Useful * with EXPUNGE, EXISTS etc. * * @param {String} command Untagged command name * @param {Function} callback Callback function with response object and continue callback function */ setHandler (command, callback) { this._globalAcceptUntagged[command.toUpperCase().trim()] = callback } // INTERNAL EVENTS /** * Error handler for the socket * * @event * @param {Event} evt Event object. See evt.data for the error */ _onError (evt) { var error if (this.isError(evt)) { error = evt } else if (evt && this.isError(evt.data)) { error = evt.data } else { error = new Error((evt && evt.data && evt.data.message) || evt.data || evt || 'Error') } this.logger.error(error) // always call onerror callback, no matter if close() succeeds or fails this.close(error).then(() => { this.onerror && this.onerror(error) }, () => { this.onerror && this.onerror(error) }) } /** * Handler for incoming data from the server. The data is sent in arbitrary * chunks and can't be used directly so this function makes sure the data * is split into complete lines before the data is passed to the command * handler * * @param {Event} evt */ _onData (evt) { clearTimeout(this._socketTimeoutTimer) // reset the timeout on each data packet const timeout = this.timeoutSocketLowerBound + Math.floor(4096 * this.timeoutSocketMultiplier) // max packet size is 4096 bytes this._socketTimeoutTimer = setTimeout(() => this._onError(new Error(' Socket timed out!')), timeout) this._incomingBuffers.push(new Uint8Array(evt.data)) // append to the incoming buffer this._parseIncomingCommands(this._iterateIncomingBuffer()) // Consume the incoming buffer } * _iterateIncomingBuffer () { let buf = this._incomingBuffers[this._incomingBuffers.length - 1] || [] let i = 0 // loop invariant: // this._incomingBuffers starts with the beginning of incoming command. // buf is shorthand for last element of this._incomingBuffers. // buf[0..i-1] is part of incoming command. while (i < buf.length) { switch (this._bufferState) { case BUFFER_STATE_LITERAL: const diff = Math.min(buf.length - i, this._literalRemaining) this._literalRemaining -= diff i += diff if (this._literalRemaining === 0) { this._bufferState = BUFFER_STATE_DEFAULT } continue case BUFFER_STATE_POSSIBLY_LITERAL_LENGTH_2: if (i < buf.length) { if (buf[i] === CARRIAGE_RETURN) { this._literalRemaining = Number(fromTypedArray(this._lengthBuffer)) + 2 // for CRLF this._bufferState = BUFFER_STATE_LITERAL } else { this._bufferState = BUFFER_STATE_DEFAULT } delete this._lengthBuffer } continue case BUFFER_STATE_POSSIBLY_LITERAL_LENGTH_1: const start = i while (i < buf.length && buf[i] >= 48 && buf[i] <= 57) { // digits i++ } if (start !== i) { const latest = buf.subarray(start, i) const prevBuf = this._lengthBuffer this._lengthBuffer = new Uint8Array(prevBuf.length + latest.length) this._lengthBuffer.set(prevBuf) this._lengthBuffer.set(latest, prevBuf.length) } if (i < buf.length) { if (this._lengthBuffer.length > 0 && buf[i] === RIGHT_CURLY_BRACKET) { this._bufferState = BUFFER_STATE_POSSIBLY_LITERAL_LENGTH_2 } else { delete this._lengthBuffer this._bufferState = BUFFER_STATE_DEFAULT } i++ } continue default: // find literal length const leftIdx = buf.indexOf(LEFT_CURLY_BRACKET, i) if (leftIdx > -1) { const leftOfLeftCurly = new Uint8Array(buf.buffer, i, leftIdx - i) if (leftOfLeftCurly.indexOf(LINE_FEED) === -1) { i = leftIdx + 1 this._lengthBuffer = new Uint8Array(0) this._bufferState = BUFFER_STATE_POSSIBLY_LITERAL_LENGTH_1 continue } } // find end of command const LFidx = buf.indexOf(LINE_FEED, i) if (LFidx > -1) { if (LFidx < buf.length - 1) { this._incomingBuffers[this._incomingBuffers.length - 1] = new Uint8Array(buf.buffer, 0, LFidx + 1) } const commandLength = this._incomingBuffers.reduce((prev, curr) => prev + curr.length, 0) - 2 // 2 for CRLF const command = new Uint8Array(commandLength) let index = 0 while (this._incomingBuffers.length > 0) { let uint8Array = this._incomingBuffers.shift() const remainingLength = commandLength - index if (uint8Array.length > remainingLength) { const excessLength = uint8Array.length - remainingLength uint8Array = uint8Array.subarray(0, -excessLength) if (this._incomingBuffers.length > 0) { this._incomingBuffers = [] } } command.set(uint8Array, index) index += uint8Array.length } yield command if (LFidx < buf.length - 1) { buf = new Uint8Array(buf.subarray(LFidx + 1)) this._incomingBuffers.push(buf) i = 0 } else { // clear the timeout when an entire command has arrived // and not waiting on more data for next command clearTimeout(this._socketTimeoutTimer) this._socketTimeoutTimer = null return } } else { return } } } } // PRIVATE METHODS /** * Processes a command from the queue. The command is parsed and feeded to a handler */ _parseIncomingCommands (commands) { for (var command of commands) { this._clearIdle() /* * The "+"-tagged response is a special case: * Either the server can asks for the next chunk of data, e.g. for the AUTHENTICATE command. * * Or there was an error in the XOAUTH2 authentication, for which SASL initial client response extension * dictates the client sends an empty EOL response to the challenge containing the error message. * * Details on "+"-tagged response: * https://tools.ietf.org/html/rfc3501#section-2.2.1 */ // if (command[0] === ASCII_PLUS) { if (this._currentCommand.data.length) { // feed the next chunk of data var chunk = this._currentCommand.data.shift() chunk += (!this._currentCommand.data.length ? EOL : '') // EOL if there's nothing more to send this.send(chunk) } else if (this._currentCommand.errorResponseExpectsEmptyLine) { this.send(EOL) // XOAUTH2 empty response, error will be reported when server continues with NO response } continue } var response try { const valueAsString = this._currentCommand.request && this._currentCommand.request.valueAsString response = parser(command, { valueAsString }) this.logger.debug('S:', () => compiler(response, false, true)) } catch (e) { this.logger.error('Error parsing imap command!', response) return this._onError(e) } this._processResponse(response) this._handleResponse(response) // first response from the server, connection is now usable if (!this._connectionReady) { this._connectionReady = true this.onready && this.onready() } } } /** * Feeds a parsed response object to an appropriate handler * * @param {Object} response Parsed command object */ _handleResponse (response) { var command = propOr('', 'command', response).toUpperCase().trim() if (!this._currentCommand) { // unsolicited untagged response if (response.tag === '*' && command in this._globalAcceptUntagged) { this._globalAcceptUntagged[command](response) this._canSend = true this._sendRequest() } } else if (this._currentCommand.payload && response.tag === '*' && command in this._currentCommand.payload) { // expected untagged response this._currentCommand.payload[command].push(response) } else if (response.tag === '*' && command in this._globalAcceptUntagged) { // unexpected untagged response this._globalAcceptUntagged[command](response) } else if (response.tag === this._currentCommand.tag) { // tagged response if (this._currentCommand.payload && Object.keys(this._currentCommand.payload).length) { response.payload = this._currentCommand.payload } this._currentCommand.callback(response) this._canSend = true this._sendRequest() } } /** * Sends a command from client queue to the server. */ _sendRequest () { if (!this._clientQueue.length) { return this._enterIdle() } this._clearIdle() // an operation was made in the precheck, no need to restart the queue manually this._restartQueue = false var command = this._clientQueue[0] if (typeof command.precheck === 'function') { // remember the context var context = command var precheck = context.precheck delete context.precheck // we need to restart the queue handling if no operation was made in the precheck this._restartQueue = true // invoke the precheck command and resume normal operation after the promise resolves precheck(context).then(() => { // we're done with the precheck if (this._restartQueue) { // we need to restart the queue handling this._sendRequest() } }).catch((err) => { // precheck failed, so we remove the initial command // from the queue, invoke its callback and resume normal operation let cmd const index = this._clientQueue.indexOf(context) if (index >= 0) { cmd = this._clientQueue.splice(index, 1)[0] } if (cmd && cmd.callback) { cmd.callback(err) this._canSend = true this._parseIncomingCommands(this._iterateIncomingBuffer()) // Consume the rest of the incoming buffer this._sendRequest() // continue sending } }) return } this._canSend = false this._currentCommand = this._clientQueue.shift() try { this._currentCommand.data = compiler(this._currentCommand.request, true) this.logger.debug('C:', () => compiler(this._currentCommand.request, false, true)) // excludes passwords etc. } catch (e) { this.logger.error('Error compiling imap command!', this._currentCommand.request) return this._onError(new Error('Error compiling imap command!')) } var data = this._currentCommand.data.shift() this.send(data + (!this._currentCommand.data.length ? EOL : '')) return this.waitDrain } /** * Emits onidle, noting to do currently */ _enterIdle () { clearTimeout(this._idleTimer) this._idleTimer = setTimeout(() => (this.onidle && this.onidle()), this.timeoutEnterIdle) } /** * Cancel idle timer */ _clearIdle () { clearTimeout(this._idleTimer) this._idleTimer = null } /** * Method processes a response into an easier to handle format. * Add untagged numbered responses (e.g. FETCH) into a nicely feasible form * Checks if a response includes optional response codes * and copies these into separate properties. For example the * following response includes a capability listing and a human * readable message: * * * OK [CAPABILITY ID NAMESPACE] All ready * * This method adds a 'capability' property with an array value ['ID', 'NAMESPACE'] * to the response object. Additionally 'All ready' is added as 'humanReadable' property. * * See possiblem IMAP Response Codes at https://tools.ietf.org/html/rfc5530 * * @param {Object} response Parsed response object */ _processResponse (response) { let command = propOr('', 'command', response).toUpperCase().trim() // no attributes if (!response || !response.attributes || !response.attributes.length) { return } // untagged responses w/ sequence numbers if (response.tag === '*' && /^\d+$/.test(response.command) && response.attributes[0].type === 'ATOM') { response.nr = Number(response.command) response.command = (response.attributes.shift().value || '').toString().toUpperCase().trim() } // no optional response code if (['OK', 'NO', 'BAD', 'BYE', 'PREAUTH'].indexOf(command) < 0) { return } // If last element of the response is TEXT then this is for humans if (response.attributes[response.attributes.length - 1].type === 'TEXT') { response.humanReadable = response.attributes[response.attributes.length - 1].value } // Parse and format ATOM values if (response.attributes[0].type === 'ATOM' && response.attributes[0].section) { const option = response.attributes[0].section.map((key) => { if (!key) { return } if (Array.isArray(key)) { return key.map((key) => (key.value || '').toString().trim()) } else { return (key.value || '').toString().toUpperCase().trim() } }) const key = option.shift() response.code = key if (option.length === 1) { response[key.toLowerCase()] = option[0] } else if (option.length > 1) { response[key.toLowerCase()] = option } } } /** * Checks if a value is an Error object * * @param {Mixed} value Value to be checked * @return {Boolean} returns true if the value is an Error */ isError (value) { return !!Object.prototype.toString.call(value).match(/Error\]$/) } // COMPRESSION RELATED METHODS /** * Sets up deflate/inflate for the IO */ enableCompression () { this._socketOnData = this.socket.ondata this.compressed = true if (typeof window !== 'undefined' && window.Worker) { this._compressionWorker = new Worker(URL.createObjectURL(new Blob([CompressionBlob]))) this._compressionWorker.onmessage = (e) => { var message = e.data.message var data = e.data.buffer switch (message) { case MESSAGE_INFLATED_DATA_READY: this._socketOnData({ data }) break case MESSAGE_DEFLATED_DATA_READY: this.waitDrain = this.socket.send(data) break } } this._compressionWorker.onerror = (e) => { this._onError(new Error('Error handling compression web worker: ' + e.message)) } this._compressionWorker.postMessage(createMessage(MESSAGE_INITIALIZE_WORKER)) } else { const inflatedReady = (buffer) => { this._socketOnData({ data: buffer }) } const deflatedReady = (buffer) => { this.waitDrain = this.socket.send(buffer) } this._compression = new Compression(inflatedReady, deflatedReady) } // override data handler, decompress incoming data this.socket.ondata = (evt) => { if (!this.compressed) { return } if (this._compressionWorker) { this._compressionWorker.postMessage(createMessage(MESSAGE_INFLATE, evt.data), [evt.data]) } else { this._compression.inflate(evt.data) } } } /** * Undoes any changes related to compression. This only be called when closing the connection */ _disableCompression () { if (!this.compressed) { return } this.compressed = false this.socket.ondata = this._socketOnData this._socketOnData = null if (this._compressionWorker) { // terminate the worker this._compressionWorker.terminate() this._compressionWorker = null } } /** * Outgoing payload needs to be compressed and sent to socket * * @param {ArrayBuffer} buffer Outgoing uncompressed arraybuffer */ _sendCompressed (buffer) { // deflate if (this._compressionWorker) { this._compressionWorker.postMessage(createMessage(MESSAGE_DEFLATE, buffer), [buffer]) } else { this._compression.deflate(buffer) } } }
JavaScript
class ZoneFinances { constructor() { } dispose() { } }
JavaScript
class PouchDb extends HTMLElement { constructor() { super(); } /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ static get tag() { return "pouch-db"; } /** * life cycle, element is afixed to the DOM */ connectedCallback() { window.addEventListener( "user-engagement", this.userEngagmentFunction.bind(this) ); window.addEventListener("get-data", this.getDataFunction.bind(this)); } /** * life cycle, element is removed from the DOM */ disconnectedCallback() { window.removeEventListener( "user-engagement", this.userEngagmentFunction.bind(this) ); window.removeEventListener("get-data", this.getDataFunction.bind(this)); } userEngagmentFunction(e) { var eventData = e.detail; var whatEvent = e.target.tagName; switch (whatEvent) { case "MULTIPLE-CHOICE": var dbType = "xapistatements"; var activityDisplay = eventData.activityDisplay; var activityId = "http://adlnet.gov/expapi/verbs/" + activityDisplay; //this may need to be changed in the future for more verbs var objectId = "http://haxcms.psu.edu/haxQuiz"; var objectName = eventData.objectName; var objectDescription = "HAX Quiz"; //hard-coded for now for results, future tracking change to pull data from eventData.x var resultScoreScaled = 1; var resultScoreMin = 0; var resultScoreMax = 100; var resultScoreRaw = 100; var resultSuccess = eventData.resultSuccess; var resultCompletion = true; var resultResponse = "sample"; var resultDuration = "sample"; //hard-coded for now for results, future tracking change to pull data from eventData.x break; default: break; } var db = new PouchDB(dbType); var remoteCouch = false; ///var remoteCouch = 'http://35.164.8.64:3000/todos'; //these need to be updated to pull from global var userEmail = "mailto:[email protected]"; var userName = "Dave Fusco"; var objectStatement = { actor: { mbox: userEmail, name: userName, objectType: "Agent", }, verb: { id: activityId, display: { "en-US": activityDisplay, }, }, object: { id: objectId, definition: { name: { "en-US": objectName, }, description: { "en-US": objectDescription, }, }, objectType: "Activity", }, result: { score: { scaled: resultScoreScaled, min: resultScoreMin, max: resultScoreMax, raw: resultScoreRaw, }, success: resultSuccess, completion: resultCompletion, response: resultResponse, duration: resultDuration, }, }; var xapistatement = { _id: new Date().toISOString(), title: JSON.stringify(objectStatement), completed: false, }; db.put(xapistatement, function callback(err, result) { if (!err) { console.log("Successfully posted a statement!"); } }); if (remoteCouch) { var opts = { live: true }; db.replicate.to(remoteCouch, opts, syncError); db.replicate.from(remoteCouch, opts, syncError); } //display for testing only - move to own elements db.allDocs({ include_docs: true, descending: true }, function (err, doc) { console.log(doc.rows); }); //display for testing only - move to own elements } getDataFunction(e) { var eventData = e.detail; var whatEvent = e.target.tagName; switch (eventData.queryRequest) { case "all-quizzes": var dbType = "xapistatements"; //this needs to be changed to be more dynamic in the future break; case "single-quiz": var dbType = "xapistatements"; //this needs to be changed to be more dynamic in the future var objectName = eventData.objectName; //"Quiz2" break; case "future-query": var dbType = "xapistatements"; var activityDisplay = eventData.activityDisplay; var objectName = eventData.objectName; var resultSuccess = eventData.resultSuccess; var resultCompletion = eventData.resultCompletion; break; default: var dbType = "xapistatements"; break; } var db = new PouchDB(dbType); var remoteCouch = false; ///var remoteCouch = 'http://35.164.8.64:3000/todos'; //ADD SINGLE-QUIZ QUERY function processxAPI(statements, callback) { var arrayxAPI = []; statements.forEach(function (statement) { var out = JSON.parse(statement.doc.title); //var jsonStatement = out.verb.display['en-US']; //verb var jsonStatement = out.object.definition.name["en-US"]; //all quizzes; quiz name arrayxAPI.push(jsonStatement); }); callback(arrayxAPI); } function processItems(statements, callback) { var map = {}; statements.forEach(function (statement) { map[statement] = (map[statement] || 0) + 1; }); callback(map); } db.allDocs({ include_docs: true, descending: true }, function (err, doc) { processxAPI( doc.rows, function displayxAPI(mapxAPI) { processItems( mapxAPI, function display(backMap) { var labelsArray = []; var resultsArray = []; for (let key of Object.keys(backMap)) { labelsArray.push(key); } for (let value of Object.values(backMap)) { resultsArray.push(value); } let queryData = [""]; queryData = { labels: labelsArray, series: [resultsArray], //activityDisplay: eventData.resultCompletion, //FUTURE //objectName: eventData.objectName, //FUTURE //resultSuccess: eventData.resultSuccess //FUTURE //resultCompletion: eventData.resultCompletion //FUTURE }; window.dispatchEvent( new CustomEvent("show-data", { bubbles: true, composed: true, cancelable: false, detail: queryData, }) ); } // end of display function ); //end of processItems } // end of displayxAPI function ); //end of processxAPI }); //end of db.allDocs } // end of getDataFunction }
JavaScript
class ContractResultDetailsViewModel extends ContractResultViewModel { static _FAIL_PROTO_ID = Number.parseInt(TransactionResult.getSuccessProtoId()); static _SUCCESS_RESULT = '0x1'; static _FAIL_RESULT = '0x0'; /** * Constructs contractResultDetails view model * * @param {ContractResult} contractResult * @param {RecordFile} recordFile * @param {Transaction} transaction * @param {ContractLog[]} contractLogs * @param {ContractStateChange[]} contractStateChanges */ constructor(contractResult, recordFile, transaction, contractLogs, contractStateChanges) { super(contractResult); Object.assign(this, { block_hash: utils.addHexPrefix(recordFile.hash), block_number: Number(recordFile.index), hash: utils.toHexString(transaction.transactionHash, true), logs: contractLogs.map((contractLog) => new ContractLogResultsViewModel(contractLog)), result: TransactionResult.getName(transaction.result), state_changes: contractStateChanges.map( (contractStateChange) => new ContractResultStateChangeViewModel(contractStateChange) ), status: transaction.result === ContractResultDetailsViewModel._FAIL_PROTO_ID ? ContractResultDetailsViewModel._SUCCESS_RESULT : ContractResultDetailsViewModel._FAIL_RESULT, }); } }
JavaScript
class Model { /** * All events fired by a model */ static SAVED = 'saved' static CREATED = 'created' static UPDATED = 'updated' static TRASHED = 'trashed' static FETCHED = 'fetched' static ATTACHED = 'attached' static DETACHED = 'detached' static DESTROYED = 'destroyed' static COLLECTED = 'collected' static ATTRIBUTE_SET = 'attributeSet' static RELATIONS_SAVED = 'relationsSaved' static RELATIONSHIP_SET = 'relationshipSet' static ATTRIBUTE_REMOVED = 'attributeRemoved' static RELATIONSHIP_REMOVED = 'relationshipRemoved' /** * Used for semi-automatic hydration client-side * @type {string} */ static CLASS_NAME = 'Model' /** * Instantiate a new model * @param resource * @param schema */ constructor (resource, schema) { this._runSetupChecks() this.schema = new Schema(schema) if (resource === null) { this._builder = new Builder(this) } else { return this._setup(resource) } } /** * Run the setup routine * @param resource * @returns {Model} * @private */ _setup (resource) { resource = cloneDeep(resource) this.isNew = true this.wasDestroyed = false this.included = this._filterIncluded(resource) this.resource = this._setData(resource) this.original = cloneDeep(this.resource) this._guardAgainstInvalidSchema() /** * Here we run any setup for the instantiated class */ this.constructor.boot() return new Proxy(this, proxyHandler) } /** * Perform a set of checks * @private */ _runSetupChecks () { if (Model.$config.http === undefined) { throw Exception.axiosNotPresent() } if (Model.$config?.typeMap === undefined) { throw Exception.typeMapNotPresent() } if (this.constructor.jsonApiType() === '') { throw Exception.jsonApiTypeNotSet(this) } if (isEmpty(this.attributes)) { throw Exception.propertyDefaultsNotSet(this) } } /** * Guard against an invalid json schema * @private */ _guardAgainstInvalidSchema () { if (!this.schema.validate(this.resource)) { throw Exception.invalidResource(this, this.schema.errors) } } /** * Sets the data on the resource or creates a default * @param resource * @returns {{data: *}} * @private */ _setData (resource) { let data if (!this.schema.isJsonApi(resource)) { data = { id: this.newId(), type: this.constructor.jsonApiType(), attributes: this._mergeDefaultAttributes(resource), relationships: {} } if (!data.id) { unset(data, 'id') } } else { data = resource?.data this.isNew = false } return { data } } /** * * @param resource * @returns {{}} * @private */ _mergeDefaultAttributes (resource) { if (!isObject(resource)) { return this.attributes } return merge( Object.assign({}, this.attributes), collect(resource).only(Object.keys(this.attributes)).all() ) } /** * Only include related models * @param resource * @returns {object} * @private */ _filterIncluded (resource) { const ids = Object.values(resource?.data?.relationships ?? {}).reduce( (ids, relationship) => { if (Array.isArray(relationship.data)) { relationship.data.forEach(({ data: id }) => ids.push(id)) } else { ids.push(relationship.data.id) } return ids }, [] ) return collect(resource?.includes ?? []) .filter( ({ id }) => ids.includes(id) ) .map( included => Model.hydrate(included) ) } /** * */ static boot () { // can be overridden to add events } /** * Gets the base entity for a given type * @param type * @returns {*} */ static entityForType (type) { if (!has(Model.$config.typeMap, type)) { throw Exception.modelMappingMissing(this, type) } return Model.$config.typeMap[type] } /** * Hydrate a model with some resource data * @param resource * @returns {*} */ static hydrate (resource) { if (!has(resource, 'data')) { resource = { data: resource } } const type = resource?.data?.type ?? null const Entity = this.entityForType(type) if (Entity.subTypeField() === null) { return new Entity(resource) } const subType = get(resource, Entity.subTypeField()) const SubEntity = Entity.children()?.[subType] ?? Entity return new SubEntity(resource) } /** * Get all child models * @returns {object} */ static children () { return {} } /** * Get all attributes that should be cast to an object * @returns {object} */ get casts () { return {} } /** * Get the field holding the type to hydrate * @returns {string|null} */ static subTypeField () { return null } /** * Get the model Axios instance * @returns {*} */ get http () { return Model.$config.http } /** * Get the model Vuex instance * @returns {*} */ get store () { return Model.$config.store } /** * Check if we use the store * @returns {boolean} */ get usingStore () { return Model?.$config?.store !== undefined } /** * Sync the model to Vuex */ syncToStore () { if (this.usingStore) { this.store.dispatch(`${Model.$config.namespace}/sync`, this) } } /** * Remove the model from Vuex */ removeFromStore () { if (this.usingStore) { this.store.dispatch(`${Model.$config.namespace}/remove`, this) } } /** * Fire model events * @param event * @param payload * @returns {Model} * @private */ _emit (event, payload = {}) { const events = Array.isArray(event) ? event : [event] events.forEach( (name) => { Model.$config.events.emit(name, payload) Model.$config.events.emit(`${this.type}.${name}`, payload) } ) return this } /** * Add event handlers * @param event * @param handler */ static on (event, handler) { const events = Array.isArray(event) ? event : [event] events.forEach(name => Model.$config.events.on( trimStart(`${this.jsonApiType()}.${name}`, '.'), handler )) } /** * Remove event handlers * @param event * @param handler */ static off (event, handler = null) { const events = Array.isArray(event) ? event : [event] events.forEach(name => Model.$config.events.off( trimStart(`${this.jsonApiType()}.${name}`, '.'), handler )) } /** * Add event handlers for the SAVED event * @param handler */ static onSaved (handler) { this.on(this.SAVED, handler) } /** * Add event handlers for the CREATED event * @param handler */ static onCreated (handler) { this.on(this.CREATED, handler) } /** * Add event handlers for the UPDATED event * @param handler */ static onUpdated (handler) { this.on(this.UPDATED, handler) } /** * Add event handlers for the TRASHED event * @param handler */ static onTrashed (handler) { this.on(this.TRASHED, handler) } /** * Add event handlers for the FETCHED event * @param handler */ static onFetched (handler) { this.on(this.FETCHED, handler) } /** * Add event handlers for the ATTACHED event * @param handler */ static onAttached (handler) { this.on(this.ATTACHED, handler) } /** * Add event handlers for the DETACHED event * @param handler */ static onDetached (handler) { this.on(this.DETACHED, handler) } /** * Add event handlers for the DESTROYED event * @param handler */ static onDestroyed (handler) { this.on(this.DESTROYED, handler) } /** * Add event handlers for the COLLECTED event * @param handler */ static onCollected (handler) { this.on(this.COLLECTED, handler) } /** * Add event handlers for the RELATIONS_SAVED event * @param handler */ static onRelationsSaved (handler) { this.on(this.RELATIONS_SAVED, handler) } /** * Add event handlers for the ATTRIBUTE_SET event * @param handler */ static onAttributeSet (handler) { this.on(this.ATTRIBUTE_SET, handler) } /** * Add event handlers for the ATTRIBUTE_REMOVED event * @param handler */ static onAttributeRemoved (handler) { this.on(this.ATTRIBUTE_REMOVED, handler) } /** * Add event handlers for the RELATIONSHIP_SET event * @param handler */ static onRelationshipSet (handler) { this.on(this.RELATIONSHIP_SET, handler) } /** * Add event handlers for the RELATIONSHIP_REMOVED event * @param handler */ static onRelationshipRemoved (handler) { this.on(this.RELATIONSHIP_REMOVED, handler) } /** * The JSON:API type, must be overridden in a child class * @returns {string} */ static jsonApiType () { return '' } /** * Holds any validation rules * * @returns {object} */ get validations () { return {} } /** * Get the formatted validation rules * * @returns {object} */ get validationRules () { return { resource: { data: { attributes: this.validations } } } } /** * Holds all allowed model attributes and their default value * @returns {object} */ get attributes () { return {} } /** * Gets the model ID * @returns {*} */ get id () { return this.resource?.data?.id ?? null } /** * Sets the ID of the model, must be a UUID * @param id */ set id (id) { this.isNew = true set(this.resource, 'data.id', id) } /** * Generate an id * @returns {string|null} */ newId () { return uuid() } /** * Gets the base uri for http requests * @returns {string} */ get baseUri () { return this.type } /** * Gets the model type * @returns {string} */ get type () { return this.resource?.data?.type ?? this.constructor.jsonApiType() } /** * Flag that describes if the model data has been modified * @returns {boolean} */ isDirty () { return !isEqual(this.original, this.resource) } /** * Get the attribute that decides if a model is trashed or not * @returns {*} * @private */ get trashedAttribute () { return Model.$config?.trashedAttribute ?? 'deletedAt' } /** * Flag that describes if the model has been soft deleted * @returns {boolean} */ isTrashed () { return this.attribute(this.trashedAttribute) instanceof Date } /** * Any attributes that are only for local consumption * @returns {*[]} */ get localAttributes () { return [ 'links', 'attributes.createdAt', 'attributes.updatedAt', `attributes.${this.trashedAttribute}` ] } /** * Get the plain object representation of the object * @returns {{data: *}} */ toJSON () { this._guardAgainstInvalidSchema() return this.resource } /** * Get the JSON:API representation of the model * @returns {object} */ toJsonApi () { this._guardAgainstInvalidSchema() const resource = cloneDeep(this.resource) this.localAttributes .map(key => `data.${key}`) .forEach(path => unset(resource, path)) return resource } /** * Check if an attribute exists * @param key * @returns {boolean|boolean} */ hasAttribute (key) { return key in this.attributes } /** * Get a model attribute * @param key * @returns {*} * @private */ _getAttribute (key) { const value = get( this.resource, `data.attributes.${key}`, get(this.attributes, key, null) ) if (has(this.casts, key)) { return this.casts[key].hydrate(value) } return value } /** * Removes a model attribute * @param key * @returns {Model} * @private */ _removeAttribute (key) { unset(this.resource, `data.attributes.${key}`) this._emit(Model.ATTRIBUTE_REMOVED, { key, model: this }) return this } /** * Sets a model attribute * @param key * @param value * @returns {Model} * @private */ _setAttribute (key, value) { if (has(this.casts, key)) { value = this.casts[key].dehydrate(value) } set(this.resource, `data.attributes.${key}`, value) this._emit(Model.ATTRIBUTE_REMOVED, { key, model: this }) return this } /** * Gets, sets or removes a model attribute * @param key * @param value * @returns {Model|null} */ attribute (key, value) { if (value === undefined) { return this._getAttribute(key) } if (!this.hasAttribute(key)) { throw Exception.forbiddenAttribute(this, key) } if (value === null) { return this._removeAttribute(key) } return this._setAttribute(key, value) } /** * Get all allowed relationships for the model * @returns {{}} */ get relationships () { return {} } /** * Denotes a relationship as hasMany * @param model * @param key * @returns {HasMany} */ hasMany (model, key) { return new HasMany(this, model, key) } /** * Denotes a relationship as hasOne * @param model * @param key * @returns {HasOne} */ hasOne (model, key) { return new HasOne(this, model, key) } /** * Check if an attribute exists * @param key * @returns {boolean|boolean} */ hasRelationship (key) { return key in this.relationships } /** * Get a model relationship * @param key * @returns {null|Relation} * @private */ _getRelationship (key) { const relation = this.relationships?.[key] return relation === undefined ? null : relation } /** * Remove a model relationship * @param key * @returns {Model} * @private */ _removeRelationship (key) { unset(this.resource, `data.relationships.${key}`) this._emit(Model.RELATIONSHIP_REMOVED, { key, model: this }) return this } /** * Set a model relationship * @param key * @param model * @returns {Model} * @private */ _setRelationship (key, model) { this.relationship(key).attach(model) if (!this.included.pluck('id').contains(model.id)) { this.included.push(model) } this._emit(Model.RELATIONSHIP_SET, { key, model: this, attached: model }) return this } /** * Gets, sets or removes a model relationship * @param key * @param value * @returns {Relation|this} */ relationship (key, value) { if (value === undefined) { return this._getRelationship(key) } if (!this.hasRelationship(key)) { throw Exception.forbiddenRelationship(this, key) } if (value === null) { return this._removeRelationship(key) } return this._setRelationship(key, value) } /** * Attach a model to a relationship * @param key * @param model */ attach (key, model) { if (!this.hasRelationship(key)) { throw Exception.forbiddenRelationship(key) } this._setRelationship(key, model) this._emit(Model.ATTACHED, { key, model: this, attached: model }) return this } /** * Detach a model from a relationship * @param key * @param model */ detach (key, model) { if (!this.hasRelationship(key)) { throw Exception.forbiddenRelationship(key) } this.relationship(key).detach(model) this._emit(Model.DETACHED, { key, model: this, detached: model }) return this } /** * Add an include query * @param args * @returns {Model} */ include (...args) { this._builder.include(...args) return this } /** * Add an append query * @param args * @returns {Model} */ append (...args) { this._builder.append(...args) return this } /** * Add a select query * @param fields * @returns {Model} */ select (...fields) { this._builder.select(...fields) return this } /** * Add a where query * @param field * @param value * @returns {Model} */ where (field, value) { this._builder.where(field, value) return this } /** * Add a where in query * @param field * @param array * @returns {Model} */ whereIn (field, array) { this._builder.whereIn(field, array) return this } /** * Add an order by query * @param args * @returns {Model} */ orderBy (...args) { this._builder.orderBy(...args) return this } /** * Add a page query * @param value * @returns {Model} */ page (value) { this._builder.page(value) return this } /** * Add a limit query * @param value * @returns {Model} */ limit (value) { this._builder.limit(value) return this } /** * Get a collection of resources * @returns {Promise<*>} */ async get (asCollection = false) { const response = await this.http.get(`${this.baseUri}${this._builder.query()}`) const collection = asCollection ? Paginator.fromResponse(response.data) : new Paginator(response.data) this._emit(Model.COLLECTED, { response, collection, model: this }) return collection } /** * Get a single resource * @param id * @returns {Promise<*>} */ async find (id) { const response = await this.http.get(`${this.baseUri}/${id}${this._builder.query()}`) const model = Model.hydrate(response.data) this._emit(Model.FETCHED, { model, response }) return Promise.resolve(model) } /** * Delete the resource from storage * @returns {Promise<*>} */ async delete () { if (this.isNew) { throw Exception.cannotDeleteModel(this) } const response = await this.http.delete(`${this.baseUri}/${this.id}`) if (this._canBeDestroyed(response)) { this.wasDestroyed = true this._emit(Model.DESTROYED, { response, model: this }) } if (!this.wasDestroyed && this._isTrashable() && !this.isTrashed()) { this.attribute(this.trashedAttribute, formatISO(new Date())) this._emit(Model.TRASHED, { response, model: this }) } return Promise.resolve(response) } /** * Helper to see if the model is trashable * @returns {boolean} * @private */ _isTrashable () { return this.attributes?.[this.trashedAttribute] !== undefined } /** * Helper to see if the wasDestroyed flag should be set * @param response * @returns {boolean} * @private */ _canBeDestroyed (response) { const wasSuccessful = response.status === Response.NO_CONTENT if (!this._isTrashable()) { return wasSuccessful } return wasSuccessful && this.isTrashed() } /** * Persist or update the resource in storage * @returns {Promise<*>} */ async createOrUpdate () { return await (this.isNew ? this.create() : this.update()) } /** * Persist the resource in storage * @returns {Promise<*>} */ async create () { if (!this.isNew) { throw Exception.cannotCreateModel(this) } const response = await this.http.post(this.baseUri, this.toJSON()) if (response.status === Response.CREATED) { await this._autoSaveRelationships() this.isNew = false this._emit([Model.CREATED, Model.SAVED], { response, model: this }) } return Promise.resolve(response) } /** * Update the resource in storage * @returns {Promise<*>} */ async update () { if (this.isNew) { throw Exception.cannotUpdateModel(this) } const response = await this.http.put(`${this.baseUri}/${this.id}`, this.toJSON()) if (response.status === Response.NO_CONTENT) { await this._autoSaveRelationships() this._emit([Model.UPDATED, Model.SAVED], { response, model: this }) } return Promise.resolve(response) } /** * Automatically save any relationships * @returns {Promise<array>} * @private */ async _autoSaveRelationships () { if (!Model.$config.autoSaveRelationships) { return Promise.resolve([]) } try { return await this.saveRelationships() } catch (e) { console.error(e) } } /** * Detect any changes to the relationship models and save them * * @returns {Promise<array>} */ async saveRelationships () { const calls = collect(this.relationships) .filter(rel => !rel.readonly) .reduce(this._flattenRelationships, []) .filter(model => model.isDirty() || model.isNew) .map(model => model.createOrUpdate().catch(err => err)) const responses = await Promise.all(calls) this._emit(Model.RELATIONS_SAVED, { responses, model: this }) return responses } /** * Flatten all resolved relationships into a collection * @param models * @param relationship * @returns {*} * @private */ _flattenRelationships (models, relationship) { const result = relationship.resolve() if (result instanceof Model) { models.push(result) } else { result.each(model => models.push(model)) } return models } /** * @returns {Builder} */ queryBuilder () { return this._builder } /** * Get a new instance of the model * @returns {Model} */ static instance () { return new this(null) } /** * Add an include clause to the query * @param args * @returns {Model} */ static include (...args) { return this.instance().include(...args) } /** * Append one or more values to the query * @param args * @returns {Model} */ static append (...args) { return this.instance().append(...args) } /** * Add a select clause to the query * @param fields * @returns {Model} */ static select (...fields) { return this.instance().select(...fields) } /** * Add a where clause to the query * @param field * @param value * @returns {Model} */ static where (field, value) { return this.instance().where(field, value) } /** * Add a where in clause to the query * @param field * @param array * @returns {Model} */ static whereIn (field, array) { return this.instance().whereIn(field, array) } /** * Add an order by clause to the query * @param args * @returns {Model} */ static orderBy (...args) { return this.instance().orderBy(...args) } /** * Add the page to the query * @param value * @returns {Model} */ static page (value) { return this.instance().page(value) } /** * Add a limit clause to the query * @param value * @returns {Model} */ static limit (value) { return this.instance().limit(value) } /** * Find a resource by its id * @param id * @returns {Promise<*>} */ static find (id) { return this.instance().find(id) } /** * Get a collection of resources * @param asCollection * @returns {Promise<*>} */ static get (asCollection = false) { return this.instance().get(asCollection) } /** * Sets the config * @param config */ static setConfig (config) { Model.$config = config if (Model.$config?.events === undefined) { Model.$config.events = new Emitter() } if (Model.$config?.namespace === undefined) { Model.$config.namespace = 'belay' } if (Model.$config?.autoSaveRelationships === undefined) { Model.$config.autoSaveRelationships = true } } }