text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Worker, MessageChannel, MessagePort, receiveMessageOnPort } from 'worker_threads'; import { once } from 'events'; import EventEmitterAsyncResource from 'eventemitter-asyncresource'; import { AsyncResource } from 'async_hooks'; import { cpus } from 'os'; import { fileURLToPath, URL } from 'url'; import { resolve } from 'path'; import { inspect, types } from 'util'; import assert from 'assert'; import { Histogram, build } from 'hdr-histogram-js'; import { performance } from 'perf_hooks'; import hdrobj from 'hdr-histogram-percentiles-obj'; import { ReadyMessage, RequestMessage, ResponseMessage, StartupMessage, commonState, kResponseCountField, kRequestCountField, kFieldCount, Transferable, Task, TaskQueue, kQueueOptions, isTaskQueue, isTransferable, markMovable, isMovable, kTransferable, kValue } from './common'; import { version } from '../package.json'; const cpuCount : number = (() => { try { return cpus().length; } catch { /* istanbul ignore next */ return 1; } })(); interface AbortSignalEventTargetAddOptions { once : boolean; }; interface AbortSignalEventTarget { addEventListener : ( name : 'abort', listener : () => void, options? : AbortSignalEventTargetAddOptions) => void; removeEventListener : ( name : 'abort', listener : () => void) => void; aborted? : boolean; } interface AbortSignalEventEmitter { off : (name : 'abort', listener : () => void) => void; once : (name : 'abort', listener : () => void) => void; } type AbortSignalAny = AbortSignalEventTarget | AbortSignalEventEmitter; function onabort (abortSignal : AbortSignalAny, listener : () => void) { if ('addEventListener' in abortSignal) { abortSignal.addEventListener('abort', listener, { once: true }); } else { abortSignal.once('abort', listener); } } class AbortError extends Error { constructor () { super('The task has been aborted'); } get name () { return 'AbortError'; } } type ResourceLimits = Worker extends { resourceLimits? : infer T; } ? T : {}; type EnvSpecifier = typeof Worker extends { new (filename : never, options?: { env: infer T }) : Worker; } ? T : never; class ArrayTaskQueue implements TaskQueue { tasks : Task[] = []; get size () { return this.tasks.length; } shift () : Task | null { return this.tasks.shift() as Task; } push (task : Task) : void { this.tasks.push(task); } remove (task : Task) : void { const index = this.tasks.indexOf(task); assert.notStrictEqual(index, -1); this.tasks.splice(index, 1); } } interface Options { filename? : string | null, name?: string, minThreads? : number, maxThreads? : number, idleTimeout? : number, maxQueue? : number | 'auto', concurrentTasksPerWorker? : number, useAtomics? : boolean, resourceLimits? : ResourceLimits, argv? : string[], execArgv? : string[], env? : EnvSpecifier, workerData? : any, taskQueue? : TaskQueue, niceIncrement? : number, trackUnmanagedFds? : boolean, } interface FilledOptions extends Options { filename : string | null, name: string, minThreads : number, maxThreads : number, idleTimeout : number, maxQueue : number, concurrentTasksPerWorker : number, useAtomics: boolean, taskQueue : TaskQueue, niceIncrement : number } const kDefaultOptions : FilledOptions = { filename: null, name: 'default', minThreads: Math.max(cpuCount / 2, 1), maxThreads: cpuCount * 1.5, idleTimeout: 0, maxQueue: Infinity, concurrentTasksPerWorker: 1, useAtomics: true, taskQueue: new ArrayTaskQueue(), niceIncrement: 0, trackUnmanagedFds: true }; interface RunOptions { transferList? : TransferList, filename? : string | null, signal? : AbortSignalAny | null, name? : string | null } interface FilledRunOptions extends RunOptions { transferList : TransferList | never, filename : string | null, signal : AbortSignalAny | null, name : string | null } const kDefaultRunOptions : FilledRunOptions = { transferList: undefined, filename: null, signal: null, name: null }; class DirectlyTransferable implements Transferable { #value : object; constructor (value : object) { this.#value = value; } get [kTransferable] () : object { return this.#value; } get [kValue] () : object { return this.#value; } } class ArrayBufferViewTransferable implements Transferable { #view : ArrayBufferView; constructor (view : ArrayBufferView) { this.#view = view; } get [kTransferable] () : object { return this.#view.buffer; } get [kValue] () : object { return this.#view; } } let taskIdCounter = 0; type TaskCallback = (err : Error, result: any) => void; // Grab the type of `transferList` off `MessagePort`. At the time of writing, // only ArrayBuffer and MessagePort are valid, but let's avoid having to update // our types here every time Node.js adds support for more objects. type TransferList = MessagePort extends { postMessage(value : any, transferList : infer T) : any; } ? T : never; type TransferListItem = TransferList extends (infer T)[] ? T : never; function maybeFileURLToPath (filename : string) : string { return filename.startsWith('file:') ? fileURLToPath(new URL(filename)) : filename; } // Extend AsyncResource so that async relations between posting a task and // receiving its result are visible to diagnostic tools. class TaskInfo extends AsyncResource implements Task { callback : TaskCallback; task : any; transferList : TransferList; filename : string; name : string; taskId : number; abortSignal : AbortSignalAny | null; abortListener : (() => void) | null = null; workerInfo : WorkerInfo | null = null; created : number; started : number; constructor ( task : any, transferList : TransferList, filename : string, name : string, callback : TaskCallback, abortSignal : AbortSignalAny | null, triggerAsyncId : number) { super('Piscina.Task', { requireManualDestroy: true, triggerAsyncId }); this.callback = callback; this.task = task; this.transferList = transferList; // If the task is a Transferable returned by // Piscina.move(), then add it to the transferList // automatically if (isMovable(task)) { // This condition should never be hit but typescript // complains if we dont do the check. /* istanbul ignore if */ if (this.transferList == null) { this.transferList = []; } this.transferList = this.transferList.concat(task[kTransferable]); this.task = task[kValue]; } this.filename = filename; this.name = name; this.taskId = taskIdCounter++; this.abortSignal = abortSignal; this.created = performance.now(); this.started = 0; } releaseTask () : any { const ret = this.task; this.task = null; return ret; } done (err : Error | null, result? : any) : void { this.runInAsyncScope(this.callback, null, err, result); this.emitDestroy(); // `TaskInfo`s are used only once. // If an abort signal was used, remove the listener from it when // done to make sure we do not accidentally leak. if (this.abortSignal && this.abortListener) { if ('removeEventListener' in this.abortSignal && this.abortListener) { this.abortSignal.removeEventListener('abort', this.abortListener); } else { (this.abortSignal as AbortSignalEventEmitter).off( 'abort', this.abortListener); } } } get [kQueueOptions] () : object | null { return kQueueOptions in this.task ? this.task[kQueueOptions] : null; } } abstract class AsynchronouslyCreatedResource { onreadyListeners : (() => void)[] | null = []; markAsReady () : void { const listeners = this.onreadyListeners; assert(listeners !== null); this.onreadyListeners = null; for (const listener of listeners) { listener(); } } isReady () : boolean { return this.onreadyListeners === null; } onReady (fn : () => void) { if (this.onreadyListeners === null) { fn(); // Zalgo is okay here. return; } this.onreadyListeners.push(fn); } abstract currentUsage() : number; } class AsynchronouslyCreatedResourcePool< T extends AsynchronouslyCreatedResource> { pendingItems = new Set<T>(); readyItems = new Set<T>(); maximumUsage : number; onAvailableListeners : ((item : T) => void)[]; constructor (maximumUsage : number) { this.maximumUsage = maximumUsage; this.onAvailableListeners = []; } add (item : T) { this.pendingItems.add(item); item.onReady(() => { /* istanbul ignore else */ if (this.pendingItems.has(item)) { this.pendingItems.delete(item); this.readyItems.add(item); this.maybeAvailable(item); } }); } delete (item : T) { this.pendingItems.delete(item); this.readyItems.delete(item); } findAvailable () : T | null { let minUsage = this.maximumUsage; let candidate = null; for (const item of this.readyItems) { const usage = item.currentUsage(); if (usage === 0) return item; if (usage < minUsage) { candidate = item; minUsage = usage; } } return candidate; } * [Symbol.iterator] () { yield * this.pendingItems; yield * this.readyItems; } get size () { return this.pendingItems.size + this.readyItems.size; } maybeAvailable (item : T) { /* istanbul ignore else */ if (item.currentUsage() < this.maximumUsage) { for (const listener of this.onAvailableListeners) { listener(item); } } } onAvailable (fn : (item : T) => void) { this.onAvailableListeners.push(fn); } } type ResponseCallback = (response : ResponseMessage) => void; const Errors = { ThreadTermination: () => new Error('Terminating worker thread'), FilenameNotProvided: () => new Error('filename must be provided to run() or in options object'), TaskQueueAtLimit: () => new Error('Task queue is at limit'), NoTaskQueueAvailable: () => new Error('No task queue available and all Workers are busy') }; class WorkerInfo extends AsynchronouslyCreatedResource { worker : Worker; taskInfos : Map<number, TaskInfo>; idleTimeout : NodeJS.Timeout | null = null; // eslint-disable-line no-undef port : MessagePort; sharedBuffer : Int32Array; lastSeenResponseCount : number = 0; onMessage : ResponseCallback; constructor ( worker : Worker, port : MessagePort, onMessage : ResponseCallback) { super(); this.worker = worker; this.port = port; this.port.on('message', (message : ResponseMessage) => this._handleResponse(message)); this.onMessage = onMessage; this.taskInfos = new Map(); this.sharedBuffer = new Int32Array( new SharedArrayBuffer(kFieldCount * Int32Array.BYTES_PER_ELEMENT)); } destroy () : void { this.worker.terminate(); this.port.close(); this.clearIdleTimeout(); for (const taskInfo of this.taskInfos.values()) { taskInfo.done(Errors.ThreadTermination()); } this.taskInfos.clear(); } clearIdleTimeout () : void { if (this.idleTimeout !== null) { clearTimeout(this.idleTimeout); this.idleTimeout = null; } } ref () : WorkerInfo { this.port.ref(); return this; } unref () : WorkerInfo { // Note: Do not call ref()/unref() on the Worker itself since that may cause // a hard crash, see https://github.com/nodejs/node/pull/33394. this.port.unref(); return this; } _handleResponse (message : ResponseMessage) : void { this.onMessage(message); if (this.taskInfos.size === 0) { // No more tasks running on this Worker means it should not keep the // process running. this.unref(); } } postTask (taskInfo : TaskInfo) { assert(!this.taskInfos.has(taskInfo.taskId)); const message : RequestMessage = { task: taskInfo.releaseTask(), taskId: taskInfo.taskId, filename: taskInfo.filename, name: taskInfo.name }; try { this.port.postMessage(message, taskInfo.transferList); } catch (err) { // This would mostly happen if e.g. message contains unserializable data // or transferList is invalid. taskInfo.done(err); return; } taskInfo.workerInfo = this; this.taskInfos.set(taskInfo.taskId, taskInfo); this.ref(); this.clearIdleTimeout(); // Inform the worker that there are new messages posted, and wake it up // if it is waiting for one. Atomics.add(this.sharedBuffer, kRequestCountField, 1); Atomics.notify(this.sharedBuffer, kRequestCountField, 1); } processPendingMessages () { // If we *know* that there are more messages than we have received using // 'message' events yet, then try to load and handle them synchronously, // without the need to wait for more expensive events on the event loop. // This would usually break async tracking, but in our case, we already have // the extra TaskInfo/AsyncResource layer that rectifies that situation. const actualResponseCount = Atomics.load(this.sharedBuffer, kResponseCountField); if (actualResponseCount !== this.lastSeenResponseCount) { this.lastSeenResponseCount = actualResponseCount; let entry; while ((entry = receiveMessageOnPort(this.port)) !== undefined) { this._handleResponse(entry.message); } } } isRunningAbortableTask () : boolean { // If there are abortable tasks, we are running one at most per Worker. if (this.taskInfos.size !== 1) return false; const [[, task]] = this.taskInfos; return task.abortSignal !== null; } currentUsage () : number { if (this.isRunningAbortableTask()) return Infinity; return this.taskInfos.size; } } class ThreadPool { publicInterface : Piscina; workers : AsynchronouslyCreatedResourcePool<WorkerInfo>; options : FilledOptions; taskQueue : TaskQueue; skipQueue : TaskInfo[] = []; completed : number = 0; runTime : Histogram; waitTime : Histogram; start : number = performance.now(); inProcessPendingMessages : boolean = false; startingUp : boolean = false; workerFailsDuringBootstrap : boolean = false; constructor (publicInterface : Piscina, options : Options) { this.publicInterface = publicInterface; this.taskQueue = options.taskQueue || new ArrayTaskQueue(); this.runTime = build({ lowestDiscernibleValue: 1 }); this.waitTime = build({ lowestDiscernibleValue: 1 }); const filename = options.filename ? maybeFileURLToPath(options.filename) : null; this.options = { ...kDefaultOptions, ...options, filename, maxQueue: 0 }; // The >= and <= could be > and < but this way we get 100 % coverage 🙃 if (options.maxThreads !== undefined && this.options.minThreads >= options.maxThreads) { this.options.minThreads = options.maxThreads; } if (options.minThreads !== undefined && this.options.maxThreads <= options.minThreads) { this.options.maxThreads = options.minThreads; } if (options.maxQueue === 'auto') { this.options.maxQueue = this.options.maxThreads ** 2; } else { this.options.maxQueue = options.maxQueue ?? kDefaultOptions.maxQueue; } this.workers = new AsynchronouslyCreatedResourcePool<WorkerInfo>( this.options.concurrentTasksPerWorker); this.workers.onAvailable((w : WorkerInfo) => this._onWorkerAvailable(w)); this.startingUp = true; this._ensureMinimumWorkers(); this.startingUp = false; } _ensureMinimumWorkers () : void { while (this.workers.size < this.options.minThreads) { this._addNewWorker(); } } _addNewWorker () : void { const pool = this; const worker = new Worker(resolve(__dirname, 'worker.js'), { env: this.options.env, argv: this.options.argv, execArgv: this.options.execArgv, resourceLimits: this.options.resourceLimits, workerData: this.options.workerData, trackUnmanagedFds: this.options.trackUnmanagedFds }); const { port1, port2 } = new MessageChannel(); const workerInfo = new WorkerInfo(worker, port1, onMessage); if (this.startingUp) { // There is no point in waiting for the initial set of Workers to indicate // that they are ready, we just mark them as such from the start. workerInfo.markAsReady(); } const message : StartupMessage = { filename: this.options.filename, name: this.options.name, port: port2, sharedBuffer: workerInfo.sharedBuffer, useAtomics: this.options.useAtomics, niceIncrement: this.options.niceIncrement }; worker.postMessage(message, [port2]); function onMessage (message : ResponseMessage) { const { taskId, result } = message; // In case of success: Call the callback that was passed to `runTask`, // remove the `TaskInfo` associated with the Worker, which marks it as // free again. const taskInfo = workerInfo.taskInfos.get(taskId); workerInfo.taskInfos.delete(taskId); pool.workers.maybeAvailable(workerInfo); /* istanbul ignore if */ if (taskInfo === undefined) { const err = new Error( `Unexpected message from Worker: ${inspect(message)}`); pool.publicInterface.emit('error', err); } else { taskInfo.done(message.error, result); } pool._processPendingMessages(); } worker.on('message', (message : ReadyMessage) => { if (message.ready === true) { if (workerInfo.currentUsage() === 0) { workerInfo.unref(); } if (!workerInfo.isReady()) { workerInfo.markAsReady(); } return; } worker.emit('error', new Error( `Unexpected message on Worker: ${inspect(message)}`)); }); worker.on('error', (err : Error) => { // Work around the bug in https://github.com/nodejs/node/pull/33394 worker.ref = () => {}; // In case of an uncaught exception: Call the callback that was passed to // `postTask` with the error, or emit an 'error' event if there is none. const taskInfos = [...workerInfo.taskInfos.values()]; workerInfo.taskInfos.clear(); // Remove the worker from the list and potentially start a new Worker to // replace the current one. this._removeWorker(workerInfo); if (workerInfo.isReady() && !this.workerFailsDuringBootstrap) { this._ensureMinimumWorkers(); } else { // Do not start new workers over and over if they already fail during // bootstrap, there's no point. this.workerFailsDuringBootstrap = true; } if (taskInfos.length > 0) { for (const taskInfo of taskInfos) { taskInfo.done(err, null); } } else { this.publicInterface.emit('error', err); } }); worker.unref(); port1.on('close', () => { // The port is only closed if the Worker stops for some reason, but we // always .unref() the Worker itself. We want to receive e.g. 'error' // events on it, so we ref it once we know it's going to exit anyway. worker.ref(); }); this.workers.add(workerInfo); } _processPendingMessages () { if (this.inProcessPendingMessages || !this.options.useAtomics) { return; } this.inProcessPendingMessages = true; try { for (const workerInfo of this.workers) { workerInfo.processPendingMessages(); } } finally { this.inProcessPendingMessages = false; } } _removeWorker (workerInfo : WorkerInfo) : void { workerInfo.destroy(); this.workers.delete(workerInfo); } _onWorkerAvailable (workerInfo : WorkerInfo) : void { while ((this.taskQueue.size > 0 || this.skipQueue.length > 0) && workerInfo.currentUsage() < this.options.concurrentTasksPerWorker) { // The skipQueue will have tasks that we previously shifted off // the task queue but had to skip over... we have to make sure // we drain that before we drain the taskQueue. const taskInfo = this.skipQueue.shift() || this.taskQueue.shift() as TaskInfo; // If the task has an abortSignal and the worker has any other // tasks, we cannot distribute the task to it. Skip for now. if (taskInfo.abortSignal && workerInfo.taskInfos.size > 0) { this.skipQueue.push(taskInfo); break; } const now = performance.now(); this.waitTime.recordValue(now - taskInfo.created); taskInfo.started = now; workerInfo.postTask(taskInfo); this._maybeDrain(); return; } if (workerInfo.taskInfos.size === 0 && this.workers.size > this.options.minThreads) { workerInfo.idleTimeout = setTimeout(() => { assert.strictEqual(workerInfo.taskInfos.size, 0); if (this.workers.size > this.options.minThreads) { this._removeWorker(workerInfo); } }, this.options.idleTimeout).unref(); } } runTask ( task : any, options : RunOptions) : Promise<any> { let { filename, name } = options; const { transferList = [], signal = null } = options; if (filename == null) { filename = this.options.filename; } if (name == null) { name = this.options.name; } if (typeof filename !== 'string') { return Promise.reject(Errors.FilenameNotProvided()); } filename = maybeFileURLToPath(filename); let resolve : (result : any) => void; let reject : (err : Error) => void; // eslint-disable-next-line const ret = new Promise((res, rej) => { resolve = res; reject = rej; }); const taskInfo = new TaskInfo( task, transferList, filename, name, (err : Error | null, result : any) => { this.completed++; if (taskInfo.started) { this.runTime.recordValue(performance.now() - taskInfo.started); } if (err !== null) { reject(err); } else { resolve(result); } }, signal, this.publicInterface.asyncResource.asyncId()); if (signal !== null) { // If the AbortSignal has an aborted property and it's truthy, // reject immediately. if ((signal as AbortSignalEventTarget).aborted) { return Promise.reject(new AbortError()); } taskInfo.abortListener = () => { // Call reject() first to make sure we always reject with the AbortError // if the task is aborted, not with an Error from the possible // thread termination below. reject(new AbortError()); if (taskInfo.workerInfo !== null) { // Already running: We cancel the Worker this is running on. this._removeWorker(taskInfo.workerInfo); this._ensureMinimumWorkers(); } else { // Not yet running: Remove it from the queue. this.taskQueue.remove(taskInfo); } }; onabort(signal, taskInfo.abortListener); } // If there is a task queue, there's no point in looking for an available // Worker thread. Add this task to the queue, if possible. if (this.taskQueue.size > 0) { const totalCapacity = this.options.maxQueue + this.pendingCapacity(); if (this.taskQueue.size >= totalCapacity) { if (this.options.maxQueue === 0) { return Promise.reject(Errors.NoTaskQueueAvailable()); } else { return Promise.reject(Errors.TaskQueueAtLimit()); } } else { if (this.workers.size < this.options.maxThreads) { this._addNewWorker(); } this.taskQueue.push(taskInfo); } return ret; } // Look for a Worker with a minimum number of tasks it is currently running. let workerInfo : WorkerInfo | null = this.workers.findAvailable(); // If we want the ability to abort this task, use only workers that have // no running tasks. if (workerInfo !== null && workerInfo.currentUsage() > 0 && signal) { workerInfo = null; } // If no Worker was found, or that Worker was handling another task in some // way, and we still have the ability to spawn new threads, do so. let waitingForNewWorker = false; if ((workerInfo === null || workerInfo.currentUsage() > 0) && this.workers.size < this.options.maxThreads) { this._addNewWorker(); waitingForNewWorker = true; } // If no Worker is found, try to put the task into the queue. if (workerInfo === null) { if (this.options.maxQueue <= 0 && !waitingForNewWorker) { return Promise.reject(Errors.NoTaskQueueAvailable()); } else { this.taskQueue.push(taskInfo); } return ret; } // TODO(addaleax): Clean up the waitTime/runTime recording. const now = performance.now(); this.waitTime.recordValue(now - taskInfo.created); taskInfo.started = now; workerInfo.postTask(taskInfo); this._maybeDrain(); return ret; } pendingCapacity () : number { return this.workers.pendingItems.size * this.options.concurrentTasksPerWorker; } _maybeDrain () { if (this.taskQueue.size === 0 && this.skipQueue.length === 0) { this.publicInterface.emit('drain'); } } async destroy () { while (this.skipQueue.length > 0) { const taskInfo : TaskInfo = this.skipQueue.shift() as TaskInfo; taskInfo.done(new Error('Terminating worker thread')); } while (this.taskQueue.size > 0) { const taskInfo : TaskInfo = this.taskQueue.shift() as TaskInfo; taskInfo.done(new Error('Terminating worker thread')); } const exitEvents : Promise<any[]>[] = []; while (this.workers.size > 0) { const [workerInfo] = this.workers; exitEvents.push(once(workerInfo.worker, 'exit')); this._removeWorker(workerInfo); } await Promise.all(exitEvents); } } class Piscina extends EventEmitterAsyncResource { #pool : ThreadPool; constructor (options : Options = {}) { super({ ...options, name: 'Piscina' }); if (typeof options.filename !== 'string' && options.filename != null) { throw new TypeError('options.filename must be a string or null'); } if (typeof options.name !== 'string' && options.name != null) { throw new TypeError('options.name must be a string or null'); } if (options.minThreads !== undefined && (typeof options.minThreads !== 'number' || options.minThreads < 0)) { throw new TypeError('options.minThreads must be a non-negative integer'); } if (options.maxThreads !== undefined && (typeof options.maxThreads !== 'number' || options.maxThreads < 1)) { throw new TypeError('options.maxThreads must be a positive integer'); } if (options.minThreads !== undefined && options.maxThreads !== undefined && options.minThreads > options.maxThreads) { throw new RangeError('options.minThreads and options.maxThreads must not conflict'); } if (options.idleTimeout !== undefined && (typeof options.idleTimeout !== 'number' || options.idleTimeout < 0)) { throw new TypeError('options.idleTimeout must be a non-negative integer'); } if (options.maxQueue !== undefined && options.maxQueue !== 'auto' && (typeof options.maxQueue !== 'number' || options.maxQueue < 0)) { throw new TypeError('options.maxQueue must be a non-negative integer'); } if (options.concurrentTasksPerWorker !== undefined && (typeof options.concurrentTasksPerWorker !== 'number' || options.concurrentTasksPerWorker < 1)) { throw new TypeError( 'options.concurrentTasksPerWorker must be a positive integer'); } if (options.useAtomics !== undefined && typeof options.useAtomics !== 'boolean') { throw new TypeError('options.useAtomics must be a boolean value'); } if (options.resourceLimits !== undefined && (typeof options.resourceLimits !== 'object' || options.resourceLimits === null)) { throw new TypeError('options.resourceLimits must be an object'); } if (options.taskQueue !== undefined && !isTaskQueue(options.taskQueue)) { throw new TypeError('options.taskQueue must be a TaskQueue object'); } if (options.niceIncrement !== undefined && (typeof options.niceIncrement !== 'number' || options.niceIncrement < 0)) { throw new TypeError('options.niceIncrement must be a non-negative integer'); } if (options.trackUnmanagedFds !== undefined && typeof options.trackUnmanagedFds !== 'boolean') { throw new TypeError('options.trackUnmanagedFds must be a boolean value'); } this.#pool = new ThreadPool(this, options); } /** @deprecated Use run(task, options) instead **/ runTask (task : any, transferList? : TransferList, filename? : string, abortSignal? : AbortSignalAny) : Promise<any>; /** @deprecated Use run(task, options) instead **/ runTask (task : any, transferList? : TransferList, filename? : AbortSignalAny, abortSignal? : undefined) : Promise<any>; /** @deprecated Use run(task, options) instead **/ runTask (task : any, transferList? : string, filename? : AbortSignalAny, abortSignal? : undefined) : Promise<any>; /** @deprecated Use run(task, options) instead **/ runTask (task : any, transferList? : AbortSignalAny, filename? : undefined, abortSignal? : undefined) : Promise<any>; /** @deprecated Use run(task, options) instead **/ runTask (task : any, transferList? : any, filename? : any, signal? : any) { // If transferList is a string or AbortSignal, shift it. if ((typeof transferList === 'object' && !Array.isArray(transferList)) || typeof transferList === 'string') { signal = filename as (AbortSignalAny | undefined); filename = transferList; transferList = undefined; } // If filename is an AbortSignal, shift it. if (typeof filename === 'object' && !Array.isArray(filename)) { signal = filename; filename = undefined; } if (transferList !== undefined && !Array.isArray(transferList)) { return Promise.reject( new TypeError('transferList argument must be an Array')); } if (filename !== undefined && typeof filename !== 'string') { return Promise.reject( new TypeError('filename argument must be a string')); } if (signal !== undefined && typeof signal !== 'object') { return Promise.reject( new TypeError('signal argument must be an object')); } return this.#pool.runTask( task, { transferList, filename: filename || null, name: 'default', signal: signal || null }); } run (task : any, options : RunOptions = kDefaultRunOptions) { if (options === null || typeof options !== 'object') { return Promise.reject( new TypeError('options must be an object')); } const { transferList, filename, name, signal } = options; if (transferList !== undefined && !Array.isArray(transferList)) { return Promise.reject( new TypeError('transferList argument must be an Array')); } if (filename != null && typeof filename !== 'string') { return Promise.reject( new TypeError('filename argument must be a string')); } if (name != null && typeof name !== 'string') { return Promise.reject(new TypeError('name argument must be a string')); } if (signal != null && typeof signal !== 'object') { return Promise.reject( new TypeError('signal argument must be an object')); } return this.#pool.runTask(task, { transferList, filename, name, signal }); } destroy () { return this.#pool.destroy(); } get options () : FilledOptions { return this.#pool.options; } get threads () : Worker[] { const ret : Worker[] = []; for (const workerInfo of this.#pool.workers) { ret.push(workerInfo.worker); } return ret; } get queueSize () : number { const pool = this.#pool; return Math.max(pool.taskQueue.size - pool.pendingCapacity(), 0); } get completed () : number { return this.#pool.completed; } get waitTime () : any { const result = hdrobj.histAsObj(this.#pool.waitTime); return hdrobj.addPercentiles(this.#pool.waitTime, result); } get runTime () : any { const result = hdrobj.histAsObj(this.#pool.runTime); return hdrobj.addPercentiles(this.#pool.runTime, result); } get utilization () : number { // The capacity is the max compute time capacity of the // pool to this point in time as determined by the length // of time the pool has been running multiplied by the // maximum number of threads. const capacity = this.duration * this.#pool.options.maxThreads; const totalMeanRuntime = this.#pool.runTime.mean * this.#pool.runTime.totalCount; // We calculate the appoximate pool utilization by multiplying // the mean run time of all tasks by the number of runtime // samples taken and dividing that by the capacity. The // theory here is that capacity represents the absolute upper // limit of compute time this pool could ever attain (but // never will for a variety of reasons. Multiplying the // mean run time by the number of tasks sampled yields an // approximation of the realized compute time. The utilization // then becomes a point-in-time measure of how active the // pool is. return totalMeanRuntime / capacity; } get duration () : number { return performance.now() - this.#pool.start; } static get isWorkerThread () : boolean { return commonState.isWorkerThread; } static get workerData () : any { return commonState.workerData; } static get version () : string { return version; } static get Piscina () { return Piscina; } static move (val : Transferable | TransferListItem | ArrayBufferView | ArrayBuffer | MessagePort) { if (val != null && typeof val === 'object' && typeof val !== 'function') { if (!isTransferable(val)) { if ((types as any).isArrayBufferView(val)) { val = new ArrayBufferViewTransferable(val as ArrayBufferView); } else { val = new DirectlyTransferable(val); } } markMovable(val); } return val; } static get transferableSymbol () { return kTransferable; } static get valueSymbol () { return kValue; } static get queueOptionsSymbol () { return kQueueOptions; } } export = Piscina;
the_stack
import { jsx } from '@emotion/core'; import React from 'react'; import formatMessage from 'format-message'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { Image, ImageFit } from 'office-ui-fabric-react/lib/Image'; import { Pivot, PivotItem, PivotLinkSize } from 'office-ui-fabric-react/lib/Pivot'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { RouteComponentProps } from '@reach/router'; import { navigate } from '@reach/router'; import { useRecoilValue } from 'recoil'; import { Toolbar, IToolbarItem } from '@bfc/ui-shared'; import { CreationFlowStatus } from '../../constants'; import { dispatcherState } from '../../recoilModel'; import { recentProjectsState, feedState, warnAboutDotNetState, warnAboutFunctionsState, } from '../../recoilModel/atoms/appState'; import TelemetryClient from '../../telemetry/TelemetryClient'; import composerDocumentIcon from '../../images/composerDocumentIcon.svg'; import stackoverflowIcon from '../../images/stackoverflowIcon.svg'; import githubIcon from '../../images/githubIcon.svg'; import noRecentBotsCover from '../../images/noRecentBotsCover.svg'; import { InstallDepModal } from '../../components/InstallDepModal'; import { missingDotnetVersionError, missingFunctionsError } from '../../utils/runtimeErrors'; import { RecentBotList } from './RecentBotList'; import { WhatsNewsList } from './WhatsNewsList'; import { CardWidget } from './CardWidget'; import * as home from './styles'; const resources = [ { imageCover: composerDocumentIcon, title: formatMessage('Documentation'), description: formatMessage('Everything you need to build sophisticated conversational experiences'), moreText: formatMessage('Learn more'), url: 'https://docs.microsoft.com/en-us/composer/', }, { imageCover: githubIcon, title: formatMessage('GitHub'), description: formatMessage('View documentation, samples, and extensions'), moreText: formatMessage('Open GitHub'), url: 'https://github.com/microsoft/BotFramework-Composer', }, { imageCover: githubIcon, title: formatMessage('Bot Framework Emulator'), description: formatMessage('Test and debug your bots in Bot Framework Emulator'), moreText: formatMessage('Download Emulator'), url: 'https://github.com/microsoft/BotFramework-Emulator/releases', }, { imageCover: stackoverflowIcon, title: formatMessage('Stack Overflow'), description: formatMessage('Connect with the community to ask and answer questions about Composer'), moreText: formatMessage('Go to Stack Overflow'), url: 'https://stackoverflow.com/questions/tagged/botframework', }, ]; const Home: React.FC<RouteComponentProps> = () => { // These variables are used in the save as method which is currently disabled until we // determine the appropriate save as behavior for parent bots and skills. Since we are // planning to add the feature back in the next release, I am commenting out this section // of code instead of removing it. See comment below for more details. // // const projectId = useRecoilValue<string>(currentProjectIdState); // const botName = useRecoilValue<string>(botDisplayNameState(projectId)); // const templateId = useRecoilValue<string>(templateIdState); const recentProjects = useRecoilValue(recentProjectsState); const feed = useRecoilValue(feedState); const { openProject, setCreationFlowStatus, setCreationFlowType, setWarnAboutDotNet, setWarnAboutFunctions, } = useRecoilValue(dispatcherState); const warnAboutDotNet = useRecoilValue(warnAboutDotNetState); const warnAboutFunctions = useRecoilValue(warnAboutFunctionsState); const onItemChosen = async (item) => { if (item?.path) { await openProject(item.path, 'default', true, null, (projectId) => { TelemetryClient.track('BotProjectOpened', { method: 'list', projectId }); }); } }; const onClickNewBot = () => { setCreationFlowType('Bot'); setCreationFlowStatus(CreationFlowStatus.NEW); navigate(`projects/create`); }; const toolbarItems: IToolbarItem[] = [ { type: 'action', text: formatMessage('Create new'), buttonProps: { iconProps: { iconName: 'Add', }, onClick: () => { onClickNewBot(); TelemetryClient.track('ToolbarButtonClicked', { name: 'new' }); }, styles: home.toolbarFirstButtonStyles, }, align: 'left', dataTestid: 'homePage-Toolbar-New', disabled: false, }, { type: 'action', text: formatMessage('Open'), buttonProps: { iconProps: { iconName: 'OpenFolderHorizontal', }, onClick: () => { setCreationFlowStatus(CreationFlowStatus.OPEN); navigate(`projects/open`); TelemetryClient.track('ToolbarButtonClicked', { name: 'openBot' }); }, styles: home.toolbarButtonStyles, }, align: 'left', dataTestid: 'homePage-Toolbar-Open', disabled: false, }, // We are temporarily disabling the save as button until we can // determine what the appropriate save as behavior should be for both // parent bots and skills. // // Associated issue: // https://github.com/microsoft/BotFramework-Composer/issues/6808#issuecomment-828758688 // // { // type: 'action', // text: formatMessage('Save as'), // buttonProps: { // iconProps: { // iconName: 'Save', // }, // onClick: () => { // setCreationFlowStatus(CreationFlowStatus.SAVEAS); // navigate(`projects/${projectId}/${templateId}/save`); // TelemetryClient.track('ToolbarButtonClicked', { name: 'saveAs' }); // }, // styles: home.toolbarButtonStyles, // }, // align: 'left', // disabled: botName ? false : true, // }, ]; return ( <div css={home.outline}> <div css={home.page}> <h1 css={home.title}>{formatMessage(`Welcome to Bot Framework Composer`)}</h1> <div css={home.leftPage} role="main"> <div css={home.recentBotsContainer}> <h2 css={home.subtitle}>{formatMessage(`Recent`)}</h2> <Toolbar css={home.toolbar} toolbarItems={toolbarItems} /> {recentProjects.length > 0 ? ( <RecentBotList recentProjects={recentProjects} onItemChosen={async (item) => { await onItemChosen(item); }} /> ) : ( <div css={home.noRecentBotsContainer}> <Image alt={formatMessage('No recent bots')} aria-label={formatMessage('No recent bots')} css={home.noRecentBotsCover} imageFit={ImageFit.centerCover} src={noRecentBotsCover} /> <div css={home.noRecentBotsDescription}> {formatMessage.rich('<Link>Create a new bot to get started</Link>', { Link: ({ children }) => ( <Link key="create-new-bot-link" onClick={() => { onClickNewBot(); TelemetryClient.track('ToolbarButtonClicked', { name: 'new' }); }} > {children} </Link> ), })} </div> </div> )} </div> <div css={home.resourcesContainer}> <h2 css={home.subtitle}>{formatMessage('Resources')}&nbsp;</h2> <div css={home.rowContainer}> {resources.map((item, index) => ( <CardWidget key={index} ariaLabel={item.title} cardType={'resource'} content={item.description} href={item.url} imageCover={item.imageCover} moreLinkText={item.moreText} target="_blank" title={item.title} /> ))} </div> </div> <div css={home.videosContainer}> <div css={home.rowContainer}> <Pivot aria-label="Videos and articles" css={home.pivotContainer} linkSize={PivotLinkSize.large}> {feed.tabs.map((tab, index) => ( <PivotItem key={index} headerText={tab.title}> {tab.viewAllLinkText && ( <Link css={home.tabRowViewMore} href={tab.viewAllLinkUrl} target={'_blank'}> {tab.viewAllLinkText} <Icon iconName={'OpenInNewWindow'}></Icon>{' '} </Link> )} <div css={home.tabRowContainer}> {tab.cards.map((card, index) => ( <CardWidget key={index} ariaLabel={card.title} cardType={tab.title === 'Videos' ? 'video' : 'article'} content={card.description} href={card.url} imageCover={card.image} target="_blank" title={card.title} /> ))} </div> </PivotItem> ))} </Pivot> </div> </div> </div> <div css={home.rightPage}> <WhatsNewsList newsList={feed.whatsNewLinks} /> </div> </div> {warnAboutDotNet && ( <InstallDepModal downloadLink={missingDotnetVersionError.link.url} downloadLinkText={formatMessage('Install .NET Core SDK')} learnMore={{ text: formatMessage('Learn more'), link: missingDotnetVersionError.linkAfterMessage.url }} text={missingDotnetVersionError.message} title={formatMessage('.NET required')} onDismiss={() => setWarnAboutDotNet(false)} /> )} {warnAboutFunctions && ( <InstallDepModal downloadLink={missingFunctionsError.link.url} downloadLinkText={formatMessage('Install Azure Functions')} learnMore={{ text: formatMessage('Learn more'), link: missingFunctionsError.linkAfterMessage.url, }} text={missingFunctionsError.message} title={formatMessage('Azure Functions required')} onDismiss={() => setWarnAboutFunctions(false)} /> )} </div> ); }; export default Home;
the_stack
import nls = require('vs/nls'); import uri from 'vs/base/common/uri'; import errors = require('vs/base/common/errors'); import {TPromise} from 'vs/base/common/winjs.base'; import {IAction} from 'vs/base/common/actions'; import treedefaults = require('vs/base/parts/tree/browser/treeDefaults'); import {IDataSource, ITree, IAccessibilityProvider, IDragAndDropData, IDragOverReaction, DRAG_OVER_ACCEPT, DRAG_OVER_REJECT, ContextMenuEvent, IRenderer} from 'vs/base/parts/tree/browser/tree'; import {ExternalElementsDragAndDropData, ElementsDragAndDropData, DesktopDragAndDropData} from 'vs/base/parts/tree/browser/treeDnd'; import {ActionBar, Separator} from 'vs/base/browser/ui/actionbar/actionbar'; import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; import dom = require('vs/base/browser/dom'); import {IMouseEvent, DragMouseEvent} from 'vs/base/browser/mouseEvent'; import {IResourceInput, IEditorInput} from 'vs/platform/editor/common/editor'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {IContextMenuService} from 'vs/platform/contextview/browser/contextView'; import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding'; import {UntitledEditorInput, IEditorGroup, IEditorStacksModel} from 'vs/workbench/common/editor'; import {ContributableActionProvider} from 'vs/workbench/browser/actionBarRegistry'; import {ITextFileService, AutoSaveMode, FileEditorInput, asFileResource} from 'vs/workbench/parts/files/common/files'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {EditorStacksModel, EditorGroup} from 'vs/workbench/common/editor/editorStacksModel'; import {keybindingForAction, SaveFileAction, RevertFileAction, SaveFileAsAction, OpenToSideAction, SelectResourceForCompareAction, CompareResourcesAction, SaveAllInGroupAction} from 'vs/workbench/parts/files/browser/fileActions'; import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService'; import {CloseOtherEditorsInGroupAction, CloseEditorAction, CloseEditorsInGroupAction} from 'vs/workbench/browser/parts/editor/editorActions'; const $ = dom.$; export class OpenEditor { constructor(private editor: IEditorInput, private group: IEditorGroup) { // noop } public get editorInput() { return this.editor; } public get editorGroup() { return this.group; } public getId(): string { return `openeditor:${this.group.id}:${this.group.indexOf(this.editor)}:${this.editor.getName()}:${this.editor.getDescription()}`; } public isPreview(): boolean { return this.group.isPreview(this.editor); } public isUntitled(): boolean { return this.editor instanceof UntitledEditorInput; } public isDirty(): boolean { return this.editor.isDirty(); } public getResource(): uri { if (this.editor instanceof FileEditorInput) { return (<FileEditorInput>this.editor).getResource(); } else if (this.editor instanceof UntitledEditorInput) { return (<UntitledEditorInput>this.editor).getResource(); } return null; } } export class DataSource implements IDataSource { public getId(tree: ITree, element: any): string { if (element instanceof EditorStacksModel) { return 'root'; } if (element instanceof EditorGroup) { return (<IEditorGroup>element).id.toString(); } return (<OpenEditor>element).getId(); } public hasChildren(tree: ITree, element: any): boolean { return element instanceof EditorStacksModel || element instanceof EditorGroup; } public getChildren(tree: ITree, element: any): TPromise<any> { if (element instanceof EditorStacksModel) { return TPromise.as((<IEditorStacksModel>element).groups); } const editorGroup = <IEditorGroup>element; return TPromise.as(editorGroup.getEditors().map(ei => new OpenEditor(ei, editorGroup))); } public getParent(tree: ITree, element: any): TPromise<any> { return TPromise.as(null); } } interface IOpenEditorTemplateData { container: HTMLElement; root: HTMLElement; name: HTMLSpanElement; description: HTMLSpanElement; actionBar: ActionBar; } interface IEditorGroupTemplateData { root: HTMLElement; name: HTMLSpanElement; actionBar: ActionBar; } export class Renderer implements IRenderer { public static ITEM_HEIGHT = 22; private static EDITOR_GROUP_TEMPLATE_ID = 'editorgroup'; private static OPEN_EDITOR_TEMPLATE_ID = 'openeditor'; constructor(private actionProvider: ActionProvider, private model: IEditorStacksModel, @ITextFileService private textFileService: ITextFileService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService ) { // noop } public getHeight(tree: ITree, element: any): number { return Renderer.ITEM_HEIGHT; } public getTemplateId(tree: ITree, element: any): string { if (element instanceof EditorGroup) { return Renderer.EDITOR_GROUP_TEMPLATE_ID; } return Renderer.OPEN_EDITOR_TEMPLATE_ID; } public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any { if (templateId === Renderer.EDITOR_GROUP_TEMPLATE_ID) { const editorGroupTemplate: IEditorGroupTemplateData = Object.create(null); editorGroupTemplate.root = dom.append(container, $('.editor-group')); editorGroupTemplate.name = dom.append(editorGroupTemplate.root, $('span.name')); editorGroupTemplate.actionBar = new ActionBar(container); editorGroupTemplate.actionBar.push(this.actionProvider.getEditorGroupActions(), { icon: true, label: false}); return editorGroupTemplate; } const editorTemplate: IOpenEditorTemplateData = Object.create(null); editorTemplate.container = container; editorTemplate.actionBar = new ActionBar(container); editorTemplate.actionBar.push(this.actionProvider.getOpenEditorActions(), { icon: true, label: false}); editorTemplate.root = dom.append(container, $('.open-editor')); editorTemplate.name = dom.append(editorTemplate.root, $('span.name')); editorTemplate.description = dom.append(editorTemplate.root, $('span.description')); return editorTemplate; } public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void { if (templateId === Renderer.EDITOR_GROUP_TEMPLATE_ID) { this.renderEditorGroup(tree, element, templateData); } else { this.renderOpenEditor(tree, element, templateData); } } private renderEditorGroup(tree: ITree, editorGroup: IEditorGroup, templateData: IOpenEditorTemplateData): void { templateData.name.textContent = editorGroup.label; templateData.actionBar.context = { group: editorGroup }; } private renderOpenEditor(tree: ITree, editor: OpenEditor, templateData: IOpenEditorTemplateData): void { editor.isPreview() ? dom.addClass(templateData.root, 'preview') : dom.removeClass(templateData.root, 'preview'); editor.isDirty() ? dom.addClass(templateData.container, 'dirty') : dom.removeClass(templateData.container, 'dirty'); const resource = editor.getResource(); templateData.root.title = resource ? resource.fsPath : ''; templateData.name.textContent = editor.editorInput.getName(); templateData.description.textContent = editor.editorInput.getDescription(); templateData.actionBar.context = { group: editor.editorGroup, editor: editor.editorInput }; } public disposeTemplate(tree: ITree, templateId: string, templateData: any): void { if (templateId === Renderer.OPEN_EDITOR_TEMPLATE_ID) { (<IOpenEditorTemplateData>templateData).actionBar.dispose(); } if (templateId === Renderer.EDITOR_GROUP_TEMPLATE_ID) { (<IEditorGroupTemplateData>templateData).actionBar.dispose(); } } } export class Controller extends treedefaults.DefaultController { constructor(private actionProvider: ActionProvider, private model: IEditorStacksModel, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IInstantiationService private instantiationService: IInstantiationService, @IContextMenuService private contextMenuService: IContextMenuService, @ITelemetryService private telemetryService: ITelemetryService, @IKeybindingService private keybindingService: IKeybindingService ) { super({ clickBehavior: treedefaults.ClickBehavior.ON_MOUSE_DOWN }); } public onClick(tree: ITree, element: any, event: IMouseEvent): boolean { // Close opened editor on middle mouse click if (element instanceof OpenEditor && event.browserEvent && event.browserEvent.button === 1 /* Middle Button */) { const position = this.model.positionOfGroup(element.editorGroup); this.editorService.closeEditor(position, element.editorInput).done(null, errors.onUnexpectedError); return true; } return super.onClick(tree, element, event); } protected onLeftClick(tree: ITree, element: any, event: IMouseEvent, origin: string = 'mouse'): boolean { const payload = { origin: origin }; const isDoubleClick = (origin === 'mouse' && event.detail === 2); // Cancel Event const isMouseDown = event && event.browserEvent && event.browserEvent.type === 'mousedown'; if (!isMouseDown) { event.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise } event.stopPropagation(); // Status group should never get selected nor expanded/collapsed if (!(element instanceof OpenEditor)) { return true; } // Set DOM focus tree.DOMFocus(); // Allow to unselect if (event.shiftKey) { const selection = tree.getSelection(); if (selection && selection.length > 0 && selection[0] === element) { tree.clearSelection(payload); } } // Select, Focus and open files else { tree.setFocus(element, payload); if (isDoubleClick) { event.preventDefault(); // focus moves to editor, we need to prevent default } tree.setSelection([element], payload); this.openEditor(element, isDoubleClick); } return true; } // Do not allow left / right to expand and collapse groups #7848 protected onLeft(tree: ITree, event: IKeyboardEvent): boolean { return true; } protected onRight(tree: ITree, event: IKeyboardEvent): boolean { return true; } protected onEnter(tree: ITree, event: IKeyboardEvent): boolean { const element = tree.getFocus(); // Editor groups should never get selected nor expanded/collapsed if (element instanceof EditorGroup) { event.preventDefault(); event.stopPropagation(); return true; } this.openEditor(element, false); return super.onEnter(tree, event); } public onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; } // Check if clicked on some element if (element === tree.getInput()) { return false; } event.preventDefault(); event.stopPropagation(); tree.setFocus(element); const group = element instanceof EditorGroup ? element : (<OpenEditor>element).editorGroup; const editor = element instanceof OpenEditor ? (<OpenEditor>element).editorInput : undefined; let anchor = { x: event.posx + 1, y: event.posy }; this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this.actionProvider.getSecondaryActions(tree, element), getKeyBinding: (action) => { const opts = this.keybindingService.lookupKeybindings(action.id); if (opts.length > 0) { return opts[0]; // only take the first one } return keybindingForAction(action.id); }, onHide: (wasCancelled?: boolean) => { if (wasCancelled) { tree.DOMFocus(); } }, getActionsContext: () => ({ group, editor }) }); return true; } private openEditor(element: OpenEditor, pinEditor: boolean): void { if (element) { this.telemetryService.publicLog('workbenchActionExecuted', { id: 'workbench.files.openFile', from: 'openEditors' }); const position = this.model.positionOfGroup(element.editorGroup); if (pinEditor) { this.editorGroupService.pinEditor(element.editorGroup, element.editorInput); } this.editorGroupService.activateGroup(element.editorGroup); this.editorService.openEditor(element.editorInput, { preserveFocus: !pinEditor }, position) .done(() => this.editorGroupService.activateGroup(element.editorGroup), errors.onUnexpectedError); } } } export class AccessibilityProvider implements IAccessibilityProvider { getAriaLabel(tree: ITree, element: any): string { if (element instanceof EditorGroup) { return nls.localize('editorGroupAriaLabel', "{0}, Editor Group", (<EditorGroup>element).label); } return nls.localize('openEditorAriaLabel', "{0}, Open Editor", (<OpenEditor>element).editorInput.getName()); } } export class ActionProvider extends ContributableActionProvider { constructor( private model: IEditorStacksModel, @IInstantiationService private instantiationService: IInstantiationService, @ITextFileService private textFileService: ITextFileService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService ) { super(); } public hasActions(tree: ITree, element: any): boolean { const multipleGroups = this.model.groups.length > 1; return element instanceof OpenEditor || (element instanceof EditorGroup && multipleGroups); } public getActions(tree: ITree, element: any): TPromise<IAction[]> { if (element instanceof OpenEditor) { return TPromise.as(this.getOpenEditorActions()); } if (element instanceof EditorGroup) { return TPromise.as(this.getEditorGroupActions()); } return TPromise.as([]); } public getOpenEditorActions(): IAction[] { return [this.instantiationService.createInstance(CloseEditorAction, CloseEditorAction.ID, CloseEditorAction.LABEL)]; } public getEditorGroupActions(): IAction[] { const saveAllAction = this.instantiationService.createInstance(SaveAllInGroupAction, SaveAllInGroupAction.ID, SaveAllInGroupAction.LABEL); return [ saveAllAction, this.instantiationService.createInstance(CloseEditorsInGroupAction, CloseEditorsInGroupAction.ID, CloseEditorsInGroupAction.LABEL) ]; } public hasSecondaryActions(tree: ITree, element: any): boolean { return element instanceof OpenEditor || element instanceof EditorGroup; } public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> { return super.getSecondaryActions(tree, element).then(result => { const autoSaveEnabled = this.textFileService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY; if (element instanceof EditorGroup) { if (!autoSaveEnabled) { result.push(this.instantiationService.createInstance(SaveAllInGroupAction, SaveAllInGroupAction.ID, nls.localize('saveAll', "Save All"))); result.push(new Separator()); } result.push(this.instantiationService.createInstance(CloseEditorsInGroupAction, CloseEditorsInGroupAction.ID, nls.localize('closeAll', "Close All"))); } else { const openEditor = <OpenEditor>element; const resource = openEditor.getResource(); if (resource) { // Open to side result.unshift(this.instantiationService.createInstance(OpenToSideAction, tree, resource, false)); if (!openEditor.isUntitled()) { // Files: Save / Revert if (!autoSaveEnabled) { result.push(new Separator()); const saveAction = this.instantiationService.createInstance(SaveFileAction, SaveFileAction.ID, SaveFileAction.LABEL); saveAction.setResource(resource); saveAction.enabled = openEditor.isDirty(); result.push(saveAction); const revertAction = this.instantiationService.createInstance(RevertFileAction, RevertFileAction.ID, RevertFileAction.LABEL); revertAction.setResource(resource); revertAction.enabled = openEditor.isDirty(); result.push(revertAction); } result.push(new Separator()); // Compare Actions const runCompareAction = this.instantiationService.createInstance(CompareResourcesAction, resource, tree); if (runCompareAction._isEnabled()) { result.push(runCompareAction); } result.push(this.instantiationService.createInstance(SelectResourceForCompareAction, resource, tree)); } // Untitled: Save / Save As else { result.push(new Separator()); if (this.untitledEditorService.hasAssociatedFilePath(resource)) { let saveUntitledAction = this.instantiationService.createInstance(SaveFileAction, SaveFileAction.ID, SaveFileAction.LABEL); saveUntitledAction.setResource(resource); result.push(saveUntitledAction); } let saveAsAction = this.instantiationService.createInstance(SaveFileAsAction, SaveFileAsAction.ID, SaveFileAsAction.LABEL); saveAsAction.setResource(resource); result.push(saveAsAction); } result.push(new Separator()); } result.push(this.instantiationService.createInstance(CloseEditorAction, CloseEditorAction.ID, nls.localize('close', "Close"))); const closeOtherEditorsInGroupAction = this.instantiationService.createInstance(CloseOtherEditorsInGroupAction, CloseOtherEditorsInGroupAction.ID, nls.localize('closeOthers', "Close Others")); closeOtherEditorsInGroupAction.enabled = openEditor.editorGroup.count > 1; result.push(closeOtherEditorsInGroupAction); result.push(this.instantiationService.createInstance(CloseEditorsInGroupAction, CloseEditorsInGroupAction.ID, nls.localize('closeAll', "Close All"))); } return result; }); } } export class DragAndDrop extends treedefaults.DefaultDragAndDrop { constructor( @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService ) { super(); } public getDragURI(tree: ITree, element: OpenEditor): string { if (!(element instanceof OpenEditor)) { return null; } const resource = element.getResource(); // Some open editors do not have a resource so use the name as drag identifier instead #7021 return resource ? resource.toString() : element.editorInput.getName(); } public onDragOver(tree: ITree, data: IDragAndDropData, target: OpenEditor|EditorGroup, originalEvent: DragMouseEvent): IDragOverReaction { if (!(target instanceof OpenEditor) && !(target instanceof EditorGroup)) { return DRAG_OVER_REJECT; } if (data instanceof ExternalElementsDragAndDropData) { let resource = asFileResource(data.getData()[0]); if (!resource) { return DRAG_OVER_REJECT; } return resource.isDirectory ? DRAG_OVER_REJECT : DRAG_OVER_ACCEPT; } if (data instanceof DesktopDragAndDropData) { return DRAG_OVER_REJECT; } if (!(data instanceof ElementsDragAndDropData)) { return DRAG_OVER_REJECT; } return DRAG_OVER_ACCEPT; } public drop(tree: ITree, data: IDragAndDropData, target: OpenEditor|EditorGroup, originalEvent: DragMouseEvent): void { let draggedElement: OpenEditor|EditorGroup; const model = this.editorGroupService.getStacksModel(); const positionOfTargetGroup = model.positionOfGroup(target instanceof EditorGroup ? target : target.editorGroup); const index = target instanceof OpenEditor ? target.editorGroup.indexOf(target.editorInput) : undefined; // Support drop from explorer viewer if (data instanceof ExternalElementsDragAndDropData) { let resource = <IResourceInput>asFileResource(data.getData()[0]); resource.options = { index, pinned: true }; this.editorService.openEditor(resource, positionOfTargetGroup).done(null, errors.onUnexpectedError); } // Drop within viewer else { let source: OpenEditor|EditorGroup[] = data.getData(); if (Array.isArray(source)) { draggedElement = source[0]; } } if (draggedElement) { if (draggedElement instanceof OpenEditor) { this.editorGroupService.moveEditor(draggedElement.editorInput, model.positionOfGroup(draggedElement.editorGroup), positionOfTargetGroup, index); } else { this.editorGroupService.moveGroup(model.positionOfGroup(draggedElement), positionOfTargetGroup); } } } }
the_stack
import { EventEmitter } from 'events'; import { createHash } from 'crypto'; import * as _ from 'underscore'; import { ExternalWindow, OpenFinWindow, Identity, GroupWindow } from '../shapes'; import * as coreState from './core_state'; import * as windowGroupsProxy from './window_groups_runtime_proxy'; import * as groupTracker from './disabled_frame_group_tracker'; import { argo } from './core_state'; import { getRegisteredExternalWindow } from './api/external_window'; let uuidSeed = 0; export class WindowGroups extends EventEmitter { constructor() { super(); windowGroupsProxy.groupProxyEvents.on('process-change', async (changeState) => { if (changeState.action === 'remove') { await this.leaveGroup(changeState.window); } if (changeState.action === 'add') { const runtimeProxyWindow = await windowGroupsProxy.getRuntimeProxyWindow(changeState.targetIdentity); this._addWindowToGroup(changeState.window.groupUuid, runtimeProxyWindow.window); const sourceWindow: OpenFinWindow = <OpenFinWindow>coreState.getWindowByUuidName(changeState.sourceIdentity.uuid, changeState.sourceIdentity.name); await runtimeProxyWindow.registerSingle(changeState.sourceIdentity); const sourceGroupUuid = sourceWindow.groupUuid; const payload = generatePayload('join', sourceWindow, runtimeProxyWindow.window, changeState.sourceGroup, this.getGroup(sourceGroupUuid)); if (sourceGroupUuid) { this.emit('group-changed', { groupUuid: sourceGroupUuid, payload }); } } }); } private _windowGroups: { [groupUuid: string]: { [windowName: string]: GroupWindow; } } = {}; public getGroup = (groupUuid: string): GroupWindow[] => { return _.values(this._windowGroups[groupUuid]); }; public getGroups = (): GroupWindow[][] => { return _.map(_.keys(this._windowGroups), (groupUuid) => { return this.getGroup(groupUuid); }); }; public hasProxyWindows = (groupUuid: string): boolean => { let hasProxyWindows = false; this.getGroup(groupUuid).forEach(win => { if (win.isProxy) { hasProxyWindows = true; } }); return hasProxyWindows; }; public getGroupHashName = (groupUuid: string): string => { const winGroup = this.getGroup(groupUuid); const hash = createHash('sha256'); winGroup.map(x => x.browserWindow.nativeId) .sort() .forEach(i => hash.update(i)); return hash.digest('hex'); } //cannot rely on nativeId as windows might leave a group after they are closed. private getWindowGroupId = (identity: Identity): string => { const { uuid, name } = identity; return [uuid, name] .map((value: string) => Buffer.from(value).toString('base64')) .join('/'); } public joinGroup = async (source: Identity, target: Identity): Promise<void> => { const [sourceWindow] = await findWindow(source); const [targetWindow, targetProxyWindow] = await findWindow(target); const sourceGroupUuid = sourceWindow.groupUuid; let targetGroupUuid = targetWindow.groupUuid; // cannot join a group with yourself if (sourceWindow.uuid === targetWindow.uuid && sourceWindow.name === targetWindow.name) { return; } // cannot join the same group you're already in if (sourceGroupUuid && targetGroupUuid && sourceGroupUuid === targetGroupUuid) { return; } // remove source from any group it belongs to if (sourceGroupUuid) { await this.leaveGroup(sourceWindow); } // _addWindowToGroup returns the group's uuid that source was added to. in // the case where target doesn't belong to a group either, it generates // a brand new group and returns its uuid sourceWindow.groupUuid = await this._addWindowToGroup(targetGroupUuid, sourceWindow); if (!targetGroupUuid) { targetWindow.groupUuid = targetGroupUuid = await this._addWindowToGroup(sourceWindow.groupUuid, targetWindow); } //we just added a proxy window, we need to take some additional actions. if (targetProxyWindow) { const windowGroup = await targetProxyWindow.register(source); windowGroup.forEach(pWin => this._addWindowToGroup(sourceWindow.groupUuid, pWin.window)); } const payload = generatePayload('join', sourceWindow, targetWindow, this.getGroup(sourceGroupUuid), this.getGroup(targetGroupUuid)); if (sourceGroupUuid) { this.emit('group-changed', { groupUuid: sourceGroupUuid, payload }); } if (targetGroupUuid) { this.emit('group-changed', { groupUuid: targetGroupUuid, payload }); } }; public leaveGroup = async (win: GroupWindow): Promise<void> => { const groupUuid = win && win.groupUuid; // cannot leave a group if you don't belong to one if (!groupUuid) { return; } await this._removeWindowFromGroup(groupUuid, win); if (groupUuid) { this.emit('group-changed', { groupUuid, payload: generatePayload('leave', win, win, this.getGroup(groupUuid), []) }); } // updating the window's groupUuid after since it still needs to receive the event win.groupUuid = null; if (groupUuid) { await this._handleDisbandingGroup(groupUuid); } }; public mergeGroups = async (source: Identity, target: Identity): Promise<void> => { const [sourceWindow] = await findWindow(source); const [targetWindow, targetProxyWindow] = await findWindow(target); let sourceGroupUuid = sourceWindow.groupUuid; let targetGroupUuid = targetWindow.groupUuid; // cannot merge a group with yourself if (source === target) { return; } // cannot merge the same group you're already in if (sourceGroupUuid && targetGroupUuid && sourceGroupUuid === targetGroupUuid) { return; } // create a group if target doesn't already belong to one if (!targetGroupUuid) { targetWindow.groupUuid = targetGroupUuid = await this._addWindowToGroup(targetGroupUuid, targetWindow); } // create a temporary group if source doesn't already belong to one if (!sourceGroupUuid) { sourceGroupUuid = await this._addWindowToGroup(sourceGroupUuid, sourceWindow); } // update each of the windows from source's group to point // to target's group _.each(this.getGroup(sourceGroupUuid), (win) => { win.groupUuid = targetGroupUuid; }); // shallow copy the windows from source's group to target's group _.extend(this._windowGroups[targetGroupUuid], this._windowGroups[sourceGroupUuid]); delete this._windowGroups[sourceGroupUuid]; //we just added a proxy window, we need to take some additional actions. if (targetProxyWindow) { const windowGroup = await targetProxyWindow.register(source); windowGroup.forEach(pWin => this._addWindowToGroup(sourceWindow.groupUuid, pWin.window)); } const payload = generatePayload('merge', sourceWindow, targetWindow, this.getGroup(sourceGroupUuid), this.getGroup(targetGroupUuid)); if (sourceGroupUuid) { this.emit('group-changed', { groupUuid: sourceGroupUuid, payload }); } if (targetGroupUuid) { this.emit('group-changed', { groupUuid: targetGroupUuid, payload }); } }; private _addWindowToGroup = async (groupUuid: string, win: GroupWindow): Promise<string> => { const windowGroupId = this.getWindowGroupId(win); const _groupUuid = groupUuid || generateUuid(); this._windowGroups[_groupUuid] = this._windowGroups[_groupUuid] || {}; const group = this.getGroup(_groupUuid); this._windowGroups[_groupUuid][windowGroupId] = win; win.groupUuid = _groupUuid; if (!argo['use-legacy-window-groups']) { groupTracker.addWindowToGroup(win); } if (!win.isProxy) { await Promise.all(group.map(async w => { if (w.isProxy) { const runtimeProxyWindow = await windowGroupsProxy.getRuntimeProxyWindow(w); await runtimeProxyWindow.registerSingle(win); } })); } return _groupUuid; }; private _removeWindowFromGroup = async (groupUuid: string, win: GroupWindow): Promise<void> => { const windowGroupId = this.getWindowGroupId(win); if (!argo['use-legacy-window-groups']) { groupTracker.removeWindowFromGroup(win); } delete this._windowGroups[groupUuid][windowGroupId]; //update proxy windows to no longer be bound to this specific window. const group = this.getGroup(groupUuid); await Promise.all(group.map(async w => { if (w.isProxy) { const runtimeProxyWindow = await windowGroupsProxy.getRuntimeProxyWindow(w); await runtimeProxyWindow.deregister(win); } })); if (win.isProxy) { const runtimeProxyWindow = await windowGroupsProxy.getRuntimeProxyWindow(win); if (runtimeProxyWindow) { await runtimeProxyWindow.destroy(); } } }; private _handleDisbandingGroup = async (groupUuid: string): Promise<void> => { const windowGroup = this.getGroup(groupUuid); const windowGroupProxies = windowGroup.filter(w => w.isProxy); if (windowGroup.length < 2 || windowGroup.length === windowGroupProxies.length) { await Promise.all(windowGroup.map(async (win) => { await this._removeWindowFromGroup(groupUuid, win); if (!win.isProxy) { this.emit('group-changed', { groupUuid, payload: generatePayload('disband', win, win, [], []) }); } win.groupUuid = null; })); delete this._windowGroups[groupUuid]; } }; } // Helpers function generateUuid(): string { return `group${uuidSeed++}`; } export interface WindowIdentifier { appUuid: string; windowName: string; } export interface GroupChangedEvent { groupUuid: string; payload: GroupChangedPayload; } export interface GroupChangedPayload { reason: string; sourceGroup: WindowIdentifier[]; sourceWindowAppUuid: string; sourceWindowName: string; targetGroup: WindowIdentifier[]; targetWindowAppUuid: string; targetWindowName: string; topic: 'window'; type: 'group-changed'; } export interface GroupEvent extends GroupChangedPayload, Identity { memberOf: string; } function generatePayload(reason: string, sourceWindow: GroupWindow, targetWindow: GroupWindow, sourceGroup: GroupWindow[], targetGroup: GroupWindow[] ): GroupChangedPayload { return { reason, sourceGroup: mapEventWindowGroups(sourceGroup), sourceWindowAppUuid: sourceWindow.app_uuid, sourceWindowName: sourceWindow.name, targetGroup: mapEventWindowGroups(targetGroup), targetWindowAppUuid: targetWindow.app_uuid, targetWindowName: targetWindow.name, topic: 'window', type: 'group-changed' }; } function mapEventWindowGroups(group: GroupWindow[]): WindowIdentifier[] { return _.map(group, (win) => { return { appUuid: win.app_uuid, windowName: win.name }; }); } /* Attempt to find a window in: 1. Current runtime (core state) 2. Another runtime (multi-runtim) 3. Current runtime (map of registered external windows) */ async function findWindow(window: Identity): Promise<[GroupWindow, windowGroupsProxy.RuntimeProxyWindow | undefined]> { let foundWindow; let proxyWindow; // Current runtime, OpenFin window foundWindow = <OpenFinWindow>coreState.getWindowByUuidName(window.uuid, window.name); if (!foundWindow) { try { // Multi-runtime, proxy window, OpenFin window proxyWindow = <windowGroupsProxy.RuntimeProxyWindow>await windowGroupsProxy.getRuntimeProxyWindow(window); foundWindow = <OpenFinWindow>proxyWindow.window; } catch (error) { // Current runtime, external window foundWindow = <ExternalWindow>getRegisteredExternalWindow(window); } } return [foundWindow, proxyWindow]; } export default new WindowGroups();
the_stack
import * as path from 'path'; import * as fs from 'fs-extra'; import * as prettier from 'prettier'; import * as ts from 'typescript'; import { ResolveConfigOptions } from 'prettier'; import { error } from './debugLog'; import { Mod, StandardDataSource } from './standard'; import { Manager } from './manage'; import { OriginType } from './scripts'; import { diff } from './diff'; import { getTemplateByTemplateType } from './templates'; const defaultTemplateCode = ` import * as Pont from 'pont-engine'; import { CodeGenerator, Interface } from "pont-engine"; export class FileStructures extends Pont.FileStructures { } export default class MyGenerator extends CodeGenerator { } `; const defaultTransformCode = ` import { StandardDataSource } from "pont-engine"; export default function(dataSource: StandardDataSource): StandardDataSource { return dataSource; } `; const defaultFetchMethodCode = ` import fetch from 'node-fetch'; export default function (url: string): string { return fetch(url).then(res => res.text()) } `; export class Mocks { enable = false; port = 8080; basePath = ''; wrapper = `{ "code": 0, "data": {response}, "message": "" }`; } export enum Surrounding { typeScript = 'typeScript', javaScript = 'javaScript' } export enum SurroundingFileName { javaScript = 'js', typeScript = 'ts' } export class DataSourceConfig { originUrl? = ''; originType = OriginType.SwaggerV2; name?: string; usingOperationId = true; usingMultipleOrigins = false; taggedByName = true; templatePath = 'serviceTemplate'; templateType = ''; surrounding = Surrounding.typeScript; outDir = 'src/service'; scannedRange = []; scannedPattern = null; transformPath = ''; fetchMethodPath = ''; prettierConfig: ResolveConfigOptions = {}; /** 单位为秒,默认 20 分钟 */ pollingTime = 60 * 20; mocks = new Mocks(); constructor(config: DataSourceConfig) { Object.keys(config).forEach((key) => { if (key === 'mocks') { this[key] = { ...this[key], ...config[key] }; } else { this[key] = config[key]; } }); } } export class Config extends DataSourceConfig { origins: Array<{ originType: OriginType; originUrl: string; name: string; usingOperationId: boolean; transformPath?: string; fetchMethodPath?: string; outDir?: string; }>; constructor(config: Config) { super(config); this.origins = config.origins || []; } static getTransformFromConfig(config: Config | DataSourceConfig) { if (config.transformPath) { const moduleResult = getTemplate(config.transformPath, '', defaultTransformCode) as any; if (moduleResult) { return moduleResult.default; } } return (id) => id; } static getFetchMethodFromConfig(config: Config | DataSourceConfig) { if (config.fetchMethodPath) { const fetchMethodPath = path.isAbsolute(config.fetchMethodPath) ? config.fetchMethodPath : path.join(process.cwd(), config.fetchMethodPath); const moduleResult = getTemplate(fetchMethodPath, '', defaultFetchMethodCode); if (moduleResult) { return moduleResult.default; } } return (id) => id; } validate() { if (this.origins && this.origins.length) { this.origins.forEach((origin, index) => { if (!origin.originUrl) { return `请在 origins[${index}] 中配置 originUrl `; } if (!origin.name) { return `请在 origins[${index}] 中配置 originUrl `; } }); } else { if (!this.originUrl) { return '请配置 originUrl 来指定远程地址。'; } } return ''; } static createFromConfigPath(configPath: string) { const content = fs.readFileSync(configPath, 'utf8'); try { const configObj = JSON.parse(content); return new Config(configObj); } catch (e) { throw new Error('pont-config.json is not a validate json'); } } getDataSourcesConfig(configDir: string) { const { origins, ...rest } = this; const commonConfig = { ...rest, outDir: path.join(configDir, this.outDir), scannedRange: Array.isArray(this.scannedRange) ? this.scannedRange.map((dir) => path.join(configDir, dir)) : [], templatePath: this.templatePath ? path.join(configDir, this.templatePath) : undefined, transformPath: this.transformPath ? path.join(configDir, this.transformPath) : undefined, fetchMethodPath: this.fetchMethodPath ? path.join(configDir, this.fetchMethodPath) : undefined }; // FIXME: origins中配的路径没有转换成绝对路径,找不到该模块 if (this.origins && this.origins.length) { return this.origins.map((origin) => { return new DataSourceConfig({ ...commonConfig, ...origin, outDir: origin.outDir ? path.join(configDir, origin.outDir) : commonConfig.outDir }); }); } return [new DataSourceConfig(commonConfig)]; } } export function format(fileContent: string, prettierOpts = {}) { try { return prettier.format(fileContent, { parser: 'typescript', trailingComma: 'all', singleQuote: true, ...prettierOpts }); } catch (e) { error(`代码格式化报错!${e.toString()}\n代码为:${fileContent}`); return fileContent; } } export function getDuplicateById<T>(arr: T[], idKey = 'name'): null | T { if (!arr || !arr.length) { return null; } let result; arr.forEach((item, itemIndex) => { if (arr.slice(0, itemIndex).find((o) => o[idKey] === item[idKey])) { result = item; return; } }); return result; } export function transformModsName(mods: Mod[]) { // 检测所有接口是否存在接口名忽略大小写时重复,如果重复,以下划线命名 mods.forEach((mod) => { const currName = mod.name; const sameMods = mods.filter((mod) => mod.name.toLowerCase() === currName.toLowerCase()); if (sameMods.length > 1) { mod.name = transformDashCase(mod.name); } }); } function transformDashCase(name: string) { return name.replace(/[A-Z]/g, (ch) => '_' + ch.toLowerCase()); } export function transformCamelCase(name: string) { let words = [] as string[]; let result = ''; if (name.includes('-')) { words = name.split('-'); } else if (name.includes(' ')) { words = name.split(' '); } else { if (typeof name === 'string') { result = name; } else { throw new Error('mod name is not a string: ' + name); } } if (words && words.length) { result = words .map((word) => { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }) .join(''); } result = result.charAt(0).toLowerCase() + result.slice(1); if (result.endsWith('Controller')) { result = result.slice(0, result.length - 'Controller'.length); } return result; } export function transformDescription(description: string) { const words = description.split(' ').filter((word) => word !== 'Controller'); const [firstWord, ...rest] = words; const sFirstWord = firstWord.charAt(0).toLowerCase() + firstWord.slice(1); return [sFirstWord, ...rest].join(''); } export function toUpperFirstLetter(text: string) { return text.charAt(0).toUpperCase() + text.slice(1); } export function getMaxSamePath(paths: string[], samePath = '') { if (!paths.length) { return samePath; } if (paths.some((path) => !path.includes('/'))) { return samePath; } const segs = paths.map((path) => { const [firstSeg, ...restSegs] = path.split('/'); return { firstSeg, restSegs }; }); if (segs.every((seg, index) => index === 0 || seg.firstSeg === segs[index - 1].firstSeg)) { return getMaxSamePath( segs.map((seg) => seg.restSegs.join('/')), samePath + '/' + segs[0].firstSeg ); } return samePath; } export function getIdentifierFromUrl(url: string, requestType: string, samePath = '') { const currUrl = url.slice(samePath.length).match(/([^\.]+)/)[0]; return ( requestType + currUrl .split('/') .map((str) => { if (str.includes('-')) { str = str.replace(/(\-\w)+/g, (_match, p1) => { if (p1) { return p1.slice(1).toUpperCase(); } }); } if (str.match(/^{.+}$/gim)) { return 'By' + toUpperFirstLetter(str.slice(1, str.length - 1)); } return toUpperFirstLetter(str); }) .join('') ); } /** some reversed keyword in js but not in java */ const TS_KEYWORDS = ['delete', 'export', 'import', 'new', 'function']; const REPLACE_WORDS = ['remove', 'exporting', 'importing', 'create', 'functionLoad']; export function getIdentifierFromOperatorId(operationId: string) { const identifier = operationId.replace(/(.+)(Using.+)/, '$1'); const index = TS_KEYWORDS.indexOf(identifier); if (index === -1) { return identifier; } return REPLACE_WORDS[index]; } export function getTemplate(templatePath, templateType, defaultValue = defaultTemplateCode) { if (!fs.existsSync(templatePath + '.ts')) { fs.writeFileSync(templatePath + '.ts', getTemplateByTemplateType(templateType) || defaultValue); } const tsResult = fs.readFileSync(templatePath + '.ts', 'utf8'); const jsResult = ts.transpileModule(tsResult, { compilerOptions: { target: ts.ScriptTarget.ES2015, module: ts.ModuleKind.CommonJS } }); const noCacheFix = (Math.random() + '').slice(2, 5); const jsName = templatePath + noCacheFix + '.js'; let moduleResult; try { // 编译到js fs.writeFileSync(jsName, jsResult.outputText, 'utf8'); // 用 node require 引用编译后的 js 代码 moduleResult = require(jsName); // 删除该文件 fs.removeSync(jsName); } catch (e) { // 删除失败,则再删除 if (fs.existsSync(jsName)) { fs.removeSync(jsName); } // 没有引用,报错 if (!moduleResult) { throw new Error(e); } } return moduleResult; } export function getTemplatesDirFile(fileName, filePath = 'templates/') { return fs.readFileSync(__dirname.substring(0, __dirname.lastIndexOf('lib')) + filePath + fileName, 'utf8'); } export function judgeTemplatesDirFileExists(fileName, filePath = 'templates/') { return fs.existsSync(__dirname.substring(0, __dirname.lastIndexOf('lib')) + filePath + fileName); } export async function lookForFiles(dir: string, fileName: string): Promise<string> { const files = await fs.readdir(dir); for (let file of files) { const currName = path.join(dir, file); const info = await fs.lstat(currName); if (info.isDirectory()) { if (file === '.git' || file === 'node_modules') { continue; } const result = await lookForFiles(currName, fileName); if (result) { return result; } } else if (info.isFile() && file === fileName) { return currName; } } } export function toDashCase(name: string) { const dashName = name .split(' ') .join('') .replace(/[A-Z]/g, (p) => '-' + p.toLowerCase()); if (dashName.startsWith('-')) { return dashName.slice(1); } return dashName; } export function toDashDefaultCase(name: string) { let dashName = name .split(' ') .join('') .replace(/[A-Z]/g, (p) => '-' + p.toLowerCase()); if (dashName.startsWith('-')) { dashName = dashName.slice(1); } if (dashName.endsWith('-controller')) { return dashName.slice(0, dashName.length - '-controller'.length); } return dashName; } /** 正则检测是否包含中文名 */ export function hasChinese(str: string) { return ( str && str.match( /[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uff1a\uff0c\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]|[\uff01-\uff5e\u3000-\u3009\u2026]/ ) ); } const PROJECT_ROOT = process.cwd(); export const CONFIG_FILE = 'pont-config.json'; export async function createManager(configFile = CONFIG_FILE) { const configPath = await lookForFiles(PROJECT_ROOT, configFile); if (!configPath) { return; } const config = Config.createFromConfigPath(configPath); const manager = new Manager(PROJECT_ROOT, config, path.dirname(configPath)); await manager.ready(); return manager; } export function diffDses(ds1: StandardDataSource, ds2: StandardDataSource) { const mapModel = (model) => Object.assign({}, model, { details: [] }) as any; const modDiffs = diff(ds1.mods.map(mapModel), ds2.mods.map(mapModel)); const boDiffs = diff(ds1.baseClasses.map(mapModel), ds2.baseClasses.map(mapModel)); return { modDiffs, boDiffs }; } export function reviseModName(modName: string) { // .replace(/\//g, '.').replace(/^\./, '').replace(/\./g, '_') 转换 / .为下划线 // exp: /api/v1/users => api_v1_users // exp: api.v1.users => api_v1_users return modName.replace(/\//g, '.').replace(/^\./, '').replace(/\./g, '_'); } /** 获取文件名名称 */ export function getFileName(fileName: string, surrounding: string) { const isInvalidSurrounding = Surrounding[surrounding]; if (isInvalidSurrounding) { return `${fileName}.${SurroundingFileName[isInvalidSurrounding]}`; } return `${fileName}.ts`; } /** 检测是否是合法url */ export function judgeIsVaildUrl(url: string) { return /^(http|https):.*?$/.test(url); }
the_stack
import { crc32 } from "crc"; import * as dgram from "dgram"; import { AddressInfo } from "net"; import { MersenneTwister19937, Random } from "random-js"; import { BehaviorSubject, Subject, Subscription } from "rxjs"; import { privateData } from "../../../shared/lib"; import { DualshockData, DualshockMeta, GenericDualshockController, UdpServerDefaults, UdpServerMessage, } from "../../models"; import { ClientRequests } from "./client-requests"; /** * Internal class data interface. */ interface InternalData { connectionStatus: BehaviorSubject<boolean>; errorSubject: Subject<Error>; infoSubject: Subject<string>; onMessageTimeout: NodeJS.Timer | null; } /** * Interface for holding information about client. */ interface ClientData { address: AddressInfo; requests: ClientRequests; } /** * Private data getter. */ const getInternals = privateData() as (self: UdpServer, init: InternalData | void) => InternalData; /** * Shorthand function for getting character code from character. * @param character Character value to get code for. * @returns Character code for provided value. */ function charCode(character: string) { return character.charCodeAt(0); } /** * UDP server class for handling communication over cemuhook UDP protocol. */ export class UdpServer { /** * Currently open socket. */ private socket: dgram.Socket | null = null; /** * Server ID to send to cemuhook. */ private serverId: number = new Random(MersenneTwister19937.autoSeed()).uint32(); /** * Connected Dualshock controllers. */ private controllers: Array<{ device: GenericDualshockController, subscription: Subscription, } | null> = new Array(4).fill(null); /** * Connected clients. */ private clients = new Map<string, ClientData>(); constructor() { getInternals(this, { connectionStatus: new BehaviorSubject<boolean>(false), errorSubject: new Subject(), infoSubject: new Subject(), onMessageTimeout: null, }); } /** * Event observable. */ public get onError() { return getInternals(this).errorSubject.asObservable(); } /** * Information observable. */ public get onInfo() { return getInternals(this).infoSubject.asObservable(); } /** * Status change observable. */ public get onStatusChange() { return getInternals(this).connectionStatus.asObservable(); } /** * Start UDP server. * @param port Custom port. * @param address Custom address. */ public async start(port?: number, address?: string) { const pd = getInternals(this); return new Promise<void>(async (resolve, reject) => { try { await this.stop(); this.socket = dgram.createSocket("udp4"); this.socket.once("error", reject); this.socket.once("listening", () => { this.socket!.removeListener("error", reject); this.socket!.on("error", pd.errorSubject.next.bind(pd.errorSubject)); this.socket!.on("message", this.onMessage.bind(this)); resolve(); }); this.socket.bind(port, address); } catch (error) { reject(error); } }); } /** * Stop UDP server. */ public async stop() { return new Promise<void>(async (resolve, reject) => { try { if (this.socket !== null) { this.socket.removeAllListeners("error"); this.socket.removeAllListeners("message"); this.socket.once("error", reject); this.socket.close(); this.socket = null; } resolve(); } catch (error) { reject(error); } }); } /** * Adds controller to server slot. * @param controller Controller to add. * @returns `false` if there are no more spots for controller. */ public addController(controller: GenericDualshockController) { const pd = getInternals(this); // tslint:disable-next-line:prefer-for-of for (let i = 0; i < this.controllers.length; i++) { if (this.controllers[i] === null) { this.controllers[i] = { device: controller, subscription: new Subscription(), }; this.controllers[i]!.subscription .add(controller.onError.subscribe((value) => pd.errorSubject.next(value))) .add(controller.onDualshockData.subscribe((value) => this.handleReport(value))); return true; } } return false; } /** * Remove all controllers or only specified controller. * @param index Index of the controller to remove. */ public removeController(index?: number) { if (index === undefined) { for (let i = 0; i < this.controllers.length; i++) { this.removeController(i); } } else if (index > 0 && index < this.controllers.length) { if (this.controllers[index] !== null) { this.controllers[index]!.subscription.unsubscribe(); this.controllers[index] = null; } } } /** * Clear client list. */ public clearClients() { this.clients.clear(); this.changeConnectionStatus(false); } /** * Begins data packet. * @param data Data to add to packet's start. * @param protocolVer Protocol version. */ private beginPacket(data: Buffer, protocolVer: number = UdpServerDefaults.MaxProtocolVer) { if (data.length >= 16) { let index = 0; data[index++] = charCode("D"); data[index++] = charCode("S"); data[index++] = charCode("U"); data[index++] = charCode("S"); data.writeUInt16LE(protocolVer, index); index += 2; data.writeUInt16LE(data.length - 16, index); index += 2; data.writeUInt32LE(0, index); index += 4; data.writeUInt32LE(this.serverId, index); index += 4; return index; } else { throw new Error(`"beginPacket" buffer size is too small (${data.length})`); } } /** * Finish packet by adding crc32 validation. * @param data Data to generate crc32 with. */ private finishPacket(data: Buffer) { data.writeUInt32LE(crc32(data), 8); } /** * Send packet to client. * @param clientEndpoint Client endpoint data. * @param data Data to send. * @param protocolVer Protocol version to use. */ private sendPacket( clientEndpoint: AddressInfo, data: Buffer, protocolVer: number = UdpServerDefaults.MaxProtocolVer, ) { const buffer = Buffer.alloc(data.length + 16); const index = this.beginPacket(buffer, protocolVer); buffer.fill(data, index); this.finishPacket(buffer); this.socket!.send(buffer, clientEndpoint.port, clientEndpoint.address, (error, bytes) => { const pd = getInternals(this); if (error) { pd.errorSubject.next(error); } else if (bytes !== buffer.length) { // tslint:disable-next-line:max-line-length pd.errorSubject.next(new Error(`failed to completely send all of buffer. Sent: ${bytes}. Buffer length: ${buffer.length}`)); } }); } /** * Data from clients handler. * @param data Data received from client. * @param clientEndpoint Client endpoint data. */ private onMessage(data: Buffer, clientEndpoint: AddressInfo) { try { if (data[0] === charCode("D") && data[1] === charCode("S") && data[2] === charCode("U") && data[3] === charCode("C") ) { this.refreshStatus(); let index = 4; const protocolVer = data.readUInt16LE(index); if (protocolVer > UdpServerDefaults.MaxProtocolVer) { // tslint:disable-next-line:max-line-length throw new Error(`outdated protocol. Received: ${protocolVer}. Current: ${UdpServerDefaults.MaxProtocolVer}.`); } else { index += 2; } const packetSize = data.readUInt16LE(index); if (packetSize < 0) { throw new Error(`negative packet size received (${packetSize}).`); } else { index += 2; } const receivedCrc = data.readUInt32LE(index); data[index++] = 0; data[index++] = 0; data[index++] = 0; data[index++] = 0; const computedCrc = crc32(data); if (receivedCrc !== computedCrc) { throw new Error(`crc mismatch. Received: ${receivedCrc}. Computed: ${computedCrc}.`); } const clientId = data.readUInt32LE(index); index += 4; const msgType = data.readUInt32LE(index); index += 4; if (msgType === UdpServerMessage.DSUC_VersionReq) { const outBuffer = Buffer.alloc(8); outBuffer.writeUInt32LE(UdpServerMessage.DSUS_VersionRsp, 0); outBuffer.writeUInt32LE(UdpServerDefaults.MaxProtocolVer, 4); this.sendPacket(clientEndpoint, outBuffer, 1001); } else if (msgType === UdpServerMessage.DSUC_ListPorts) { const numOfPadRequests = data.readInt32LE(index); if (numOfPadRequests < 0 || numOfPadRequests > 4) { // tslint:disable-next-line:max-line-length throw new Error(`number of pad requests is out of range. Range: [0; 4]. Request: ${numOfPadRequests}.`); } else { index += 4; } for (let i = 0; i < numOfPadRequests; i++) { if (data[index + i] > 3) { // tslint:disable-next-line:max-line-length throw new Error(`request index for ${i} pad is out of range. Range: [0; 3]. Request: ${data[index + i]}.`); } } const outBuffer = Buffer.alloc(16); for (let i = 0; i < numOfPadRequests; i++) { const requestIndex = data[index + i]; const controller = this.controllers[requestIndex]; const meta = controller ? controller.device.dualShockMeta : null; if (meta !== null) { outBuffer.writeUInt32LE(UdpServerMessage.DSUS_PortInfo, 0); let outIndex = 4; outBuffer[outIndex++] = meta.padId; outBuffer[outIndex++] = meta.state; outBuffer[outIndex++] = meta.model; outBuffer[outIndex++] = meta.connectionType; if (meta.macAddress !== null && meta.macAddress.length === 17) { const mac = meta.macAddress.split(":").map((part) => parseInt(part, 16)); for (const macPart of mac) { outBuffer[outIndex++] = macPart; } } else { for (let j = 0; j < 6; j++) { outBuffer[outIndex++] = 0; } } outBuffer[outIndex++] = meta.batteryStatus; outBuffer[outIndex++] = 0; this.sendPacket(clientEndpoint, outBuffer, 1001); } } } else if (msgType === UdpServerMessage.DSUC_PadDataReq) { const registrationFlags = data[index++]; const idToRRegister = data[index++]; const connectionId: string = `${clientEndpoint.family}_${clientEndpoint.address}:${clientEndpoint.port}_${clientId}`; let macToRegister: string | string[] = ["", "", "", "", "", ""]; let client: ClientData | undefined; for (let i = 0; i < macToRegister.length; i++, index++) { macToRegister[i] = `${data[index] < 15 ? "0" : ""}${data[index].toString(16)}`; } macToRegister = macToRegister.join(":"); client = this.clients.get(connectionId); if (client === undefined) { this.clients.set(connectionId, { address: clientEndpoint, requests: new ClientRequests() }); client = this.clients.get(connectionId)!; getInternals(this).infoSubject.next(`New connection established: ${connectionId}.`); } client.requests.registerPadRequest(registrationFlags, idToRRegister, macToRegister); } } } catch (error) { getInternals(this).errorSubject.next(error); } } /** * Handle reports emitted by controller. * @param data Event data to handle. */ private handleReport(data: DualshockData) { try { if (this.socket !== null) { const meta = data.meta; const clients = this.getClientsForReport(meta); if (clients.length > 0) { const report = data.report; const outBuffer = Buffer.alloc(100); let outIndex = this.beginPacket(outBuffer, 1001); outBuffer.writeUInt32LE(UdpServerMessage.DSUS_PadDataRsp, outIndex); outIndex += 4; outBuffer[outIndex++] = meta.padId; outBuffer[outIndex++] = meta.state; outBuffer[outIndex++] = meta.model; outBuffer[outIndex++] = meta.connectionType; const mac = meta.macAddress.split(":").map((part) => parseInt(part, 16)); for (const macPart of mac) { outBuffer[outIndex++] = macPart; } outBuffer[outIndex++] = meta.batteryStatus; outBuffer[outIndex++] = meta.isActive ? 0x01 : 0x00; outBuffer.writeUInt32LE(report.packetCounter, outIndex); outIndex += 4; outBuffer[outIndex] = 0; if (report.button.dPad.LEFT) { outBuffer[outIndex] |= 0x80; } if (report.button.dPad.DOWN) { outBuffer[outIndex] |= 0x40; } if (report.button.dPad.RIGHT) { outBuffer[outIndex] |= 0x20; } if (report.button.dPad.UP) { outBuffer[outIndex] |= 0x10; } if (report.button.options) { outBuffer[outIndex] |= 0x08; } if (report.button.R3) { outBuffer[outIndex] |= 0x04; } if (report.button.L3) { outBuffer[outIndex] |= 0x02; } if (report.button.share) { outBuffer[outIndex] |= 0x01; } outBuffer[++outIndex] = 0; if (report.button.SQUARE) { outBuffer[outIndex] |= 0x80; } if (report.button.CROSS) { outBuffer[outIndex] |= 0x40; } if (report.button.CIRCLE) { outBuffer[outIndex] |= 0x20; } if (report.button.TRIANGLE) { outBuffer[outIndex] |= 0x10; } if (report.button.R1) { outBuffer[outIndex] |= 0x08; } if (report.button.L1) { outBuffer[outIndex] |= 0x04; } if (report.button.R2) { outBuffer[outIndex] |= 0x02; } if (report.button.L2) { outBuffer[outIndex] |= 0x01; } outBuffer[++outIndex] = (report.button.PS) ? 0x01 : 0x00; outBuffer[++outIndex] = (report.button.touch) ? 0x01 : 0x00; outBuffer[++outIndex] = report.position.left.x; outBuffer[++outIndex] = report.position.left.y; outBuffer[++outIndex] = report.position.right.x; outBuffer[++outIndex] = report.position.right.y; outBuffer[++outIndex] = report.button.dPad.LEFT ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.dPad.DOWN ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.dPad.RIGHT ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.dPad.UP ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.SQUARE ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.CROSS ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.CIRCLE ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.TRIANGLE ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.R1 ? 0xFF : 0x00; outBuffer[++outIndex] = report.button.L1 ? 0xFF : 0x00; outBuffer[++outIndex] = report.trigger.R2; outBuffer[++outIndex] = report.trigger.L2; outIndex++; outBuffer[outIndex++] = report.trackPad.first.isActive ? 0x01 : 0x00; outBuffer[outIndex++] = report.trackPad.first.id; outBuffer.writeUInt16LE(report.trackPad.first.x, outIndex); outIndex += 2; outBuffer.writeUInt16LE(report.trackPad.first.y, outIndex); outIndex += 2; outBuffer[outIndex++] = report.trackPad.second.isActive ? 0x01 : 0x00; outBuffer[outIndex++] = report.trackPad.second.id; outBuffer.writeUInt16LE(report.trackPad.second.x, outIndex); outIndex += 2; outBuffer.writeUInt16LE(report.trackPad.second.y, outIndex); outIndex += 2; outBuffer.writeUInt32LE(report.motionTimestamp.getLowBitsUnsigned(), outIndex); outIndex += 4; outBuffer.writeUInt32LE(report.motionTimestamp.getHighBitsUnsigned(), outIndex); outIndex += 4; outBuffer.writeFloatLE(report.accelerometer.x, outIndex); outIndex += 4; outBuffer.writeFloatLE(report.accelerometer.y, outIndex); outIndex += 4; outBuffer.writeFloatLE(report.accelerometer.z, outIndex); outIndex += 4; outBuffer.writeFloatLE(report.gyro.x, outIndex); outIndex += 4; outBuffer.writeFloatLE(report.gyro.y, outIndex); outIndex += 4; outBuffer.writeFloatLE(report.gyro.z, outIndex); outIndex += 4; this.finishPacket(outBuffer); for (const client of clients) { this.socket.send(outBuffer, client.port, client.address, (error, bytes) => { const pd = getInternals(this); if (error) { pd.errorSubject.next(error); } else if (bytes !== outBuffer.length) { // tslint:disable-next-line:max-line-length pd.errorSubject.next(new Error(`failed to completely send all of buffer. Sent: ${bytes}. Buffer length: ${outBuffer.length}`)); } }); } } } } catch (error) { const stringifiedData = JSON.stringify(data, undefined, " "); if (error instanceof Error) { error.message += ` (\n${stringifiedData}\n).`; } else { error += ` (\n${stringifiedData}\n).`; } getInternals(this).errorSubject.next(error); } } /** * Status timeout used to detect lost UDP connection. */ private refreshStatus() { const internals = getInternals(this); if (internals.onMessageTimeout !== null) { clearTimeout(internals.onMessageTimeout); internals.onMessageTimeout = null; } this.changeConnectionStatus(true); internals.onMessageTimeout = setTimeout(() => { this.changeConnectionStatus(false); internals.onMessageTimeout = null; }, UdpServerDefaults.ClientTimeoutLimit); } /** * Change status indicating whether a connection to UDP server is established. * @param status New connection status. */ private changeConnectionStatus(status: boolean) { const internals = getInternals(this); if (status !== internals.connectionStatus.value) { internals.connectionStatus.next(status); } } /** * Retrieve active clients associated with provided metadata. * @param meta Metadata to search for clients by. * @returns Array of client endpoint data. */ private getClientsForReport(meta: DualshockMeta) { const clients: AddressInfo[] = []; const clientsToDelete: string[] = []; const currentTime = Date.now(); for (const [id, { address, requests }] of this.clients) { if (currentTime - requests.timeForAllPads < UdpServerDefaults.ClientTimeoutLimit) { clients.push(address); } else if ( (meta.padId < requests.timeForPadById.length) && (currentTime - requests.timeForPadById[meta.padId] < UdpServerDefaults.ClientTimeoutLimit) ) { clients.push(address); } else if ( requests.timeForPadByMac.has(meta.macAddress) && (currentTime - requests.timeForPadByMac.get(meta.macAddress)! < UdpServerDefaults.ClientTimeoutLimit) ) { clients.push(address); } else { let isClientOk = false; for (const time of requests.timeForPadById) { if (currentTime - time < UdpServerDefaults.ClientTimeoutLimit) { isClientOk = true; break; } } if (!isClientOk) { for (const [mac, time] of requests.timeForPadByMac) { if (currentTime - time < UdpServerDefaults.ClientTimeoutLimit) { isClientOk = true; break; } } if (!isClientOk) { clientsToDelete.push(id); } } } } for (const client of clientsToDelete) { this.clients.delete(client); getInternals(this).infoSubject.next(`Connection dropped: ${client}.`); } return clients; } }
the_stack
// The phosphorus runtime for Scratch // Provides methods expected at runtime by scripts created by the compiler and an environment for Scratch scripts to run namespace P.runtime { export type Fn = () => void; // Current runtime var runtime: Runtime; // Current stage var self: P.core.Stage; // Current sprite or stage var S: P.core.Base; // Current thread state. var R; // Stack of states (R) for this thread var STACK; // Current procedure call, if any. Contains arguments. var C: ThreadCall; // This thread's call (C) stack var CALLS; // If level of layers of "Run without screen refresh" we are in // Each level (usually procedures) of depth will increment and decrement as they start and stop. // As long as this is greater than 0, functions will run without waiting for the screen. var WARP: number; // BASE is the first ran function of a thread, used as an identifier var BASE; // The ID of the active thread in the Runtime's queue var THREAD: number; // The next function to run immediately after this one. var IMMEDIATE: Fn | null | undefined; // Has a "visual change" been made in this frame? var VISUAL: boolean; // Note: // Your editor might warn you about "unused variables" or things like that. // Due to the nature of the runtime you should ignore these warnings. const epoch = Date.UTC(2000, 0, 1); const INSTRUMENTS = P.audio.instruments; const DRUMS = P.audio.drums; const DIGIT = /\d/; var bool = function(v) { return +v !== 0 && v !== '' && v !== 'false' && v !== false; }; var compare = function(x, y) { if ((typeof x === 'number' || DIGIT.test(x)) && (typeof y === 'number' || DIGIT.test(y))) { var nx = +x; var ny = +y; if (nx === nx && ny === ny) { return nx < ny ? -1 : nx === ny ? 0 : 1; } } var xs = ('' + x).toLowerCase(); var ys = ('' + y).toLowerCase(); return xs < ys ? -1 : xs === ys ? 0 : 1; }; var numLess = function(nx, y) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; if (ny === ny) { return nx < ny; } } var ys = ('' + y).toLowerCase(); return '' + nx < ys; }; var numGreater = function(nx, y) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; if (ny === ny) { return nx > ny; } } var ys = ('' + y).toLowerCase(); return '' + nx > ys; }; var equal = function(x: any, y: any) { if ((typeof x === 'number' || typeof x === 'boolean' || DIGIT.test(x)) && (typeof y === 'number' || typeof x === 'boolean' || DIGIT.test(y))) { var nx = +x; var ny = +y; if (nx === nx && ny === ny) { return nx === ny; } } var xs = ('' + x).toLowerCase(); var ys = ('' + y).toLowerCase(); return xs === ys; }; // Equality testing optimized for the first argument always being a number. var numEqual = function(nx: number, y: any) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; return ny === ny && nx === ny; } return false; }; var numEqualExperimental = function(nx: number, y: any) { var ny = +y; return ny === ny && nx === ny; }; var numLessExperimental = function(nx: number, y: any) { var ny = +y; return ny === ny && nx < y; }; var numGreaterExperimental = function(nx: number, y: any) { var ny = +y; return ny === ny && nx > y; }; // Equality testing optimized for either argument never being number-like. var strEqual = function(a: any, b: any) { return (a + '').toLowerCase() === (b + '').toLowerCase(); }; var stringContains = function(baseString: string, needle: string) { return baseString.toLowerCase().indexOf(needle.toLowerCase()) > -1; }; var mod = function(x, y) { var r = x % y; // need special behavior for handling negatives if (r / y < 0) { r += y; } return r; }; var random = function(x, y) { var fractional = (typeof x === 'string' && !isNaN(+x) && x.indexOf('.') > -1) || (typeof y === 'string' && !isNaN(+y) && y.indexOf('.') > -1); x = +x || 0; y = +y || 0; if (x > y) { var tmp = y; y = x; x = tmp; } if (!fractional && (x % 1 === 0 && y % 1 === 0)) { return Math.floor(Math.random() * (y - x + 1)) + x; } return Math.random() * (y - x) + x; }; // Clone a sprite var clone = function(name) { const parent = name === '_myself_' ? S : self.getObject(name); if (!parent || !P.core.isSprite(parent)) { // sprites that do not exist and stages cannot be cloned return; } const c = parent.clone(); self.children.splice(self.children.indexOf(parent), 0, c); runtime.triggerFor(c, 'whenCloned'); if (c.visible) { VISUAL = true; } }; var getVars = function(name) { return self.vars[name] !== undefined ? self.vars : S.vars; }; var getLists = function(name) { if (self.lists[name] !== undefined) return self.lists; if (S.lists[name] === undefined) { S.lists[name] = []; } return S.lists; }; var listIndex = function(list, index, length) { var i = index | 0; if (i === index) return i > 0 && i <= length ? i - 1 : -1; if (index === 'random' || index === 'any') { return Math.random() * length | 0; } if (index === 'last') { return length - 1; } return i > 0 && i <= length ? i - 1 : -1; }; var contentsOfList = function(list) { var isSingle = true; for (var i = list.length; i--;) { if (list[i].length !== 1) { isSingle = false; break; } } return list.join(isSingle ? '' : ' '); }; var getLineOfList = function(list, index) { var i = listIndex(list, index, list.length); return i !== -1 ? list[i] : ''; }; var listContains = function(list, value) { for (var i = list.length; i--;) { if (equal(list[i], value)) return true; } return false; }; var listIndexOf = function(list, value) { for (var i = 0; i < list.length; i++) { if (equal(list[i], value)) return i + 1; } return 0; }; var appendToList = function(list, value) { list.push(value); }; var deleteLineOfList = function(list, index) { if (index === 'all') { list.length = 0; } else { var i = listIndex(list, index, list.length); if (i === list.length - 1) { list.pop(); } else if (i !== -1) { list.splice(i, 1); } } }; var insertInList = function(list, index, value) { var i = listIndex(list, index, list.length + 1); if (i === list.length) { list.push(value); } else if (i !== -1) { list.splice(i, 0, value); } }; var setLineOfList = function(list, index, value) { var i = listIndex(list, index, list.length); if (i !== -1) { list[i] = value; } }; // "Watched" variants of the above that set modified=true var watchedAppendToList = function(list, value) { appendToList(list, value); if (!list.modified) list.modified = true; }; var watchedDeleteLineOfList = function(list, index) { deleteLineOfList(list, index); if (!list.modified) list.modified = true; }; var watchedDeleteAllOfList = function(list) { list.length = 0; if (!list.modified) list.modified = true; }; var watchedInsertInList = function(list, index, value) { insertInList(list, index, value); if (!list.modified) list.modified = true; }; var watchedSetLineOfList = function(list, index, value) { setLineOfList(list, index, value); if (!list.modified) list.modified = true; }; var mathFunc = function(f, x) { switch (f) { case 'abs': return Math.abs(x); case 'floor': return Math.floor(x); case 'sqrt': return Math.sqrt(x); case 'ceiling': return Math.ceil(x); case 'cos': return Math.cos(x * Math.PI / 180); case 'sin': return Math.sin(x * Math.PI / 180); case 'tan': return Math.tan(x * Math.PI / 180); case 'asin': return Math.asin(x) * 180 / Math.PI; case 'acos': return Math.acos(x) * 180 / Math.PI; case 'atan': return Math.atan(x) * 180 / Math.PI; case 'ln': return Math.log(x); case 'log': return Math.log(x) / Math.LN10; case 'e ^': return Math.exp(x); case '10 ^': return Math.exp(x * Math.LN10); } return 0; }; var attribute = function(attr, objName) { // https://github.com/LLK/scratch-vm/blob/e236d29ff5e03f7c4d77a614751da860521771fd/src/blocks/scratch3_sensing.js#L280 const o = self.getObject(objName); if (!o) return 0; if (P.core.isSprite(o)) { switch (attr) { case 'x position': return o.scratchX; case 'y position': return o.scratchY; case 'direction': return o.direction; case 'costume #': return o.currentCostumeIndex + 1; case 'costume name': return o.costumes[o.currentCostumeIndex].name; case 'size': return o.scale * 100; case 'volume': return o.volume * 100; } } else { switch (attr) { case 'background #': case 'backdrop #': return o.currentCostumeIndex + 1; case 'backdrop name': return o.costumes[o.currentCostumeIndex].name; case 'volume': return o.volume * 100; } } const value = o.vars[attr]; if (value !== undefined) { return value; } return 0; }; var timeAndDate = function(format: any): number { switch (format) { case 'year': return new Date().getFullYear(); case 'month': return new Date().getMonth() + 1; case 'date': return new Date().getDate(); case 'day of week': return new Date().getDay() + 1; case 'hour': return new Date().getHours(); case 'minute': return new Date().getMinutes(); case 'second': return new Date().getSeconds(); } return 0; } /** * Converts the name of a key to its code */ export function getKeyCode(keyName: any): string { keyName = keyName + ''; switch (keyName.toLowerCase()) { case 'space': return P.core.SpecialKeys.Space; case 'left arrow': return P.core.SpecialKeys.Left; case 'up arrow': return P.core.SpecialKeys.Up; case 'right arrow': return P.core.SpecialKeys.Right; case 'down arrow': return P.core.SpecialKeys.Down; case 'any': return 'any'; } return '' + keyName.toUpperCase().charCodeAt(0); } var getKeyCode3 = function(keyName: any): string { switch (keyName.toLowerCase()) { case 'space': return P.core.SpecialKeys.Space; case 'left arrow': return P.core.SpecialKeys.Left; case 'up arrow': return P.core.SpecialKeys.Up; case 'right arrow': return P.core.SpecialKeys.Right; case 'down arrow': return P.core.SpecialKeys.Down; // Scratch 3 added support for 'enter' case 'enter': return P.core.SpecialKeys.Enter; case 'any': return 'any'; } return '' + keyName.toUpperCase().charCodeAt(0); }; // Load audio methods if audio is supported const audioContext = P.audio.context; if (audioContext) { var playNote = function(key, duration) { var span; var spans = INSTRUMENTS[S.instrument]; for (var i = 0, l = spans.length; i < l; i++) { span = spans[i]; if (span.top >= key || span.top === 128) break; } return playSpan(span, key, duration); }; var playSpan = function(span, key, duration) { const node = P.audio.playSpan(span, key, duration, S.getAudioNode()); return { stopped: false, node, base: BASE, }; }; var applySoundEffects = function(node: AudioBufferSourceNode) { node.playbackRate.value = Math.pow(2, (S.soundFilters.pitch / 10 / 12)); }; var updateSoundEffectsOnAllSounds = function() { for (const sound of S.activeSounds) { if (sound.node) { applySoundEffects(sound.node as AudioBufferSourceNode); } } }; var playSound = function(sound: P.core.Sound): P.core.ActiveSound { const node = sound.createSourceNode(); applySoundEffects(node); node.connect(S.getAudioNode()); return { stopped: false, node, base: BASE, }; }; var startSound = function(sound: P.core.Sound) { // todo: this is a hack, won't work with clones // https://github.com/forkphorus/forkphorus/issues/298 for (const s of S.activeSounds) { if (s.node === sound.source) { s.stopped = true; break; } } const node = sound.createSourceNode(); applySoundEffects(node); node.connect(S.getAudioNode()); }; } var save = function() { STACK.push(R); R = {}; }; var restore = function() { R = STACK.pop(); }; var call = function(procedure: P.core.Procedure, id, values) { if (procedure) { STACK.push(R); CALLS.push(C); C = { base: procedure.fn, fn: S.fns[id], args: procedure.call(values), numargs: [], boolargs: [], stack: STACK = [], warp: procedure.warp, }; R = {}; if (C.warp || WARP) { WARP++; IMMEDIATE = procedure.fn; } else { if (VISUAL) { // Look through the call stack and determine if this procedure has already been called once. // If so, we'll delay this thread until the next iteration instead of setting IMMEDIATE // See https://scratch.mit.edu/projects/337681947/ for an example // 5 is an arbitrary number that works good enough and limits the possible performance impact for (var i = CALLS.length, j = 5; i-- && j--;) { if (CALLS[i].base === procedure.fn) { runtime.queue[THREAD] = { sprite: S, base: BASE, fn: procedure.fn, calls: CALLS, warp: WARP }; return; } } } IMMEDIATE = procedure.fn; } } else { IMMEDIATE = S.fns[id]; } }; var endCall = function() { if (CALLS.length) { if (WARP) WARP--; IMMEDIATE = C.fn; C = CALLS.pop(); STACK = C.stack; R = STACK.pop(); } }; var cloudVariableChanged = function(name) { if (self.cloudHandler) { self.cloudHandler.variableChanged(name); } }; var parseColor = function(color: any): number { return P.utils.parseColor(color); }; var sceneChange = function() { return runtime.trigger('whenSceneStarts', self.getCostumeName()); }; var broadcast = function(name) { return runtime.trigger('whenIReceive', name); }; var running = function(bases) { for (var j = 0; j < runtime.queue.length; j++) { if (runtime.queue[j] && bases.indexOf(runtime.queue[j]!.base) !== -1) return true; } return false; }; var queue = function(id) { if (WARP) { IMMEDIATE = S.fns[id]; } else { forceQueue(id); } }; var forceQueue = function(id) { runtime.queue[THREAD] = { sprite: S, base: BASE, fn: S.fns[id], calls: CALLS, warp: WARP }; }; type ThreadResume = any; interface ThreadCall { fn?: Fn; stack: ThreadResume[]; [s: string]: any; } interface Thread { sprite: P.core.Base; base: Fn; fn: Fn; calls: ThreadCall[]; warp: number; } export class Runtime { public queue: Array<Thread | undefined> = []; public isRunning: boolean = false; public timerStart: number = 0; public baseTime: number = 0; public baseNow: number = 0; public interval: number; public isTurbo: boolean = false; public framerate: number = 30; public currentMSecs: number = 0; public whenTimerMSecs: number = 0; constructor(public stage: P.core.Stage) { // Fix scoping this.onError = this.onError.bind(this); this.step = this.step.bind(this); } startThread(sprite: core.Base, base: Fn, replaceExisting: boolean) { const thread: Thread = { sprite: sprite, base: base, fn: base, calls: [{ args: [], stack: [{}], }], warp: 0 }; // Find if this spread is already being executed. for (let i = 0; i < this.queue.length; i++) { const q = this.queue[i]; if (q && q.sprite === sprite && q.base === base) { if (replaceExisting) { this.queue[i] = thread; } return; } } this.queue.push(thread); } /** * Triggers an event for a single sprite. */ triggerFor(sprite: P.core.Base, event: string, arg?: any): Fn[] { let threads: Fn[]; let replaceExisting = true; switch (event) { case 'whenClicked': threads = sprite.listeners.whenClicked; break; case 'whenCloned': threads = sprite.listeners.whenCloned; break; case 'whenGreenFlag': threads = sprite.listeners.whenGreenFlag; break; case 'whenKeyPressed': replaceExisting = false; threads = sprite.listeners.whenKeyPressed[arg] || []; if (arg !== 'any') { const anyThreads = sprite.listeners.whenKeyPressed.any; if (anyThreads) { threads = threads.concat(anyThreads); } } break; case 'whenSceneStarts': threads = sprite.listeners.whenSceneStarts[('' + arg).toLowerCase()]; break; case 'whenIReceive': arg = '' + arg; // TODO: remove toLowerCase() check? threads = sprite.listeners.whenIReceive[arg] || sprite.listeners.whenIReceive[arg.toLowerCase()]; break; case 'edgeActivated': threads = sprite.listeners.edgeActivated; break; default: throw new Error('Unknown trigger event: ' + event); } if (threads) { for (let i = 0; i < threads.length; i++) { this.startThread(sprite, threads[i], replaceExisting); } } return threads || []; } /** * Triggers an event on all sprites. */ trigger(event: string, arg?: any) { let threads: Fn[] = []; for (let i = this.stage.children.length; i--;) { threads = threads.concat(this.triggerFor(this.stage.children[i], event, arg)); } return threads.concat(this.triggerFor(this.stage, event, arg)); } /** * Trigger's the project's green flag. */ triggerGreenFlag() { this.timerStart = this.now(); this.trigger('whenGreenFlag'); this.trigger('edgeActivated'); } /** * Begins the runtime's event loop. * Does not start any scripts. */ start() { this.isRunning = true; if (this.interval) return; window.addEventListener('error', this.onError); this.baseTime = Date.now(); this.interval = setInterval(this.step, 1000 / this.framerate); if (audioContext) audioContext.resume(); this.stage.startExtensions(); } /** * Pauses the event loop */ pause() { if (this.interval) { this.baseNow = this.now(); clearInterval(this.interval); this.interval = 0; window.removeEventListener('error', this.onError); if (audioContext) audioContext.suspend(); this.stage.pauseExtensions(); } this.isRunning = false; } /** * Resets the interval loop without the effects of pausing/starting */ resetInterval() { if (!this.isRunning) { throw new Error('Cannot restart interval when paused'); } if (this.interval) { clearInterval(this.interval); } this.interval = setInterval(this.step, 1000 / this.framerate); } /** * Stops this runtime. * - stops all scripts * - removes all clones * - resets filters, speech bubbles, sounds * - Does *NOT* stop the event loop. Use pause() for that. */ stopAll() { this.stage.hidePrompt = false; this.stage.prompter.style.display = 'none'; this.stage.promptId = this.stage.nextPromptId = 0; this.queue.length = 0; this.stage.resetFilters(); this.stage.stopSounds(); for (var i = 0; i < this.stage.children.length; i++) { const c = this.stage.children[i]; if (c.isClone) { c.remove(); this.stage.children.splice(i, 1); i -= 1; } else { c.resetFilters(); if (c.saying && P.core.isSprite(c)) c.say(''); c.stopSounds(); } } } /** * The current time in the project */ now(): number { return this.baseNow + Date.now() - this.baseTime; } resetTimer() { this.timerStart = this.now(); this.whenTimerMSecs = 0; } evaluateExpression(sprite: P.core.Base, fn: () => any) { // We will load a few runtime values for this. // These are the values that are most commonly used in expressions, in addition the runtime methods. self = this.stage; runtime = this; S = sprite; try { return fn(); } catch (e) { return undefined; } } /** * Advances one frame into the future. */ step() { // Reset runtime variables self = this.stage; runtime = this; VISUAL = false; // TODO: instead of looping through all sprites, maintain a separate list of draggable sprites? for (var i = 0; i < this.stage.children.length; i++) { const c = this.stage.children[i]; if (c.isDragging) { c.moveTo(c.dragOffsetX + c.stage.mouseX, c.dragOffsetY + c.stage.mouseY); } } if (audioContext && audioContext.state === 'suspended') { audioContext.resume(); } const start = Date.now(); this.currentMSecs = this.whenTimerMSecs = this.now(); const queue = this.queue; do { for (THREAD = 0; THREAD < queue.length; THREAD++) { const thread = queue[THREAD]; if (thread) { // Load thread data S = thread.sprite; IMMEDIATE = thread.fn; BASE = thread.base; CALLS = thread.calls; C = CALLS.pop(); STACK = C.stack; R = STACK.pop(); queue[THREAD] = undefined; WARP = thread.warp; while (IMMEDIATE) { const fn = IMMEDIATE; IMMEDIATE = null; fn(); } STACK.push(R); CALLS.push(C); } } // Remove empty elements in the queue list for (let i = queue.length; i--;) { if (!queue[i]) { queue.splice(i, 1); } } } while ((this.isTurbo || !VISUAL) && Date.now() - start < 1000 / this.framerate && queue.length); this.stage.updateExtensions(); this.stage.draw(); } onError(e) { clearInterval(this.interval); this.handleError(e.error); } handleError(e) { // Default error handler console.error(e); } } export function createContinuation(source: string): P.runtime.Fn { // TODO: make understandable var result = '(function() {\n'; var brackets = 0; var delBrackets = 0; var shouldDelete = false; var here = 0; var length = source.length; while (here < length) { var i = source.indexOf('{', here); var j = source.indexOf('}', here); var k = source.indexOf('return;', here); if (k === -1) k = length; if (i === -1 && j === -1) { if (!shouldDelete) { result += source.slice(here, k); } break; } if (i === -1) i = length; if (j === -1) j = length; if (shouldDelete) { if (i < j) { delBrackets++; here = i + 1; } else { delBrackets--; if (!delBrackets) { shouldDelete = false; } here = j + 1; } } else { if (brackets === 0 && k < i && k < j) { result += source.slice(here, k); break; } if (i < j) { result += source.slice(here, i + 1); brackets++; here = i + 1; } else { result += source.slice(here, j); here = j + 1; if (source.substr(j, 8) === '} else {') { if (brackets > 0) { result += '} else {'; here = j + 8; } else { shouldDelete = true; delBrackets = 0; } } else { if (brackets > 0) { result += '}'; brackets--; } } } } } result += '})'; return scopedEval(result); } // Evaluate JavaScript within the scope of the runtime. export function scopedEval(source: string): any { return eval(source); } }
the_stack
import { ParametricSelector, Selector } from "reselect" import { cnst } from "../../Data/Function" import { notNullStrUndef } from "../../Data/List" import { fromJust, INTERNAL_shallowEquals, isMaybe, isNothing, Just, Maybe, Nothing, Some } from "../../Data/Maybe" import { fromMap, lookup, OrderedMap, toMap } from "../../Data/OrderedMap" const maybeEquals = (x: any, y: any) => isMaybe (x) && isMaybe (y) ? INTERNAL_shallowEquals (x) (y) : x === y /** * ```haskell * createMapSelector :: ((s, p) -> Map String v) * -> (...(String -> (s, p) -> ...(Just a))) * -> (...((s, p) -> ...b)) * -> (...((v, p) -> ...c)) * -> (...a -> ...b -> ...c -> r) * -> String * -> (s, p) * -> Maybe r * ``` * * `createMapSelector mapSelector (...global) (...map_value) f key` creates a * special selector for Redux that is based on an `OrderedMap`. The special * thing is that it caches the selector results based on the `key` in the map * that is returned from applying the `mapSelector` function to the passed * state. So it's basically a Reselect selector for all keys in the map * together. You can set `global` selector, that access the whole app state, as * well as `map_value` selectors, that access the value at the current key. `f` * takes all selector results and produces a value that is returned and also * cached for the current `key`. */ export const createMapMaybeSelectorDebug = (debug_origin?: string) => <S, P1, V extends Some> (mapSelector: PSelector<S, P1, OrderedMap<string, V>>) => <K extends PSelectorWithKey<S, any, any>[]> (...globalSelectorsWithKey: K) => <G extends PSelector<S, any, any>[]> (...globalSelectors: G) => <M extends PSelector<V, any, any>[]> (...valueSelectors: M) => <R extends Some, P extends CombineProps<P1, K, G, M> = CombineProps<P1, K, G, M>> (fold: Callback<S, V, K, G, M, R>): CreatedParametricSelector<S, P, R> => { const debug = notNullStrUndef (debug_origin) if (debug) { console.log (`createMapMaybeSelector: "${debug_origin}"`) } let prevState: S | undefined = undefined // let prevMap: OrderedMap<string, V> | undefined const prevValues: Map<string, V> = new Map () const keyMap: Map< string, [MappedReturnType<MappedReturnType<K>>, MappedReturnType<G>, MappedReturnType<M>] > = new Map () let resMap: Map<string, R> = new Map () const justResMap: Map<string, Just<R>> = new Map () const g = (key_str: string) => (state: S, props: P): Maybe<R> => { let res = resMap .get (key_str) let mres = justResMap .get (key_str) if (state === prevState && mres !== undefined) { if (debug) { console.log ("createMapMaybeSelector: equal state, no recalc") } return mres } // const mkey_str = normalize (typeof key === "function" ? key (state) : key) // if (isNothing (mkey_str)) { // return Nothing // } // const key_str = fromJust (mkey_str) const map = mapSelector (state, props) const mvalue = lookup (key_str) (map) if (isNothing (mvalue)) { if (debug) { console.log ("createMapMaybeSelector: no value available") } return Nothing } const value = fromJust (mvalue) const newGlobalValuesWithKeyMaybe = globalSelectorsWithKey .map (s => s (key_str) (state, props)) as MappedReturnType<MappedReturnType<K>> if (newGlobalValuesWithKeyMaybe .some (isNothing)) { return Nothing } const newGlobalValuesWithKey = newGlobalValuesWithKeyMaybe .map (fromJust) as MappedMaybeI<MappedReturnType<MappedReturnType<K>>> const newGlobalValues = globalSelectors .map (s => s (state, props)) as MappedReturnType<G> const prevGlobalKeyAndGlobalValues = keyMap .get (key_str) const prevMapValue = prevValues .get (key_str) if ( mres !== undefined && ( (state === prevState && keyMap .has (key_str)) || ( maybeEquals (value, prevMapValue) && prevGlobalKeyAndGlobalValues !== undefined && (newGlobalValuesWithKeyMaybe as any[]) .every ((x, i) => INTERNAL_shallowEquals (x) (prevGlobalKeyAndGlobalValues [0] [i])) && (newGlobalValues as any[]) .every ((x, i) => x === prevGlobalKeyAndGlobalValues [1] [i]) ) )) { if (debug) { console.log (state === prevState && keyMap .has (key_str)) if (prevGlobalKeyAndGlobalValues !== undefined) { console.log ((newGlobalValues as any[]) .every ((x, i) => x === prevGlobalKeyAndGlobalValues [1] [i])) } console.log ( "new filterText = ", newGlobalValues [0] ) console.log ( "prev filterText = ", prevGlobalKeyAndGlobalValues === undefined ? undefined : prevGlobalKeyAndGlobalValues [1] [0] ) console.log ("createMapMaybeSelector: equal substate, no recalc") } return mres } if (debug) { console.log ("createMapMaybeSelector: recalc") } const newMapValueValues = valueSelectors .map (s => s (value, props)) as MappedReturnType<M> // prevMap = map prevValues .set (key_str, value) keyMap .set (key_str, [ newGlobalValuesWithKeyMaybe, newGlobalValues, newMapValueValues ]) res = fold (...newGlobalValuesWithKey as any) (...newGlobalValues as any) (...newMapValueValues as any) mres = Just (res) resMap .set (key_str, res) justResMap .set (key_str, mres) prevState = state return mres } g.getCacheAt = (key_str: string): Maybe<R> => Maybe (resMap .get (key_str)) g.setCacheAt = (key_str: string) => (x: R) => { resMap .set (key_str, x) justResMap .set (key_str, Just (x)) } g.getCache = () => fromMap (resMap) g.setCache = (m: OrderedMap<string, R>) => { resMap = toMap (m) as Map<string, R> resMap .forEach ((v, k) => justResMap .set (k, Just (v))) } // g.setBaseMap = (m: OrderedMap<string, V>) => { prevMap = m } g.setState = (s: S) => { prevState = s } return g } export const createMapMaybeSelector = createMapMaybeSelectorDebug () /** * ```haskell * createMapSelector :: (s -> Map String v) * -> (...(s -> ...a)) * -> (...(v -> ...b)) * -> (...a -> ...b -> r) * -> String * -> s * -> Maybe r * ``` * * `createMapSelector mapSelector (...global) (...map_value) f key` creates a * special selector for Redux that is based on an `OrderedMap`. The special * thing is that it caches the selector results based on the `key` in the map * that is returned from applying the `mapSelector` function to the passed * state. So it's basically a Reselect selector for all keys in the map * together. You can set `global` selector, that access the whole app state, as * well as `map_value` selectors, that access the value at the current key. `f` * takes all selector results and produces a value that is returned and also * cached for the current `key`. */ export const createMapMaybeSelectorS = <S, V extends Some> (mapSelector: Selector<S, OrderedMap<string, V>>) => <G extends Selector<S, any>[]> (...globalSelectors: G) => <M extends Selector<V, any>[]> (...valueSelectors: M) => <R extends Some> (fold: CallbackWithoutKeys<S, V, G, M, R>): CreatedSelector<S, R> => createMapMaybeSelector (mapSelector) () (...globalSelectors) (...valueSelectors) (cnst (fold)) as CreatedSelector<S, R> /** * ```haskell * createMapSelector :: ((s, p) -> Map String v) * -> (...((s, p) -> ...a)) * -> (...((v, p) -> ...b)) * -> (...a -> ...b -> r) * -> String * -> (s, p) * -> Maybe r * ``` * * `createMapSelector mapSelector (...global) (...map_value) f key` creates a * special selector for Redux that is based on an `OrderedMap`. The special * thing is that it caches the selector results based on the `key` in the map * that is returned from applying the `mapSelector` function to the passed * state. So it's basically a Reselect selector for all keys in the map * together. You can set `global` selector, that access the whole app state, as * well as `map_value` selectors, that access the value at the current key. `f` * takes all selector results and produces a value that is returned and also * cached for the current `key`. */ export const createMapMaybeSelectorSWithProps = <S, P1, V extends Some> (mapSelector: PSelector<S, P1, OrderedMap<string, V>>) => <G extends PSelector<S, any, any>[]> (...globalSelectors: G) => <M extends PSelector<V, any, any>[]> (...valueSelectors: M) => <R extends Some, P extends P1 & Props<G> & Props<M> = P1 & Props<G> & Props<M>> (fold: CallbackWithoutKeys<S, V, G, M, R>): CreatedParametricSelector<S, P, R> => createMapMaybeSelector (mapSelector) () (...globalSelectors) (...valueSelectors) (cnst (fold)) // Type inference test: // // const test = createMapSelector (() => OrderedMap.fromUniquePairs<string, { value: number }>()) // (() => 2, () => "string") // (() => [2], () => [true]) // ((test, test2) => (arr1, arr2) => ["test"]) // @ts-ignore type MappedReturnType<A extends ((...args: any[]) => any)[]> = { [K in keyof A]: ReturnType<A[K]> } type MappedMaybeI<A extends Maybe<Some>[]> = { [K in keyof A]: A[K] extends Maybe<infer AI> ? AI : never } type Props<S> = S extends ParametricSelector<any, infer I, any>[] ? I : never type CombineProps< M, K extends PSelectorWithKey<any, any, any>[], G extends PSelector<any, any, any>[], V extends PSelector<any, any, any>[] > = M & Props<MappedReturnType<K>> & Props<G> & Props<V> type Callback < S, V, K extends PSelectorWithKey<S, any, any>[], G extends PSelector<S, any, any>[], M extends PSelector<V, any, any>[], R > = (...globalValuesWithKey: MappedMaybeI<MappedReturnType<MappedReturnType<K>>>) => (...globalValues: MappedReturnType<G>) => (...mapValueValues: MappedReturnType<M>) => R type CallbackWithoutKeys < S, V, G extends PSelector<S, any, any>[], M extends PSelector<V, any, any>[], R > = (...globalValues: MappedReturnType<G>) => (...mapValueValues: MappedReturnType<M>) => R interface Cache<S, R> { getCacheAt (key_str: string): Maybe<R> setCacheAt (key_str: string): (x: R) => void getCache (): OrderedMap<string, R> setCache (m: OrderedMap<string, R>): void // setBaseMap (m: OrderedMap<string, V>): void setState (s: S): void } interface CreatedSelector<S, R> extends Cache<S, R> { (key_str: string): (state: S) => Maybe<R> } interface CreatedParametricSelector<S, P, R> extends Cache<S, R> { (key_str: string): (state: S, props: P) => Maybe<R> } type PSelector<S, P, R> = ParametricSelector<S, P, R> export type PSelectorWithKey<S, P, R> = (key_str: string) => ParametricSelector<S, P, R>
the_stack
import axios from 'axios'; import throat from 'throat'; import { Account } from '../account'; import { GraphManager } from '../graphManager'; import { Organization } from '../organization'; import { GitHubTokenManager } from '../../github/tokenManager'; import RenderHtmlMail from '../../lib/emailRender'; import { wrapError, sortByCaseInsensitive } from '../../utils'; import { Repository } from '../repository'; import { RestLibrary } from '../../lib/github'; import { AllAvailableAppPurposes, AppPurpose, AppPurposeToConfigurationName, GitHubAppAuthenticationType, IGitHubAppConfiguration } from '../../github'; import { OrganizationSetting } from '../../entities/organizationSettings/organizationSetting'; import { OrganizationSettingProvider } from '../../entities/organizationSettings/organizationSettingProvider'; import { IMail } from '../../lib/mailProvider'; import { ILinkProvider } from '../../lib/linkProviders'; import { ICacheHelper } from '../../lib/caching'; import { createPortalSudoInstance, IPortalSudo } from '../../features'; import { IOperationsCoreOptions, OperationsCore } from './core'; import { linkAccounts as linkAccountsMethod } from './link'; import { sendTerminatedAccountMail as sendTerminatedAccountMailMethod } from './unlinkMail'; import { CoreCapability, ICachedEmployeeInformation, ICacheOptions, ICorporateLink, ICreatedLinkOutcome, ICreateLinkOptions, ICrossOrganizationMembershipByOrganization, ICrossOrganizationTeamMembership, IGetAuthorizationHeader, IMapPlusMetaCost, IOperationsCentralOperationsToken, IOperationsHierarchy, IOperationsLegalEntities, IOperationsLinks, IOperationsLockdownFeatureFlags, IOperationsNotifications, IOperationsRepositoryMetadataProvider, IOperationsServiceAccounts, IOperationsTemplates, IPagedCrossOrganizationCacheOptions, IPromisedLinks, IPurposefulGetAuthorizationHeader, ISupportedLinkTypeOutcome, IUnlinkMailStatus, SupportedLinkType, UnlinkPurpose } from '../../interfaces'; import { CreateError, ErrorHelper } from '../../transitional'; import { Team } from '../team'; import { IRepositoryMetadataProvider } from '../../entities/repositoryMetadata/repositoryMetadataProvider'; import { isAuthorizedSystemAdministrator } from './administration'; export * from './core'; const throwIfOrganizationIdsMissing = true; const SecondsBetweenOrganizationSettingUpdatesCheck = 60 * 2; // every 2 minutes, check for dynamic app updates let DynamicRestartCheckHandle = null; const ParallelLinkLookup = 4; export const RedisPrefixManagerInfoCache = 'employeewithmanager:'; const defaultGitHubPageSize = 100; export interface ICrossOrganizationMembersResult extends Map<number, ICrossOrganizationMembershipByOrganization> { } export interface IOperationsOptions extends IOperationsCoreOptions { // cacheProvider: ICacheHelper; // config: any; github: RestLibrary; // insights: TelemetryClient; // linkProvider: ILinkProvider; // mailAddressProvider: IMailAddressProvider; // mailProvider: IMailProvider; repositoryMetadataProvider: IRepositoryMetadataProvider; } export class Operations extends OperationsCore implements IOperationsLegalEntities, IOperationsServiceAccounts, IOperationsTemplates, IOperationsLinks, IOperationsNotifications, IOperationsHierarchy, IOperationsCentralOperationsToken, IOperationsRepositoryMetadataProvider, IOperationsLockdownFeatureFlags { private _cache: ICacheHelper; private _graphManager: GraphManager; private _organizationNames: string[]; private _organizations: Map<string, Organization>; private _uncontrolledOrganizations: Map<string, Organization>; private _organizationOriginalNames: any; private _organizationNamesWithAuthorizationHeaders: Map<string, IPurposefulGetAuthorizationHeader>; private _defaultPageSize: number; private _organizationIds: Map<number, Organization>; private _dynamicOrganizationSettings: OrganizationSetting[]; private _dynamicOrganizationIds: Set<number>; private _portalSudo: IPortalSudo; private _tokenManager: GitHubTokenManager; private _repositoryMetadataProvider: IRepositoryMetadataProvider; get graphManager(): GraphManager { return this._graphManager; } get defaultPageSize(): number { return this._defaultPageSize; } constructor(options: IOperationsOptions) { super(options); this.addCapability(CoreCapability.Providers); this.addCapability(CoreCapability.LegalEntities); this.addCapability(CoreCapability.ServiceAccounts); this.addCapability(CoreCapability.Templates); this.addCapability(CoreCapability.Links); this.addCapability(CoreCapability.LockdownFeatureFlags); this.addCapability(CoreCapability.GitHubCentralOperations); this.addCapability(CoreCapability.RepositoryMetadataProvider); this.addCapability(CoreCapability.Hiearchy); this.addCapability(CoreCapability.Notifications); const providers = options.providers; const config = providers.config; this._cache = providers.cacheProvider; this._graphManager = new GraphManager(this); if (!options.repositoryMetadataProvider) { throw new Error('repositoryMetadataProvider required'); } this._repositoryMetadataProvider = options.repositoryMetadataProvider; this._uncontrolledOrganizations = new Map(); this._defaultPageSize = this.config && this.config.github && this.config.github.api && this.config.github.api.defaultPageSize ? this.config.github.api.defaultPageSize : defaultGitHubPageSize; const hasModernGitHubApps = config.github?.app; const purposesToConfigurations = new Map<AppPurpose, IGitHubAppConfiguration>(); if (hasModernGitHubApps) { for (let purpose of AllAvailableAppPurposes) { const configKey = AppPurposeToConfigurationName[purpose]; const configValue = config.github.app[configKey]; if (configValue) { purposesToConfigurations.set(purpose, configValue); } } } this._tokenManager = new GitHubTokenManager({ configurations: purposesToConfigurations, app: this.providers.app, }); this._dynamicOrganizationIds = new Set(); this._dynamicOrganizationSettings = []; } protected get tokenManager() { return this._tokenManager; } get repositoryMetadataProvider() { return this._repositoryMetadataProvider; } async initialize() { await super.initialize(); const hasModernGitHubApps = this.config.github && this.config.github.app; // const hasConfiguredOrganizations = this.config.github.organizations && this.config.github.organizations.length; const organizationSettingsProvider = this.providers.organizationSettingsProvider; if (hasModernGitHubApps && organizationSettingsProvider) { const dynamicOrganizations = (await organizationSettingsProvider.queryAllOrganizations()).filter(dynamicOrg => dynamicOrg.active === true && !dynamicOrg.hasFeature('ignore')); this._dynamicOrganizationSettings = dynamicOrganizations; this._dynamicOrganizationIds = new Set(dynamicOrganizations.map(org => Number(org.organizationId))); } if (this._dynamicOrganizationSettings && organizationSettingsProvider) { DynamicRestartCheckHandle = setInterval(restartAfterDynamicConfigurationUpdate.bind(null, 10, 120, this.initialized, organizationSettingsProvider), 1000 * SecondsBetweenOrganizationSettingUpdatesCheck); } if (throwIfOrganizationIdsMissing) { this.getOrganizationIds(); } this._portalSudo = createPortalSudoInstance(this.providers); return this; } get previewMediaTypes() { return { repository: { // this will allow GitHub Enterprise Cloud "visibility" fields to appear getDetails: 'nebula-preview', list: 'nebula-preview', }, }; } get organizationNames(): string[] { if (!this._organizationNames) { const names = []; const processed = new Set<string>(); for (const dynamic of this._dynamicOrganizationSettings) { const lowercase = dynamic.organizationName.toLowerCase(); processed.add(lowercase); names.push(lowercase); } for (let i = 0; i < this.config.github.organizations.length; i++) { const lowercase = this.config.github.organizations[i].name.toLowerCase(); if (!processed.has(lowercase)) { names.push(lowercase); processed.add(lowercase); } } this._organizationNames = names.sort(sortByCaseInsensitive); } return this._organizationNames; } getOrganizationIds(): number[] { if (!this._organizationIds) { const organizations = this.organizations; this._organizationIds = new Map(); this._dynamicOrganizationSettings.map(entry => { if (entry.active) { const org = this.getOrganization(entry.organizationName.toLowerCase()); this._organizationIds.set(Number(entry.organizationId), org); } }); // This check only runs on _static_ configuration entries, since adopted // GitHub App organizations must always have an organization ID. for (let i = 0; i < this.config.github.organizations.length; i++) { const organizationConfiguration = this.config.github.organizations[i]; const organization = organizations.get(organizationConfiguration.name.toLowerCase()); if (!organization) { throw new Error(`Missing organization configuration ${organizationConfiguration.name}`); } if (!organizationConfiguration.id) { if (throwIfOrganizationIdsMissing) { throw new Error(`Organization ${organization.name} is not configured with an 'id' which can lead to issues if the organization is renamed. throwIfOrganizationIdsMissing is true: id is required`); } else { console.warn(`Organization ${organization.name} is not configured with an 'id' which can lead to issues if the organization is renamed.`); } } else if (!this._organizationIds.has(organizationConfiguration.id)) { this._organizationIds.set(organizationConfiguration.id, organization); } } } return Array.from(this._organizationIds.keys()); } private createOrganization(name: string, settings: OrganizationSetting, centralOperationsFallbackToken: string, appAuthenticationType: GitHubAppAuthenticationType): Organization { name = name.toLowerCase(); let ownerToken = null; if (!settings) { let staticSettings = null; const group = this.config.github.organizations; for (let i = 0; i < group.length; i++) { if (group[i].name && group[i].name.toLowerCase() === name) { const staticOrganizationSettings = group[i]; if (staticOrganizationSettings.ownerToken) { ownerToken = staticOrganizationSettings.ownerToken; } staticSettings = staticOrganizationSettings; break; } } try { settings = OrganizationSetting.CreateFromStaticSettings(staticSettings); settings.active = true; } catch (translateStaticSettingsError) { throw new Error(`This application is not able to translate the static configuration for the ${name} organization. Specific error: ${translateStaticSettingsError.message}`); } } if (!settings) { throw new Error(`This application is not configured for the ${name} organization`); } const hasDynamicSettings = this._dynamicOrganizationIds && settings.organizationId && this._dynamicOrganizationIds.has(Number(settings.organizationId)); return new Organization(this, name, settings, this.getAuthorizationHeader.bind(this, name, settings, ownerToken, centralOperationsFallbackToken, appAuthenticationType), this.getAuthorizationHeader.bind(this, name, settings, ownerToken, centralOperationsFallbackToken, GitHubAppAuthenticationType.ForceSpecificInstallation), hasDynamicSettings); } get organizations() { if (!this._organizations) { const organizations = new Map<string, Organization>(); const names = this.organizationNames; const centralOperationsToken = this.config.github.operations.centralOperationsToken; for (let i = 0; i < names.length; i++) { const name = names[i]; let dynamicSettings: OrganizationSetting = null; this._dynamicOrganizationSettings.map(dos => { if (dos.active && dos.organizationName.toLowerCase() === name.toLowerCase()) { dynamicSettings = dos; } }); const organization = this.createOrganization(name, dynamicSettings, centralOperationsToken, GitHubAppAuthenticationType.BestAvailable); organizations.set(name, organization); } this._organizations = organizations; } return this._organizations; } private getAlternateOrganization(name: string, alternativeType) { // An 'alternate' organization is one whose static settings come from a // different location within the github.organizations config file. const lowercase = name.toLowerCase(); const list = this.config.github.organizations[alternativeType]; if (list) { for (let i = 0; i < list.length; i++) { const settings = list[i]; if (settings && settings.name && settings.name.toLowerCase() === lowercase) { const centralOperationsToken = this.config.github.operations.centralOperationsToken; return this.createOrganization(lowercase, settings, centralOperationsToken, GitHubAppAuthenticationType.BestAvailable); } } } } getOnboardingOrganization(name: string) { // Specialized method to retrieve a new organization via the onboarding configuration collection, if any const value = this.getAlternateOrganization(name, 'onboarding'); if (value) { return value; } throw new Error(`No onboarding organization settings configured for the ${name} organization`); } getUnconfiguredOrganization(settings: OrganizationSetting): Organization { return this.createOrganization(settings.organizationName.toLowerCase(), settings, null, GitHubAppAuthenticationType.BestAvailable); } getUncontrolledOrganization(organizationName: string, organizationId?: number): Organization { organizationName = organizationName.toLowerCase(); const officialOrganization = this.organizations.get(organizationName); if (officialOrganization) { return officialOrganization; } if (this._uncontrolledOrganizations.has(organizationName)) { return this._uncontrolledOrganizations.get(organizationName); } const emptySettings = new OrganizationSetting(); emptySettings.operationsNotes = `Uncontrolled Organization - ${organizationName}`; const centralOperationsToken = this.config.github.operations.centralOperationsToken; const org = this.createOrganization(organizationName, emptySettings, centralOperationsToken, GitHubAppAuthenticationType.ForceSpecificInstallation); this._uncontrolledOrganizations.set(organizationName, org); org.uncontrolled = true; return org; } getPublicOnlyAccessOrganization(organizationName: string, organizationId?: number): Organization { organizationName = organizationName.toLowerCase(); const emptySettings = new OrganizationSetting(); emptySettings.operationsNotes = `Uncontrolled public organization - ${organizationName}`; const publicAccessToken = this.config.github.operations.publicAccessToken; if (!publicAccessToken) { throw new Error('not configured for public read-only tokens'); } const org = this.createOrganization(organizationName, emptySettings, publicAccessToken, GitHubAppAuthenticationType.ForceSpecificInstallation); this._uncontrolledOrganizations.set(organizationName, org); org.uncontrolled = true; return org; } isIgnoredOrganization(name: string): boolean { const value = this.getAlternateOrganization(name, 'onboarding') || this.getAlternateOrganization(name, 'ignore'); return !!value; } isManagedOrganization(name: string) { try { this.getOrganization(name.toLowerCase()); return true; } catch (unmanaged) { return this.isIgnoredOrganization(name); } } getOrganizations(organizationList?: string[]): Organization[] { if (!organizationList) { return Array.from(this.organizations.values()); } const references = []; organizationList.forEach(orgName => { const organization = this.getOrganization(orgName); references.push(organization); }); return references; } getPrimaryOrganizationName(): string { const id = this.config.github && this.config.github.operations && this.config.github.operations.primaryOrganizationId ? this.config.github.operations.primaryOrganizationId : null; if (id) { return this.getOrganizationById(Number(id)).name; } return this.getOrganizationOriginalNames()[0]; } getOrganizationOriginalNames(): string[] { if (!this._organizationOriginalNames) { const names: string[] = []; const visited = new Set<string>(); for (const entry of this._dynamicOrganizationSettings) { if (entry.active) { names.push(entry.organizationName); const lowercase = entry.organizationName.toLowerCase(); visited.add(lowercase); } } for (let i = 0; i < this.config.github.organizations.length; i++) { const original = this.config.github.organizations[i].name; const lowercase = original.toLowerCase(); if (!visited.has(lowercase)) { names.push(original); visited.add(lowercase); } } this._organizationOriginalNames = names.sort(sortByCaseInsensitive); } return this._organizationOriginalNames; } translateOrganizationNamesFromLowercase(object) { const orgs = this.getOrganizationOriginalNames(); orgs.forEach(name => { const lc = name.toLowerCase(); if (name !== lc && object[lc] !== undefined) { object[name] = object[lc]; delete object[lc]; } }); return object; } get organizationNamesWithAuthorizationHeaders() { if (!this._organizationNamesWithAuthorizationHeaders) { const tokens = new Map<string, IPurposefulGetAuthorizationHeader>(); const visited = new Set<string>(); for (const entry of this._dynamicOrganizationSettings) { const lowercase = entry.organizationName.toLowerCase(); if (entry.active && !visited.has(lowercase)) { visited.add(lowercase); const orgInstance = this.getOrganization(lowercase); const token = orgInstance.getAuthorizationHeader(); tokens.set(lowercase, token); } } for (let i = 0; i < this.config.github.organizations.length; i++) { const name = this.config.github.organizations[i].name.toLowerCase(); if (visited.has(name)) { continue; } visited.add(name); const orgInstance = this.getOrganization(name); const token = orgInstance.getAuthorizationHeader(); tokens.set(name, token); } this._organizationNamesWithAuthorizationHeaders = tokens; } return this._organizationNamesWithAuthorizationHeaders; } async getCachedEmployeeManagementInformation(corporateId: string): Promise<ICachedEmployeeInformation> { const key = `${RedisPrefixManagerInfoCache}${corporateId}`; const currentManagerIfAny = await this._cache.getObjectCompressed(key); return currentManagerIfAny as ICachedEmployeeInformation; } linkAccounts(options: ICreateLinkOptions): Promise<ICreatedLinkOutcome> { return linkAccountsMethod(this, options); } async validateCorporateAccountCanLink(corporateId: string): Promise<ISupportedLinkTypeOutcome> { const { graphProvider } = this.providers; const graphEntry = await graphProvider.getUserAndManagerById(corporateId); // NOTE: This assumption, that a user without a manager must be a Service Account, // is a bit of a hack. It means that the CEO will be flagged as a service account if // they find the time to use this app. This code prioritizes the more common scenario, // that a user without an assigned manager in the directory is a Service Account. if (graphEntry && !graphEntry.manager) { return { type: SupportedLinkType.ServiceAccount, graphEntry }; } return { type: SupportedLinkType.User, graphEntry }; } async terminateLinkAndMemberships(thirdPartyId, options?: any): Promise<string[]> { const insights = this.insights; options = options || {}; let history: string[] = []; const continueOnError = options.continueOnError || false; let errors = 0; const account: Account = this.getAccount(thirdPartyId); const reason = options.reason || 'Automated processPendingUnlink operation'; const purpose = options.purpose as UnlinkPurpose || UnlinkPurpose.Unknown; try { // Uses an ID-based lookup on GitHub in case the user was renamed. // Also retrieves the link into memory in the account instance. await account.getDetailsAndDirectLink(); } catch (noDirectDetails) { ++errors; insights?.trackException({ exception: noDirectDetails }); // not a fatal error in this method however history.push(noDirectDetails.toString()); } insights?.trackEvent({ name: 'UserUnlinkStart', properties: { id: account.id, login: account.login, reason: reason, purpose, continueOnError: continueOnError ? 'continue on errors' : 'halt on errors', }, }); // GitHub memberships try { const removal = await account.removeManagedOrganizationMemberships(); history.push(...removal.history); if (removal.error) { throw removal.error; // unclear if this is actually ideal } } catch (removeOrganizationsError) { ++errors; // If a removal error occurs, do not remove the link and throw and error // so that the link data and information is still present until the issue // can be cleared insights?.trackException({ exception: removeOrganizationsError }); if (!continueOnError) { throw removeOrganizationsError; } history.push(`Organization removal error: ${removeOrganizationsError.toString()}`); } // Link try { if (account.link) { history.push(... await account.removeLink()); } } catch (removeLinkError) { ++errors; insights?.trackException({ exception: removeLinkError }); if (account.id && !account.login) { // If the account information could not be resolved through the // GitHub API for this _id_, then the user deleted their account, // or is using a different one now, etc., so try deleting the // associated link still by searching for it by _ID_. // TODO: Ported code from account.ts, remains unimp. It's OK. } if (!continueOnError) { throw removeLinkError; } history.push(`Unlink error: ${removeLinkError.toString()}`); } // Collaborator permissions to repositories try { const removed = await account.removeCollaboratorPermissions(); history.push(...removed.history); if (removed.error) { throw removed.error; } } catch (removeCollaboratorsError) { ++errors; insights?.trackException({ exception: removeCollaboratorsError }); if (account.id && !account.login) { // If the account information could not be resolved through the // GitHub API for this _id_, then the user deleted their account, // or is using a different one now, etc., so try deleting the // associated link still by searching for it by _ID_. // TODO: Ported code from account.ts, remains unimp. It's OK. } if (!continueOnError) { throw removeCollaboratorsError; } history.push(`Collaborator remove error: ${removeCollaboratorsError.toString()}`); } // Notify try { const status = await this.sendTerminatedAccountMail(account, purpose, history, errors); if (status) { history.push(`Unlink e-mail sent to manager: to=${status.to.join(', ')} bcc=${status.bcc.join(', ')}, receipt=${status.receipt}`); } else { history.push('Service not configured to notify by mail'); } } catch (notifyTerminationMailError) { insights?.trackException({ exception: notifyTerminationMailError }); // Notification should never throw history.push('Unlink e-mail COULD NOT be sent to manager'); } // Telemetry insights?.trackEvent({ name: 'UserUnlink', properties: { id: account.id, login: account.login, reason: reason, purpose, continueOnError: continueOnError ? 'continue on errors' : 'halt on errors', history: JSON.stringify(history), }, }); return history; } getOperationsMailAddress(): string { return this.config.brand.operationsMail; } getInfrastructureNotificationsMail(): string { return this.config.notifications.infrastructureNotificationsMail || this.getOperationsMailAddress(); } getLinksNotificationMailAddress(): string { return this.config.notifications.linksMailAddress || this.getOperationsMailAddress(); } getRepositoriesNotificationMailAddress(): string { return this.config.notifications.reposMailAddress || this.getOperationsMailAddress(); } private sendTerminatedAccountMail(account: Account, purpose: UnlinkPurpose, details: string[], errorsCount: number): Promise<IUnlinkMailStatus> { return sendTerminatedAccountMailMethod(this, account, purpose, details, errorsCount); } getDefaultRepositoryTemplateNames(): string[] { if (this.config.github && this.config.github.templates && this.config.github.templates.defaultTemplates && this.config.github.templates.defaultTemplates.length > 0) { return this.config.github.templates.defaultTemplates as string[]; } return null; } getDefaultLegalEntities(): string[] { if (this.config.legalEntities && this.config.legalEntities.defaultOrganizationEntities && this.config.legalEntities.defaultOrganizationEntities.length > 0) { return this.config.legalEntities.defaultOrganizationEntities as string[]; } return null; } getOrganization(name: string): Organization { if (!name) { throw CreateError.ParameterRequired('name'); } const lc = name.toLowerCase(); const organization = this.organizations.get(lc); if (!organization) { throw CreateError.NotFound(`Could not find configuration for the "${name}" organization.`); } return organization; } isOrganizationManagedById(organizationId: number): boolean { try { this.getOrganizationById(organizationId); return true; } catch (notConfigured) { return false; } } getOrganizationById(organizationId: number): Organization { if (typeof (organizationId) === 'string') { organizationId = parseInt(organizationId, 10); console.warn(`getOrganizationById: organizationId must be a number`); } if (!this._organizationIds) { this.getOrganizationIds(); } const org = this._organizationIds.get(organizationId); if (!org) { throw CreateError.NotFound(`getOrganizationById: no configured ID for an organization with ID ${organizationId}`); } return org; } async getRepos(options?: ICacheOptions): Promise<Repository[]> { const repos: Repository[] = []; const cacheOptions = options || { maxAgeSeconds: this.defaults.crossOrgsReposStaleSecondsPerOrg, }; // CONSIDER: Cross-org functionality might be best in the GitHub library itself const orgs = this.organizations.values(); for (let organization of orgs) { try { const organizationRepos = await organization.getRepositories(cacheOptions); repos.push(...organizationRepos); } catch (orgReposError) { console.dir(orgReposError); } } return repos; } getLinks(options?: any): Promise<ICorporateLink[]> { // Design change in the TypeScript version: this returns true link objects now, // but caches hydrated links behind the scenes options = options || { includeNames: true, includeId: true, includeServiceAccounts: true, }; const caching = { maxAgeSeconds: options.maxAgeSeconds || this.defaults.corporateLinksStaleSeconds, backgroundRefresh: true, }; delete options.maxAgeSeconds; delete options.backgroundRefresh; const linkProvider = this.providers.linkProvider; options.lp = linkProvider.serializationIdentifierVersion; return new Promise((resolve, reject) => { return this.github.links.getCachedLinks( getPromisedLinks.bind(null, linkProvider), options, caching, (ee, ll) => { let rehydratedLinks = null; if (!ee) { try { rehydratedLinks = linkProvider.rehydrateLinks(ll); } catch (rehydrationError) { ee = rehydrationError; } } if (ee) { return reject(ee); } return resolve(rehydratedLinks); }); }); } async getLinksMapFromThirdPartyIds(thirdPartyIds: string[]): Promise<Map<number, ICorporateLink>> { const map = new Map<number, ICorporateLink>(); if (thirdPartyIds.length === 0) { return map; } const group = await this.getLinksFromThirdPartyIds(thirdPartyIds); for (let link of group) { if (link && link.thirdPartyId) { map.set(Number(link.thirdPartyId), link); } } return map; } async getLinksFromThirdPartyIds(thirdPartyIds: string[]): Promise<ICorporateLink[]> { const corporateLinks: ICorporateLink[] = []; const throttle = throat(ParallelLinkLookup); await Promise.all(thirdPartyIds.map(thirdPartyId => throttle(async () => { try { const link = await this.getLinkByThirdPartyId(thirdPartyId); if (link) { corporateLinks.push(link); } } catch (noLinkError) { if (!ErrorHelper.IsNotFound(noLinkError)) { console.dir(noLinkError); } } }))); return corporateLinks; } async getLinksFromCorporateIds(corporateIds: string[]): Promise<ICorporateLink[]> { const corporateLinks: ICorporateLink[] = []; const throttle = throat(ParallelLinkLookup); await Promise.all(corporateIds.map(corporateId => throttle(async () => { try { const links = await this.providers.linkProvider.queryByCorporateId(corporateId); if (links && links.length === 1) { corporateLinks.push(links[0]); } else if (links.length > 1) { throw new Error('Multiple links not supported'); } } catch (noLinkError) { console.dir(noLinkError); } }))); return corporateLinks; } getLinkByThirdPartyId(thirdPartyId: string): Promise<ICorporateLink> { const linkProvider = this.providers.linkProvider; return linkProvider.getByThirdPartyId(thirdPartyId); } getLinkByThirdPartyUsername(username: string): Promise<ICorporateLink> { const linkProvider = this.providers.linkProvider; return linkProvider.getByThirdPartyUsername(username); } getMailAddressFromCorporateUsername(corporateUsername: string): Promise<string> { if (!this.providers.mailAddressProvider) { throw new Error('No mailAddressProvider available'); } return this.providers.mailAddressProvider.getAddressFromUpn(corporateUsername); } async getMailAddressesFromCorporateUsernames(corporateUsernames: string[]): Promise<string[]> { // This is a best-faith effort but will not fail if some are not returned. const throttle = throat(2); const addresses: string[] = []; await Promise.all(corporateUsernames.map(username => throttle(async () => { try { const address = await this.getMailAddressFromCorporateUsername(username); if (address) { addresses.push(address); } } catch (ignoreError) { console.log('getMailAddressesFromCorporateUsernames error:'); console.warn(ignoreError); } }))); return addresses; } async tryGetLink(id: string, options?): Promise<ICorporateLink> { if (this.providers.linkProvider) { try { const link = await this.getLinkByThirdPartyId(id); return link; } catch (error) { if (ErrorHelper.IsNotFound(error)) { return null; } else { throw error; } } } // This literally retrieves the cache of all links, built from a time before link provider. const links = await this.getLinks(options); const reduced = links.filter(link => { // was 'ghid' in the prior implementation before link interfaces return link && link.thirdPartyId == id /* allow string comparisons */; }); if (reduced.length > 1) { throw new Error(`Multiple links were present for the same GitHub user ${id}`); } return reduced.length === 1 ? reduced[0] : null; } getTeamsWithMembers(options?: ICrossOrganizationTeamMembership): Promise<any> { const cacheOptions: IPagedCrossOrganizationCacheOptions = {}; options = options || {}; cacheOptions.backgroundRefresh = options.backgroundRefresh !== undefined ? options.backgroundRefresh : true; cacheOptions.maxAgeSeconds = options.maxAgeSeconds || 60 * 10; cacheOptions.individualMaxAgeSeconds = options.individualMaxAgeSeconds; delete options.backgroundRefresh; delete options.maxAgeSeconds; delete options.individualMaxAgeSeconds; return this.github.crossOrganization.teamMembers(this._organizationNamesWithAuthorizationHeaders, options, cacheOptions); } getRepoCollaborators(options: IPagedCrossOrganizationCacheOptions): Promise<any> { const cacheOptions: IPagedCrossOrganizationCacheOptions = {}; options = options || {}; cacheOptions.backgroundRefresh = options.backgroundRefresh !== undefined ? options.backgroundRefresh : true; cacheOptions.maxAgeSeconds = options.maxAgeSeconds || 60 * 10; cacheOptions.individualMaxAgeSeconds = options.individualMaxAgeSeconds; delete options.backgroundRefresh; delete options.maxAgeSeconds; delete options.individualMaxAgeSeconds; return this.github.crossOrganization.repoCollaborators(this.organizationNamesWithAuthorizationHeaders, options, cacheOptions); } getRepoTeams(options: IPagedCrossOrganizationCacheOptions): Promise<any> { const cacheOptions: IPagedCrossOrganizationCacheOptions = {}; options = options || {}; cacheOptions.backgroundRefresh = options.backgroundRefresh !== undefined ? options.backgroundRefresh : true; cacheOptions.maxAgeSeconds = options.maxAgeSeconds || 60 * 10; cacheOptions.individualMaxAgeSeconds = options.individualMaxAgeSeconds; delete options.backgroundRefresh; delete options.maxAgeSeconds; delete options.individualMaxAgeSeconds; return this.github.crossOrganization.repoTeams(this.organizationNamesWithAuthorizationHeaders, options, cacheOptions); } async getCrossOrganizationTeams(options?: any): Promise<ICrossOrganizationMembersResult> { if (!options.maxAgeSeconds) { options.maxAgeSeconds = this.defaults.crossOrgsMembersStaleSecondsPerOrg; } if (options.backgroundRefresh === undefined) { options.backgroundRefresh = true; } const cacheOptions = { maxAgeSeconds: options.maxAgeSeconds, backgroundRefresh: options.backgroundRefresh, }; delete options.maxAgeSeconds; delete options.backgroundRefresh; const values = await this.github.crossOrganization.teams(this.organizationNamesWithAuthorizationHeaders, options, cacheOptions); const results = crossOrganizationResults(this, values, 'id'); return results; } async getMembers(options?: ICacheOptions): Promise<ICrossOrganizationMembersResult> { options = options || {}; if (!options.maxAgeSeconds) { options.maxAgeSeconds = this.defaults.crossOrgsMembersStaleSecondsPerOrg; } if (options.backgroundRefresh === undefined) { options.backgroundRefresh = true; } const cacheOptions = { maxAgeSeconds: options.maxAgeSeconds, backgroundRefresh: options.backgroundRefresh, }; delete options.maxAgeSeconds; delete options.backgroundRefresh; const values = await this.github.crossOrganization.orgMembers(this.organizationNamesWithAuthorizationHeaders, options, cacheOptions); const crossOrgReturn = crossOrganizationResults(this, values, 'id') as any as ICrossOrganizationMembersResult; return crossOrgReturn; } // Feature flags allowSelfServiceTeamMemberToMaintainerUpgrades() { return this.config?.features?.allowTeamMemberToMaintainerSelfUpgrades === true; } allowUnauthorizedNewRepositoryLockdownSystemFeature() { return this.config?.features?.allowUnauthorizedNewRepositoryLockdownSystem === true; } allowUnauthorizedForkLockdownSystemFeature() { // This feature has a hard dependency on the new repo lockdown system itself return this.allowUnauthorizedNewRepositoryLockdownSystemFeature() && this.config && this.config.features && this.config.features.allowUnauthorizedForkLockdownSystem === true; } allowTransferLockdownSystemFeature() { // This feature has a hard dependency on the new repo lockdown system itself return this.allowUnauthorizedNewRepositoryLockdownSystemFeature() && this.config && this.config.features && this.config.features.allowUnauthorizedTransferLockdownSystem === true; } allowUndoSystem() { return this.config?.features?.features.allowUndoSystem === true; } // Eventually link/unlink should move from context into operations here to centralize more than just the events async fireLinkEvent(value): Promise<void> { await fireEvent(this.config, 'link', value); } async fireUnlinkEvent(value): Promise<void> { await fireEvent(this.config, 'unlink', value); } get systemAccountsByUsername(): string[] { return this.config?.github?.systemAccounts ? this.config.github.systemAccounts.logins : []; } isSystemAdministrator(corporateId: string, corporateUsername: string) { if (!this.initialized) { throw new Error('The application is not yet initialized'); } return isAuthorizedSystemAdministrator(this.providers, corporateId, corporateUsername); } isPortalSudoer(githubLogin: string, link: ICorporateLink) { if (!this.initialized) { throw new Error('The application is not yet initialized'); } return this._portalSudo.isSudoer(githubLogin, link); } isSystemAccountByUsername(username: string): boolean { const lc = username.toLowerCase(); const usernames = this.systemAccountsByUsername; for (let i = 0; i < usernames.length; i++) { if (usernames[i].toLowerCase() === lc) { return true; } } return false; } getCentralOperationsToken(): IGetAuthorizationHeader { const func = getCentralOperationsAuthorizationHeader.bind(null, this) as IGetAuthorizationHeader; return func; } getPublicReadOnlyToken(): IGetAuthorizationHeader { const func = getReadOnlyAuthorizationHeader.bind(null, this) as IGetAuthorizationHeader; return func; } getAccount(id: string) { const entity = { id }; return new Account(entity, this, getCentralOperationsAuthorizationHeader.bind(null, this)); } async getAccountWithDetailsAndLink(id: string): Promise<Account> { const account = this.getAccount(id); return await account.getDetailsAndLink(); } async getAuthenticatedAccount(token: string): Promise<Account> { const github = this.github; const parameters = {}; try { const entity = await github.post(`token ${token}`, 'users.getAuthenticated', parameters); const account = new Account(entity, this, getCentralOperationsAuthorizationHeader.bind(null, this)); return account; } catch (error) { throw wrapError(error, 'Could not get details about the authenticated account'); } } getTeamByIdWithOrganization(id: number, organizationName: string, entity?: any): Team { const organization = this.getOrganization(organizationName); return organization.team(id, entity); } getOrganizationFromUrl(url: string): Organization { const asUrl = new URL(url); const paths = asUrl.pathname.split('/').filter(real => real); if (paths[0] !== 'repos') { throw CreateError.InvalidParameters(`At this time, the first path segment must be "repos": ${url}`); } const orgName = paths[1]; return this.getOrganization(orgName); } getRepositoryWithOrganizationFromUrl(url: string): Repository { const asUrl = new URL(url); const paths = asUrl.pathname.split('/').filter(real => real); if (paths[0] !== 'repos') { throw CreateError.InvalidParameters(`At this time, the first path segment must be "repos": ${url}`); } const orgName = paths[1]; const repoName = paths[2]; return this.getRepositoryWithOrganization(repoName, orgName); } getRepositoryWithOrganization(repositoryName: string, organizationName: string, entity?: any): Repository { const organization = this.getOrganization(organizationName); return organization.repository(repositoryName, entity); } async sendMail(mail: IMail): Promise<any> { const mailProvider = this.providers.mailProvider; const insights = this.providers.insights; const customData = { receipt: null, eventName: undefined, }; try { const mailResult = await mailProvider.sendMail(mail); customData.receipt = mailResult; insights.trackEvent({ name: 'MailSuccess', properties: customData }); return mailResult; } catch (mailError) { customData.eventName = 'MailFailure'; insights.trackException({ exception: mailError, properties: customData }); throw mailError; } } async emailRender(emailViewName: string, contentOptions: any): Promise<string> { const appDirectory = this.config.typescript.appDirectory; return await RenderHtmlMail(appDirectory, emailViewName, contentOptions); } } interface IFireEventResult { url: string; value: string; body: string; headers: any; statusCode: any; } async function fireEvent(config, configurationName, value): Promise<IFireEventResult[]> { if (!config || !config.github || !config.github.links || !config.github.links.events || !config.github.links.events) { return; } const userAgent = config.userAgent || 'Unknown user agent'; const httpUrls = config.github.links.events.http; if (!httpUrls || !httpUrls[configurationName]) { return; } const urlOrUrls = httpUrls[configurationName]; let urls = Array.isArray(urlOrUrls) ? urlOrUrls : [urlOrUrls]; let results: IFireEventResult[] = []; for (const httpUrl of urls) { try { const response = await axios({ method: 'POST', url: httpUrl, data: value, headers: { 'User-Agent': userAgent, 'X-Repos-Event': configurationName, }, }); results.push({ url: httpUrl, value, headers: response.headers, body: response.data as any, // axios returns unknown now statusCode: response.status, }); } catch (ignoredTechnicalError) { /* ignored */ // TODO: telemetry console.warn(ignoredTechnicalError); console.log(); } } return results; } export function getReadOnlyAuthorizationHeader(self: Operations): IPurposefulGetAuthorizationHeader { const s = (self || this) as Operations; if (s.config?.github?.operations?.publicAccessToken) { const capturedToken = s.config.github.operations.publicAccessToken; return async () => { return { value: `token ${capturedToken}`, purpose: null, source: 'public read-only token', }; }; } else { throw new Error('No public read-only token configured.'); } } export function getCentralOperationsAuthorizationHeader(self: Operations): IPurposefulGetAuthorizationHeader { const s = (self || this) as Operations; if (s.config.github && s.config.github.operations && s.config.github.operations.centralOperationsToken) { const capturedToken = s.config.github.operations.centralOperationsToken; return async () => { return { value: `token ${capturedToken}`, purpose: null, // legacy source: 'central operations token', }; }; } else if (s.getOrganizations.length === 0) { throw new Error('No central operations token nor any organizations configured.'); } // Fallback to the first configured organization as a convenience // CONSIDER: would randomizing the organization be better, or a priority based on known-rate limit remaining? const firstOrganization = s.getOrganizations()[0]; return firstOrganization.getAuthorizationHeader(); } function crossOrganizationResults(operations: Operations, results, keyProperty) { keyProperty = keyProperty || 'id'; const map: IMapPlusMetaCost = new Map(); operations.translateOrganizationNamesFromLowercase(results.orgs); for (const orgName of Object.getOwnPropertyNames(results.orgs)) { const orgValues = results.orgs[orgName]; for (let i = 0; i < orgValues.length; i++) { const val = orgValues[i]; const key = val[keyProperty]; if (!key) { throw new Error(`Entity missing property ${key} during consolidation processing.`); } let mapEntry = map.get(key); if (!mapEntry) { mapEntry = { orgs: {}, }; mapEntry[keyProperty] = key; map.set(key, mapEntry); } mapEntry.orgs[orgName] = val; } } map.headers = results.headers; map.cost = results.cost; return map; } async function getPromisedLinks(linkProvider: ILinkProvider): Promise<IPromisedLinks> { // TODO: consider looking at the options as to how to include/exclude properties etc. // today (TypeScript update with PGSQL) the 'options' have zero impact on what is actually returned... const links = await linkProvider.getAll(); const jsonLinks = linkProvider.dehydrateLinks(links); const dataObject: IPromisedLinks = { headers: { 'type': 'links', }, data: jsonLinks, }; return dataObject; } function restartAfterDynamicConfigurationUpdate(minimumSeconds: number, maximumSeconds: number, appInitialized: Date, organizationSettingsProvider: OrganizationSettingProvider) { didDynamicConfigurationUpdate(appInitialized, organizationSettingsProvider).then(changed => { if (changed) { const randomSeconds = Math.floor(Math.random() * (maximumSeconds - minimumSeconds + 1) + minimumSeconds); console.log(`changes to dynamic configuration detected since ${appInitialized}, restarting in ${randomSeconds}s`); setInterval(() => { console.log(`shutting down process due to dynamic configuration changes being detected at least ${randomSeconds} seconds ago...`); return process.exit(0); }, randomSeconds * 1000); if (DynamicRestartCheckHandle) { clearInterval(DynamicRestartCheckHandle); } } }).catch(error => { console.dir(error); }); } async function didDynamicConfigurationUpdate(appInitialized: Date, organizationSettingsProvider: OrganizationSettingProvider): Promise<boolean> { try { const allOrganizations = await organizationSettingsProvider.queryAllOrganizations(); const activeOrganizations = allOrganizations.filter(org => org.active); for (const organization of activeOrganizations) { if (organization.updated > appInitialized) { console.log(`organization ${organization.organizationName} was updated ${organization.updated} vs app started time of ${appInitialized}`); return true; } } } catch (updateOrganizationsError) { console.dir(updateOrganizationsError); } return false; }
the_stack
import { $TSAny, $TSContext, $TSObject, AmplifyCategories, AmplifySupportedService, exitOnNextTick, getMigrateResourceMessageForOverride, pathManager, ResourceDoesNotExistError, stateManager, } from 'amplify-cli-core'; import { alphanumeric, printer, prompter, Validator } from 'amplify-prompts'; import * as fs from 'fs-extra'; import * as path from 'path'; import { v4 as uuid } from 'uuid'; import { DDBStackTransform } from '../cdk-stack-builder/ddb-stack-transform'; import { DynamoDBAttributeDefType, DynamoDBCLIInputs, DynamoDBCLIInputsGSIType, DynamoDBCLIInputsKeyType, } from '../service-walkthrough-types/dynamoDB-user-input-types'; import { DynamoDBInputState } from './dynamoDB-input-state'; // keep in sync with ServiceName in amplify-AmplifyCategories.STORAGE-function, but probably it will not change export async function addWalkthrough(context: $TSContext, defaultValuesFilename: string) { printer.blankLine(); printer.info('Welcome to the NoSQL DynamoDB database wizard'); printer.info('This wizard asks you a series of questions to help determine how to set up your NoSQL database table.'); printer.blankLine(); const defaultValuesSrc = path.join(__dirname, '..', 'default-values', defaultValuesFilename); const { getAllDefaults } = await import(defaultValuesSrc); const { amplify } = context; const defaultValues = getAllDefaults(amplify.getProjectDetails()); const resourceName = await askResourceNameQuestion(defaultValues); // Cannot be changed once added const tableName = await askTableNameQuestion(defaultValues, resourceName); // Cannot be changed once added const { attributeAnswers, indexableAttributeList } = await askAttributeListQuestion(); const partitionKey = await askPrimaryKeyQuestion(indexableAttributeList, attributeAnswers); // Cannot be changed once added let cliInputs: DynamoDBCLIInputs = { resourceName, tableName, partitionKey, }; cliInputs.sortKey = await askSortKeyQuestion(indexableAttributeList, attributeAnswers, cliInputs.partitionKey.fieldName); cliInputs.gsi = await askGSIQuestion(indexableAttributeList, attributeAnswers); cliInputs.triggerFunctions = await askTriggersQuestion(context, cliInputs.resourceName); const cliInputsState = new DynamoDBInputState(cliInputs.resourceName); cliInputsState.saveCliInputPayload(cliInputs); const stackGenerator = new DDBStackTransform(cliInputs.resourceName); stackGenerator.transform(); return cliInputs.resourceName; } export async function updateWalkthrough(context: $TSContext) { const amplifyMeta = stateManager.getMeta(); const dynamoDbResources: $TSObject = {}; Object.keys(amplifyMeta[AmplifyCategories.STORAGE]).forEach(resourceName => { if ( amplifyMeta[AmplifyCategories.STORAGE][resourceName].service === AmplifySupportedService.DYNAMODB && amplifyMeta[AmplifyCategories.STORAGE][resourceName].mobileHubMigrated !== true && amplifyMeta[AmplifyCategories.STORAGE][resourceName].serviceType !== 'imported' ) { dynamoDbResources[resourceName] = amplifyMeta[AmplifyCategories.STORAGE][resourceName]; } }); if (!amplifyMeta[AmplifyCategories.STORAGE] || Object.keys(dynamoDbResources).length === 0) { const errMessage = 'No resources to update. You need to add a resource.'; printer.error(errMessage); context.usageData.emitError(new ResourceDoesNotExistError(errMessage)); exitOnNextTick(0); return; } const resources = Object.keys(dynamoDbResources); const resourceName = await prompter.pick('Specify the resource that you would want to update', resources); // Check if we need to migrate to cli-inputs.json const cliInputsState = new DynamoDBInputState(resourceName); const headlessMigrate = context.input.options?.yes || context.input.options?.forcePush || context.input.options?.headless; if (!cliInputsState.cliInputFileExists()) { if (headlessMigrate || (await prompter.yesOrNo(getMigrateResourceMessageForOverride(AmplifyCategories.STORAGE, resourceName), true))) { cliInputsState.migrate(); const stackGenerator = new DDBStackTransform(resourceName); stackGenerator.transform(); } else { return; } } const cliInputs = cliInputsState.getCliInputPayload(); let existingAttributeDefinitions: DynamoDBCLIInputsKeyType[] = []; if (cliInputs.partitionKey) { existingAttributeDefinitions.push(cliInputs.partitionKey); } if (cliInputs.sortKey) { existingAttributeDefinitions.push(cliInputs.sortKey); } if (cliInputs.gsi && cliInputs.gsi.length > 0) { cliInputs.gsi.forEach((gsi: DynamoDBCLIInputsGSIType) => { if (gsi.partitionKey) { existingAttributeDefinitions.push(gsi.partitionKey); } if (gsi.sortKey) { existingAttributeDefinitions.push(gsi.sortKey); } }); } if (!cliInputs.resourceName) { throw new Error('resourceName not found in cli-inputs'); } const { attributeAnswers, indexableAttributeList } = await askAttributeListQuestion(existingAttributeDefinitions); cliInputs.gsi = await askGSIQuestion(indexableAttributeList, attributeAnswers, cliInputs.gsi); cliInputs.triggerFunctions = await askTriggersQuestion(context, cliInputs.resourceName, cliInputs.triggerFunctions); cliInputsState.saveCliInputPayload(cliInputs); const stackGenerator = new DDBStackTransform(cliInputs.resourceName); stackGenerator.transform(); return cliInputs; } async function askTriggersQuestion(context: $TSContext, resourceName: string, existingTriggerFunctions?: string[]): Promise<string[]> { let triggerFunctions: string[] = existingTriggerFunctions || []; if (!existingTriggerFunctions || existingTriggerFunctions.length === 0) { if (await prompter.confirmContinue('Do you want to add a Lambda Trigger for your Table?')) { let triggerName; try { // @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 2. triggerName = await addTrigger(context, resourceName); return [triggerName]; } catch (e) { printer.error(e.message); } } } else { let triggerName; let continueWithTriggerOperationQuestion = true; while (continueWithTriggerOperationQuestion) { const triggerOperationAnswer = await prompter.pick('Select from the following options', [ 'Add a Trigger', 'Remove a trigger', `I'm done`, ]); switch (triggerOperationAnswer) { case 'Add a Trigger': { try { triggerName = await addTrigger(context, resourceName, triggerFunctions); triggerFunctions.push(triggerName); continueWithTriggerOperationQuestion = false; } catch (e) { printer.error(e.message); continueWithTriggerOperationQuestion = true; } break; } case 'Remove a trigger': { try { if (triggerFunctions.length === 0) { throw new Error('No triggers found associated with this table'); } else { triggerName = await removeTrigger(context, resourceName, triggerFunctions); const index = triggerFunctions.indexOf(triggerName); if (index >= 0) { triggerFunctions.splice(index, 1); continueWithTriggerOperationQuestion = false; } else { throw new Error('Could not find trigger function'); } } } catch (e) { printer.error(e.message); continueWithTriggerOperationQuestion = true; } break; } case `I'm done`: { continueWithTriggerOperationQuestion = false; break; } default: printer.error(`${triggerOperationAnswer} not supported`); } } } return triggerFunctions; } async function askGSIQuestion( indexableAttributeList: string[], attributeDefinitions: DynamoDBAttributeDefType[], existingGSIList?: DynamoDBCLIInputsGSIType[], ) { printer.blankLine(); printer.info( 'You can optionally add global secondary indexes for this table. These are useful when you run queries defined in a different column than the primary key.', ); printer.info('To learn more about indexes, see:'); printer.info( 'https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.SecondaryIndexes', ); printer.blankLine(); let gsiList: DynamoDBCLIInputsGSIType[] = []; if ( existingGSIList && !!existingGSIList.length && (await prompter.yesOrNo('Do you want to keep existing global seconday indexes created on your table?', true)) ) { gsiList = existingGSIList; } if (await prompter.yesOrNo('Do you want to add global secondary indexes to your table?', true)) { let continuewithGSIQuestions = true; while (continuewithGSIQuestions) { if (indexableAttributeList.length > 0) { const gsiNameValidator = (message: string): Validator => (input: string) => /^[a-zA-Z0-9_-]+$/.test(input) ? true : message; const gsiName = await prompter.input('Provide the GSI name', { validate: gsiNameValidator('You can use the following characters: a-z A-Z 0-9 - _'), }); const gsiPartitionKeyName = await prompter.pick('Choose partition key for the GSI', [...new Set(indexableAttributeList)]); const gsiPrimaryKeyIndex = attributeDefinitions.findIndex( (attr: DynamoDBAttributeDefType) => attr.AttributeName === gsiPartitionKeyName, ); /* eslint-enable */ let gsiItem: DynamoDBCLIInputsGSIType = { name: gsiName, partitionKey: { fieldName: gsiPartitionKeyName, fieldType: attributeDefinitions[gsiPrimaryKeyIndex].AttributeType, }, }; const sortKeyOptions = indexableAttributeList.filter((att: string) => att !== gsiPartitionKeyName); if (sortKeyOptions.length > 0) { if (await prompter.yesOrNo('Do you want to add a sort key to your global secondary index?', true)) { const gsiSortKeyName = await prompter.pick('Choose sort key for the GSI', [...new Set(sortKeyOptions)]); const gsiSortKeyIndex = attributeDefinitions.findIndex( (attr: DynamoDBAttributeDefType) => attr.AttributeName === gsiSortKeyName, ); gsiItem.sortKey = { fieldName: gsiSortKeyName, fieldType: attributeDefinitions[gsiSortKeyIndex].AttributeType, }; } } gsiList.push(gsiItem); continuewithGSIQuestions = await prompter.yesOrNo('Do you want to add more global secondary indexes to your table?', true); } else { printer.error('You do not have any other attributes remaining to configure'); break; } } } return gsiList; } async function askSortKeyQuestion( indexableAttributeList: string[], attributeDefinitions: DynamoDBAttributeDefType[], partitionKeyFieldName: string, ): Promise<undefined | DynamoDBCLIInputsKeyType> { if (await prompter.yesOrNo('Do you want to add a sort key to your table?', true)) { // Ask for sort key if (attributeDefinitions.length > 1) { const sortKeyName = await prompter.pick( 'Choose sort key for the table', indexableAttributeList.filter((att: string) => att !== partitionKeyFieldName), ); const sortKeyAttrTypeIndex = attributeDefinitions.findIndex((attr: DynamoDBAttributeDefType) => attr.AttributeName === sortKeyName); return { fieldName: sortKeyName, fieldType: attributeDefinitions[sortKeyAttrTypeIndex].AttributeType, }; } else { printer.error('You must add additional keys in order to select a sort key.'); } } return; } async function askPrimaryKeyQuestion(indexableAttributeList: string[], attributeDefinitions: DynamoDBAttributeDefType[]) { printer.blankLine(); printer.info( 'Before you create the database, you must specify how items in your table are uniquely organized. You do this by specifying a primary key. The primary key uniquely identifies each item in the table so that no two items can have the same key. This can be an individual column, or a combination that includes a primary key and a sort key.', ); printer.blankLine(); printer.info('To learn more about primary keys, see:'); printer.info( 'https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey', ); printer.blankLine(); const partitionKeyName = await prompter.pick('Choose partition key for the table', indexableAttributeList); const primaryAttrTypeIndex = attributeDefinitions.findIndex((attr: DynamoDBAttributeDefType) => attr.AttributeName === partitionKeyName); return { fieldName: partitionKeyName, fieldType: attributeDefinitions[primaryAttrTypeIndex].AttributeType, }; } async function askAttributeListQuestion(existingAttributeDefinitions?: DynamoDBCLIInputsKeyType[]) { const attributeTypes = { string: { code: 'string', indexable: true }, number: { code: 'number', indexable: true }, binary: { code: 'binary', indexable: true }, boolean: { code: 'boolean', indexable: false }, list: { code: 'list', indexable: false }, map: { code: 'map', indexable: false }, null: { code: 'null', indexable: false }, 'string-set': { code: 'string-set', indexable: false }, 'number-set': { code: 'number-set', indexable: false }, 'binary-set': { code: 'binary-set', indexable: false }, }; printer.blankLine(); printer.info('You can now add columns to the table.'); printer.blankLine(); let continueAttributeQuestion = true; let attributeAnswers: DynamoDBAttributeDefType[] = []; let indexableAttributeList: string[] = []; let existingAttributes: DynamoDBAttributeDefType[] = []; if (existingAttributeDefinitions) { existingAttributes = existingAttributeDefinitions.map((attr: DynamoDBCLIInputsKeyType) => { return { AttributeName: attr.fieldName, AttributeType: attr.fieldType, }; }); } if (existingAttributes.length > 0) { attributeAnswers = existingAttributes; indexableAttributeList = attributeAnswers.map((attr: DynamoDBAttributeDefType) => attr.AttributeName); continueAttributeQuestion = await prompter.yesOrNo('Would you like to add another column?', true); } while (continueAttributeQuestion) { const attributeNameValidator = (message: string): Validator => (input: string) => /^[a-zA-Z0-9_-]+$/.test(input) ? true : message; const attributeName = await prompter.input('What would you like to name this column', { validate: attributeNameValidator('You can use the following characters: a-z A-Z 0-9 - _'), }); const attributeType = await prompter.pick('Choose the data type', Object.keys(attributeTypes)); if (attributeAnswers.findIndex((attribute: DynamoDBAttributeDefType) => attribute.AttributeName === attributeName) !== -1) { continueAttributeQuestion = await prompter.confirmContinue('This attribute was already added. Do you want to add another attribute?'); continue; } attributeAnswers.push({ AttributeName: attributeName, // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message AttributeType: attributeTypes[attributeType].code, }); // @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message if (attributeTypes[attributeType].indexable) { indexableAttributeList.push(attributeName); } continueAttributeQuestion = await prompter.yesOrNo('Would you like to add another column?', true); } return { attributeAnswers, indexableAttributeList }; } async function askTableNameQuestion(defaultValues: any, resourceName: string) { const tableNameValidator = (message: string): Validator => (input: string) => /^[a-zA-Z0-9._-]+$/.test(input) ? true : message; const tableName = await prompter.input('Provide table name', { validate: tableNameValidator('You can use the following characters: a-z A-Z 0-9 . - _'), initial: resourceName || defaultValues['tableName'], }); return tableName; } async function askResourceNameQuestion(defaultValues: any): Promise<string> { const resourceName = await prompter.input('Provide a friendly name', { validate: alphanumeric(), initial: defaultValues['resourceName'], }); return resourceName; } async function removeTrigger(context: $TSContext, resourceName: string, triggerList: string[]) { const functionName = await prompter.pick('Select from the function you would like to remove', triggerList); const projectBackendDirPath = context.amplify.pathManager.getBackendDirPath(); const functionCFNFilePath = path.join(projectBackendDirPath, 'function', functionName, `${functionName}-cloudformation-template.json`); if (fs.existsSync(functionCFNFilePath)) { const functionCFNFile = context.amplify.readJsonFile(functionCFNFilePath); delete functionCFNFile.Resources[`${resourceName}TriggerPolicy`]; delete functionCFNFile.Resources[`${resourceName}Trigger`]; // Update the functions resource const functionCFNString = JSON.stringify(functionCFNFile, null, 4); fs.writeFileSync(functionCFNFilePath, functionCFNString, 'utf8'); } return functionName; } async function addTrigger(context: $TSContext, resourceName: string, triggerList: string[]) { const triggerTypeAnswer = await prompter.pick('Select from the following options', [ 'Choose an existing function from the project', 'Create a new function', ]); let functionName; if (triggerTypeAnswer === 'Choose an existing function from the project') { let lambdaResources = await getLambdaFunctions(context); if (triggerList) { const filteredLambdaResources: string[] = []; lambdaResources.forEach((lambdaResource: string) => { if (triggerList.indexOf(lambdaResource) === -1) { filteredLambdaResources.push(lambdaResource); } }); lambdaResources = filteredLambdaResources; } if (lambdaResources.length === 0) { throw new Error("No functions were found in the project. Use 'amplify add function' to add a new function."); } functionName = await prompter.pick('Select from the following options', lambdaResources); } else { // Create a new lambda trigger const targetDir = context.amplify.pathManager.getBackendDirPath(); const [shortId] = uuid().split('-'); functionName = `${resourceName}Trigger${shortId}`; const pluginDir = __dirname; const defaults = { functionName: `${functionName}`, roleName: `${resourceName}LambdaRole${shortId}`, }; const copyJobs = [ { dir: pluginDir, template: path.join('..', '..', '..', '..', 'resources', 'triggers', 'dynamoDB', 'lambda-cloudformation-template.json.ejs'), target: path.join(targetDir, 'function', functionName, `${functionName}-cloudformation-template.json`), }, { dir: pluginDir, template: path.join('..', '..', '..', '..', 'resources', 'triggers', 'dynamoDB', 'event.json'), target: path.join(targetDir, 'function', functionName, 'src', 'event.json'), }, { dir: pluginDir, template: path.join('..', '..', '..', '..', 'resources', 'triggers', 'dynamoDB', 'index.js'), target: path.join(targetDir, 'function', functionName, 'src', 'index.js'), }, { dir: pluginDir, template: path.join('..', '..', '..', '..', 'resources', 'triggers', 'dynamoDB', 'package.json.ejs'), target: path.join(targetDir, 'function', functionName, 'src', 'package.json'), }, ]; // copy over the files await context.amplify.copyBatch(context, copyJobs, defaults); // Update amplify-meta and backend-config const backendConfigs = { service: AmplifySupportedService.LAMBDA, providerPlugin: 'awscloudformation', build: true, }; context.amplify.updateamplifyMetaAfterResourceAdd('function', functionName, backendConfigs); printer.success(`Successfully added resource ${functionName} locally`); } const projectBackendDirPath = context.amplify.pathManager.getBackendDirPath(); const functionCFNFilePath = path.join(projectBackendDirPath, 'function', functionName, `${functionName}-cloudformation-template.json`); if (fs.existsSync(functionCFNFilePath)) { const functionCFNFile = context.amplify.readJsonFile(functionCFNFilePath); // Update parameters block functionCFNFile.Parameters[`storage${resourceName}Name`] = { Type: 'String', Default: `storage${resourceName}Name`, }; functionCFNFile.Parameters[`storage${resourceName}Arn`] = { Type: 'String', Default: `storage${resourceName}Arn`, }; functionCFNFile.Parameters[`storage${resourceName}StreamArn`] = { Type: 'String', Default: `storage${resourceName}Arn`, }; // Update policies functionCFNFile.Resources[`${resourceName}TriggerPolicy`] = { DependsOn: ['LambdaExecutionRole'], Type: 'AWS::IAM::Policy', Properties: { PolicyName: `lambda-trigger-policy-${resourceName}`, Roles: [ { Ref: 'LambdaExecutionRole', }, ], PolicyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: ['dynamodb:DescribeStream', 'dynamodb:GetRecords', 'dynamodb:GetShardIterator', 'dynamodb:ListStreams'], Resource: [ { Ref: `storage${resourceName}StreamArn`, }, ], }, ], }, }, }; // Add TriggerResource functionCFNFile.Resources[`${resourceName}Trigger`] = { Type: 'AWS::Lambda::EventSourceMapping', DependsOn: [`${resourceName}TriggerPolicy`], Properties: { BatchSize: 100, Enabled: true, EventSourceArn: { Ref: `storage${resourceName}StreamArn`, }, FunctionName: { 'Fn::GetAtt': ['LambdaFunction', 'Arn'], }, StartingPosition: 'LATEST', }, }; // Update dependsOn const amplifyMetaFilePath = pathManager.getAmplifyMetaFilePath(); const amplifyMeta = context.amplify.readJsonFile(amplifyMetaFilePath); const resourceDependsOn = amplifyMeta.function[functionName].dependsOn || []; let resourceExists = false; resourceDependsOn.forEach((resource: any) => { if (resource.resourceName === resourceName) { resourceExists = true; resourceDependsOn.attributes = ['Name', 'Arn', 'StreamArn']; } }); if (!resourceExists) { resourceDependsOn.push({ category: AmplifyCategories.STORAGE, resourceName, attributes: ['Name', 'Arn', 'StreamArn'], }); } // Update the functions resource const functionCFNString = JSON.stringify(functionCFNFile, null, 4); fs.writeFileSync(functionCFNFilePath, functionCFNString, 'utf8'); context.amplify.updateamplifyMetaAfterResourceUpdate('function', functionName, 'dependsOn', resourceDependsOn); printer.success(`Successfully updated resource ${functionName} locally`); if (await prompter.confirmContinue(`Do you want to edit the local ${functionName} lambda function now?`)) { await context.amplify.openEditor(context, `${projectBackendDirPath}/function/${functionName}/src/index.js`); } } else { throw new Error(`Function ${functionName} does not exist`); } return functionName; } async function getLambdaFunctions(context: $TSContext) { const { allResources } = await context.amplify.getResourceStatus(); const lambdaResources = allResources .filter((resource: any) => resource.service === AmplifySupportedService.LAMBDA) .map((resource: any) => resource.resourceName); return lambdaResources; } export function migrate(context: $TSContext, projectPath: any, resourceName: any) { const resourceDirPath = path.join(projectPath, 'amplify', 'backend', AmplifyCategories.STORAGE, resourceName); const cfnFilePath = path.join(resourceDirPath, `${resourceName}-cloudformation-template.json`); // Removes dangling commas from a JSON const removeDanglingCommas = (value: any) => { const regex = /,(?!\s*?[{["'\w])/g; return value.replace(regex, ''); }; /* Current Dynamo CFN's have a trailing comma (accepted by CFN), but fails on JSON.parse(), hence removing it */ let oldcfnString = fs.readFileSync(cfnFilePath, 'utf8'); oldcfnString = removeDanglingCommas(oldcfnString); const oldCfn = JSON.parse(oldcfnString); const newCfn = {}; Object.assign(newCfn, oldCfn); // Add env parameter if (!(newCfn as any).Parameters) { (newCfn as any).Parameters = {}; } (newCfn as any).Parameters.env = { Type: 'String', }; // Add conditions block if (!(newCfn as any).Conditions) { (newCfn as any).Conditions = {}; } (newCfn as any).Conditions.ShouldNotCreateEnvResources = { 'Fn::Equals': [ { Ref: 'env', }, 'NONE', ], }; // Add if condition for resource name change (newCfn as any).Resources.DynamoDBTable.Properties.TableName = { 'Fn::If': [ 'ShouldNotCreateEnvResources', { Ref: 'tableName', }, { 'Fn::Join': [ '', [ { Ref: 'tableName', }, '-', { Ref: 'env', }, ], ], }, ], }; const jsonString = JSON.stringify(newCfn, null, '\t'); fs.writeFileSync(cfnFilePath, jsonString, 'utf8'); } export function getIAMPolicies(resourceName: string, crudOptions: $TSAny) { let policy = {}; const actions: string[] = []; crudOptions.forEach((crudOption: $TSAny) => { switch (crudOption) { case 'create': actions.push('dynamodb:Put*', 'dynamodb:Create*', 'dynamodb:BatchWriteItem'); break; case 'update': actions.push('dynamodb:Update*', 'dynamodb:RestoreTable*'); break; case 'read': actions.push('dynamodb:Get*', 'dynamodb:BatchGetItem', 'dynamodb:List*', 'dynamodb:Describe*', 'dynamodb:Scan', 'dynamodb:Query'); break; case 'delete': actions.push('dynamodb:Delete*'); break; default: console.log(`${crudOption} not supported`); } }); policy = { Effect: 'Allow', Action: actions, Resource: crudOptions.customPolicyResource ? crudOptions.customPolicyResource : [ { Ref: `${AmplifyCategories.STORAGE}${resourceName}Arn` }, { 'Fn::Join': [ '/', [ { Ref: `${AmplifyCategories.STORAGE}${resourceName}Arn`, }, 'index/*', ], ], }, ], }; const attributes = ['Name', 'Arn', 'StreamArn']; return { policy, attributes }; }
the_stack
import * as React from 'react' import { DiffLineType, DiffHunk, DiffLine, DiffSelection, ITextDiffData, } from '../../models/diff' import { getLineFilters, getFileContents, highlightContents, } from './syntax-highlighting' import { ITokens, ILineTokens, IToken } from '../../lib/highlighter/types' import { assertNever, assertNonNullable, forceUnwrap, } from '../../lib/fatal-error' import classNames from 'classnames' import { List, AutoSizer, CellMeasurerCache, CellMeasurer, ListRowProps, } from 'react-virtualized' import { SideBySideDiffRow } from './side-by-side-diff-row' import memoize from 'memoize-one' import { findInteractiveDiffRange, DiffRangeType } from './diff-explorer' import { ChangedFile, DiffRow, DiffRowType, canSelect, getDiffTokens, SimplifiedDiffRowData, SimplifiedDiffRow, IDiffRowData, DiffColumn, } from './diff-helpers' import { showContextualMenu } from '../main-process-proxy' import { getTokens } from './diff-syntax-mode' import { ITextDiffUtilsProps } from './text-diff' import { DiffSearchInput } from './diff-search-input' import { escapeRegExp } from '../../lib/helpers/regex' const DefaultRowHeight = 20 const MaxLineLengthToCalculateDiff = 240 export interface ISelectionPoint { readonly column: DiffColumn readonly row: number } export interface ISelection { readonly from: ISelectionPoint readonly to: ISelectionPoint readonly isSelected: boolean } type ModifiedLine = { line: DiffLine; diffLineNumber: number } interface ISideBySideDiffProps extends ITextDiffUtilsProps { /** The file whose diff should be displayed. */ readonly file: ChangedFile /** The diff that should be rendered */ readonly diff: ITextDiffData /** * Whether we'll show the diff in a side-by-side layout. */ readonly showSideBySideDiff: boolean } interface ISideBySideDiffState { /** * The list of syntax highlighting tokens corresponding to * the previous contents of the file. */ readonly beforeTokens?: ITokens /** * The list of syntax highlighting tokens corresponding to * the next contents of the file. */ readonly afterTokens?: ITokens /** * Indicates whether the user is doing a text selection and in which * column is doing it. This allows us to limit text selection to that * specific column via CSS. */ readonly selectingTextInRow?: 'before' | 'after' /** * The current diff selection. This is used while * dragging the mouse over different lines to know where the user started * dragging and whether the selection is to add or remove lines from the * selection. **/ readonly temporarySelection?: ISelection /** * Indicates the hunk that the user is currently hovering via the gutter. * * In this context, a hunk is not exactly equivalent to a diff hunk, but * instead marks a group of consecutive added/deleted lines. * * As an example, the following diff will contain a single diff hunk * (marked by the line starting with @@) but in this context we'll have two * hunks: * * | @@ -1,4 +1,4 @@ * | line 1 * | -line 2 * | +line 2a * | line 3 * | -line 4 * | +line 4a * * This differentiation makes selecting multiple lines by clicking on the * gutter more user friendly, since only consecutive modified lines get selected. */ readonly hoveredHunk?: number readonly isSearching: boolean readonly searchQuery?: string readonly searchResults?: SearchResults readonly selectedSearchResult: number | undefined } const listRowsHeightCache = new CellMeasurerCache({ defaultHeight: DefaultRowHeight, fixedWidth: true, }) export class SideBySideDiff extends React.Component< ISideBySideDiffProps, ISideBySideDiffState > { private virtualListRef = React.createRef<List>() public constructor(props: ISideBySideDiffProps) { super(props) this.state = { isSearching: false, selectedSearchResult: undefined, } } public componentDidMount() { this.initDiffSyntaxMode() window.addEventListener('keydown', this.onWindowKeyDown) // Listen for the custom event find-text (see app.tsx) // and trigger the search plugin if we see it. document.addEventListener('find-text', this.showSearch) } public componentWillUnmount() { window.removeEventListener('keydown', this.onWindowKeyDown) document.removeEventListener('mouseup', this.onEndSelection) document.removeEventListener('find-text', this.showSearch) } public componentDidUpdate(prevProps: ISideBySideDiffProps) { if (!highlightParametersEqual(this.props, prevProps)) { this.initDiffSyntaxMode() this.clearListRowsHeightCache() } } public render() { const rows = getDiffRows(this.props.diff, this.props.showSideBySideDiff) const containerClassName = classNames('side-by-side-diff-container', { 'unified-diff': !this.props.showSideBySideDiff, [`selecting-${this.state.selectingTextInRow}`]: this.props.showSideBySideDiff && this.state.selectingTextInRow !== undefined, editable: canSelect(this.props.file), }) return ( <div className={containerClassName} onMouseDown={this.onMouseDown}> {this.state.isSearching && ( <DiffSearchInput onSearch={this.onSearch} onClose={this.onSearchCancel} /> )} <div className="side-by-side-diff cm-s-default"> <AutoSizer onResize={this.clearListRowsHeightCache}> {({ height, width }) => ( <List deferredMeasurementCache={listRowsHeightCache} width={width} height={height} rowCount={rows.length} rowHeight={this.getRowHeight} rowRenderer={this.renderRow} ref={this.virtualListRef} // The following properties are passed to the list // to make sure that it gets re-rendered when any of // them change. isSearching={this.state.isSearching} selectedSearchResult={this.state.selectedSearchResult} searchQuery={this.state.searchQuery} showSideBySideDiff={this.props.showSideBySideDiff} beforeTokens={this.state.beforeTokens} afterTokens={this.state.afterTokens} temporarySelection={this.state.temporarySelection} hoveredHunk={this.state.hoveredHunk} isSelectable={canSelect(this.props.file)} fileSelection={this.getSelection()} /> )} </AutoSizer> </div> </div> ) } private renderRow = ({ index, parent, style, key }: ListRowProps) => { const rows = getDiffRows(this.props.diff, this.props.showSideBySideDiff) const row = rows[index] if (row === undefined) { return null } const rowWithTokens = this.createFullRow(row, index) const isHunkHovered = 'hunkStartLine' in row && this.state.hoveredHunk === row.hunkStartLine return ( <CellMeasurer cache={listRowsHeightCache} columnIndex={0} key={key} parent={parent} rowIndex={index} > <div key={key} style={style}> <SideBySideDiffRow row={rowWithTokens} numRow={index} isDiffSelectable={canSelect(this.props.file)} isHunkHovered={isHunkHovered} showSideBySideDiff={this.props.showSideBySideDiff} onStartSelection={this.onStartSelection} onUpdateSelection={this.onUpdateSelection} onMouseEnterHunk={this.onMouseEnterHunk} onMouseLeaveHunk={this.onMouseLeaveHunk} onClickHunk={this.onClickHunk} onContextMenuLine={this.onContextMenuLine} onContextMenuHunk={this.onContextMenuHunk} onContextMenuText={this.onContextMenuText} /> </div> </CellMeasurer> ) } private getRowHeight = (row: { index: number }) => { return listRowsHeightCache.rowHeight(row) ?? DefaultRowHeight } private clearListRowsHeightCache = () => { listRowsHeightCache.clearAll() } private async initDiffSyntaxMode() { const { file, diff, repository } = this.props // Store the current props to that we can see if anything // changes from underneath us as we're making asynchronous // operations that makes our data stale or useless. const propsSnapshot = this.props const lineFilters = getLineFilters(diff.hunks) const tabSize = 4 const contents = await getFileContents(repository, file, lineFilters) if (!highlightParametersEqual(this.props, propsSnapshot)) { return } const tokens = await highlightContents(contents, tabSize, lineFilters) if (!highlightParametersEqual(this.props, propsSnapshot)) { return } this.setState({ beforeTokens: tokens.oldTokens, afterTokens: tokens.newTokens, }) } private getSelection(): DiffSelection | undefined { return canSelect(this.props.file) ? this.props.file.selection : undefined } private createFullRow(row: SimplifiedDiffRow, numRow: number): DiffRow { if (row.type === DiffRowType.Added) { return { ...row, data: this.getRowDataPopulated( row.data, numRow, this.props.showSideBySideDiff ? DiffColumn.After : DiffColumn.Before, this.state.afterTokens ), } } if (row.type === DiffRowType.Deleted) { return { ...row, data: this.getRowDataPopulated( row.data, numRow, DiffColumn.Before, this.state.beforeTokens ), } } if (row.type === DiffRowType.Modified) { return { ...row, beforeData: this.getRowDataPopulated( row.beforeData, numRow, DiffColumn.Before, this.state.beforeTokens ), afterData: this.getRowDataPopulated( row.afterData, numRow, DiffColumn.After, this.state.afterTokens ), } } if (row.type === DiffRowType.Context) { const lineTokens = getTokens(row.beforeLineNumber, this.state.beforeTokens) ?? getTokens(row.afterLineNumber, this.state.afterTokens) const beforeTokens = [...row.beforeTokens] const afterTokens = [...row.afterTokens] if (lineTokens !== null) { beforeTokens.push(lineTokens) afterTokens.push(lineTokens) } const beforeSearchTokens = this.getSearchTokens(numRow, DiffColumn.Before) if (beforeSearchTokens !== undefined) { beforeSearchTokens.forEach(x => beforeTokens.push(x)) } const afterSearchTokens = this.getSearchTokens(numRow, DiffColumn.After) if (afterSearchTokens !== undefined) { afterSearchTokens.forEach(x => afterTokens.push(x)) } return { ...row, beforeTokens, afterTokens } } return row } private getRowDataPopulated( data: SimplifiedDiffRowData, row: number, column: DiffColumn, tokens: ITokens | undefined ): IDiffRowData { const searchTokens = this.getSearchTokens(row, column) const lineTokens = getTokens(data.lineNumber, tokens) const finalTokens = [...data.tokens] if (searchTokens !== undefined) { searchTokens.forEach(x => finalTokens.push(x)) } if (lineTokens !== null) { finalTokens.push(lineTokens) } return { ...data, tokens: finalTokens, isSelected: isInSelection( data.diffLineNumber, row, column, this.getSelection(), this.state.temporarySelection ), } } private getSearchTokens(row: number, column: DiffColumn) { const { searchResults: searchTokens, selectedSearchResult } = this.state if (searchTokens === undefined) { return undefined } const lineTokens = searchTokens.getLineTokens(row, column) if (lineTokens === undefined) { return undefined } if (lineTokens !== undefined && selectedSearchResult !== undefined) { const selected = searchTokens.get(selectedSearchResult) if (row === selected?.row && column === selected.column) { if (lineTokens[selected.offset] !== undefined) { const selectedToken = { [selected.offset]: { length: selected.length, token: 'selected' }, } return [lineTokens, selectedToken] } } } return [lineTokens] } private getDiffLineNumber( rowNumber: number, column: DiffColumn ): number | null { const rows = getDiffRows(this.props.diff, this.props.showSideBySideDiff) const row = rows[rowNumber] if (row === undefined) { return null } if (row.type === DiffRowType.Added || row.type === DiffRowType.Deleted) { return row.data.diffLineNumber } if (row.type === DiffRowType.Modified) { return column === DiffColumn.After ? row.afterData.diffLineNumber : row.beforeData.diffLineNumber } return null } /** * This handler is used to limit text selection to a single column. * To do so, we store the last column where the user clicked and use * that information to add a CSS class on the container div * (e.g `selecting-before`). * * Then, via CSS we can disable text selection on the column that is * not being selected. */ private onMouseDown = (event: React.MouseEvent<HTMLDivElement>) => { if (!this.props.showSideBySideDiff) { return } if (!(event.target instanceof HTMLElement)) { return } // We need to use the event target since the current target will // always point to the container. const isSelectingBeforeText = event.target.closest('.before') const isSelectingAfterText = event.target.closest('.after') if (isSelectingBeforeText !== null) { this.setState({ selectingTextInRow: 'before' }) } else if (isSelectingAfterText !== null) { this.setState({ selectingTextInRow: 'after' }) } } private onStartSelection = ( row: number, column: DiffColumn, isSelected: boolean ) => { const point: ISelectionPoint = { row, column } const temporarySelection = { from: point, to: point, isSelected } this.setState({ temporarySelection }) document.addEventListener('mouseup', this.onEndSelection, { once: true }) } private onUpdateSelection = (row: number, column: DiffColumn) => { const { temporarySelection } = this.state if (temporarySelection === undefined) { return } const to = { row, column } this.setState({ temporarySelection: { ...temporarySelection, to } }) } private onEndSelection = () => { let selection = this.getSelection() const { temporarySelection } = this.state if (selection === undefined || temporarySelection === undefined) { return } const { from: tmpFrom, to: tmpTo, isSelected } = temporarySelection const fromRow = Math.min(tmpFrom.row, tmpTo.row) const toRow = Math.max(tmpFrom.row, tmpTo.row) for (let row = fromRow; row <= toRow; row++) { const lineBefore = this.getDiffLineNumber(row, tmpFrom.column) const lineAfter = this.getDiffLineNumber(row, tmpTo.column) if (lineBefore !== null) { selection = selection.withLineSelection(lineBefore, isSelected) } if (lineAfter !== null) { selection = selection.withLineSelection(lineAfter, isSelected) } } this.props.onIncludeChanged?.(selection) this.setState({ temporarySelection: undefined }) } private onMouseEnterHunk = (hunkStartLine: number) => { if (this.state.temporarySelection === undefined) { this.setState({ hoveredHunk: hunkStartLine }) } } private onMouseLeaveHunk = () => { this.setState({ hoveredHunk: undefined }) } private onClickHunk = (hunkStartLine: number, select: boolean) => { if (this.props.onIncludeChanged === undefined) { return } const { diff } = this.props const selection = this.getSelection() if (selection !== undefined) { const range = findInteractiveDiffRange(diff.hunks, hunkStartLine) if (range !== null) { const { from, to } = range const sel = selection.withRangeSelection(from, to - from + 1, select) this.props.onIncludeChanged(sel) } } } /** * Handler to show a context menu when the user right-clicks on the diff text. */ private onContextMenuText = () => { const selectionLength = window.getSelection()?.toString().length ?? 0 showContextualMenu([ { label: 'Copy', // When using role="copy", the enabled attribute is not taken into account. role: selectionLength > 0 ? 'copy' : undefined, enabled: selectionLength > 0, }, ]) } /** * Handler to show a context menu when the user right-clicks on a line number. * * @param diffLineNumber the line number the diff where the user clicked */ private onContextMenuLine = (diffLineNumber: number) => { const { file, diff } = this.props if (!canSelect(file)) { return } if (this.props.onDiscardChanges === undefined) { return } const range = findInteractiveDiffRange(diff.hunks, diffLineNumber) if (range === null || range.type === null) { return } showContextualMenu([ { label: this.getDiscardLabel(range.type, 1), action: () => this.onDiscardChanges(diffLineNumber), }, ]) } /** * Handler to show a context menu when the user right-clicks on the gutter hunk handler. * * @param hunkStartLine The start line of the hunk where the user clicked. */ private onContextMenuHunk = (hunkStartLine: number) => { if (!canSelect(this.props.file)) { return } if (this.props.onDiscardChanges === undefined) { return } const range = findInteractiveDiffRange(this.props.diff.hunks, hunkStartLine) if (range === null || range.type === null) { return } showContextualMenu([ { label: this.getDiscardLabel(range.type, range.to - range.from + 1), action: () => this.onDiscardChanges(range.from, range.to), }, ]) } private getDiscardLabel(rangeType: DiffRangeType, numLines: number): string { const suffix = this.props.askForConfirmationOnDiscardChanges ? '…' : '' let type = '' if (rangeType === DiffRangeType.Additions) { type = 'Added' } else if (rangeType === DiffRangeType.Deletions) { type = 'Removed' } else if (rangeType === DiffRangeType.Mixed) { type = 'Modified' } else { assertNever(rangeType, `Invalid range type: ${rangeType}`) } const plural = numLines > 1 ? 's' : '' return `Discard ${type} Line${plural}${suffix}` } private onDiscardChanges(startLine: number, endLine: number = startLine) { const selection = this.getSelection() if (selection === undefined) { return } if (this.props.onDiscardChanges === undefined) { return } const newSelection = selection .withSelectNone() .withRangeSelection(startLine, endLine - startLine + 1, true) this.props.onDiscardChanges(this.props.diff, newSelection) } private onWindowKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) { return } const isCmdOrCtrl = event.metaKey && !event.ctrlKey if (isCmdOrCtrl && !event.shiftKey && !event.altKey && event.key === 'f') { event.preventDefault() this.showSearch() } } private showSearch = () => { if (!this.state.isSearching) { this.resetSearch(true) } } private onSearch = (searchQuery: string, direction: 'next' | 'previous') => { let { selectedSearchResult, searchResults: searchResults } = this.state const { diff, showSideBySideDiff } = this.props // If the query is unchanged and we've got tokens we'll continue, else we'll restart if (searchQuery === this.state.searchQuery && searchResults !== undefined) { if (selectedSearchResult === undefined) { selectedSearchResult = 0 } else { const delta = direction === 'next' ? 1 : -1 // http://javascript.about.com/od/problemsolving/a/modulobug.htm selectedSearchResult = (selectedSearchResult + delta + searchResults.length) % searchResults.length } } else { searchResults = calcSearchTokens(diff, showSideBySideDiff, searchQuery) selectedSearchResult = 0 if (searchResults === undefined || searchResults.length === 0) { this.resetSearch(true) return } } const scrollToRow = searchResults.get(selectedSearchResult)?.row if (scrollToRow !== undefined) { this.virtualListRef.current?.scrollToRow(scrollToRow) } this.setState({ searchQuery, searchResults, selectedSearchResult }) } private onSearchCancel = () => { this.resetSearch(false) } private resetSearch(isSearching: boolean) { this.setState({ selectedSearchResult: undefined, searchQuery: undefined, searchResults: undefined, isSearching, }) } } /** * Checks to see if any key parameters in the props object that are used * when performing highlighting has changed. This is used to determine * whether highlighting should abort in between asynchronous operations * due to some factor (like which file is currently selected) have changed * and thus rendering the in-flight highlighting data useless. */ function highlightParametersEqual( newProps: ISideBySideDiffProps, prevProps: ISideBySideDiffProps ) { return ( newProps === prevProps || (newProps.file.id === prevProps.file.id && newProps.diff.text === prevProps.diff.text && newProps.showSideBySideDiff === prevProps.showSideBySideDiff) ) } /** * Memoized function to calculate the actual rows to display side by side * as a diff. * * @param diff The diff to use to calculate the rows. * @param showSideBySideDiff Whether or not show the diff in side by side mode. */ const getDiffRows = memoize(function ( diff: ITextDiffData, showSideBySideDiff: boolean ): ReadonlyArray<SimplifiedDiffRow> { const outputRows = new Array<SimplifiedDiffRow>() for (const hunk of diff.hunks) { for (const row of getDiffRowsFromHunk(hunk, showSideBySideDiff)) { outputRows.push(row) } } return outputRows }) /** * Returns an array of rows with the needed data to render a side-by-side diff * with them. * * In some situations it will merge a deleted an added row into a single * modified row, in order to display them side by side (This happens when there * are consecutive added and deleted rows). * * @param hunk The hunk to use to extract the rows data * @param showSideBySideDiff Whether or not show the diff in side by side mode. */ function getDiffRowsFromHunk( hunk: DiffHunk, showSideBySideDiff: boolean ): ReadonlyArray<SimplifiedDiffRow> { const rows = new Array<SimplifiedDiffRow>() /** * Array containing multiple consecutive added/deleted lines. This * is used to be able to merge them into modified rows. */ let modifiedLines = new Array<ModifiedLine>() for (const [num, line] of hunk.lines.entries()) { const diffLineNumber = hunk.unifiedDiffStart + num if (line.type === DiffLineType.Delete || line.type === DiffLineType.Add) { modifiedLines.push({ line, diffLineNumber }) continue } if (modifiedLines.length > 0) { // If the current line is not added/deleted and we have any added/deleted // line stored, we need to process them. for (const row of getModifiedRows(modifiedLines, showSideBySideDiff)) { rows.push(row) } modifiedLines = [] } if (line.type === DiffLineType.Hunk) { rows.push({ type: DiffRowType.Hunk, content: line.content }) continue } if (line.type === DiffLineType.Context) { assertNonNullable( line.oldLineNumber, `No oldLineNumber for ${diffLineNumber}` ) assertNonNullable( line.newLineNumber, `No newLineNumber for ${diffLineNumber}` ) rows.push({ type: DiffRowType.Context, content: line.content, beforeLineNumber: line.oldLineNumber, afterLineNumber: line.newLineNumber, beforeTokens: [], afterTokens: [], }) continue } assertNever(line.type, `Invalid line type: ${line.type}`) } // Do one more pass to process the remaining list of modified lines. if (modifiedLines.length > 0) { for (const row of getModifiedRows(modifiedLines, showSideBySideDiff)) { rows.push(row) } } return rows } function getModifiedRows( addedDeletedLines: ReadonlyArray<ModifiedLine>, showSideBySideDiff: boolean ): ReadonlyArray<SimplifiedDiffRow> { if (addedDeletedLines.length === 0) { return [] } const hunkStartLine = addedDeletedLines[0].diffLineNumber const addedLines = new Array<ModifiedLine>() const deletedLines = new Array<ModifiedLine>() for (const line of addedDeletedLines) { if (line.line.type === DiffLineType.Add) { addedLines.push(line) } else if (line.line.type === DiffLineType.Delete) { deletedLines.push(line) } } const output = new Array<SimplifiedDiffRow>() const diffTokensBefore = new Array<ILineTokens | undefined>() const diffTokensAfter = new Array<ILineTokens | undefined>() // To match the behavior of github.com, we only highlight differences between // lines on hunks that have the same number of added and deleted lines. const shouldDisplayDiffInChunk = addedLines.length === deletedLines.length if (shouldDisplayDiffInChunk) { for (let i = 0; i < deletedLines.length; i++) { const addedLine = addedLines[i] const deletedLine = deletedLines[i] if ( addedLine.line.content.length < MaxLineLengthToCalculateDiff && deletedLine.line.content.length < MaxLineLengthToCalculateDiff ) { const { before, after } = getDiffTokens( deletedLine.line.content, addedLine.line.content ) diffTokensBefore[i] = before diffTokensAfter[i] = after } } } let indexModifiedRow = 0 while ( showSideBySideDiff && indexModifiedRow < addedLines.length && indexModifiedRow < deletedLines.length ) { const addedLine = forceUnwrap( 'Unexpected null line', addedLines[indexModifiedRow] ) const deletedLine = forceUnwrap( 'Unexpected null line', deletedLines[indexModifiedRow] ) // Modified lines output.push({ type: DiffRowType.Modified, beforeData: getDataFromLine( deletedLine, 'oldLineNumber', diffTokensBefore.shift() ), afterData: getDataFromLine( addedLine, 'newLineNumber', diffTokensAfter.shift() ), hunkStartLine, }) indexModifiedRow++ } for (let i = indexModifiedRow; i < deletedLines.length; i++) { const line = forceUnwrap('Unexpected null line', deletedLines[i]) output.push({ type: DiffRowType.Deleted, data: getDataFromLine(line, 'oldLineNumber', diffTokensBefore.shift()), hunkStartLine, }) } for (let i = indexModifiedRow; i < addedLines.length; i++) { const line = forceUnwrap('Unexpected null line', addedLines[i]) // Added line output.push({ type: DiffRowType.Added, data: getDataFromLine(line, 'newLineNumber', diffTokensAfter.shift()), hunkStartLine, }) } return output } function getDataFromLine( { line, diffLineNumber }: { line: DiffLine; diffLineNumber: number }, lineToUse: 'oldLineNumber' | 'newLineNumber', diffTokens: ILineTokens | undefined ): SimplifiedDiffRowData { const lineNumber = forceUnwrap( `Expecting ${lineToUse} value for ${line}`, line[lineToUse] ) const tokens = new Array<ILineTokens>() if (diffTokens !== undefined) { tokens.push(diffTokens) } return { content: line.content, lineNumber, diffLineNumber, noNewLineIndicator: line.noTrailingNewLine, tokens, } } /** * Helper class that lets us index search results both by their row * and column for fast lookup durig the render phase but also by their * relative order (index) allowing us to efficiently perform backwards search. */ class SearchResults { private readonly lookup = new Map<string, ILineTokens>() private readonly hits = new Array<[number, DiffColumn, number, number]>() private getKey(row: number, column: DiffColumn) { return `${row}.${column}` } public add(row: number, column: DiffColumn, offset: number, length: number) { const key = this.getKey(row, column) const existing = this.lookup.get(key) const token: IToken = { length, token: 'search-result' } if (existing !== undefined) { existing[offset] = token } else { this.lookup.set(key, { [offset]: token }) } this.hits.push([row, column, offset, length]) } public get length() { return this.hits.length } public get(index: number) { const hit = this.hits[index] return hit === undefined ? undefined : { row: hit[0], column: hit[1], offset: hit[2], length: hit[3] } } public getLineTokens(row: number, column: DiffColumn) { return this.lookup.get(this.getKey(row, column)) } } function calcSearchTokens( diff: ITextDiffData, showSideBySideDiffs: boolean, searchQuery: string ): SearchResults | undefined { if (searchQuery.length === 0) { return undefined } const hits = new SearchResults() const searchRe = new RegExp(escapeRegExp(searchQuery), 'gi') const rows = getDiffRows(diff, showSideBySideDiffs) for (const [rowNumber, row] of rows.entries()) { if (row.type === DiffRowType.Hunk) { continue } for (const column of enumerateColumnContents(row, showSideBySideDiffs)) { for (const match of column.content.matchAll(searchRe)) { if (match.index !== undefined) { hits.add(rowNumber, column.type, match.index, match[0].length) } } } } return hits } function* enumerateColumnContents( row: SimplifiedDiffRow, showSideBySideDiffs: boolean ): IterableIterator<{ type: DiffColumn; content: string }> { if (row.type === DiffRowType.Hunk) { yield { type: DiffColumn.Before, content: row.content } } else if (row.type === DiffRowType.Added) { const type = showSideBySideDiffs ? DiffColumn.After : DiffColumn.Before yield { type, content: row.data.content } } else if (row.type === DiffRowType.Deleted) { yield { type: DiffColumn.Before, content: row.data.content } } else if (row.type === DiffRowType.Context) { yield { type: DiffColumn.Before, content: row.content } if (showSideBySideDiffs) { yield { type: DiffColumn.After, content: row.content } } } else if (row.type === DiffRowType.Modified) { yield { type: DiffColumn.Before, content: row.beforeData.content } yield { type: DiffColumn.After, content: row.afterData.content } } else { assertNever(row, `Unknown row type ${row}`) } } function isInSelection( diffLineNumber: number, row: number, column: DiffColumn, selection: DiffSelection | undefined, temporarySelection: ISelection | undefined ) { const isInStoredSelection = selection?.isSelected(diffLineNumber) ?? false if (temporarySelection === undefined) { return isInStoredSelection } const isInTemporary = isInTemporarySelection(row, column, temporarySelection) if (temporarySelection.isSelected) { return isInStoredSelection || isInTemporary } else { return isInStoredSelection && !isInTemporary } } export function isInTemporarySelection( row: number, column: DiffColumn, selection: ISelection | undefined ): selection is ISelection { if (selection === undefined) { return false } if ( row >= Math.min(selection.from.row, selection.to.row) && row <= Math.max(selection.to.row, selection.from.row) && (column === selection.from.column || column === selection.to.column) ) { return true } return false }
the_stack
import { Writer } from './writer.ts'; import { Reader } from './reader.ts'; import { findOneDocument, findMultipleDocuments, updateDocument, parseDatabaseStorage } from './core.ts'; import { Document, DatabaseConfig, Query, QueryFunction, Update, UpdateFunction, Acceptable } from './types.ts'; import { cleanArray, deepClone, isObjectEmpty, prepareObject, isArray, isFunction, isObject, isString, isUndefined, isNull } from './utils.ts'; // * Version 1.0: // * Searching for single document // * Refactor internal types // * Rename optimize to batching // * JSON stringify during batching for speedup // TODO: Before Writing & After Reading configuration // TODO: Config with skip, limit, sort, immutable // TODO: Make documents storage read only // TODO: Finish testing // TODO: Examples /** * # AloeDB 🌿 * Light, Embeddable, NoSQL database for Deno * * [Deno](https://deno.land/x/aloedb) | [Github](https://github.com/Kirlovon/AloeDB) */ export class Database<Schema extends Acceptable<Schema> = Document> { /** * In-Memory documents storage. * * ***WARNING:*** It is better not to modify these documents manually, as the changes will not pass the necessary checks. * ***However, if you modify storage manualy, call the method `await db.save()` to save your changes.*** */ public documents: Schema[] = []; /** Data writing manager. */ private readonly writer?: Writer; /** Database configuration. */ private readonly config: DatabaseConfig = { path: undefined, pretty: true, autoload: true, autosave: true, batching: true, immutable: true, validator: undefined }; /** * Create database collection to store documents. * @param config Database configuration or path to the database file. */ constructor(config?: Partial<DatabaseConfig> | string) { if (isUndefined(config)) config = { autoload: false, autosave: false }; if (isString(config)) config = { path: config, autoload: true, autosave: true }; if (!isObject(config)) throw new TypeError('Config must be an object or a string'); // Disable autosave if path is not specified if (isUndefined(config?.path)) config.autosave = false; // Merge default config with users config this.config = { ...this.config, ...config }; // Writer initialization if (this.config.path) { this.writer = new Writer(this.config.path); if (this.config.autoload) this.loadSync(); } } /** * Insert a document. * @param document Document to insert. * @returns Inserted document. */ public async insertOne(document: Schema): Promise<Schema> { const { immutable, validator, autosave } = this.config; if (!isObject(document)) throw new TypeError('Document must be an object'); prepareObject(document); if (validator) validator(document); if (isObjectEmpty(document)) return {} as Schema; const internal: Schema = deepClone(document); this.documents.push(internal); if (autosave) await this.save(); return immutable ? deepClone(internal) : internal; } /** * Inserts multiple documents. * @param documents Array of documents to insert. * @returns Array of inserted documents. */ public async insertMany(documents: Schema[]): Promise<Schema[]> { const { immutable, validator, autosave } = this.config; if (!isArray(documents)) throw new TypeError('Input must be an array'); const inserted: Schema[] = []; for (let i = 0; i < documents.length; i++) { const document: Schema = documents[i]; if (!isObject(document)) throw new TypeError('Documents must be an objects'); prepareObject(document); if (validator) validator(document); if (isObjectEmpty(document)) continue; const internal: Schema = deepClone(document); inserted.push(internal); } this.documents = [...this.documents, ...inserted]; if (autosave) await this.save(); return immutable ? deepClone(inserted) : inserted; } /** * Find document by search query. * @param query Document selection criteria. * @returns Found document. */ public async findOne(query?: Query<Schema> | QueryFunction<Schema>): Promise<Schema | null> { const { immutable } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); const found: number | null = findOneDocument<Schema>(query, this.documents); if (isNull(found)) return null; const position: number = found; const document: Schema = this.documents[position]; return immutable ? deepClone(document) : document; } /** * Find multiple documents by search query. * @param query Documents selection criteria. * @returns Found documents. */ public async findMany(query?: Query<Schema> | QueryFunction<Schema>): Promise<Schema[]> { const { immutable } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); // Optimization for empty queries if (isUndefined(query) || (isObject(query) && isObjectEmpty(query))) { return immutable ? deepClone(this.documents) : [...this.documents]; } const found: number[] = findMultipleDocuments<Schema>(query, this.documents); if (found.length === 0) return []; const documents: Schema[] = []; for (let i = 0; i < found.length; i++) { const position: number = found[i]; const document: Schema = this.documents[position]; documents.push(document); } return immutable ? deepClone(documents) : documents; } /** * Modifies an existing document that match search query. * @param query Document selection criteria. * @param update The modifications to apply. * @returns Found document with applied modifications. */ public async updateOne(query: Query<Schema> | QueryFunction<Schema>, update: Update<Schema> | UpdateFunction<Schema>): Promise<Schema | null> { const { validator, autosave, immutable } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); if (!isObject(update) && !isFunction(update)) throw new TypeError('Update must be an object or function'); const found: number | null = findOneDocument<Schema>(query, this.documents); if (isNull(found)) return null; const position: number = found; const document: Schema = this.documents[position]; const updated: Schema = updateDocument<Schema>(document, update); if (validator) validator(updated); if (isObjectEmpty(updated)) { this.documents.splice(position, 1); return {} as Schema; } this.documents[position] = updated; if (autosave) await this.save(); return immutable ? deepClone(updated) : updated; } /** * Modifies all documents that match search query. * @param query Documents selection criteria. * @param update The modifications to apply. * @returns Found documents with applied modifications. */ public async updateMany(query: Query<Schema> | QueryFunction<Schema>, update: Update<Schema> | UpdateFunction<Schema>): Promise<Schema[]> { const { validator, autosave, immutable } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); if (!isObject(update) && !isFunction(update)) throw new TypeError('Update must be an object or function'); const found: number[] = findMultipleDocuments<Schema>(query, this.documents); if (found.length === 0) return []; const temporary: Schema[] = [...this.documents]; const updatedDocuments: Schema[] = []; let deleted: boolean = false; for (let i = 0; i < found.length; i++) { const position: number = found[i]; const document: Schema = temporary[position]; const updated: Schema = updateDocument<Schema>(document, update); if (validator) validator(updated); if (isObjectEmpty(updated)) { deleted = true; delete temporary[position]; continue; } temporary[position] = updated; updatedDocuments.push(updated); } this.documents = deleted ? cleanArray(temporary) : temporary; if (autosave) await this.save(); return immutable ? deepClone(updatedDocuments) : updatedDocuments; } /** * Deletes first found document that matches the search query. * @param query Document selection criteria. * @returns Deleted document. */ public async deleteOne(query?: Query<Schema> | QueryFunction<Schema>): Promise<Schema | null> { const { autosave } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); const found: number | null = findOneDocument<Schema>(query, this.documents); if (isNull(found)) return null; const position: number = found; const deleted: Schema = this.documents[position]; this.documents.splice(position, 1); if (autosave) await this.save(); return deleted; } /** * Deletes all documents that matches the search query. * @param query Document selection criteria. * @returns Array of deleted documents. */ public async deleteMany(query?: Query<Schema> | QueryFunction<Schema>): Promise<Schema[]> { const { autosave } = this.config; if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); const found: number[] = findMultipleDocuments<Schema>(query, this.documents); if (found.length === 0) return []; const temporary: Schema[] = [...this.documents]; const deleted: Schema[] = []; for (let i = 0; i < found.length; i++) { const position: number = found[i]; const document: Schema = temporary[position]; deleted.push(document); delete temporary[position]; } this.documents = cleanArray(temporary); if (autosave) await this.save(); return deleted; } /** * Count found documents. * @param query Documents selection criteria. * @returns Documents count. */ public async count(query?: Query<Schema> | QueryFunction<Schema>): Promise<number> { if (!isUndefined(query) && !isObject(query) && !isFunction(query)) throw new TypeError('Query must be an object or function'); // Optimization for empty queries if (isUndefined(query) || (isObject(query) && isObjectEmpty(query))) return this.documents.length; const found: number[] = findMultipleDocuments<Schema>(query, this.documents); return found.length; } /** * Delete all documents. */ public async drop(): Promise<void> { this.documents = []; if (this.config.autosave) await this.save(); } /** * Load data from storage file. */ public async load(): Promise<void> { const { path, validator } = this.config; if (!path) return; const content: string = await Reader.read(path); const documents: Document[] = parseDatabaseStorage(content); // Schema validation if (validator) { for (let i = 0; i < documents.length; i++) validator(documents[i]) } this.documents = documents as Schema[]; } /** * Synchronously load data from storage file. */ public loadSync(): void { const { path, validator } = this.config; if (!path) return; const content: string = Reader.readSync(path); const documents: Document[] = parseDatabaseStorage(content); // Schema validation if (validator) { for (let i = 0; i < documents.length; i++) validator(documents[i]) } this.documents = documents as Schema[]; } /** * Write documents to the database storage file. * Called automatically after each insert, update or delete operation. _(Only if `autosave` parameter is set to `true`)_ */ public async save(): Promise<void> { if (!this.writer) return; if (this.config.batching) { this.writer.batchWrite(this.documents, this.config.pretty); // Should be without await } else { await this.writer.write(this.documents, this.config.pretty); } } }
the_stack
import { Appservice, IAppserviceOptions, Intent, MatrixBridge, REMOTE_ROOM_INFO_ACCOUNT_DATA_EVENT_TYPE, REMOTE_ROOM_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX, REMOTE_USER_INFO_ACCOUNT_DATA_EVENT_TYPE, REMOTE_USER_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX } from "../../src"; import * as expect from "expect"; import * as simple from "simple-mock"; describe('MatrixBridge', () => { describe('getRemoteUserInfo', () => { it('should get remote user information', async () => { const userId = "@someone:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteObject = {id: "TESTING_1234", extraKey: true}; const intent = new Intent(options, userId, appservice); const registeredSpy = simple.mock(intent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const accountDataSpy = simple.stub().callFn((eventType) => { expect(eventType).toEqual(REMOTE_USER_INFO_ACCOUNT_DATA_EVENT_TYPE); return Promise.resolve(remoteObject); }); intent.underlyingClient.getAccountData = accountDataSpy; const bridge = new MatrixBridge(appservice); const result = await bridge.getRemoteUserInfo(intent); expect(result).toBeDefined(); expect(result).toMatchObject(remoteObject); expect(registeredSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); }); }); describe('setRemoteUserInfo', () => { it('should set remote user information', async () => { const userId = "@someone:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteObject = {id: "TESTING_1234", extraKey: true}; const intent = new Intent(options, userId, appservice); const registeredSpy = simple.mock(intent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const accountDataSpy = simple.stub().callFn((eventType, c) => { expect(eventType).toEqual(REMOTE_USER_INFO_ACCOUNT_DATA_EVENT_TYPE); expect(c).toMatchObject(remoteObject); return Promise.resolve(); }); intent.underlyingClient.setAccountData = accountDataSpy; const botIntent = new Intent(options, "@bot:example.org", appservice); (<any>appservice).botIntent = botIntent; // Workaround for using a fake appservice const botRegisteredSpy = simple.mock(botIntent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const botAccountDataSpy = simple.stub().callFn((eventType, c) => { expect(eventType).toEqual(REMOTE_USER_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX + "." + remoteObject.id); expect(c).toMatchObject({id: userId}); return Promise.resolve(); }); appservice.botIntent.underlyingClient.setAccountData = botAccountDataSpy; const bridge = new MatrixBridge(appservice); await bridge.setRemoteUserInfo(intent, remoteObject); expect(registeredSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); expect(botRegisteredSpy.callCount).toBe(1); expect(botAccountDataSpy.callCount).toBe(1); }); }); describe('getRemoteRoomInfo', () => { it('should get remote room information', async () => { const userId = "@someone:example.org"; const roomId = "!a:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteObject = {id: "TESTING_1234", extraKey: true}; const intent = new Intent(options, userId, appservice); (<any>appservice).botIntent = intent; // Workaround for using a fake appservice const registeredSpy = simple.mock(intent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const accountDataSpy = simple.stub().callFn((eventType, rid) => { expect(eventType).toEqual(REMOTE_ROOM_INFO_ACCOUNT_DATA_EVENT_TYPE); expect(rid).toEqual(roomId); return Promise.resolve(remoteObject); }); intent.underlyingClient.getRoomAccountData = accountDataSpy; const bridge = new MatrixBridge(appservice); const result = await bridge.getRemoteRoomInfo(roomId); expect(result).toBeDefined(); expect(result).toMatchObject(remoteObject); expect(registeredSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); }); }); describe('setRemoteRoomInfo', () => { it('should set remote room information', async () => { const userId = "@someone:example.org"; const roomId = "!a:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteObject = {id: "TESTING_1234", extraKey: true}; const intent = new Intent(options, userId, appservice); (<any>appservice).botIntent = intent; // Workaround for using a fake appservice const registeredSpy = simple.mock(intent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const roomAccountDataSpy = simple.stub().callFn((eventType, rid, c) => { expect(eventType).toEqual(REMOTE_ROOM_INFO_ACCOUNT_DATA_EVENT_TYPE); expect(rid).toEqual(roomId); expect(c).toMatchObject(remoteObject); return Promise.resolve(); }); intent.underlyingClient.setRoomAccountData = roomAccountDataSpy; const accountDataSpy = simple.stub().callFn((eventType, c) => { expect(eventType).toEqual(REMOTE_ROOM_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX + "." + remoteObject.id); expect(c).toMatchObject({id: roomId}); return Promise.resolve(); }); intent.underlyingClient.setAccountData = accountDataSpy; const bridge = new MatrixBridge(appservice); await bridge.setRemoteRoomInfo(roomId, remoteObject); expect(registeredSpy.callCount).toBe(2); expect(roomAccountDataSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); }); }); describe('getMatrixRoomIdForRemote', () => { it('should return the right room ID', async () => { const userId = "@someone:example.org"; const roomId = "!a:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteId = "TESTING_1234"; const intent = new Intent(options, userId, appservice); (<any>appservice).botIntent = intent; // Workaround for using a fake appservice const registeredSpy = simple.mock(intent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const accountDataSpy = simple.stub().callFn((eventType) => { expect(eventType).toEqual(REMOTE_ROOM_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX + "." + remoteId); return Promise.resolve({id: roomId}); }); intent.underlyingClient.getAccountData = accountDataSpy; const bridge = new MatrixBridge(appservice); const result = await bridge.getMatrixRoomIdForRemote(remoteId); expect(result).toEqual(roomId); expect(registeredSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); }); }); describe('getIntentForRemote', () => { it('should return the right user intent', async () => { const userId = "@someone:example.org"; const asToken = "s3cret"; const hsUrl = "https://localhost"; const appservice = <Appservice>{botUserId: userId}; const options = <IAppserviceOptions>{ homeserverUrl: hsUrl, registration: { as_token: asToken, }, }; const remoteId = "TESTING_1234"; const intent = new Intent(options, userId, appservice); const botIntent = new Intent(options, "@bot:example.org", appservice); (<any>appservice).botIntent = botIntent; // Workaround for using a fake appservice const registeredSpy = simple.mock(botIntent, "ensureRegistered").callFn(() => { return Promise.resolve(); }); const accountDataSpy = simple.stub().callFn((eventType) => { expect(eventType).toEqual(REMOTE_USER_MAP_ACCOUNT_DATA_EVENT_TYPE_PREFIX + "." + remoteId); return Promise.resolve({id: userId}); }); botIntent.underlyingClient.getAccountData = accountDataSpy; const getIntentSpy = simple.mock(appservice, "getIntentForUserId").callFn((uid) => { expect(uid).toEqual(userId); return intent; }); const bridge = new MatrixBridge(appservice); const result = await bridge.getIntentForRemote(remoteId); expect(result).toEqual(intent); expect(registeredSpy.callCount).toBe(1); expect(accountDataSpy.callCount).toBe(1); expect(getIntentSpy.callCount).toBe(1); }); }); });
the_stack
module androidui { import View = android.view.View; import ViewGroup = android.view.ViewGroup; import FrameLayout = android.widget.FrameLayout; import MotionEvent = android.view.MotionEvent; import KeyEvent = android.view.KeyEvent; import Intent = android.content.Intent; import ActivityThread = android.app.ActivityThread; import UIClient = androidui.AndroidUI.UIClient; import ViewRootImpl = android.view.ViewRootImpl; export class AndroidUI { static BindToElementName = 'AndroidUI'; androidUIElement:AndroidUIElement; private _canvas:HTMLCanvasElement = document.createElement("canvas"); get windowManager(){ return this.mApplication.getWindowManager(); } private mActivityThread:ActivityThread; private _viewRootImpl:android.view.ViewRootImpl; private mApplication:android.app.Application; appName:string; private uiClient:AndroidUI.UIClient; private viewsDependOnDebugLayout = new Set<View>(); private showDebugLayoutDefault = false; private _windowBound = new android.graphics.Rect(); private tempRect = new android.graphics.Rect(); get windowBound():android.graphics.Rect{ return this._windowBound; } private touchEvent = new MotionEvent(); private ketEvent = new KeyEvent(); constructor(androidUIElement:AndroidUIElement) { this.androidUIElement = androidUIElement; if(androidUIElement[AndroidUI.BindToElementName]){ throw Error('already init a AndroidUI with this element'); } androidUIElement[AndroidUI.BindToElementName] = this; this.init(); } private init() { this.appName = document.title; this._viewRootImpl = new android.view.ViewRootImpl(); this.initAndroidUIElement(); this.initApplication(); this.androidUIElement.appendChild(this._canvas); this.initEvent(); this.initRootSizeChange(); this._viewRootImpl.setView(this.windowManager.getWindowsLayout()); this._viewRootImpl.initSurface(this._canvas); this.initBrowserVisibleChange(); this.initLaunchActivity(); this.initGlobalCrashHandle(); } private initApplication() { const appName = this.androidUIElement.getAttribute('appName'); let appClazz; if (appName) { try { appClazz = eval(appName); } catch (e) { } } appClazz = appClazz || android.app.Application; this.mApplication = new appClazz(this); this.mApplication.onCreate(); } private initLaunchActivity(){ this.mActivityThread = new ActivityThread(this); //launch activity defined in 'android-ui' element for(let ele of Array.from(this.androidUIElement.children)){ let tagName = ele.tagName; if(tagName != 'ACTIVITY') continue; let activityName = ele.getAttribute('name') || ele.getAttribute('android:name') || 'android.app.Activity'; let intent = new Intent(activityName); this.mActivityThread.overrideNextWindowAnimation(null, null, null, null); let activity = this.mActivityThread.handleLaunchActivity(intent); if (activity) { this.androidUIElement.removeChild(ele); // show layout defined in activity tag for(let element of Array.from((<HTMLElement>ele).children)){ android.view.LayoutInflater.from(activity).inflate(<HTMLElement>element, activity.getWindow().mContentParent, true); } //activity could have a attribute defined callback when created let onCreateFunc = ele.getAttribute('oncreate'); if(onCreateFunc && typeof window[onCreateFunc] === "function"){ window[onCreateFunc].call(this, activity); } } } this.mActivityThread.initWithPageStack();//restore activity here. } private initGlobalCrashHandle(){ window.onerror = (sMsg,sUrl,sLine)=>{ if(window.confirm(android.R.string_.crash_catch_alert+'\n'+sMsg)){ //reload will clear console's log. window.location.reload(); } } } /** * @returns {boolean} is bound change */ private refreshWindowBound():boolean { let boundLeft = this.androidUIElement.offsetLeft; let boundTop = this.androidUIElement.offsetTop; let parent = this.androidUIElement.parentElement; if(parent){ boundLeft += parent.offsetLeft; boundTop += parent.offsetTop; parent = parent.parentElement; } let boundRight = boundLeft + this.androidUIElement.offsetWidth; let boundBottom = boundTop + this.androidUIElement.offsetHeight; if(this._windowBound && this._windowBound.left == boundLeft && this._windowBound.top == boundTop && this._windowBound.right == boundRight && this._windowBound.bottom == boundBottom){ return false; } this._windowBound.set(boundLeft, boundTop, boundRight, boundBottom); return true; } private initAndroidUIElement(){ if (this.androidUIElement.style.display==='none') { this.androidUIElement.style.display = ''; } this.androidUIElement.setAttribute('tabindex', '0');//let element could get focus. so the key event can handle. this.androidUIElement.focus(); this.androidUIElement.onblur = (e) => { this._viewRootImpl.ensureTouchMode(true); }; } private initEvent(){ this.initTouchEvent(); this.initMouseEvent(); this.initKeyEvent(); this.initGenericEvent(); } private initTouchEvent() { this.androidUIElement.addEventListener('touchstart', (e)=> { this.refreshWindowBound(); if(e.target!=document.activeElement || !this.androidUIElement.contains(<HTMLElement>document.activeElement)){ this.androidUIElement.focus(); } this.touchEvent.initWithTouch(<any>e, MotionEvent.ACTION_DOWN, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('touchmove', (e)=> { this.touchEvent.initWithTouch(<any>e, MotionEvent.ACTION_MOVE, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('touchend', (e)=> { this.touchEvent.initWithTouch(<any>e, MotionEvent.ACTION_UP, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('touchcancel', (e)=> { this.touchEvent.initWithTouch(<any>e, MotionEvent.ACTION_CANCEL, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); } private initMouseEvent(){ function mouseToTouchEvent(e:MouseEvent){ let touch:Touch = { identifier: 0, target: null, screenX: e.screenX, screenY: e.screenY, clientX: e.clientX, clientY: e.clientY, pageX: e.pageX, pageY: e.pageY }; return { changedTouches : [touch], targetTouches : [touch], touches : e.type === 'mouseup' ? [] : [touch], timeStamp : e.timeStamp }; } let isMouseDown = false; this.androidUIElement.addEventListener('mousedown', (e:MouseEvent)=> { isMouseDown = true; this.refreshWindowBound(); if(e.target!=document.activeElement || !this.androidUIElement.contains(<HTMLElement>document.activeElement)){ this.androidUIElement.focus(); } this.touchEvent.initWithTouch(<any>mouseToTouchEvent(e), MotionEvent.ACTION_DOWN, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('mousemove', (e)=> { if(!isMouseDown) return; this.touchEvent.initWithTouch(<any>mouseToTouchEvent(e), MotionEvent.ACTION_MOVE, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('mouseup', (e)=> { isMouseDown = false; this.touchEvent.initWithTouch(<any>mouseToTouchEvent(e), MotionEvent.ACTION_UP, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('mouseleave', (e)=> { if(e.fromElement === this.androidUIElement){ isMouseDown = false; this.touchEvent.initWithTouch(<any>mouseToTouchEvent(e), MotionEvent.ACTION_CANCEL, this._windowBound); if(this._viewRootImpl.dispatchInputEvent(this.touchEvent)){ e.stopPropagation(); e.preventDefault(); return true; } } }, true); let scrollEvent = new MotionEvent(); //Action_Scroll this.androidUIElement.addEventListener('mousewheel', (e:MouseWheelEvent)=> { scrollEvent.initWithMouseWheel(<WheelEvent><any>e); if(this._viewRootImpl.dispatchInputEvent(scrollEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); } private initKeyEvent(){ this.androidUIElement.addEventListener('keydown', (e:KeyboardEvent)=> { this.ketEvent.initKeyEvent(e, KeyEvent.ACTION_DOWN); if(this._viewRootImpl.dispatchInputEvent(this.ketEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); this.androidUIElement.addEventListener('keyup', (e:KeyboardEvent)=> { this.ketEvent.initKeyEvent(e, KeyEvent.ACTION_UP); if(this._viewRootImpl.dispatchInputEvent(this.ketEvent)){ e.stopPropagation(); e.preventDefault(); return true; } }, true); } private initGenericEvent(){ // No generic Event current. Hover event should listen & dispatch here } private initRootSizeChange(){ const inner_this = this; window.addEventListener('resize', ()=>{ inner_this.notifyRootSizeChange(); }); let lastWidth = this.androidUIElement.offsetWidth; let lastHeight = this.androidUIElement.offsetHeight; if(lastWidth>0 && lastHeight>0) this.notifyRootSizeChange(); setInterval(()=>{ let width = inner_this.androidUIElement.offsetWidth; let height = inner_this.androidUIElement.offsetHeight; if(lastHeight !== height || lastWidth !== width){ lastWidth = width; lastHeight = height; inner_this.notifyRootSizeChange(); } }, 500); } private initBrowserVisibleChange(){ var eventName = 'visibilitychange'; if (document['webkitHidden'] != undefined) { eventName = 'webkitvisibilitychange'; } document.addEventListener(eventName, ()=>{ if(document['hidden'] || document['webkitHidden']){ //hidden this.mActivityThread.scheduleApplicationHide(); }else{ //show this.mActivityThread.scheduleApplicationShow(); this._viewRootImpl.invalidate(); } }, false); } private notifyRootSizeChange(){ if(this.refreshWindowBound()) { let density = android.content.res.Resources.getDisplayMetrics().density; this.tempRect.set(this._windowBound.left * density, this._windowBound.top * density, this._windowBound.right * density, this._windowBound.bottom * density); let width = this._windowBound.width(); let height = this._windowBound.height(); this._canvas.width = width * density; this._canvas.height = height * density; this._canvas.style.width = width + "px"; this._canvas.style.height = height + "px"; this._viewRootImpl.notifyResized(this.tempRect); } } viewAttachedDependOnDebugLayout(view:View):void{ this.viewsDependOnDebugLayout.add(view); this.showDebugLayout(); } viewDetachedDependOnDebugLayout(view:View):void{ this.viewsDependOnDebugLayout.delete(view); if(this.viewsDependOnDebugLayout.size==0 && !this.showDebugLayoutDefault){ this.hideDebugLayout(); } } setDebugEnable(enable = true){ ViewRootImpl.DEBUG_FPS = enable; this.setShowDebugLayout(enable); } setShowDebugLayout(showDebugLayoutDefault = true){ this.showDebugLayoutDefault = showDebugLayoutDefault; if(showDebugLayoutDefault){ this.showDebugLayout(); }else{ this.hideDebugLayout(); } } private showDebugLayout(){ if(this.windowManager.getWindowsLayout().bindElement.parentNode === null){ this.androidUIElement.appendChild(this.windowManager.getWindowsLayout().bindElement); } } private hideDebugLayout(){ if(this.windowManager.getWindowsLayout().bindElement.parentNode === this.androidUIElement){ this.androidUIElement.removeChild(this.windowManager.getWindowsLayout().bindElement); } } setUIClient(uiClient:UIClient){ this.uiClient = uiClient; } showAppClosed():void { AndroidUI.showAppClosed(this); } private static showAppClosed(androidUI:AndroidUI) { //NOTE: will override by NativeApi androidUI.androidUIElement.parentNode.removeChild(androidUI.androidUIElement); if(androidUI.uiClient && androidUI.uiClient.shouldShowAppClosed){ androidUI.uiClient.shouldShowAppClosed(androidUI); } } } export module AndroidUI{ export interface UIClient{ shouldShowAppClosed?(androidUI:AndroidUI); } } }
the_stack
import {ByteReader, concatByteArrays, EOF} from "teamten-ts-utils"; import {hi, lo, toHexByte, toHexWord} from "z80-base"; import {ProgramAnnotation} from "./ProgramAnnotation.js"; import {AbstractTrs80File} from "./Trs80File.js"; import { CmdLoadBlockChunk, CmdLoadModuleHeaderChunk, CmdProgram, CmdTransferAddressChunk, encodeCmdProgram } from "./CmdProgram.js"; import {ProgramBuilder} from "./ProgramBuilder.js"; const FILE_HEADER = 0x55; const DATA_HEADER = 0x3C; const END_OF_FILE_MARKER = 0x78; const FILENAME_LENGTH = 6; export const MAX_SYSTEM_CHUNK_DATA_SIZE = 256; /** * Represents a chunk of bytes from the file, with a checksum. */ export class SystemChunk { public readonly loadAddress: number; public readonly data: Uint8Array; public readonly checksum: number; constructor(loadAddress: number, data: Uint8Array, checksum?: number) { if (data.length > MAX_SYSTEM_CHUNK_DATA_SIZE) { throw new Error("system chunks can at most hold " + MAX_SYSTEM_CHUNK_DATA_SIZE + " bytes"); } if (data.length === 0) { throw new Error("system chunk cannot have no data"); } this.loadAddress = loadAddress; this.data = data; this.checksum = checksum ?? SystemChunk.computeChecksum(loadAddress, data); } /** * Whether the checksum supplied on tape matches what we compute. */ public isChecksumValid(): boolean { return SystemChunk.computeChecksum(this.loadAddress, this.data) === this.checksum; } /** * Compute the chunk checksum of load address and its data. */ private static computeChecksum(loadAddress: number, data: Uint8Array): number { let checksum = 0; // Include load address and data. checksum += (loadAddress >> 8) & 0xFF; checksum += loadAddress & 0xFF; for (const b of data) { checksum += b; } return checksum & 0xFF; } } /** * Class representing a SYSTEM (machine language) program. If the "error" field is set, then something * went wrong with the program and the data may be partially loaded. */ export class SystemProgram extends AbstractTrs80File { public readonly className = "SystemProgram"; public readonly filename: string; public readonly chunks: SystemChunk[]; public readonly entryPointAddress: number; public readonly annotations: ProgramAnnotation[]; constructor(binary: Uint8Array, error: string | undefined, filename: string, chunks: SystemChunk[], entryPointAddress: number, annotations: ProgramAnnotation[]) { super(binary, error, annotations); this.filename = clipSystemProgramFilename(filename); this.chunks = chunks; this.entryPointAddress = entryPointAddress; this.annotations = annotations; } public getDescription(): string { let description = "System program (" + this.filename; if (this.entryPointAddress === 0) { const address = this.guessEntryAddress(); if (address !== undefined) { description += ", /" + address; } } description += ")"; return description; } /** * Guess an entry address in case one wasn't specified in the program. */ public guessEntryAddress(): number | undefined { // For now just take the address of the first chunk. We may want to do something more clever, // like find the minimum load address that's not in video memory. I suspect that programs // without load addresses probably aren't doing clever things like that. return this.chunks.length === 0 ? undefined : this.chunks[0].loadAddress; } /** * Convert an address in memory to the original byte offset in the binary. Returns undefined if * not found in any chunk. */ public addressToByteOffset(address: number): number | undefined { // Skip file header and block header. let offset = 1 + FILENAME_LENGTH + 4; for (const chunk of this.chunks) { if (address >= chunk.loadAddress && address < chunk.loadAddress + chunk.data.length) { return offset + (address - chunk.loadAddress); } // Skip checksum and block header of the next block. offset += chunk.data.length + 5; } return undefined; } /** * Create the CMD version of this system program. * * @param filename name to use in case the system program doesn't have one. */ public toCmdProgram(filename?: string): CmdProgram { const cmdChunks = []; const cmdFilename = this.filename !== "" ? this.filename : (filename ?? ""); if (cmdFilename !== "") { cmdChunks.push(CmdLoadModuleHeaderChunk.fromFilename(cmdFilename)); } for (const chunk of this.chunks) { cmdChunks.push(CmdLoadBlockChunk.fromData(chunk.loadAddress, chunk.data)); } cmdChunks.push(CmdTransferAddressChunk.fromEntryPointAddress(this.entryPointAddress)); const binary = encodeCmdProgram(cmdChunks); return new CmdProgram(binary, undefined, [], cmdChunks, this.filename, this.entryPointAddress); } /** * Create a new system program just like this one, but with the specified entry point address. * @param entryPointAddress */ public withEntryPointAddress(entryPointAddress: number): SystemProgram { return new SystemProgram(encodeSystemProgram(this.filename, this.chunks, entryPointAddress), this.error, this.filename, this.chunks, entryPointAddress, this.annotations); } } /** * Decodes a system program from the binary. If the binary is not at all a system * program, returns undefined. If it's a system program with decoding errors, returns * partially-decoded binary and sets the "error" field. */ export function decodeSystemProgram(binary: Uint8Array): SystemProgram | undefined { const chunks: SystemChunk[] = []; const annotations: ProgramAnnotation[] = []; let entryPointAddress = 0; const b = new ByteReader(binary); const headerByte = b.read(); if (headerByte === EOF) { return undefined; } if (headerByte !== FILE_HEADER) { return undefined; } annotations.push(new ProgramAnnotation("System file header", b.addr() - 1, b.addr())); let filename = b.readString(FILENAME_LENGTH); // Make a SystemProgram object with what we have so far. const makeSystemProgram = (error?: string) => { const programBinary = binary.subarray(0, b.addr()); return new SystemProgram(programBinary, error, filename, chunks, entryPointAddress, annotations); }; if (filename.length < FILENAME_LENGTH) { // Binary is truncated. return makeSystemProgram("File is truncated at filename"); } filename = filename.trim(); annotations.push(new ProgramAnnotation(`Filename "${filename}"`, b.addr() - FILENAME_LENGTH, b.addr())); while (true) { const marker = b.read(); if (marker === EOF) { return makeSystemProgram("File is truncated at start of block"); } if (marker === END_OF_FILE_MARKER) { annotations.push(new ProgramAnnotation("End of file marker", b.addr() - 1, b.addr())); break; } if (marker !== DATA_HEADER) { // Here if the marker is 0x55, we could guess that it's a high-speed cassette header. return makeSystemProgram("Unexpected byte " + toHexByte(marker) + " at start of block"); } annotations.push(new ProgramAnnotation("Data chunk marker", b.addr() - 1, b.addr())); let length = b.read(); if (length === EOF) { return makeSystemProgram("File is truncated at block length"); } // 0 means 256. if (length === 0) { length = 256; } annotations.push(new ProgramAnnotation(`Length (${length} byte${length === 1 ? "" : "s"})`, b.addr() - 1, b.addr())); const loadAddress = b.readShort(false); if (loadAddress === EOF) { return makeSystemProgram("File is truncated at load address"); } annotations.push(new ProgramAnnotation(`Address (0x${toHexWord(loadAddress)})`, b.addr() - 2, b.addr())); const dataStartAddr = b.addr(); const data = b.readBytes(length); if (data.length < length) { return makeSystemProgram("File is truncated at data"); } annotations.push(new ProgramAnnotation(`Chunk data`, dataStartAddr, b.addr())); const checksum = b.read(); if (loadAddress === EOF) { return makeSystemProgram("File is truncated at checksum"); } const systemChunk = new SystemChunk(loadAddress, data, checksum); chunks.push(systemChunk); annotations.push(new ProgramAnnotation( `Checksum (0x${toHexByte(checksum)}, ${systemChunk.isChecksumValid() ? "" : "in"}valid)`, b.addr() - 1, b.addr())); } entryPointAddress = b.readShort(false); if (entryPointAddress === EOF) { entryPointAddress = 0; return makeSystemProgram("File is truncated at entry point address"); } annotations.push(new ProgramAnnotation(`Jump address (0x${toHexWord(entryPointAddress)})`, b.addr() - 2, b.addr())); return makeSystemProgram(); } /** * Return a filename that can fit into a system program. The returned string is not padded. */ function clipSystemProgramFilename(filename: string): string { return filename.slice(0, FILENAME_LENGTH); } /** * Generate a binary for the specified parts of a system program. * @param filename a six-character max filename, preferably in upper case. * @param chunks a list of chunks to load into memory. * @param entryPointAddress where to launch the program. */ export function encodeSystemProgram(filename: string, chunks: SystemChunk[], entryPointAddress: number): Uint8Array { const binaryParts: Uint8Array[] = []; binaryParts.push(new Uint8Array([FILE_HEADER])); filename = clipSystemProgramFilename(filename).toUpperCase(); filename = filename.padEnd(FILENAME_LENGTH, " "); binaryParts.push(new TextEncoder().encode(filename)); for (const chunk of chunks) { let length = chunk.data.length; if (length === 256) { length = 0; } binaryParts.push(new Uint8Array([DATA_HEADER, length, lo(chunk.loadAddress), hi(chunk.loadAddress), ... chunk.data, chunk.checksum])); } binaryParts.push(new Uint8Array([END_OF_FILE_MARKER, lo(entryPointAddress), hi(entryPointAddress)])); return concatByteArrays(binaryParts); } /** * Builds a system program from chunks of memory. */ export class SystemProgramBuilder extends ProgramBuilder { /** * Get system chunks for the bytes given so far. */ public getChunks(): SystemChunk[] { // Sort blocks by address. this.blocks.sort((a, b) => a.address - b.address); return this.blocks .flatMap(block => block.breakInto(MAX_SYSTEM_CHUNK_DATA_SIZE)) .map(block => new SystemChunk(block.address, new Uint8Array(block.bytes))); } }
the_stack
import type { MaybeTDN, MaybeVariables, Data, Variables, ComponentDocument, OptimisticResponseType, RefetchQueriesType, MutationUpdaterFn, } from '@apollo-elements/core/types'; import type { PropertyValues } from 'lit'; import type { FetchResult, MutationOptions, ErrorPolicy, } from '@apollo/client/core'; import { GraphQLScriptChildMixin } from '@apollo-elements/mixins/graphql-script-child-mixin'; import { ApolloElement } from './apollo-element.js'; import { ApolloMutationController } from '@apollo-elements/core/apollo-mutation-controller'; import { controlled } from '@apollo-elements/core/decorators'; import { customElement, state, property } from '@lit/reactive-element/decorators.js'; import { isEmpty } from '@apollo-elements/core/lib/helpers'; import { bound } from '@apollo-elements/core/lib/bound'; import { MutationCompletedEvent, MutationErrorEvent, WillMutateEvent, WillNavigateEvent, } from './events.js'; declare global { interface HTMLElementTagNameMap { 'apollo-mutation': ApolloMutationElement } } /** @noInheritDoc */ interface ButtonLikeElement extends HTMLElement { disabled: boolean; } /** @noInheritDoc */ interface InputLikeElement extends HTMLElement { value: string; disabled: boolean; } /** @ignore */ export class WillMutateError extends Error {} const defaultTemplate = document.createElement('template'); defaultTemplate.innerHTML = `<slot></slot>`; /** * Simple Mutation component that takes a button or link-wrapped button as it's trigger. * When loading, it disables the button. * On error, it toasts a snackbar with the error message. * You can pass a `variables` object property, * or if all your variables properties are strings, * you can use the element's data attributes * * See [`ApolloMutationInterface`](https://apolloelements.dev/api/core/interfaces/mutation) for more information on events * * @fires {WillMutateEvent} will-mutate - The element is about to mutate. Useful for setting variables. Prevent default to prevent mutation. Detail is `{ element: this }` * @fires {WillNavigateEvent} will-navigate - The mutation resolved and the element is about to navigate. cancel the event to handle navigation yourself e.g. using a client-side router. . `detail` is `{ data: Data, element: this }` * @fires {MutationCompletedEvent} mutation-completed - The mutation resolves. `detail` is `{ data: Data, element: this }` * @fires {MutationErrorEvent} mutation-error - The mutation rejected. `detail` is `{ error: ApolloError, element: this }` * @fires {ApolloElementEvent} apollo-element-disconnected - The element disconnected from the DOM * @fires {ApolloElementEvent} apollo-element-connected - The element connected to the DOM * * @slot - Mutations typically trigger when clicking a button. * Slot in an element with a `trigger` attribute to assign it as the element's trigger. * The triggering element. Must be a button or and anchor that wraps a button. * * You may also slot in input elements with the `data-variable="variableName"` attribute. * It's `value` property gets the value for the corresponding variable. * * @example <caption>Using data attributes</caption> * ```html * <apollo-mutation data-type="Type" data-action="ACTION"> * <mwc-button trigger>OK</mwc-button> * </apollo-mutation> * ``` * Will mutate with the following as `variables`: * ```json * { * "type": "Type", * "action": "ACTION" * } * ``` * * @example <caption>Using data attributes and variables</caption> * ```html * <apollo-mutation data-type="Quote" data-action="FLUB"> * <mwc-button trigger label="OK"></mwc-button> * <mwc-textfield * data-variable="name" * value="Neil" * label="Name"></mwc-textfield> * <mwc-textarea * data-variable="comment" * value="That's one small step..." * label="comment"></mwc-textarea> * </apollo-mutation> * ``` * Will mutate with the following as `variables`: * ```json * { * "name": "Neil", * "comment": "That's one small step...", * "type": "Quote", * "action": "FLUB" * } * ``` * * @example <caption>Using variable-for inputs</caption> * ```html * <label>Comment <input variable-for="comment-mutation" value="Hey!"></label> * <button trigger-for="comment-mutation">OK</button> * <apollo-mutation id="comment-mutation"></apollo-mutation> * ``` * Will mutate with the following as `variables`: * ```json * { "comment": "Hey!" } * ``` * * @example <caption>Using data attributes and variables with input property</caption> * ```html * <apollo-mutation data-type="Type" data-action="ACTION" input-key="actionInput"> * <mwc-button trigger label="OK"></mwc-button> * <mwc-textfield * data-variable="comment" * value="Hey!" * label="comment"></mwc-textfield> * </apollo-mutation> * ``` * Will mutate with the following as `variables`: * ```json * { * "actionInput": { * "comment": "Hey!", * "type": "Type", * "action": "ACTION" * } * } * ``` * * @example <caption>Using DOM properties</caption> * ```html * <apollo-mutation id="mutation"> * <mwc-button trigger label="OK"></mwc-button> * </apollo-mutation> * <script> * document.getElementById('mutation').mutation = SomeMutation; * document.getElementById('mutation').variables = { * type: "Type", * action: "ACTION" * }; * </script> * ``` * * Will mutate with the following as `variables`: * * ```json * { * "type": "Type", * "action": "ACTION" * } * ``` */ @customElement('apollo-mutation') export class ApolloMutationElement<D extends MaybeTDN = MaybeTDN, V = MaybeVariables<D>> extends GraphQLScriptChildMixin(ApolloElement)<D, V> { static readonly is: 'apollo-mutation' = 'apollo-mutation'; /** * False when the element is a link. */ private static isButton(node: Element|null): node is ButtonLikeElement { return !!node && node.tagName !== 'A'; } private static isLink(node: Element|null): node is HTMLAnchorElement { return node instanceof HTMLAnchorElement; } private static toVariables<T>(acc: T, element: InputLikeElement): T { // querySelectorAll ensures the data-variable attr exists // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return { ...acc, [element.dataset.variable!]: element.value }; } private static isTriggerNode(node: Node): node is HTMLElement { return node instanceof HTMLElement && node.hasAttribute('trigger'); } private static debounce(f: () => void, timeout: number): () => void { let timer: number; return () => { clearTimeout(timer); timer = window.setTimeout(() => { f(); }, timeout); }; } private inFlightTrigger: HTMLElement | null = null; private doMutate = (): void => void (this.mutate().catch(() => void 0)); private debouncedMutate = this.doMutate; #buttonMO?: MutationObserver; #listeners = new WeakMap<Element, string>(); get #root(): ShadowRoot | Document | DocumentFragment | null { const root = this.getRootNode(); if (root instanceof ShadowRoot || root instanceof Document || root instanceof DocumentFragment) return root; else return null; } /** * Variable input nodes */ protected get inputs(): InputLikeElement[] { const forInputs = (this.id && this.#root ? Array.from(this.#root.querySelectorAll(`[variable-for="${this.id}"]`)) : []) as InputLikeElement[]; return forInputs.concat(Array.from(this.querySelectorAll<InputLikeElement>('[data-variable]'))); } /** * Slotted trigger nodes */ protected get triggers(): Element[] { const forTriggers = (this.id && this.#root) ? this.#root.querySelectorAll(`[trigger-for="${this.id}"]`) : []; return Array.from(forTriggers).concat(Array.from(this.querySelectorAll('[trigger]'))); } /** * If the slotted trigger node is a button, the trigger * If the slotted trigger node is a link with a button as it's first child, the button */ protected get buttons(): ButtonLikeElement[] { const { isButton, isLink } = ApolloMutationElement; return this.triggers.map(x => { if (isLink(x) && isButton(x.firstElementChild)) /* c8 ignore next 3 */ return x.firstElementChild; else return x; }).filter(isButton); } get template(): HTMLTemplateElement { return super.template ?? defaultTemplate; } controller: ApolloMutationController<D, V> = new ApolloMutationController<D, V>(this, null, { onCompleted: data => { const trigger = this.inFlightTrigger; this.didMutate(); this.dispatchEvent(new MutationCompletedEvent<D, V>(this)); if (ApolloMutationElement.isLink(trigger) || trigger?.closest?.('a[trigger]')) this.willNavigate(data, trigger); }, onError: () => { this.didMutate(); this.dispatchEvent(new MutationErrorEvent<D, V>(this)); }, }); /** * When set, variable data attributes will be packed into an * object property with the name of this property * @example <caption>Using the input-key attribute</caption> * ```html * <apollo-mutation id="a" data-variable="var"></apollo-mutation> * <apollo-mutation id="b" input-key="input" data-variable="var"></apollo-mutation> * <script> * console.log(a.variables) // { variable: 'var' } * console.log(b.variables) // { input: { variable: 'var' } } * </script> * ``` * @summary key to wrap variables in e.g. `input`. */ @property({ attribute: 'input-key', reflect: true }) inputKey: string|null = null; /** * @summary Optional number of milliseconds to wait between calls */ @property({ type: Number, reflect: true }) debounce: number | null = null; /** * @summary Whether the mutation was called */ @controlled() @property({ type: Boolean, reflect: true }) called = false; /** @summary The mutation. */ @controlled() @state() mutation: null | ComponentDocument<D> = null; /** @summary Context passed to the link execution chain. */ @controlled({ path: 'options' }) @state() context?: Record<string, unknown>; /** * An object that represents the result of this mutation that will be optimistically * stored before the server has actually returned a result, or a unary function that * takes the mutation's variables and returns such an object. * * This is most often used for optimistic UI, where we want to be able to see * the result of a mutation immediately, and update the UI later if any errors * appear. * @example <caption>Using a function</caption> * ```ts * element.optimisticResponse = ({ name }: HelloMutationVariables) => ({ * __typename: 'Mutation', * hello: { * __typename: 'Greeting', * name, * }, * }); * ``` */ @controlled({ path: 'options' }) @state() optimisticResponse?: OptimisticResponseType<D, V>; /** * An object that maps from the name of a variable as used in the mutation GraphQL document to that variable's value. * * @summary Mutation variables. */ @controlled() @state() variables: Variables<D, V> | null = null; /** * @summary If true, the returned data property will not update with the mutation result. */ @controlled({ path: 'options' }) @property({ attribute: 'ignore-results', type: Boolean }) ignoreResults = false; /** * Queries refetched as part of refetchQueries are handled asynchronously, * and are not waited on before the mutation is completed (resolved). * Setting this to true will make sure refetched queries are completed * before the mutation is considered done. false by default. * @attr await-refetch-queries */ @controlled({ path: 'options' }) @property({ attribute: 'await-refetch-queries', type: Boolean }) awaitRefetchQueries = false; /** * Specifies the ErrorPolicy to be used for this mutation. * @attr error-policy */ @controlled({ path: 'options' }) @property({ attribute: 'error-policy' }) errorPolicy?: ErrorPolicy; /** * Specifies the FetchPolicy to be used for this mutation. * @attr fetch-policy */ @controlled({ path: 'options' }) @property({ attribute: 'fetch-policy' }) fetchPolicy?: 'no-cache'; /** * A list of query names which will be refetched once this mutation has returned. * This is often used if you have a set of queries which may be affected by a mutation and will have to update. * Rather than writing a mutation query reducer (i.e. `updateQueries`) for this, * you can refetch the queries that will be affected * and achieve a consistent store once these queries return. * @attr refetch-queries */ @controlled({ path: 'options' }) @property({ attribute: 'refetch-queries', converter: { fromAttribute(newVal) { return !newVal ? null : newVal .split(',') .map(x => x.trim()); }, }, }) refetchQueries: RefetchQueriesType<D> | null = null; /** * Define this function to determine the URL to navigate to after a mutation. * Function can be synchronous or async. * If this function is not defined, will navigate to the `href` property of the link trigger. * @example <caption>Navigate to a post's page after creating it</caption> * ```html * <apollo-mutation id="mutation"> * <script type="application/graphql"> * mutation CreatePostMutation($title: String, $content: String) { * createPost(title: $title, content: $content) { * slug * } * } * </script> * <mwc-textfield label="Post title" data-variable="title"></mwc-textfield> * <mwc-textarea label="Post Content" data-variable="content"></mwc-textarea> * </apollo-mutation> * * <script> * document.getElementById('mutation').resolveURL = * data => `/posts/${data.createPost.slug}/`; * </script> * ``` * @param data mutation data * @param trigger the trigger element which triggered this mutation * @returns url to navigate to */ resolveURL?(data: Data<D>, trigger: HTMLElement): string | Promise<string>; constructor() { super(); // eslint-disable-next-line @typescript-eslint/no-this-alias const el = this; Object.defineProperty(this.controller, 'variables', { get(): Variables<D, V> | null { if (this.__variables) return this.__variables; else { return ( el.getVariablesFromInputs() ?? // @ts-expect-error: TODO: Find a better way to do this el.getDOMVariables() as Variables<D, V> ); } }, set(v: Variables<D, V> | null) { this.__variables = v ?? undefined; }, }); this.onSlotchange(); } private onLightDomMutation(records: MutationRecord[]) { /* eslint-disable easy-loops/easy-loops */ for (const record of records) { for (const node of record.removedNodes as NodeListOf<HTMLElement>) { const type = this.#listeners.get(node); if (type == null) return; /* c8 ignore next */ node.removeEventListener(type, this.onTriggerEvent); this.#listeners.delete(node); } for (const node of record.addedNodes) { if (ApolloMutationElement.isTriggerNode(node)) this.addTriggerListener(node); } } /* eslint-enable easy-loops/easy-loops */ } private onSlotchange(): void { for (const button of this.buttons) this.addTriggerListener(button); for (const trigger of this.triggers) this.addTriggerListener(trigger); } private addTriggerListener(element: Element) { const eventType = element?.getAttribute?.('trigger') || 'click'; if ( !this.#listeners.has(element) && element.hasAttribute('trigger') || !element.closest('[trigger]') ) { element.addEventListener(eventType, this.onTriggerEvent, { passive: element.hasAttribute('passive'), }); this.#listeners.set(element, eventType); } } private willMutate(trigger: HTMLElement): void { if (!this.dispatchEvent(new WillMutateEvent<D, V>(this))) throw new WillMutateError('mutation was canceled'); this.inFlightTrigger = trigger; for (const button of this.buttons) button.disabled = true; for (const input of this.inputs) input.disabled = true; } private async willNavigate( data: Data<D>|null|undefined, triggeringElement: HTMLElement ): Promise<void> { if (!this.dispatchEvent(new WillNavigateEvent(this))) return; const href = triggeringElement.closest<HTMLAnchorElement>('a[trigger]')?.href; const url = typeof this.resolveURL !== 'function' ? href // If we get here without `data`, it's due to user error : await this.resolveURL(this.data!, triggeringElement); // eslint-disable-line @typescript-eslint/no-non-null-assertion history.replaceState(data, WillNavigateEvent.type, url); } private didMutate(): void { this.inFlightTrigger = null; for (const button of this.buttons) button.disabled = false; for (const input of this.inputs) input.disabled = false; } @bound private onTriggerEvent(event: Event): void { event.preventDefault(); if (this.inFlightTrigger) return; try { this.willMutate(event.target as HTMLElement); } catch (e) { return; } this.debouncedMutate(); } protected createRenderRoot(): ShadowRoot|HTMLElement { if (this.hasAttribute('no-shadow')) { const root = this.appendChild(document.createElement('div')); root.classList.add(this.getAttribute('no-shadow') || 'output'); this.#buttonMO = new MutationObserver(records => this.onLightDomMutation(records)); this.#buttonMO.observe(this, { childList: true, attributes: false, characterData: false }); return root; } else return super.createRenderRoot(); } /** * Constructs a variables object from the element's data-attributes and any slotted variable inputs. */ protected getVariablesFromInputs(): Variables<D, V> | null { if (isEmpty(this.dataset) && isEmpty(this.inputs)) return null; const input = { ...this.dataset, ...this.inputs.reduce(ApolloMutationElement.toVariables, {}), }; if (this.inputKey) return { [this.inputKey]: input } as unknown as Variables<D, V>; else return input as Variables<D, V>; } update(changed: PropertyValues<this>): void { if (changed.has('debounce')) { this.debouncedMutate = this.debounce == null ? this.doMutate : ApolloMutationElement.debounce(this.doMutate, this.debounce); } super.update(changed); } /** * A function which updates the apollo cache when the query responds. * This function will be called twice over the lifecycle of a mutation. * Once at the very beginning if an optimisticResponse was provided. * The writes created from the optimistic data will be rolled back before * the second time this function is called which is when the mutation has * succesfully resolved. At that point update will be called with the actual * mutation result and those writes will not be rolled back. * * The reason a DataProxy is provided instead of the user calling the methods * directly on ApolloClient is that all of the writes are batched together at * the end of the update, and it allows for writes generated by optimistic * data to be rolled back. */ public updater?( ...params: Parameters<MutationUpdaterFn<Data<D>, Variables<D, V>>> ): ReturnType<MutationUpdaterFn<Data<D>, Variables<D, V>>>; public mutate( params?: Partial<MutationOptions<Data<D>, Variables<D, V>>> ): Promise<FetchResult<Data<D>>> { return this.controller.mutate({ ...params, update: this.updater }); } }
the_stack
import { applierAction, applierContext, applierQuery, AttributeContextParameters, AttributeResolutionApplier, AttributeResolutionApplierCapabilities, CdmAttributeContext, cdmAttributeContextType, CdmAttributeResolutionGuidance, PrimitiveAppliers, relationshipInfo, ResolvedAttribute, ResolvedAttributeSet, ResolvedTraitSet, resolveOptions } from '../internal'; export class AttributeResolutionContext { public actionsModify: AttributeResolutionApplier[]; public actionsGroupAdd: AttributeResolutionApplier[]; public actionsRoundAdd: AttributeResolutionApplier[]; public actionsAttributeAdd: AttributeResolutionApplier[]; public actionsRemove: AttributeResolutionApplier[]; /** * @internal */ public traitsToApply: ResolvedTraitSet; /** * @internal */ public applierCaps: AttributeResolutionApplierCapabilities; public resGuide: CdmAttributeResolutionGuidance; public resOpt: resolveOptions; constructor(resOpt: resolveOptions, resGuide: CdmAttributeResolutionGuidance, traits: ResolvedTraitSet) { // collect a set of appliers for all traits this.traitsToApply = traits; this.resGuide = resGuide; this.resOpt = resOpt; this.actionsModify = []; this.actionsGroupAdd = []; this.actionsRoundAdd = []; this.actionsAttributeAdd = []; this.actionsRemove = []; this.applierCaps = undefined; this.resOpt = resOpt.copy(); if (resGuide) { if (!this.applierCaps) { this.applierCaps = { canAlterDirectives: false, canCreateContext: false, canRemove: false, canAttributeModify: false, canGroupAdd: false, canRoundAdd: false, canAttributeAdd: false }; } const addApplier = (apl: AttributeResolutionApplier): boolean => { // Collect the code that will perform the right action. // Associate with the resolved trait and get the priority if (apl.willAttributeModify && apl.doAttributeModify) { this.actionsModify.push(apl); this.applierCaps.canAttributeModify = true; } if (apl.willAttributeAdd && apl.doAttributeAdd) { this.actionsAttributeAdd.push(apl); this.applierCaps.canAttributeAdd = true; } if (apl.willGroupAdd && apl.doGroupAdd) { this.actionsGroupAdd.push(apl); this.applierCaps.canGroupAdd = true; } if (apl.willRoundAdd && apl.doRoundAdd) { this.actionsRoundAdd.push(apl); this.applierCaps.canRoundAdd = true; } if (apl.willAlterDirectives && apl.doAlterDirectives) { this.applierCaps.canAlterDirectives = true; apl.doAlterDirectives(this.resOpt, resGuide); } if (apl.willCreateContext && apl.doCreateContext) { this.applierCaps.canCreateContext = true; } if (apl.willRemove) { this.actionsRemove.push(apl); this.applierCaps.canRemove = true; } return true; }; if (resGuide.removeAttribute) { addApplier(PrimitiveAppliers.isRemoved); } if (resGuide.imposedDirectives) { addApplier(PrimitiveAppliers.doesImposeDirectives); } if (resGuide.removedDirectives) { addApplier(PrimitiveAppliers.doesRemoveDirectives); } if (resGuide.addSupportingAttribute) { addApplier(PrimitiveAppliers.doesAddSupportingAttribute); } if (resGuide.renameFormat) { addApplier(PrimitiveAppliers.doesDisambiguateNames); } if (resGuide.cardinality === 'many') { addApplier(PrimitiveAppliers.doesExplainArray); } if (resGuide.entityByReference) { addApplier(PrimitiveAppliers.doesReferenceEntityVia); } if (resGuide.selectsSubAttribute && resGuide.selectsSubAttribute.selects === 'one') { addApplier(PrimitiveAppliers.doesSelectAttributes); } // sorted by priority this.actionsModify = this.actionsModify.sort( (lhs: AttributeResolutionApplier, rhs: AttributeResolutionApplier) => lhs.priority - rhs.priority); this.actionsGroupAdd = this.actionsGroupAdd.sort( (lhs: AttributeResolutionApplier, rhs: AttributeResolutionApplier) => lhs.priority - rhs.priority); this.actionsRoundAdd = this.actionsRoundAdd.sort( (lhs: AttributeResolutionApplier, rhs: AttributeResolutionApplier) => lhs.priority - rhs.priority); this.actionsAttributeAdd = this.actionsAttributeAdd.sort( (lhs: AttributeResolutionApplier, rhs: AttributeResolutionApplier) => lhs.priority - rhs.priority); } } /** * Returns a RelationshipInfo instance containing information about how the entity attribute relationship should be resolved * @param resOpt * @param arc * @internal */ public getRelationshipInfo(): relationshipInfo { let hasRef: boolean = false; let isByRef: boolean = false; let isArray: boolean = false; let selectsOne: boolean = false; let maxDepthExceeded: boolean = this.resOpt.depthInfo.maxDepthExceeded; if (this.resGuide) { if (this.resGuide.entityByReference !== undefined && this.resGuide.entityByReference.allowReference === true) { hasRef = true; } if (this.resOpt.directives) { // based on directives if (hasRef) { isByRef = this.resOpt.directives.has('referenceOnly'); } selectsOne = this.resOpt.directives.has('selectOne'); isArray = this.resOpt.directives.has('isArray'); } if (!selectsOne && maxDepthExceeded) { // if max depth exceeded, stop and resolve by reference isByRef = true; } } return { isByRef: isByRef, isArray: isArray, selectsOne: selectsOne }; } } /** * @internal */ export class ResolvedAttributeSetBuilder { /** * @internal */ public ras: ResolvedAttributeSet; public inheritedMark: number; constructor() { this.ras = new ResolvedAttributeSet(); } /** * @internal */ public mergeAttributes(rasNew: ResolvedAttributeSet): void { // let bodyCode = () => { if (rasNew) { this.takeReference(this.ras.mergeSet(rasNew)); if (rasNew.depthTraveled > this.ras.depthTraveled) { this.ras.depthTraveled = rasNew.depthTraveled; } } } // return p.measure(bodyCode); } /** * @internal */ public takeReference(rasNew: ResolvedAttributeSet): void { // let bodyCode = () => { if (this.ras !== rasNew) { if (rasNew) { rasNew.addRef(); } if (this.ras) { this.ras.release(); } this.ras = rasNew; } } // return p.measure(bodyCode); } /** * @internal */ public giveReference(): ResolvedAttributeSet { const rasRef: ResolvedAttributeSet = this.ras; if (this.ras) { this.ras.release(); if (this.ras.refCnt === 0) { this.ras = undefined; } } return rasRef; } /** * @internal */ public ownOne(ra: ResolvedAttribute): void { // let bodyCode = () => { // save the current context const attCtx: CdmAttributeContext = this.ras.attributeContext; this.takeReference(new ResolvedAttributeSet()); this.ras.merge(ra); // reapply the old attribute context this.ras.setAttributeContext(attCtx); } // return p.measure(bodyCode); } public applyTraits(arc: AttributeResolutionContext): void { // let bodyCode = () => { if (this.ras && arc && arc.traitsToApply) { this.takeReference(this.ras.applyTraitsResolutionGuidance(arc.traitsToApply, arc.resOpt, arc.resGuide, arc.actionsModify)); } } // return p.measure(bodyCode); } public generateApplierAttributes(arc: AttributeResolutionContext, applyTraitsToNew: boolean): void { // let bodyCode = () => { if (!arc || !arc.applierCaps) { return; } if (!this.ras) { this.takeReference(new ResolvedAttributeSet()); } // make sure all of the 'source' attributes know about this context const set: ResolvedAttribute[] = this.ras.set; if (set) { const l: number = set.length; for (let i: number = 0; i < l; i++) { set[i].arc = arc; } // the resolution guidance may be asking for a one time 'take' or avoid of attributes from the source // this also can re-order the attributes if (arc.resGuide && arc.resGuide.selectsSubAttribute && arc.resGuide.selectsSubAttribute.selects === 'some' && (arc.resGuide.selectsSubAttribute.selectsSomeTakeNames || arc.resGuide.selectsSubAttribute.selectsSomeAvoidNames)) { // we will make a new resolved attribute set from the 'take' list const takeSet: ResolvedAttribute[] = []; const selectsSomeTakeNames: string[] = arc.resGuide.selectsSubAttribute.selectsSomeTakeNames; const selectsSomeAvoidNames: string[] = arc.resGuide.selectsSubAttribute.selectsSomeAvoidNames; if (selectsSomeTakeNames && !selectsSomeAvoidNames) { // make an index that goes from name to insertion order const inverted: Map<string, number> = new Map<string, number>(); for (let iOrder: number = 0; iOrder < l; iOrder++) { inverted.set(set[iOrder].resolvedName, iOrder); } for (const take of selectsSomeTakeNames) { // if in the original set of attributes, take it in the new order if (inverted.has(take)) { takeSet.push(set[inverted.get(take)]); } } } if (selectsSomeAvoidNames) { // make a quick look up of avoid names const avoid: Set<string> = new Set<string>(); for (const avoidName of selectsSomeAvoidNames) { avoid.add(avoidName); } for (let iAtt: number = 0; iAtt < l; iAtt++) { // only take the ones not in avoid the list given if (!avoid.has(set[iAtt].resolvedName)) { takeSet.push(set[iAtt]); } } } // replace the guts of the resolvedAttributeSet with this this.ras.alterSetOrderAndScope(takeSet); } } // get the new atts and then add them one at a time into this set const newAtts: ResolvedAttribute[] = this.getApplierGeneratedAttributes(arc, true, applyTraitsToNew); if (newAtts) { const l: number = newAtts.length; let ras: ResolvedAttributeSet = this.ras; for (let i: number = 0; i < l; i++) { // here we want the context that was created in the appliers ras = ras.merge(newAtts[i]); } this.takeReference(ras); } } // return p.measure(bodyCode); } public removeRequestedAtts(): void { // let bodyCode = () => { if (this.ras) { const marker: [number, number] = [0, 0]; marker['1'] = this.inheritedMark; this.takeReference(this.ras.removeRequestedAtts(marker)); this.inheritedMark = marker['1']; } } // return p.measure(bodyCode); } public markInherited(): void { // let bodyCode = () => { if (this.ras && this.ras.set) { this.inheritedMark = this.ras.set.length; const countSet: (rasSub: ResolvedAttributeSet, offset: number) => number = (rasSub: ResolvedAttributeSet, offset: number): number => { let last: number = offset; if (rasSub && rasSub.set) { for (const resolvedSet of rasSub.set) { if ((resolvedSet.target as ResolvedAttributeSet).set) { last = countSet((resolvedSet.target as ResolvedAttributeSet), last); } else { last++; } } } return last; }; this.inheritedMark = countSet(this.ras, 0); } else { this.inheritedMark = 0; } } // return p.measure(bodyCode); } public markOrder(): void { // let bodyCode = () => { const markSet: (rasSub: ResolvedAttributeSet, inheritedMark: number, offset: number) => number = (rasSub: ResolvedAttributeSet, inheritedMark: number, offset: number): number => { let last: number = offset; if (rasSub && rasSub.set) { rasSub.insertOrder = last; for (const resolvedSet of rasSub.set) { if ((resolvedSet.target as ResolvedAttributeSet).set) { last = markSet((resolvedSet.target as ResolvedAttributeSet), inheritedMark, last); } else { if (last >= inheritedMark) { resolvedSet.insertOrder = last; } last++; } } } return last; }; markSet(this.ras, this.inheritedMark, 0); } // return p.measure(bodyCode); } // tslint:disable-next-line: max-func-body-length private getApplierGeneratedAttributes( arc: AttributeResolutionContext, clearState: boolean, applyModifiers: boolean): ResolvedAttribute[] { // let bodyCode = () => { if (!this.ras || !this.ras.set) { return undefined; } if (!arc || !arc.applierCaps) { return undefined; } const caps: AttributeResolutionApplierCapabilities = arc.applierCaps; if (!(caps.canAttributeAdd || caps.canGroupAdd || caps.canRoundAdd)) { return undefined; } const resAttOut: (ResolvedAttribute)[] = []; // this function constructs a 'plan' for building up the resolved attributes // that get generated from a set of traits being applied to a set of attributes. // it manifests the plan into an array of resolved attributes there are a few levels of hierarchy to consider. // 1. once per set of attributes, the traits may want to generate attributes. // this is an attribute that is somehow descriptive of the whole set, // even if it has repeating patterns, like the count for an expanded array. // 2. it is possible that some traits (like the array expander) want to keep generating new attributes for some run. // each time they do this is considered a 'round'the traits are given a chance to generate attributes once per round. // every set gets at least one round, so these should be the attributes that describe the set of other attributes. // for example, the foreign key of a relationship or the 'class' of a polymorphic type, etc. // 3. for each round, there are new attributes created based on the resolved attributes from the // previous round(or the starting atts for this set) the previous round attribute need to be 'done' // having traits applied before they are used as sources for the current round. // the goal here is to process each attribute completely before moving on to the next one // that may need to start out clean if (clearState) { const toClear: ResolvedAttribute[] = this.ras.set; const l: number = toClear.length; for (let i: number = 0; i < l; i++) { toClear[i].applierState = undefined; } } // make an attribute context to hold attributes that are generated from appliers // there is a context for the entire set and one for each 'round' of applications that happen let attCtxContainerGroup: CdmAttributeContext = this.ras.attributeContext; if (attCtxContainerGroup) { const acp: AttributeContextParameters = { under: attCtxContainerGroup, type: cdmAttributeContextType.generatedSet, name: '_generatedAttributeSet' }; attCtxContainerGroup = CdmAttributeContext.createChildUnder(arc.resOpt, acp); } let attCtxContainer: CdmAttributeContext = attCtxContainerGroup; const makeResolvedAttribute: ( resAttSource: ResolvedAttribute, action: AttributeResolutionApplier, queryAdd: applierQuery, doAdd: applierAction, state: string) => applierContext = (resAttSource: ResolvedAttribute, action: AttributeResolutionApplier, queryAdd: applierQuery, doAdd: applierAction, state: string): applierContext => { const appCtx: applierContext = { state: state, resOpt: arc.resOpt, attCtx: attCtxContainer, resAttSource: resAttSource, resGuide: arc.resGuide }; if (resAttSource && resAttSource.target && (resAttSource.target as ResolvedAttributeSet).set) { return appCtx; } // makes no sense for a group // will something add? if (queryAdd(appCtx)) { // may want to make a new attribute group // make the 'new' attribute look like any source attribute // for the duration of this call to make a context. there could be state needed appCtx.resAttNew = resAttSource; if (this.ras.attributeContext && action.willCreateContext && action.willCreateContext(appCtx)) { action.doCreateContext(appCtx); } // make a new resolved attribute as a place to hold results appCtx.resAttNew = new ResolvedAttribute(appCtx.resOpt, undefined, undefined, appCtx.attCtx); // copy state from source appCtx.resAttNew.applierState = {}; if (resAttSource && resAttSource.applierState) { Object.assign(appCtx.resAttNew.applierState, resAttSource.applierState); } // if applying traits, then add the sets traits as a staring point if (applyModifiers) { appCtx.resAttNew.resolvedTraits = arc.traitsToApply.deepCopy(); } // make it doAdd(appCtx); // combine resolution guidence for this set with anything new from the new attribute // tslint:disable-next-line: max-line-length appCtx.resGuideNew = (appCtx.resGuide).combineResolutionGuidance(appCtx.resGuideNew); appCtx.resAttNew.arc = new AttributeResolutionContext(arc.resOpt, appCtx.resGuideNew, appCtx.resAttNew.resolvedTraits); if (applyModifiers) { // add the sets traits back in to this newly added one appCtx.resAttNew.resolvedTraits = appCtx.resAttNew.resolvedTraits.mergeSet(arc.traitsToApply); // be sure to use the new arc, the new attribute may have added actions. For now, only modify and remove will get acted on because recursion. ugh. // do all of the modify traits if (appCtx.resAttNew.arc.applierCaps.canAttributeModify) { // modify acts on the source and we should be done with it appCtx.resAttSource = appCtx.resAttNew; } for (const modAct of appCtx.resAttNew.arc.actionsModify) { // using a new trait now //appCtx.resTrait = modAct.rt; if (modAct.willAttributeModify(appCtx)) { modAct.doAttributeModify(appCtx); } } } appCtx.resAttNew.completeContext(appCtx.resOpt); // tie this new resolved att to the source via lineage if (appCtx.resAttNew.attCtx && resAttSource && resAttSource.attCtx && (!resAttSource.applierState || !resAttSource.applierState.flex_remove)) { if (resAttSource.attCtx.lineage && resAttSource.attCtx.lineage.length > 0) { for (const lineage of resAttSource.attCtx.lineage) { appCtx.resAttNew.attCtx.addLineage(lineage); } } else { appCtx.resAttNew.attCtx.addLineage(resAttSource.attCtx); } } } return appCtx; }; // get the one time atts if (caps.canGroupAdd) { for (const action of arc.actionsGroupAdd) { const appCtx: applierContext = makeResolvedAttribute(undefined, action, action.willGroupAdd, action.doGroupAdd, 'group'); // save it if (appCtx && appCtx.resAttNew) { resAttOut.push(appCtx.resAttNew); } } } // now starts a repeating pattern of rounds // first step is to get attribute that are descriptions of the round. // do this once and then use them as the first entries in the first set of 'previous' atts for the loop // make an attribute context to hold attributes that are generated from appliers in this round let round: number = 0; if (attCtxContainerGroup) { const acp: AttributeContextParameters = { under: attCtxContainerGroup, type: cdmAttributeContextType.generatedRound, name: '_generatedAttributeRound0' }; attCtxContainer = CdmAttributeContext.createChildUnder(arc.resOpt, acp); } let resAttsLastRound: (ResolvedAttribute)[] = []; if (caps.canRoundAdd) { for (const action of arc.actionsRoundAdd) { const appCtx: applierContext = makeResolvedAttribute(undefined, action, action.willRoundAdd, action.doRoundAdd, 'round'); // save it if (appCtx && appCtx.resAttNew) { // overall list resAttOut.push(appCtx.resAttNew); // previous list resAttsLastRound.push(appCtx.resAttNew); } } } // the first per-round set of attributes is the set owned by this object resAttsLastRound = resAttsLastRound.concat(this.ras.set); // now loop over all of the previous atts until they all say 'stop' if (resAttsLastRound.length) { let continues: number = 0; do { continues = 0; const resAttThisRound: (ResolvedAttribute)[] = []; if (caps.canAttributeAdd) { for (const att of resAttsLastRound) { for (const action of arc.actionsAttributeAdd) { const appCtx: applierContext = makeResolvedAttribute(att, action, action.willAttributeAdd, action.doAttributeAdd, 'detail'); // save it if (appCtx && appCtx.resAttNew) { // overall list resAttOut.push(appCtx.resAttNew); resAttThisRound.push(appCtx.resAttNew); if (appCtx.continue) { continues++; } } } } } resAttsLastRound = resAttThisRound; round++; if (attCtxContainerGroup) { const acp: AttributeContextParameters = { under: attCtxContainerGroup, type: cdmAttributeContextType.generatedRound, name: `_generatedAttributeRound${round}` }; attCtxContainer = CdmAttributeContext.createChildUnder(arc.resOpt, acp); } } while (continues); } return resAttOut; } // return p.measure(bodyCode); } }
the_stack
import sinon from "sinon"; import IDB, { open, execute } from "../../src/adapters/IDB"; import { v4 as uuid4 } from "uuid"; import { StorageProxy } from "../../src/adapters/base"; import { KintoIdObject } from "kinto-http"; import { expectAsyncError } from "../test_utils"; const { expect } = intern.getPlugin("chai"); intern.getPlugin("chai").should(); const { describe, it, before, beforeEach, after, afterEach } = intern.getPlugin("interface.bdd"); /** @test {IDB} */ describe("adapter.IDB", () => { let sandbox: sinon.SinonSandbox, db: IDB<any>; beforeEach(() => { sandbox = sinon.createSandbox(); db = new IDB("test/foo"); return db.clear(); }); afterEach(() => sandbox.restore()); /** @test {IDB#open} */ describe("#open", () => { it("should be fullfilled when a connection is opened", async () => { await db.open(); }); it("should reject on open request error", async () => { const fakeOpenRequest = {} as IDBOpenDBRequest; sandbox.stub(indexedDB, "open").returns(fakeOpenRequest); const db = new IDB("another/db"); const prom = db.open(); fakeOpenRequest.onerror!({ target: { error: new Error("fail") } } as any); await expectAsyncError(() => prom, "fail"); }); }); /** @test {IDB#close} */ describe("#close", () => { it("should be fullfilled when a connection is closed", async () => { await db.close(); }); it("should be fullfilled when no connection has been opened", async () => { db["_db"] = null; await db.close(); }); it("should close an opened connection to the database", async () => { await db.close(); expect(db["_db"]).to.equal(null); }); }); /** @test {IDB#clear} */ describe("#clear", () => { it("should clear the database", async () => { await db.execute((transaction) => { transaction.create({ id: "1" }); transaction.create({ id: "2" }); }); await db.clear(); const list = await db.list(); list.should.have.lengthOf(0); }); it("should isolate records by collection", async () => { const db1 = new IDB("main/tippytop"); const db2 = new IDB("main/tippytop-2"); await db1.open(); await db1.execute((t) => t.create({ id: "1" })); await db1.saveLastModified(42); await db1.close(); await db2.open(); await db2.execute((t) => t.create({ id: "1" })); await db2.execute((t) => t.create({ id: "2" })); await db2.saveLastModified(43); await db2.close(); await db1.clear(); expect(await db1.list()).to.have.length(0); expect(await db1.getLastModified()).to.equal(42); expect(await db2.list()).to.have.length(2); expect(await db2.getLastModified()).to.equal(43); }); it("should reject on transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { callback({ index() { return { openKeyCursor() { throw new Error("transaction error"); }, }; }, } as any); }); await expectAsyncError(() => db.clear(), /transaction error/); }); }); /** @test {IDB#execute} */ describe("#execute", () => { it("should return a promise", async () => { await db.execute(() => {}); }); describe("No preloading", () => { it("should open a connection to the db", async () => { const open = sandbox .stub(db, "open") .returns(Promise.resolve({} as IDB<any>)); await db.execute(() => {}); return sinon.assert.calledOnce(open); }); it("should execute the specified callback", async () => { const callback = sandbox.spy(); await db.execute(callback); return sinon.assert.called(callback); }); it("should fail if the callback returns a promise", async () => { const callback = () => Promise.resolve(); await expectAsyncError(() => db.execute(callback), /Promise/); }); it("should rollback if the callback fails", async () => { const callback = (transaction: any) => { transaction.execute((t: StorageProxy<any>) => t.create({ id: "1", foo: "bar" }) ); throw new Error("Unexpected"); }; try { await db.execute(callback); } catch (e) {} expect(await db.list()).to.deep.equal([]); }); it("should provide a transaction parameter", async () => { const callback = sandbox.spy(); await db.execute(callback); const handler = callback.getCall(0).args[0]; expect(handler).to.have.property("get").to.be.a("function"); expect(handler).to.have.property("create").to.be.a("function"); expect(handler).to.have.property("update").to.be.a("function"); expect(handler).to.have.property("delete").to.be.a("function"); }); it("should create a record", async () => { const data = { id: "1", foo: "bar" }; await db.execute((t) => t.create(data)); const list = await db.list(); list.should.deep.equal([data]); }); it("should update a record", async () => { const data = { id: "1", foo: "bar" }; await db.execute((t) => t.create(data)); await db.execute((t) => { t.update({ ...data, foo: "baz" }); }); const res = await db.get(data.id); res!.foo.should.equal("baz"); }); it("should delete a record", async () => { const data = { id: "1", foo: "bar" }; await db.execute((t) => t.create(data)); await db.execute((transaction) => { transaction.delete(data.id); }); const id = await db.get(data.id); expect(id).to.equal(undefined); }); it("should reject on store method error", async () => { sandbox .stub(db, "prepare") .callsFake(async (name, callback, options) => { const abort = (e: Error) => { throw e; }; callback( { openCursor: () => ({ set onsuccess(cb: (arg0: { target: {} }) => void) { cb({ target: {} }); }, }), add() { throw new Error("add error"); }, } as any, abort ); }); await expectAsyncError( () => db.execute((transaction) => transaction.create({ id: "42" })), "add error" ); }); it("should reject on transaction error", async () => { sandbox .stub(db, "prepare") .callsFake(async (name, callback, options) => { return callback({ openCursor() { throw new Error("transaction error"); }, } as any); }); await expectAsyncError( () => db.execute((transaction) => transaction.create({} as any), { preload: ["1", "2"], }), "transaction error" ); }); }); describe("Preloaded records", () => { const articles: KintoIdObject[] = []; for (let i = 0; i < 100; i++) { articles.push({ id: `${i}`, title: `title${i}` }); } const preload: string[] = []; for (let i = 0; i < 10; i++) { preload.push(articles[Math.floor(Math.random() * articles.length)].id); } it("should expose preloaded records using get()", async () => { await db.execute((t) => articles.map((a) => t.create(a))); const preloaded = await db.execute( (transaction) => { return preload.map((p) => transaction.get(p)); }, { preload } ); preloaded.forEach((p, i) => { expect(p.title).eql(articles[parseInt(preload[i], 10)].title); }); }); }); }); /** @test {IDB#get} */ describe("#get", () => { beforeEach(() => { return db.execute((t) => t.create({ id: "1", foo: "bar" })); }); it("should retrieve a record from its id", async () => { const res = await db.get("1"); res!.foo.should.equal("bar"); }); it("should return undefined when record is not found", async () => { const res = await db.get("999"); expect(res).to.equal(undefined); }); it("should reject on transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { return callback({ get() { throw new Error("transaction error"); }, } as any); }); await expectAsyncError( () => db.get(undefined as any), /transaction error/ ); }); }); /** @test {IDB#list} */ describe("#list", () => { beforeEach(() => { return db.execute((transaction) => { for (let id = 1; id <= 10; id++) { // id is indexed, name is not transaction.create({ id: id.toString(), name: "#" + id }); } }); }); it("should retrieve the list of records", async () => { const list = await db.list(); list.should.have.lengthOf(10); }); it("should prefix error encountered", async () => { sandbox.stub(db, "open").returns(Promise.reject("error")); await expectAsyncError( () => db.list(), /^IndexedDB list()/, IDB.IDBError ); }); it("should reject on transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { return callback({ index() { return { getAll() { throw new Error("transaction error"); }, }; }, } as any); }); await expectAsyncError( () => db.list(), "IndexedDB list() transaction error", IDB.IDBError ); }); it("should isolate records by collection", async () => { const db1 = new IDB("main/tippytop"); const db2 = new IDB("main/tippytop-2"); await db1.clear(); await db2.clear(); await db1.open(); await db2.open(); await db1.execute((t) => t.create({ id: "1" })); await db2.execute((t) => t.create({ id: "1" })); await db2.execute((t) => t.create({ id: "2" })); await db1.close(); await db2.close(); expect(await db1.list()).to.have.length(1); expect(await db2.list()).to.have.length(2); }); describe("Filters", () => { describe("on non-indexed fields", () => { describe("single value", () => { it("should filter the list on a single pre-indexed column", async () => { const list = await db.list({ filters: { name: "#4" } }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); }); describe("multiple values", () => { it("should filter the list on a single pre-indexed column", async () => { const list = await db.list({ filters: { name: ["#4", "#5"] } }); list.should.deep.equal([ { id: "4", name: "#4" }, { id: "5", name: "#5" }, ]); }); it("should handle non-existent keys", async () => { const list = await db.list({ filters: { name: ["#4", "qux"] } }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); it("should handle empty lists", async () => { const list = await db.list({ filters: { name: [] } }); list.should.deep.equal([]); }); }); describe("combined with indexed fields", () => { it("should filter list on both indexed and non-indexed columns", async () => { const list = await db.list({ filters: { name: "#4", id: "4" } }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); }); }); describe("on indexed fields", () => { describe("single value", () => { it("should filter the list on a single pre-indexed column", async () => { const list = await db.list({ filters: { id: "4" } }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); }); describe("multiple values", () => { it("should filter the list on a single pre-indexed column", async () => { const list = await db.list({ filters: { id: ["5", "4"] } }); list.should.deep.equal([ { id: "4", name: "#4" }, { id: "5", name: "#5" }, ]); }); it("should filter the list combined with other filters", async () => { const list = await db.list({ filters: { id: ["5", "4"], name: "#4" }, }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); it("should handle non-existent keys", async () => { const list = await db.list({ filters: { id: ["4", "9999"] } }); list.should.deep.equal([{ id: "4", name: "#4" }]); }); it("should handle empty lists", async () => { const list = await db.list({ filters: { id: [] } }); list.should.deep.equal([]); }); }); }); }); }); /** * @deprecated * @test {IDB#loadDump} */ describe("Deprecated #loadDump", () => { it("should call importBulk", async () => { const importBulkStub = sandbox .stub(db, "importBulk") .returns(Promise.resolve([])); await db.loadDump([{ id: "1", last_modified: 0, foo: "bar" }]); return sinon.assert.calledOnce(importBulkStub); }); }); /** @test {IDB#getLastModified} */ describe("#getLastModified", () => { it("should reject with any encountered transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { return callback({ get() { throw new Error("transaction error"); }, } as any); }); await expectAsyncError(() => db.getLastModified(), /transaction error/); }); }); /** @test {IDB#saveLastModified} */ describe("#saveLastModified", () => { it("should resolve with lastModified value", async () => { const res = await db.saveLastModified(42); res.should.equal(42); }); it("should save a lastModified value", async () => { await db.saveLastModified(42); const res = await db.getLastModified(); res.should.equal(42); }); it("should allow updating previous value", async () => { await db.saveLastModified(42); await db.saveLastModified(43); const res = await db.getLastModified(); res.should.equal(43); }); it("should reject on transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { return callback({ delete() { throw new Error("transaction error"); }, } as any); }); await expectAsyncError( () => db.saveLastModified(undefined as any), /transaction error/ ); }); }); /** @test {IDB#importBulk} */ describe("#importBulk", () => { it("should import a list of records.", async () => { const res = await db.importBulk([ { id: "1", foo: "bar", last_modified: 0 }, { id: "2", foo: "baz", last_modified: 1 }, ]); res.should.have.lengthOf(2); }); it("should override existing records.", async () => { await db.importBulk([ { id: "1", foo: "bar", last_modified: 0 }, { id: "2", foo: "baz", last_modified: 1 }, ]); await db.importBulk([ { id: "1", foo: "baz", last_modified: 2 }, { id: "3", foo: "bab", last_modified: 2 }, ]); const list = await db.list(); list.should.deep.equal([ { id: "1", foo: "baz", last_modified: 2 }, { id: "2", foo: "baz", last_modified: 1 }, { id: "3", foo: "bab", last_modified: 2 }, ]); }); it("should update the collection lastModified value.", async () => { await db.importBulk([ { id: uuid4(), title: "foo", last_modified: 1457896541 }, { id: uuid4(), title: "bar", last_modified: 1458796542 }, ]); const lastModified = await db.getLastModified(); lastModified.should.equal(1458796542); }); it("should preserve older collection lastModified value.", async () => { await db.saveLastModified(1458796543); await db.importBulk([ { id: uuid4(), title: "foo", last_modified: 1457896541 }, { id: uuid4(), title: "bar", last_modified: 1458796542 }, ]); const lastModified = await db.getLastModified(); lastModified.should.equal(1458796543); }); it("should reject on transaction error", async () => { sandbox.stub(db, "prepare").callsFake(async (name, callback, options) => { return callback({ put() { throw new Error("transaction error"); }, } as any); }); await expectAsyncError( () => db.importBulk([{ id: "1", last_modified: 0, foo: "bar" }]), /^IndexedDB importBulk()/, IDB.IDBError ); }); }); /** @test {IDB#list} */ /** @test {IDB#getLastModified} */ describe("With custom dbName", () => { it("should isolate records by dbname", async () => { const db1 = new IDB("main/tippytop", { dbName: "KintoDB" }); const db2 = new IDB("main/tippytop", { dbName: "RemoteSettings" }); await db1.clear(); await db2.clear(); await db1.open(); await db2.open(); await db1.execute((t) => t.create({ id: "1" })); await db2.execute((t) => t.create({ id: "1" })); await db2.execute((t) => t.create({ id: "2" })); await db1.close(); await db2.close(); expect(await db1.list()).to.have.length(1); expect(await db2.list()).to.have.length(2); }); it("should isolate timestamps by dbname", async () => { const db1 = new IDB("main/tippytop", { dbName: "KintoDB" }); const db2 = new IDB("main/tippytop", { dbName: "RemoteSettings" }); await db1.open(); await db2.open(); await db1.saveLastModified(41); await db2.saveLastModified(42); await db1.close(); await db2.close(); expect(await db1.getLastModified()).to.be.equal(41); expect(await db2.getLastModified()).to.be.equal(42); }); }); /** @test {IDB#saveMetadata} */ describe("#saveMetadata", () => { it("should return null when no metadata is found", async () => { const metadata = await db.getMetadata(); expect(metadata).to.equal(null); }); it("should store metadata in db", async () => { await db.saveMetadata({ id: "abc", schema: { type: "object" } }); const retrieved = await db.getMetadata(); expect(retrieved.id, "abc"); }); }); /** @test {IDB#open} */ describe("#migration", () => { let idb: IDB<any>; async function createOldDB(dbName: string) { const oldDb = await open(dbName, { version: 1, onupgradeneeded: (event: IDBVersionChangeEvent) => { // https://github.com/Kinto/kinto.js/blob/v11.2.2/src/adapters/IDB.js#L154-L171 const db = (event.target as IDBRequest<IDBDatabase>).result; db.createObjectStore(dbName, { keyPath: "id" }); db.createObjectStore("__meta__", { keyPath: "name" }); }, }); await execute( oldDb, dbName, (store) => { store.put({ id: "1" }); store.put({ id: "2" }); }, { mode: "readwrite" } ); await execute( oldDb, "__meta__", (store) => { store.put({ name: "lastModified", value: 43 }); }, { mode: "readwrite" } ); oldDb.close(); // synchronous. } const cid = "main/tippytop"; before(async () => { await createOldDB(cid); await createOldDB("another/not-migrated"); idb = new IDB(cid, { migrateOldData: true, }); }); after(() => { return idb.close(); }); it("should migrate records", async () => { const list = await idb.list(); list.should.deep.equal([{ id: "1" }, { id: "2" }]); }); it("should migrate timestamps", async () => { const lastModified = await idb.getLastModified(); lastModified.should.equal(43); }); it("should create the collections store", async () => { const metadata = { id: "abc" }; await idb.saveMetadata(metadata); (await idb.getMetadata()).should.deep.equal(metadata); }); it("should not fail if already migrated", async () => { await idb.close(); await idb.open(); await idb.close(); await idb.open(); }); it("should delete the old database", async () => { await expectAsyncError(() => open(cid, { version: 1, onupgradeneeded: (event) => (event.target as IDBRequest<IDBDatabase>).transaction!.abort(), }) ); }); it("should not delete other databases", async () => { await open("another/not-migrated", { version: 1, onupgradeneeded: (event) => (event.target as IDBRequest<IDBDatabase>).transaction!.abort(), }); }); it("should not migrate if option is set to false", async () => { const idb = new IDB("another/not-migrated", { migrateOldData: false }); const list = await idb.list(); list.should.deep.equal([]); }); it("should not fail if old database is broken or incomplete", async () => { const oldDb = await open("some/db", { version: 1, onupgradeneeded: (event) => {}, }); oldDb.close(); const idb = new IDB("some/db", { migrateOldData: true }); await idb.open(); }); }); });
the_stack
import * as chai from 'chai'; import {TestHelper} from '../TestHelper'; import chaiHttp = require('chai-http'); import {FixtureUtils} from '../../fixtures/FixtureUtils'; import {ICourse} from '../../../shared/models/ICourse'; import {ILecture} from '../../../shared/models/ILecture'; import {IUnit} from '../../../shared/models/units/IUnit'; import * as util from 'util'; import {Course} from '../../src/models/Course'; import {IUser} from '../../../shared/models/IUser'; import {ICodeKataModel} from '../../src/models/units/CodeKataUnit'; import {IFreeTextUnit} from '../../../shared/models/units/IFreeTextUnit'; import {ITaskUnitModel} from '../../src/models/units/TaskUnit'; import {IFreeTextUnitModel} from '../../src/models/units/FreeTextUnit'; import {ICodeKataUnit} from '../../../shared/models/units/ICodeKataUnit'; import {ITaskUnit} from '../../../shared/models/units/ITaskUnit'; import {extractSingleMongoId} from '../../src/utilities/ExtractMongoId'; // how can i do this in the usual import scheme as above? // 'track()' needs to be chained to the require in order to be able to delete all created temporary files afterwards // see also: https://github.com/bruce/node-temp const temp = require('temp').track(); const createTempFile = util.promisify(temp.open); chai.use(chaiHttp); const should = chai.should(); const BASE_URL = '/api/duplicate'; const testHelper = new TestHelper(BASE_URL); /** * Provides simple shared setup functionality used by the duplicate access denial unit tests. * It finds a targetCourse (ICourseModel) that doesn't share any of the teachers with the given input course. * Then it finds the unauthorizedTeacher, which is simply a random teacher of the targetCourse. * * @param course The course for which the "unauthorized teacher set" is to be generated. * @returns An object with the targetCourse and unauthorizedTeacher. */ async function prepareUnauthorizedTeacherSetFor(course: ICourse) { const authorizedTeachers = [course.courseAdmin, ...course.teachers]; const targetCourse = await Course.findOne({ courseAdmin: {$nin: authorizedTeachers}, teachers: {$nin: authorizedTeachers} }); const unauthorizedTeacher = await FixtureUtils.getRandomTeacherForCourse(targetCourse); return {targetCourse, unauthorizedTeacher}; } /** * Provides simple shared setup functionality used by the duplicate access denial unit tests. * It first gets a random teacher for the input course. * Then it finds a targetCourse (ICourseModel) for that teacher. * * @param course The course for which the "other course set" is to be generated. * @returns An object with the targetCourse and teacher. */ async function prepareOtherTargetCourseSetFor(course: ICourse) { const teacher = await FixtureUtils.getRandomTeacherForCourse(course); const targetCourse = await Course.findOne({ courseAdmin: {$ne: teacher}, teachers: {$ne: teacher} }); return {targetCourse, teacher}; } async function testForbidden(user: IUser, urlPostfix = '', sendData: object) { const result = await testHelper.commonUserPostRequest(user, urlPostfix, sendData); result.status.should.be.equal(403); } async function testSuccess(user: IUser, urlPostfix = '', sendData: object, errorMsg = '') { const response = await testHelper.commonUserPostRequest(user, urlPostfix, sendData); response.status.should.be.equal(200, errorMsg + ' -> ' + response.body.message); should.exist(response.body._id, 'Response body doesn\'t have an _id property'); should.equal(1, Object.keys(response.body).length, 'The duplication response apparently contains more than just the ID'); return response.body._id; } async function testNotFound(what: string, sendData?: string | object) { const admin = await FixtureUtils.getRandomAdmin(); const result = await testHelper.commonUserPostRequest(admin, `/${what}/000000000000000000000000`, sendData); result.status.should.be.equal(404); } describe('Duplicate', async () => { beforeEach(async () => { await testHelper.resetForNextTest(); }); describe(`POST ${BASE_URL}`, async () => { it('should duplicate units', async () => { const units = await FixtureUtils.getUnits(); for (const unit of units) { const course = await FixtureUtils.getCourseFromUnit(unit); const lecture = await FixtureUtils.getLectureFromUnit(unit); const teacher = await FixtureUtils.getRandomTeacherForCourse(course); const duplicateId = await testSuccess(teacher, `/unit/${unit._id}`, {lectureId: lecture._id}, 'failed to duplicate ' + unit.name + ' into ' + lecture.name + ' from ' + course.name); const getResponse = await testHelper.basicUserGetRequest(teacher, `/api/units/${duplicateId}`); getResponse.status.should.be.equal(200); const unitJson: IUnit = getResponse.body; // TODO: share this check since it is the same one as in export.ts should.equal(unit.name, unitJson.name, 'Duplicate name mismatch'); // check nullable fields if (unit.description != null) { unitJson.description.should.be.equal(unit.description); } else { should.not.exist(unitJson.description); } if (unit.weight != null) { unitJson.weight.should.be.equal(unit.weight); } else { should.not.exist(unitJson.weight); } // 'progressableUnits' do have some additional fields if (unit.progressable === true) { unitJson.progressable.should.be.equal(unit.progressable); const progressableUnit = <any>unit; if (progressableUnit.deadline != null) { (<any>unitJson).deadline.should.be.equal(progressableUnit.deadline); } } (<any>unitJson).__t.should.be.equal((<any>unit).__t); // check different types switch ((<any>unit).__t) { case 'free-text': (<IFreeTextUnit>unitJson).markdown.should.be.equal((<IFreeTextUnitModel>unit).markdown); break; case 'code-kata': const codeKataUnit = <ICodeKataModel>unit; (<ICodeKataUnit>unitJson).definition.should.be.equal(codeKataUnit.definition); (<ICodeKataUnit>unitJson).code.should.be.equal(codeKataUnit.code); (<ICodeKataUnit>unitJson).test.should.be.equal(codeKataUnit.test); break; case 'task': const taskUnit = <ITaskUnitModel>unit; (<ITaskUnit>unitJson).tasks.should.be.instanceOf(Array).and.have.lengthOf(taskUnit.tasks.length); // maybe further test single tasks? break; default: // should this fail the test? process.stderr.write('duplicate for "' + unit.type + '" is not completly tested'); break; } } }); it('should duplicate lectures', async () => { const lectures = await FixtureUtils.getLectures(); for (const lecture of lectures) { const course = await FixtureUtils.getCourseFromLecture(lecture); const teacher = await FixtureUtils.getRandomTeacherForCourse(course); const duplicateId = await testSuccess(teacher, `/lecture/${lecture._id}`, {courseId: course._id}, 'failed to import ' + lecture.name + ' into ' + course.name); const getResponse = await testHelper.basicUserGetRequest(teacher, `/api/lecture/${duplicateId}`); getResponse.status.should.be.equal(200); const lectureJson: ILecture = getResponse.body; lectureJson.name.should.be.equal(lecture.name); lectureJson.description.should.be.equal(lecture.description); lectureJson.units.should.be.instanceOf(Array).and.have.lengthOf(lecture.units.length); const updatedCourse = await Course.find({lectures: { $in: [ lectureJson._id ] }}); updatedCourse.should.be.instanceOf(Array).and.have.lengthOf(1); updatedCourse[0]._id.toString().should.be.equal(course._id.toString()); updatedCourse[0].lectures.should.be.instanceOf(Array).and.have.lengthOf(course.lectures.length + 1); } }); it('should duplicate courses', async () => { const courses = await FixtureUtils.getCourses(); for (const course of courses) { const teacher = await FixtureUtils.getRandomTeacherForCourse(course); const duplicateId = await testSuccess(teacher, `/course/${course._id}`, {courseAdmin: teacher._id}, 'failed to duplicate ' + course.name); const getResponse = await testHelper.basicUserGetRequest(teacher, `/api/courses/${duplicateId}/edit`); getResponse.status.should.be.equal(200); const courseJson: ICourse = getResponse.body; courseJson.active.should.be.equal(false); courseJson.courseAdmin.should.be.equal(extractSingleMongoId(teacher)); courseJson.name.startsWith(course.name).should.be.equal(true); courseJson.description.should.be.equal(course.description); courseJson.lectures.should.be.instanceOf(Array).and.have.lengthOf(course.lectures.length); // Test optional params if (course.accessKey) { courseJson.accessKey.should.be.equal(course.accessKey); } } }); it('should forbid unit duplication for an unauthorized teacher', async () => { const unit = await FixtureUtils.getRandomUnit(); const course = await FixtureUtils.getCourseFromUnit(unit); const {targetCourse, unauthorizedTeacher} = await prepareUnauthorizedTeacherSetFor(course); const targetLecture = await FixtureUtils.getRandomLectureFromCourse(targetCourse); await testForbidden(unauthorizedTeacher, `/unit/${unit._id}`, {lectureId: targetLecture._id}); }); it('should forbid lecture duplication for an unauthorized teacher', async () => { const lecture = await FixtureUtils.getRandomLecture(); const course = await FixtureUtils.getCourseFromLecture(lecture); const {targetCourse, unauthorizedTeacher} = await prepareUnauthorizedTeacherSetFor(course); await testForbidden(unauthorizedTeacher, `/lecture/${lecture._id}`, {courseId: targetCourse._id}); }); it('should forbid course duplication for an unauthorized teacher', async () => { const course = await FixtureUtils.getRandomCourse(); const {unauthorizedTeacher} = await prepareUnauthorizedTeacherSetFor(course); await testForbidden(unauthorizedTeacher, `/course/${course._id}`, {courseAdmin: unauthorizedTeacher._id}); }); it('should forbid unit duplication when given a different target lecture without authorization', async () => { const unit = await FixtureUtils.getRandomUnit(); const course = await FixtureUtils.getCourseFromUnit(unit); const {teacher, targetCourse} = await prepareOtherTargetCourseSetFor(course); const targetLecture = await FixtureUtils.getRandomLectureFromCourse(targetCourse); await testForbidden(teacher, `/unit/${unit._id}`, {lectureId: targetLecture._id}); }); it('should forbid lecture duplication when given a different target course without authorization', async () => { const lecture = await FixtureUtils.getRandomLecture(); const course = await FixtureUtils.getCourseFromLecture(lecture); const {teacher, targetCourse} = await prepareOtherTargetCourseSetFor(course); await testForbidden(teacher, `/lecture/${lecture._id}`, {courseId: targetCourse._id}); }); it('should respond with 404 for a unit id that doesn\'t exist', async () => { const targetLecture = await FixtureUtils.getRandomLecture(); await testNotFound('/unit/000000000000000000000000', {lectureId: targetLecture._id}); }); it('should respond with 404 for a lecture id that doesn\'t exist', async () => { const targetCourse = await FixtureUtils.getRandomCourse(); await testNotFound('/lecture/000000000000000000000000', {courseId: targetCourse._id}); }); it('should respond with 404 for a course id that doesn\'t exist', async () => { await testNotFound('/course/000000000000000000000000'); }); it('should respond with 404 for a target lecture id that doesn\'t exist (unit duplication)', async () => { const unit = await FixtureUtils.getRandomUnit(); await testNotFound(`/unit/${unit._id}`, {lectureId: '000000000000000000000000'}); }); it('should respond with 404 for a target course id that doesn\'t exist (lecture duplication)', async () => { const lecture = await FixtureUtils.getRandomLecture(); await testNotFound(`/lecture/${lecture._id}`, {courseId: '000000000000000000000000'}); }); }); });
the_stack
import * as React from 'react'; import { taxonomy, ITermStore } from "@pnp/sp-taxonomy"; // Office ui fabric react controls import { TagPicker } from 'office-ui-fabric-react/lib/components/pickers/TagPicker/TagPicker'; import { DefaultButton, ActionButton } from 'office-ui-fabric-react/lib/Button'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { ChoiceGroup, IChoiceGroupOption } from 'office-ui-fabric-react/lib/ChoiceGroup'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; // Represents a taxonomy term. export interface ITaxonomyTerm { name: string; key: string; } // Represents the properties of the term picker component. export interface ITermPickerProps { IsMultiValue: boolean; TermSetId: string; LabelText: string; SelectedTerms: any[] } // Represents the local state of the term picker component. export interface ISelectTermsState { TaxonomyTerms: ITaxonomyTerm[]; showPanel: boolean; SelectedChoiceGroupTerm: ITaxonomyTerm; SelectedTerms: any[]; PickerText: string; } let taxonomyOptions: IChoiceGroupOption[] = []; export default class TermsPickerComponent extends React.Component<ITermPickerProps, ISelectTermsState> { constructor(props, state: ISelectTermsState) { super(props); let initialTaxonomyTermsArray: ITaxonomyTerm[] = []; this.state = { TaxonomyTerms: initialTaxonomyTermsArray, showPanel: false, SelectedChoiceGroupTerm: { name: null, key: null }, SelectedTerms: [], PickerText: "", } } // Creates the choice group to be displayed in the pciker panel. public createTaxonomyChoiceGroup() { taxonomyOptions = []; if (this.state.TaxonomyTerms.length > 0) { this.state.TaxonomyTerms.forEach(trm => { taxonomyOptions.push( { key: trm.key, text: trm.name } ) }) } } public render(): React.ReactElement<ITermPickerProps> { this.createTaxonomyChoiceGroup(); return ( <div> <div className="ms-Grid"> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12 ms-lg12"> <Label>{this.props.LabelText}</Label> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm8 ms-lg8"> <TagPicker onResolveSuggestions={this._onFilterChanged.bind(this)} selectedItems={this.state.SelectedTerms} getTextFromItem={this._getTextFromItem.bind(this)} itemLimit={this.props.IsMultiValue ? 100 : 1} disabled={true} /> </div> <div className="ms-Grid-col ms-sm4 ms-lg4"> <ActionButton primary={true} onClick={this._onShowPanel.bind(this)} iconProps={{ iconName: 'MultiSelectMirrored' }} /> </div> </div> </div> <Panel isOpen={this.state.showPanel} type={PanelType.smallFixedFar} onDismiss={this._handlePanelDismiss.bind(this)} headerText="Select terms" closeButtonAriaLabel="Close" > <div style={this.state.TaxonomyTerms.length == 0 ? { display: "none" } : {}}> <ChoiceGroup options={taxonomyOptions} onChange={this._onTaxonomyChoiceChange.bind(this)} required={true} selectedKey={this.state.SelectedChoiceGroupTerm.key} /> <br /> <DefaultButton primary={true} text="Select" onClick={this._handleSelectedTaxonomyTerm.bind(this)} /> <br /> <br /> <TextField label="Selected tags : " value={this.state.PickerText} multiline rows={4} onChanged={this._handlePickerTextChange.bind(this)} /> <br /> <br /> <DefaultButton primary={true} text="Done" onClick={this._handlePickerDone.bind(this)} /> </div> <div style={this.state.TaxonomyTerms.length == 0 ? {} : { display: "none" }}> <Label>No terms available....</Label> </div> </Panel> </div> ); } // Component did mount - fetches the available terms from the term set. // If existing terms are passed to the component through the 'SelectedTerms' property, it resolves // the terms from the available set and adds them to the local state. public componentDidMount() { this.GetTerms().then(resp => { let setSelectedTerms: ITaxonomyTerm[] = []; if (this.props.SelectedTerms.length > 0 && this.state.TaxonomyTerms.length > 0) { this.props.SelectedTerms.forEach(selectedTrm => { // Checks if the selected terms that was send as a property is valid (ie present in the available terms from termstore) var checkForExistingValidTerm = this.state.TaxonomyTerms.filter(trm => { return (trm.name.toLowerCase() === selectedTrm.name.toLowerCase() && trm.key === selectedTrm.key) }) // If valid, add it to the selected terms of LOCAL STATE if (checkForExistingValidTerm.length > 0) { setSelectedTerms.push(selectedTrm); } }) } this.setState({ SelectedTerms: setSelectedTerms, PickerText: this._getPickerTextString(setSelectedTerms) }) }) } // Fetches the terms from the term set and sets the TaxonomyTerms (available terms) in the local state. public async GetTerms(): Promise<any> { try { const store: ITermStore = await taxonomy.termStores.getByName("<TERM_STORE_NAME>"); const setWithData = await store.getTermSetById(this.props.TermSetId); const terms = await setWithData.terms.get(); let taxonomyTerms: ITaxonomyTerm[] = new Array(); if (terms.length > 0) { terms.forEach(trm => { taxonomyTerms.push({ name: trm.Name, key: trm.Id.split('(')[1].replace(')/', '') }) }); this.setState({ TaxonomyTerms: taxonomyTerms }) } } catch (error) { console.log("An error occurred while fetching the terms from the term store...."); } return ""; } public _onShowPanel() { this.setState({ showPanel: true }) } // This method is called when the panel is dismissed. So on the "DONE" button click, // this method is automatically called. Also on the 'X' button click. // On DONE button click in the picker panel, we only set the showPanel value to false. private _handlePanelDismiss() { // Push the data into component property. if (this.state.SelectedTerms.length > 0) { this.props.SelectedTerms.length = 0; this.state.SelectedTerms.forEach(trm => { this.props.SelectedTerms.push(trm); }) } // Reset the picker text in case it was modified by the user manually. // The next time it is opened, it will show the text of the selected terms. this.setState({ PickerText: this._getPickerTextString(this.state.SelectedTerms), }) } private _onFilterChanged = (filterText: string, tagList: { key: string; name: string }[]): { key: string; name: string }[] => { return filterText ? this.state.TaxonomyTerms.filter(tag => tag.name.toLowerCase().indexOf(filterText.toLowerCase()) === 0) : []; }; public _getTextFromItem(item: any): any { return item.Text; } // Sets the selected term on change of term in the picker panel. private _onTaxonomyChoiceChange = (ev: React.FormEvent<HTMLInputElement>, option: any): void => { this.setState({ SelectedChoiceGroupTerm: { name: option.text, key: option.key } }) } private _handleSelectedTaxonomyTerm = (): void => { let selectedTerms: ITaxonomyTerm[] = this.state.SelectedTerms; // Handles the state and picker textbox if the field is multi-select if (this.props.IsMultiValue) { selectedTerms = this.state.SelectedTerms; // Check if the term is already selected let existingTerm = selectedTerms.filter(trm => { return trm.name.toLowerCase() === this.state.SelectedChoiceGroupTerm.name.toLowerCase() }) if (existingTerm.length == 0) { selectedTerms.push( { name: this.state.SelectedChoiceGroupTerm.name, key: this.state.SelectedChoiceGroupTerm.key } ); } this.setState({ SelectedTerms: selectedTerms, PickerText: this._getPickerTextString(this.state.SelectedTerms) }) } // Handles the state and picker textbox if the field is single-select else { selectedTerms = []; selectedTerms.push( { name: this.state.SelectedChoiceGroupTerm.name, key: this.state.SelectedChoiceGroupTerm.key } ); this.setState({ SelectedTerms: selectedTerms, PickerText: selectedTerms[0].name }) } } // Handle the close panel on "Done" button click // When the showPanel is set to false, the onDismiss method will be automatically executed. private _handlePickerDone = (): void => { this.setState({ showPanel: false }) } // Generates the ';' separated string for selected terms private _getPickerTextString(selectedTerms: any[]): string { let pickerTextString: string = ""; if (selectedTerms.length > 0) { pickerTextString = selectedTerms.map(trm => { return trm.name }).join('; ') } return pickerTextString; } // Handles manual change to the picker control. private _handlePickerTextChange(value) { if (value !== "") { let selectedTerms: any[] = []; let pickerSelectedTerms: any[] = value.split(';'); pickerSelectedTerms.forEach((pickerSelectedTerm: string) => { pickerSelectedTerm = pickerSelectedTerm.trim(); let filteredTerm = this.state.TaxonomyTerms.filter((trm) => { return trm.name.toLowerCase() == pickerSelectedTerm.toLowerCase() }) // Push the term only if it resolved. if (filteredTerm.length > 0) { selectedTerms.push(filteredTerm[0]); } }) this.setState({ PickerText: value, SelectedTerms: selectedTerms }) } else { this.setState({ PickerText: value, SelectedTerms: [] }) } } }
the_stack
import { DataAccessTypes } from '@requestnetwork/types'; import TransactionIndex from '../src/transaction-index/index'; import TimestampByLocation from '../src/transaction-index/timestamp-by-location'; const testBlock: DataAccessTypes.IBlockHeader = { channelIds: { 'request-1': [1] }, topics: { 'request-1': ['topic-1'] }, version: '2.0', }; describe('TransactionIndex', () => { let transactionIndex: TransactionIndex; beforeEach(async () => { transactionIndex = new TransactionIndex(); }); describe('addTransaction', () => { it('addTransaction() should be fullfilled', async () => { await transactionIndex.addTransaction('', testBlock, 0); }); it('calls locationByTopic and timestampByLocation', async () => { const pushStorageLocationIndexedWithBlockTopicsMock = jest.fn(); (transactionIndex as any).locationByTopic.pushStorageLocationIndexedWithBlockTopics = pushStorageLocationIndexedWithBlockTopicsMock; const pushTimestampByLocationMock = jest.fn(); (transactionIndex as any).timestampByLocation.pushTimestampByLocation = pushTimestampByLocationMock; await transactionIndex.addTransaction('abcd', testBlock, 2); expect(pushStorageLocationIndexedWithBlockTopicsMock).toHaveBeenCalledWith('abcd', testBlock); expect(pushTimestampByLocationMock).toHaveBeenCalledWith('abcd', 2); }); }); describe('getStorageLocationList', () => { beforeEach(async () => { // mock location by topic (transactionIndex as any).locationByTopic.getStorageLocationsFromChannelId = jest.fn(() => [ 'a', 'b', 'c', ]); const timestampByLocation: TimestampByLocation = (transactionIndex as any) .timestampByLocation; await timestampByLocation.pushTimestampByLocation('a', 9); await timestampByLocation.pushTimestampByLocation('b', 10); await timestampByLocation.pushTimestampByLocation('c', 11); }); it('getStorageLocationList() should be fullfilled', async () => { await expect(transactionIndex.getStorageLocationList('')); }); it('should return all if timestamp not specified', async () => { const storageLocationList = await transactionIndex.getStorageLocationList(''); expect(storageLocationList).toEqual(['a', 'b', 'c']); }); it('should filter data if timestamp specified', async () => { const storageLocationList1 = await transactionIndex.getStorageLocationList('', { to: 10, }); expect(storageLocationList1).toEqual(['a', 'b']); const storageLocationList2 = await transactionIndex.getStorageLocationList('', { from: 10, to: 11, }); expect(storageLocationList2).toEqual(['b', 'c']); const storageLocationList3 = await transactionIndex.getStorageLocationList('', { from: 11, to: 12, }); expect(storageLocationList3).toEqual(['c']); const storageLocationList4 = await transactionIndex.getStorageLocationList('', { from: 12, to: 13, }); expect(storageLocationList4).toEqual([]); }); }); describe('getChannelIdsForTopic', () => { it('getChannelIdsForTopic() should be fullfilled', async () => { await expect(transactionIndex.getChannelIdsForTopic('')); }); it('getChannelIdsForTopic() should support multiple channel ids for topic', async () => { await transactionIndex.addTransaction( 'dataId1', { channelIds: { 'channel-1': [1], 'channel-2': [2], }, topics: { 'channel-1': ['topic-a'], 'channel-2': ['topic-a'], }, version: '2.0', }, 1, ); const channels = await transactionIndex.getChannelIdsForTopic('topic-a'); expect(channels).toEqual(['channel-1', 'channel-2']); }); it('getChannelIdsForTopic() should support multiple channel ids for topic with time boundaries', async () => { await transactionIndex.addTransaction( 'dataId1', { channelIds: { 'channel-1': [1], 'channel-2': [2], }, topics: { 'channel-1': ['topic-a'], 'channel-2': ['topic-a'], }, version: '2.0', }, 2, ); await transactionIndex.addTransaction( 'dataId2', { channelIds: { 'channel-2': [1], 'channel-3': [2], }, topics: {}, version: '2.0', }, 10, ); await transactionIndex.addTransaction( 'dataId3', { channelIds: { 'channel-3': [0], }, topics: { 'channel-3': ['topic-b'], }, version: '2.0', }, 20, ); expect(await transactionIndex.getChannelIdsForTopic('topic-a', { from: 3 })).toEqual([ 'channel-2', ]); expect(await transactionIndex.getChannelIdsForTopic('topic-a', { to: 3 })).toEqual([ 'channel-1', 'channel-2', ]); expect(await transactionIndex.getChannelIdsForTopic('topic-a', { from: 11 })).toEqual([]); expect(await transactionIndex.getChannelIdsForTopic('topic-a', { to: 1 })).toEqual([]); expect(await transactionIndex.getChannelIdsForTopic('topic-b', { to: 11 })).toEqual([ 'channel-3', ]); expect(await transactionIndex.getChannelIdsForTopic('topic-b', { from: 11 })).toEqual([ 'channel-3', ]); }); }); describe('getChannelIdsForMultipleTopics', () => { it('getChannelIdsForMultipleTopics() should be full filled', async () => { await expect(transactionIndex.getChannelIdsForMultipleTopics([])); }); it('getChannelIdsForMultipleTopics() should support multiple channel ids for multiple topics', async () => { await transactionIndex.addTransaction( 'dataId1', { channelIds: { 'channel-1': [1], 'channel-2': [2], 'channel-3': [3], }, topics: { 'channel-1': ['topic-a'], 'channel-2': ['topic-a'], 'channel-3': ['topic-b'], 'channel-4': ['topic-b', 'topic-c'], }, version: '2.0', }, 1, ); expect(await transactionIndex.getChannelIdsForMultipleTopics(['topic-a'])).toEqual([ 'channel-1', 'channel-2', ]); expect(await transactionIndex.getChannelIdsForMultipleTopics(['topic-b'])).toEqual([ 'channel-3', 'channel-4', ]); expect(await transactionIndex.getChannelIdsForMultipleTopics(['topic-c'])).toEqual([ 'channel-4', ]); }); it('getChannelIdsForMultipleTopics() should support multiple channel ids for multiple topics with boundaries', async () => { await transactionIndex.addTransaction( 'dataId1', { channelIds: { 'channel-1': [1], 'channel-2': [2], }, topics: { 'channel-1': ['topic-a'], 'channel-2': ['topic-b'], }, version: '2.0', }, 1, ); await transactionIndex.addTransaction( 'dataId2', { channelIds: { 'channel-1': [1], 'channel-3': [2], }, topics: { 'channel-3': ['topic-c', 'topic-b'], }, version: '2.0', }, 3, ); await transactionIndex.addTransaction( 'dataId3', { channelIds: { 'channel-4': [1], 'channel-5': [2], }, topics: { 'channel-4': ['topic-c'], 'channel-5': ['topic-d', 'topic-a'], }, version: '2.0', }, 10, ); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-a', 'topic-b'], { from: 2 }), ).toEqual(['channel-1', 'channel-5', 'channel-3']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-a', 'topic-b'], { from: 4 }), ).toEqual(['channel-5']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-a', 'topic-b'], { to: 2 }), ).toEqual(['channel-1', 'channel-2']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-a', 'topic-b'], { from: 2, to: 4, }), ).toEqual(['channel-1', 'channel-3']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-b', 'topic-c'], { from: 2 }), ).toEqual(['channel-3', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-b', 'topic-c'], { from: 4 }), ).toEqual(['channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-b', 'topic-c'], { to: 2 }), ).toEqual(['channel-2']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-b', 'topic-c'], { from: 2, to: 4, }), ).toEqual(['channel-3']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-d', 'topic-c'], { from: 2 }), ).toEqual(['channel-5', 'channel-3', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-d', 'topic-c'], { from: 4 }), ).toEqual(['channel-5', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-d', 'topic-c'], { to: 2 }), ).toEqual([]); expect( await transactionIndex.getChannelIdsForMultipleTopics(['topic-d', 'topic-c'], { from: 2, to: 4, }), ).toEqual(['channel-3']); expect( await transactionIndex.getChannelIdsForMultipleTopics([ 'topic-a', 'topic-b', 'topic-c', 'topic-d', ]), ).toEqual(['channel-1', 'channel-5', 'channel-2', 'channel-3', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics( ['topic-a', 'topic-b', 'topic-c', 'topic-d'], { from: 2 }, ), ).toEqual(['channel-1', 'channel-5', 'channel-3', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics( ['topic-a', 'topic-b', 'topic-c', 'topic-d'], { from: 4 }, ), ).toEqual(['channel-5', 'channel-4']); expect( await transactionIndex.getChannelIdsForMultipleTopics( ['topic-a', 'topic-b', 'topic-c', 'topic-d'], { to: 2 }, ), ).toEqual(['channel-1', 'channel-2']); expect( await transactionIndex.getChannelIdsForMultipleTopics( ['topic-a', 'topic-b', 'topic-c', 'topic-d'], { from: 2, to: 4 }, ), ).toEqual(['channel-1', 'channel-3']); }); }); });
the_stack
import { Blending, Color, DepthTest, mat4, MaterialFromShader, MeshBuilder, quat, RenderBuffer, RenderTarget, RenderTexture, Shader, shaderProp, SimpleTexturedMaterial, Texture, Texture2D, TextureData, TextureFormat, TextureImporter, Utils, vec2, vec4, WrapMode, ZograRenderer } from "@sardinefish/zogra-renderer"; import raindropTexture from "../assets/img/raindrop.png"; import { BlurRenderer } from "./blur"; import { RainDrop } from "./raindrop"; import { randomRange } from "./random"; import defaultFrag from "./shader/2d-frag.glsl"; import defaultVert from "./shader/2d-vert.glsl"; import mistBackground from "./shader/bg-mist.glsl"; import composeFrag from "./shader/compose.glsl"; import dropletVert from "./shader/droplet-vert.glsl"; import dropletFrag from "./shader/droplet.glsl"; import raindropErase from "./shader/erase.glsl"; import raindropFrag from "./shader/raindrop-frag.glsl"; import raindropVert from "./shader/raindrop-vert.glsl"; import { Time } from "./utils"; class RaindropMaterial extends MaterialFromShader(new Shader(raindropVert, raindropFrag, { blendRGB: [Blending.OneMinusDstColor, Blending.OneMinusSrcColor], depth: DepthTest.Disable, zWrite: false, attributes: { size: "aSize", modelMatrix: "aModelMatrix", } })) { @shaderProp("uMainTex", "tex2d") texture: Texture | null = null; @shaderProp("uSize", "float") size: number = 0; } class DropletMaterial extends MaterialFromShader(new Shader(dropletVert, dropletFrag, { blendRGB: [Blending.OneMinusDstColor, Blending.OneMinusSrcColor], depth: DepthTest.Disable, zWrite: false, attributes: { size: "aSize", modelMatrix: "aModelMatrix", } })) { @shaderProp("uMainTex", "tex2d") texture: Texture | null = null; @shaderProp("uSpawnRect", "vec4") spawnRect: vec4 = vec4(0, 0, 1, 1); @shaderProp("uSizeRange", "vec2") sizeRange: vec2 = vec2(10, 20); @shaderProp("uSeed", "float") seed: number = 1; } class FinalCompose extends MaterialFromShader(new Shader(defaultVert, composeFrag, { blend: [Blending.SrcAlpha, Blending.OneMinusSrcAlpha], depth: DepthTest.Disable, zWrite: false })) { @shaderProp("uMainTex", "tex2d") background: Texture | null = null; @shaderProp("uBackgroundSize", "vec4") backgroundSize: vec4 = vec4.one(); @shaderProp("uRaindropTex", "tex2d") raindropTex: Texture | null = null; @shaderProp("uDropletTex", "tex2d") dropletTex: Texture | null = null; @shaderProp("uMistTex", "tex2d") mistTex: Texture | null = null; @shaderProp("uSmoothRaindrop", "vec2") smoothRaindrop: vec2 = vec2(0.95, 1.0); @shaderProp("uRefractParams", "vec2") refractParams: vec2 = vec2(0.4, 0.6); @shaderProp("uLightPos", "vec4") lightPos: vec4 = vec4(.5, .5, 2, 1); @shaderProp("uDiffuseColor", "color") diffuseLight: Color = new Color(0.3, 0.3, 0.3, 0.8); @shaderProp("uSpecularParams", "vec4") specularParams: vec4 = vec4(1, 1, 1, 32); @shaderProp("uBump", "float") bump: number = 1; } class RaindropErase extends SimpleTexturedMaterial(new Shader(defaultVert, raindropErase, { // blend: [Blending.Zero, Blending.OneMinusSrcAlpha], blendRGB: [Blending.Zero, Blending.OneMinusSrcAlpha], blendAlpha: [Blending.Zero, Blending.OneMinusSrcAlpha], })) { @shaderProp("uEraserSmooth", "vec2") eraserSize: vec2 = vec2(0.93, 1.0); } const MistAccumulate = SimpleTexturedMaterial(new Shader(defaultVert, defaultFrag, { blend: [Blending.One, Blending.One] })); class MistBackgroundCompose extends SimpleTexturedMaterial(new Shader(defaultVert, mistBackground, { blend: [Blending.SrcAlpha, Blending.OneMinusSrcAlpha] })) { @shaderProp("uMistColor", "color") mistColor: Color = new Color(0.01, 0.01, 0.01, 1); @shaderProp("uMistTex", "tex2d") mistTex: Texture | null = null; } export interface RenderOptions { canvas: HTMLCanvasElement; width: number; height: number; background: TextureData | string; /** * Background blur steps used for background & raindrop refract image. * Value should be integer from 0 to log2(backgroundSize). * Recommend 3 or 4 */ backgroundBlurSteps: number; /** * Enable blurry mist effect */ mist: boolean; /** * [r, g, b, a] mist color, each component in range (0..1). * The alpha is used for whole mist layer. * Recommend [0.01, 0.01, 0.01, 1] */ mistColor: [number, number, number, number]; /** * Describe how long takes mist alpha from 0 to 1 */ mistTime: number; /** * Background blur steps used for mist. * Value should be integer from 0 to log2(backgroundSize). * Recommended value = backgroundBlurSteps + 1 */ mistBlurStep: number; /** * Tiny droplet spawn rate. */ dropletsPerSeconds: number; /** * Random size range of tiny drplets. * Recommend [10, 30] */ dropletSize: [number, number]; /** * Smooth range [a, b] of raindrop edge. * Recommend [0.96, 1.0] * * Larger range of (b - a) have smoother edge. * * Lower value b makes raindrop larger with a distort edge */ smoothRaindrop: [number, number]; /** * Refract uv scale of minimal raindrop. * Recommend in range (0.2, 0.6) */ refractBase: number, /** * Refract uv scaled by raindrop size. * Rocommend in range (0.4, 0.8) */ refractScale: number, /** * Describe how raindrops are composed. * * - `smoother` compose raindrops normal with 'exclusion' blend mode * * - `harder` compose raindrops normal with 'normal' blend mode */ raindropCompose: "smoother" | "harder" /** * Screen space (0..1) light direction or position. * Recommend [-1, 1, 2, 0] * * - Use [x, y, z, 0] to indicate a direction * * - Use [x, y, z, 1] to indicate a position */ raindropLightPos: [number, number, number, number]; /** * Lambertian diffuse lighting Color. * Recommend [0.3, 0.3, 0.3] */ raindropDiffuseLight: [number, number, number]; /** * Higher value makes more shadow. * Recommend in range (0.6..0.8) */ raindropShadowOffset: number; /** * Similar to `smoothRaindrop`. Used to erase droplets & mist. * Recommended value [0.93, 1.0] */ raindropEraserSize: [number, number]; /** * Specular light clor. * Recommend disable it with [0, 0, 0] :) */ raindropSpecularLight: [number, number, number]; /** * Blinn-Phong exponent representing shininess. * Value from 0 to 1024 is ok */ raindropSpecularShininess: number; /** * Will apply to calculate screen space normal for lighting. * Larger value makes raindrops looks more flat. * Recommend in range (0.3..1) */ raindropLightBump: number, } export class RaindropRenderer { renderer: ZograRenderer; options: RenderOptions; private raindropTex: Texture2D = null as any; private originalBackground: Texture2D = null as any; private background: RenderTexture; private raindropComposeTex: RenderTexture; private dropletTexture: RenderTexture; private mistTexture: RenderTexture; private blurryBackground: RenderTexture; private mistBackground: RenderTexture; private blurRenderer: BlurRenderer; private matrlCompose = new FinalCompose(); private matrlRaindrop = new RaindropMaterial(); private matrlDroplet = new DropletMaterial(); private matrlErase = new RaindropErase(); private matrlMist = new MistAccumulate(); private matrlMistCompose = new MistBackgroundCompose(); private projectionMatrix: mat4; private mesh = MeshBuilder.quad(); private raindropBuffer = new RenderBuffer({ size: "float", modelMatrix: "mat4", }, 3000); // deubg: DebugLayerRenderer = new DebugLayerRenderer(); constructor(options: RenderOptions) { this.renderer = new ZograRenderer(options.canvas); this.renderer.gl.getExtension("EXT_color_buffer_float"); this.options = options; this.projectionMatrix = mat4.ortho(0, options.width, 0, options.height, 1, -1); this.raindropComposeTex = new RenderTexture(options.width, options.height, false); this.background = new RenderTexture(options.width, options.height, false); this.dropletTexture = new RenderTexture(options.width, options.height, false); this.blurryBackground = new RenderTexture(options.width, options.height, false); this.mistBackground = new RenderTexture(options.width, options.height, false); this.mistTexture = new RenderTexture(options.width, options.height, false, TextureFormat.R16F); this.blurRenderer = new BlurRenderer(this.renderer); this.renderer.setViewProjection(mat4.identity(), this.projectionMatrix); } async loadAssets() { // this.renderer.blit(null, RenderTarget.CanvasTarget); this.raindropTex = await TextureImporter .buffer(raindropTexture) .then(t=>t.tex2d()); this.matrlRaindrop.texture = this.raindropTex; this.matrlDroplet.texture = this.raindropTex; await this.reloadBackground(); } async reloadBackground() { this.originalBackground?.destroy(); if (typeof (this.options.background) === "string") { this.originalBackground = await TextureImporter .url(this.options.background) .then(t => t.tex2d({ wrapMpde: WrapMode.Clamp })); this.originalBackground.wrapMode = WrapMode.Clamp; this.originalBackground.updateParameters(); } else { this.originalBackground = new Texture2D(); this.originalBackground.setData(this.options.background); this.originalBackground.updateParameters(); } const [srcRect, dstRect] = Utils.imageResize(this.originalBackground.size, this.background.size, Utils.ImageSizing.Cover); this.renderer.blit(this.originalBackground, this.background, this.renderer.assets.materials.blitCopy, srcRect, dstRect); this.background.generateMipmap(); this.blurBackground(); } resize() { this.renderer.setSize(this.options.width, this.options.height); this.projectionMatrix = mat4.ortho(0, this.options.width, 0, this.options.height, 1, -1); this.renderer.setViewProjection(mat4.identity(), this.projectionMatrix); this.raindropComposeTex.resize(this.options.width, this.options.height); this.background.resize(this.options.width, this.options.height); this.dropletTexture.resize(this.options.width, this.options.height); this.blurryBackground.resize(this.options.width, this.options.height); this.mistBackground.resize(this.options.width, this.options.height); this.mistTexture.resize(this.options.width, this.options.height); const [srcRect, dstRect] = Utils.imageResize(this.originalBackground.size, this.background.size, Utils.ImageSizing.Cover); this.renderer.blit(this.originalBackground, this.background, this.renderer.assets.materials.blitCopy, srcRect, dstRect); this.background.generateMipmap(); this.blurBackground(); } render(raindrops: RainDrop[], time: Time) { this.drawDroplet(time); this.drawMist(time.dt); this.drawRaindrops(raindrops); this.renderer.setRenderTarget(RenderTarget.CanvasTarget); this.renderer.clear(Color.black); this.drawBackground(); this.matrlCompose.background = this.blurryBackground; this.matrlCompose.backgroundSize = vec4(this.options.width, this.options.height, 1 / this.options.width, 1 / this.options.height); this.matrlCompose.raindropTex = this.raindropComposeTex; this.matrlCompose.dropletTex = this.dropletTexture; this.matrlCompose.mistTex = this.mistTexture; this.matrlCompose.smoothRaindrop = vec2(...this.options.smoothRaindrop); this.matrlCompose.refractParams = vec2(this.options.refractBase, this.options.refractScale); this.matrlCompose.lightPos = vec4(...this.options.raindropLightPos); this.matrlCompose.diffuseLight = new Color(...this.options.raindropDiffuseLight, this.options.raindropShadowOffset); this.matrlCompose.specularParams = vec4(...this.options.raindropSpecularLight, this.options.raindropSpecularShininess); this.matrlCompose.bump = this.options.raindropLightBump; this.renderer.blit(null, RenderTarget.CanvasTarget, this.matrlCompose); } private blurBackground() { // Blur background with N steps downsample + N steps upsample if (!this.options.mist) { this.blurRenderer.blur(this.background, this.options.backgroundBlurSteps, this.blurryBackground); } else { // Downsample to max steps // Then upsample from a larger texture before smaller texture to avoid override this.blurRenderer.init(this.background); this.blurRenderer.downSample(this.background, Math.max(this.options.backgroundBlurSteps, this.options.mistBlurStep)); if (this.options.backgroundBlurSteps === this.options.mistBlurStep) { this.blurRenderer.upSample(this.options.backgroundBlurSteps, this.blurryBackground); this.renderer.blit(this.blurryBackground, this.mistBackground); } else if (this.options.mistBlurStep > this.options.backgroundBlurSteps) { this.blurRenderer.upSample(this.options.backgroundBlurSteps, this.blurryBackground); this.blurRenderer.upSample(this.options.mistBlurStep, this.mistBackground); } else { this.blurRenderer.upSample(this.options.mistBlurStep, this.mistBackground); this.blurRenderer.upSample(this.options.backgroundBlurSteps, this.blurryBackground); } } } private drawMist(dt: number) { if (!this.options.mist) return; this.matrlMist.color.r = dt / this.options.mistTime; this.renderer.blit(this.renderer.assets.textures.default, this.mistTexture, this.matrlMist); } private drawBackground() { this.renderer.blit(this.blurryBackground, RenderTarget.CanvasTarget); if (this.options.mist) { this.matrlMistCompose.mistTex = this.mistTexture; this.matrlMistCompose.texture = this.mistBackground; this.matrlMistCompose.mistColor = new Color(...this.options.mistColor); this.renderer.blit(this.mistBackground, RenderTarget.CanvasTarget, this.matrlMistCompose); } } private drawRaindrops(raindrops: RainDrop[]) { if (raindrops.length > this.raindropBuffer.length) this.raindropBuffer.resize(this.raindropBuffer.length * 2); this.renderer.setRenderTarget(this.raindropComposeTex); this.renderer.clear(Color.black.transparent()); for (let i = 0; i < raindrops.length; i++) { const raindrop = raindrops[i]; const model = mat4.rts(quat.identity(), raindrop.pos.toVec3(), raindrop.size.toVec3(1)); this.raindropBuffer[i].modelMatrix.set(model); this.raindropBuffer[i].size[0] = raindrop.size.x / 100; } switch (this.options.raindropCompose) { case "smoother": this.matrlRaindrop.shader.setPipelineStates({ blendRGB: [Blending.OneMinusDstColor, Blending.OneMinusSrcColor] }); this.matrlDroplet.shader.setPipelineStates({ blendRGB: [Blending.OneMinusDstColor, Blending.OneMinusSrcColor], }); break; case "harder": this.matrlRaindrop.shader.setPipelineStates({ blendRGB: [Blending.One, Blending.OneMinusSrcAlpha] }); this.matrlDroplet.shader.setPipelineStates({ blendRGB: [Blending.One, Blending.OneMinusSrcAlpha], }); break; } this.renderer.drawMeshInstance(this.mesh, this.raindropBuffer, this.matrlRaindrop, raindrops.length); this.matrlErase.eraserSize = vec2(...this.options.raindropEraserSize); this.renderer.blit(this.raindropComposeTex, this.dropletTexture, this.matrlErase); if (this.options.mist) this.renderer.blit(this.raindropComposeTex, this.mistTexture, this.matrlErase); } private drawDroplet(time: Time) { this.renderer.setRenderTarget(this.dropletTexture); const count = this.options.dropletsPerSeconds * time.dt; this.matrlDroplet.spawnRect = vec4(0, 0, this.options.width, this.options.height); this.matrlDroplet.sizeRange = vec2(...this.options.dropletSize); this.matrlDroplet.seed = randomRange(0, 133); this.renderer.drawMeshProceduralInstance(this.mesh, this.matrlDroplet, count); } }
the_stack
import uuid from "uuid"; import App from "../../app"; import { defaultOptionalSteps, damagePositions, randomFromList, } from "./damageReports/constants"; import * as damageReportFunctions from "./damageReports/functions"; import processReport from "./processReport"; import DamageStep from "./damageStep"; import DamageTask from "./damageTask"; import {Station, Card} from "../stationSet"; const damageStepFunctions: {[key: string]: any} = {...damageReportFunctions}; // TODO: Replace these anys with proper type defintitions export interface DamageStepContext extends System { damageSteps: any[]; simulator: any; stations: Station[]; deck: any; room: any; location: string; crew: any; damageTeamCrew: any; damageTeamCrewCount: any; securityTeamCrew: any; } export interface DamageStepArgs { preamble: string; name: string; orders: string; inventory: any; room: string; code: string; backup: string; equipment: string; query: string; end: boolean; message: string; destination: string; reactivate: boolean; cleanup: boolean; type: string; } export class Macro { id: string; event: string; args: string; delay: number; noCancelOnReset: boolean; constructor(params: Macro) { this.id = params.id || uuid.v4(); this.event = params.event || ""; this.args = params.args || "{}"; this.delay = params.delay || 0; this.noCancelOnReset = params.noCancelOnReset || false; } } export class Damage { systemId?: string; damaged?: boolean; report?: string | null; reportSteps?: any; requested?: boolean; currentStep?: number; reactivationCode?: string | null; reactivationRequester?: string | null; neededReactivationCode?: string | null; exocompParts?: string[]; validate?: boolean; destroyed?: boolean; which?: string; constructor(params: Damage = {}, systemId: string) { this.systemId = systemId; this.damaged = params.damaged || false; this.report = params.report || null; this.reportSteps = params.reportSteps || null; this.requested = params.requested || false; this.currentStep = params.currentStep || 0; this.reactivationCode = params.reactivationCode || null; this.reactivationRequester = params.reactivationRequester || null; this.neededReactivationCode = params.neededReactivationCode || null; this.exocompParts = params.exocompParts || []; this.validate = params.validate || false; this.destroyed = params.destroyed || false; this.which = params.which || "default"; } } interface Power { power: number; powerLevels: number[]; defaultLevel: number; } export class System { id: string; class: string; type: string; simulatorId: string; name: string | null; storedDisplayName: string; upgradeName: string; upgraded: boolean; upgradeBoard: string | null; upgradeMacros: any[]; power: Power; damage: Damage; extra: boolean; locations: string[]; requiredDamageSteps: DamageStep[]; optionalDamageSteps: DamageStep[]; damageTasks: DamageTask[]; wing: "left" | "right"; stealthCompromised: boolean; [key: string]: any; constructor(params: any = {}) { this.id = params.id || uuid.v4(); this.class = "System"; this.type = "System"; this.simulatorId = params.simulatorId || null; this.name = params.name || null; this.wing = params.wing || "left"; this.storedDisplayName = params.storedDisplayName || params.displayName || params.name; this.upgradeName = params.upgradeName || this.storedDisplayName; this.upgraded = params.upgraded || false; this.upgradeBoard = params.upgradeBoard || null; this.upgradeMacros = []; params.upgradeMacros && params.upgradeMacros.forEach((m: Macro) => this.upgradeMacros.push(new Macro(m)), ); this.stealthCompromised = false; this.power = params.power ? {...params.power} : { power: 5, powerLevels: params.extra ? [] : [5], defaultLevel: 0, }; this.damage = new Damage(params.damage || {}, this.id); this.extra = params.extra || false; this.locations = params.locations || []; this.requiredDamageSteps = []; this.optionalDamageSteps = []; params.requiredDamageSteps && params.requiredDamageSteps.forEach((s: DamageStep) => this.requiredDamageSteps.push(new DamageStep(s)), ); params.optionalDamageSteps && params.optionalDamageSteps.forEach((s: DamageStep) => this.optionalDamageSteps.push(new DamageStep(s)), ); // Task-based damage reports this.damageTasks = []; params.damageTasks && params.damageTasks.forEach((s: DamageTask) => this.damageTasks.push(new DamageTask(s)), ); } get stealthFactor(): number | null { if (this.stealthCompromised) return 0.8; return null; } set displayName(value) { this.storedDisplayName = value; } get displayName() { if (this.upgraded && this.upgradeName) { return this.upgradeName; } return this.storedDisplayName; } trainingMode() { return; } setWing(wing) { this.wing = wing; } updateName({ name, displayName, upgradeName, }: { name: string; displayName: string; upgradeName: string; }) { if (name || name === "") this.name = name; if (displayName || displayName === "") this.displayName = displayName; if (upgradeName || upgradeName === "") this.upgradeName = upgradeName; } setUpgradeMacros(macros: Macro[]) { this.upgradeMacros = macros || []; } setUpgradeBoard(board: string) { this.upgradeBoard = board; } upgrade() { this.upgraded = true; } updateLocations(locations: string[]) { this.locations = locations || []; } setPower(powerLevel: number) { this.power.power = powerLevel; } setPowerLevels(levels: number[]) { this.power.powerLevels = levels; if (this.power.defaultLevel >= levels.length) { this.power.defaultLevel = levels.length - 1; } } setDefaultPowerLevel(level: number) { this.power.defaultLevel = level; } break(report: string, destroyed: boolean, which: string = "default") { this.damage.damaged = true; if (destroyed) this.damage.destroyed = true; this.damage.report = processReport(report, this); this.damage.requested = false; this.damage.currentStep = 0; this.damage.which = which; } addDamageStep({ name, args, type, }: { name: string; args: string; type: string; }) { this[`${type}DamageSteps`].push(new DamageStep({name, args})); } updateDamageStep({id, name, args}: {id: string; name: string; args: string}) { const step = this.requiredDamageSteps.find(s => s.id === id) || this.optionalDamageSteps.find(s => s.id === id); step.update({name, args}); } removeDamageStep(stepId: string) { // Check both required and optional this.requiredDamageSteps = this.requiredDamageSteps.filter( s => s.id !== stepId, ); this.optionalDamageSteps = this.optionalDamageSteps.filter( s => s.id !== stepId, ); } generateDamageReport(stepCount = 5) { const sim = App.simulators.find(s => s.id === this.simulatorId); const decks = App.decks.filter(d => d.simulatorId === this.simulatorId); const rooms = App.rooms.filter(r => this.locations.indexOf(r.id) > -1); const crew = App.crew.filter(c => c.simulatorId === this.simulatorId); // // Gather Information // // Get the damage team positions const damageTeamCrew = crew .map(c => c.position) .filter(c => damagePositions.indexOf(c) > -1) .filter((c, i, a) => a.indexOf(c) === i); const damageTeamCrewCount = crew .filter(c => damagePositions.indexOf(c.position) > -1) .reduce((prev, next) => { prev[next.position] = prev[next.position] ? prev[next.position] + 1 : 1; return prev; }, {}); const securityTeamCrew = crew .map(c => c.position) .filter(c => c.indexOf("Security") > -1); const stations = sim.stations; const components = stations.reduce((prev: string[], s: Station) => { return prev.concat(s.cards.map((c: Card) => c.component)); }, []); const widgets = stations .reduce((prev: string[], s: Station) => { return prev.concat(s.widgets); }, []) .filter((c: string, i: number, a: string[]) => a.indexOf(c) !== i); const damageSteps = []; // // Create a list of all the damage report steps // // Remove power if the system has power if ( this.power.powerLevels && this.power.powerLevels.length > 0 && components.indexOf("PowerDistribution") > -1 ) { damageSteps.push({name: "power", args: {end: false}}); } // Add in any required damage steps at the start this.requiredDamageSteps .concat(sim.requiredDamageSteps) .filter(step => step.args.end !== true) .forEach(step => damageSteps.push(step)); let hasDamageTeam = false; // Add in a number of optional steps let optionalSteps = defaultOptionalSteps .concat(this.optionalDamageSteps) .concat(sim.optionalDamageSteps) .filter((step: DamageStep) => { if (step.name === "damageTeam") { const output = damageTeamCrew.length > 0 && this.locations.length > 0 && components.indexOf("DamageTeams") > -1; hasDamageTeam = output; return output; } if (step.name === "damageTeamMessage") { return ( (components.indexOf("Messaging") > -1 || widgets.indexOf("messages") > -1) && damageTeamCrew.length > 0 && hasDamageTeam ); } if (step.name === "remoteAccess") { return widgets.indexOf("remote") > -1; } if (step.name === "sendInventory") { return ( App.inventory.filter( i => i.simulatorId === this.simulatorId && i.metadata.type === "repair", ).length > 0 ); } if (step.name === "longRangeMessage") { return ( widgets.indexOf("composer") > -1 && components.indexOf("LongRangeComm") > -1 && this.class !== "LongRangeComm" ); } if (step.name === "probeLaunch") { return ( components.indexOf("ProbeConstruction") > -1 && this.class !== "Probes" ); } if (step.name === "generic") return true; if (step.name === "securityTeam") { return ( components.indexOf("SecurityTeams") > -1 && securityTeamCrew.length > -1 ); } if (step.name === "securityEvac") { return components.indexOf("SecurityDecks") > -1 && decks.length > -1; } if (step.name === "internalCall") { return ( components.indexOf("CommInternal") > -1 && decks.length > -1 && this.class !== "InternalComm" ); } if (step.name === "exocomps") { return ( components.indexOf("Exocomps") > -1 && App.exocomps.find(e => e.simulatorId === sim.id) ); } if (step.name === "softwarePanel") { return App.softwarePanels.find(e => e.simulatorId === sim.id); } if (step.name === "computerCore") { return components.indexOf("ComputerCore") > -1; } return false; }); let stepIteration = 0; // Start with a damage team, if possible if (optionalSteps.find((s: DamageStep) => s.name === "damageTeam")) { damageSteps.push({name: "damageTeam", args: {}}); stepIteration = 1; } while (damageSteps.length < stepCount && stepIteration < 50) { // Ensure we don't infinitely loop stepIteration++; // Grab a random optional step const stepIndex = Math.floor(Math.random() * optionalSteps.length); if (optionalSteps.length > 0) { if ( optionalSteps[stepIndex].name === "generic" || !damageSteps.find(d => d.name === optionalSteps[stepIndex].name) ) { damageSteps.push(optionalSteps[stepIndex]); if (optionalSteps[stepIndex].name !== "damageTeam") { // We need to remove this optional step from the list so it is not repeated; // Keep damage teams so we can get a cleanup team. optionalSteps = optionalSteps.filter( (_: never, i: number) => i !== stepIndex, ); } } else if ( optionalSteps[stepIndex].name === "damageTeam" && damageSteps.filter(d => d.name === "damageTeam").length === 1 ) { // Clear the damage team damageSteps.push({name: "damageTeam", args: {end: true}}); // Add a cleanup team damageSteps.push({ name: "damageTeam", args: {end: false, cleanup: true}, }); } } } // Finishing Steps // Add in any required damage steps at the end this.requiredDamageSteps .concat(sim.requiredDamageSteps) .filter(step => step.args.end === true) .forEach(step => damageSteps.push(step)); // Clear out any damage teams if (damageSteps.find(d => d.name === "damageTeam")) { damageSteps.push({name: "damageTeam", args: {end: true}}); } // Add power if the system has power if (damageSteps.find(d => d.name === "power")) { damageSteps.push({name: "power", args: {end: true}}); } // Add the finishing step. Include reactivation code. damageSteps.push({name: "finish", args: {reactivate: true}}); // Now put together our damage report usign the damage step functions // Pick a location for the damage team const randomRoom = randomFromList(this.locations || []); const room = rooms.find(r => r.id === randomRoom); const deck = room && App.decks.find(d => d.id === room.deckId); const randomLocation = randomFromList( App.rooms.filter(r => r.simulatorId === this.simulatorId), ); const randomLocationDeck = randomLocation ? App.decks.find(d => d.id === randomLocation.deckId) : {number: null}; const location = room ? `${room.name}, Deck ${deck.number}` : deck ? `Deck ${deck.number}` : randomLocation ? `${randomLocation.name}, Deck ${randomLocationDeck?.number}` : "None"; // First create our context object const context = Object.assign( { damageSteps, simulator: sim, stations, deck, room, location, crew, damageTeamCrew, damageTeamCrewCount, securityTeamCrew, }, this, ); const damageReport = damageSteps .map((d, index) => ({ ...d, report: damageStepFunctions[d.name](d.args || {}, context, index), })) .filter(f => f.report) .reduce((prev, {report}, index) => { return `${prev} Step ${index + 1}: ${report} `; }, ""); return damageReport; } damageReport(report: string) { this.damage.report = processReport(report, this); this.damage.requested = false; } repair() { this.damage.damaged = false; this.damage.destroyed = false; this.damage.report = null; this.damage.requested = false; this.damage.neededReactivationCode = null; this.damage.reactivationCode = null; this.damage.reactivationRequester = null; this.damage.exocompParts = []; this.damage.currentStep = 0; this.damage.which = null; } updateCurrentStep(step: number) { this.damage.currentStep = step; } requestReport() { this.damage.requested = true; } reactivationCode(code: string, station: string) { this.damage.reactivationCode = code; this.damage.reactivationRequester = station; } reactivationCodeResponse(response: string) { this.damage.reactivationCode = null; this.damage.reactivationRequester = null; } // Damage Tasks // As a side note, can I just say how much more elegant // the damage tasks system is already? Look at this! // It's much simpler. Why didn't I do it this // way in the first place? ~A addDamageTask(task: DamageTask) { if (!task || !task.id || this.damageTasks.find(t => t.id === task.id)) return; this.damageTasks.push(new DamageTask(task)); } updateDamageTask(task: DamageTask) { this.damageTasks.find(t => t.id === task.id).update(task); } removeDamageTask(id: String) { this.damageTasks = this.damageTasks.filter(t => t.id !== id); } }
the_stack
import * as React from 'react'; import { Box as ReakitBox } from 'reakit'; import { useClassName, createComponent, createElement, createHook, useUniqueId } from '../utils'; import { Button, ButtonProps } from '../Button'; import { Box, BoxProps } from '../Box'; import { Card, CardProps } from '../Card'; import { Icon, IconProps } from '../Icon'; import { ModalContext } from '../Modal'; import { Overlay, OverlayProps } from '../Overlay'; import { Text, TextProps } from '../Text'; import * as styles from './Callout.styles'; export type LocalCalloutProps = { /** The title of the callout. */ title?: string | React.ReactElement<any>; /** Indicates if the callout has a tint. */ hasTint?: boolean; /** Function to invoke when the close button is pressed. */ onClickClose?: ButtonProps['onClick']; /** Indicates if a close button should be visible. */ showCloseButton?: boolean; /** Indicates if the callout is standalone. */ standalone?: boolean; /** Type of callout. */ type?: 'info' | 'danger' | 'warning' | 'success'; /** Footer of the callout. */ footer?: string | React.ReactElement<any>; /** Props to spread on the close button. */ closeButtonProps?: Omit<ButtonProps, 'children'>; /** Props to spread on the icon. */ iconProps?: IconProps; }; export type CalloutProps = CardProps & LocalCalloutProps; export type CalloutContextOptions = CalloutProps & { descriptionId?: string; titleId?: string }; export const CalloutContext = React.createContext<CalloutContextOptions>({}); const useProps = createHook<CalloutProps>( (props, { themeKey }) => { const { closeButtonProps = {}, iconProps, onClickClose, overrides, footer, standalone, showCloseButton, title, ...restProps } = props; const cardProps = Card.useProps({ ...restProps, standalone: true }); const className = useClassName({ style: styles.Callout, styleProps: props, themeKey, prevClassName: cardProps.className, }); const calloutCloseClassName = useClassName({ style: styles.CalloutClose, styleProps: props, themeKey, themeKeySuffix: 'Close', prevClassName: closeButtonProps.className, }); const titleId = useUniqueId(); const descriptionId = useUniqueId(); const context = React.useMemo(() => ({ descriptionId, titleId, ...props }), [descriptionId, props, titleId]); const children = ( <CalloutContext.Provider value={context}> <Box display="flex"> {standalone ? ( props.children ) : ( <React.Fragment> <CalloutIcon iconProps={iconProps} overrides={overrides} /> <Box> {title && ( <CalloutHeader overrides={overrides}> {typeof title === 'string' ? <CalloutTitle overrides={overrides}>{title}</CalloutTitle> : title} </CalloutHeader> )} <CalloutContent overrides={overrides}>{props.children}</CalloutContent> {footer && <CalloutFooter overrides={overrides}>{footer}</CalloutFooter>} </Box> </React.Fragment> )} </Box> {showCloseButton && ( <Button.Close className={calloutCloseClassName} onClick={onClickClose} size={title ? undefined : 'small'} {...closeButtonProps} /> )} </CalloutContext.Provider> ); return { ...cardProps, 'aria-describedby': props.children ? descriptionId : undefined, 'aria-labelledby': props.title ? titleId : undefined, className, children, }; }, { defaultProps: { type: 'info' }, themeKey: 'Callout' } ); export const Callout = createComponent<CalloutProps>( (props) => { const textProps = useProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: textProps }); }, { attach: { useProps, displayName: 'Callout', }, themeKey: 'Callout', } ); ////////////////////////////// export type LocalCalloutContentProps = {}; export type CalloutContentProps = BoxProps & LocalCalloutContentProps; const useCalloutContentProps = createHook<CalloutContentProps>( (props, { themeKey }) => { const boxProps = Box.useProps(props); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutContent, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: boxProps.className, }); return { id: props.id || contextProps.descriptionId, ...boxProps, className }; }, { themeKey: 'Callout.Content' } ); export const CalloutContent = createComponent<CalloutContentProps>( (props) => { const calloutContentProps = useCalloutContentProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutContentProps, }); }, { attach: { useProps: useCalloutContentProps, displayName: 'Callout.Content' }, themeKey: 'Callout.Content', } ); ////////////////////////////// export type LocalCalloutHeaderProps = {}; export type CalloutHeaderProps = BoxProps & LocalCalloutHeaderProps; const useCalloutHeaderProps = createHook<CalloutHeaderProps>( (props, { themeKey }) => { const boxProps = Box.useProps(props); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutHeader, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: boxProps.className, }); return { ...boxProps, className }; }, { themeKey: 'Callout.Header' } ); export const CalloutHeader = createComponent<CalloutHeaderProps>( (props) => { const calloutHeaderProps = useCalloutHeaderProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutHeaderProps, }); }, { attach: { useProps: useCalloutHeaderProps, displayName: 'Callout.Header' }, themeKey: 'Callout.Header', } ); ////////////////////////////// export type LocalCalloutTitleProps = {}; export type CalloutTitleProps = TextProps & LocalCalloutTitleProps; const useCalloutTitleProps = createHook<CalloutTitleProps>( (props, { themeKey }) => { const textProps = Text.useProps(props); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutTitle, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: textProps.className, }); return { id: contextProps.titleId, ...textProps, className }; }, { themeKey: 'Callout.Title' } ); export const CalloutTitle = createComponent<CalloutTitleProps>( (props) => { const calloutTitleProps = useCalloutTitleProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutTitleProps, }); }, { attach: { useProps: useCalloutTitleProps, displayName: 'Callout.Title' }, defaultProps: { use: 'span', }, themeKey: 'Callout.Title', } ); ////////////////////////////// export type LocalCalloutFooterProps = {}; export type CalloutFooterProps = BoxProps & LocalCalloutFooterProps; const useCalloutFooterProps = createHook<CalloutFooterProps>( (props, { themeKey }) => { const boxProps = Box.useProps(props); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutFooter, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: boxProps.className, }); return { ...boxProps, className }; }, { themeKey: 'Callout.Footer' } ); export const CalloutFooter = createComponent<CalloutFooterProps>( (props) => { const calloutFooterProps = useCalloutFooterProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutFooterProps, }); }, { attach: { useProps: useCalloutFooterProps, displayName: 'Callout.Footer' }, themeKey: 'Callout.Footer', } ); ////////////////////////////// export type LocalCalloutIconProps = { iconProps?: Omit<IconProps, 'icon'>; }; export type CalloutIconProps = BoxProps & LocalCalloutIconProps; const useCalloutIconProps = createHook<CalloutIconProps>( (props, { themeKey }) => { const { iconProps, ...restProps } = props; const boxProps = Box.useProps(restProps); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutIconWrapper, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: boxProps.className, }); const icon = ( <Icon aria-hidden color={contextProps.type} fontSize={!contextProps.title ? '300' : undefined} icon={contextProps.type} {...iconProps} /> ); let children = <CalloutContent id={undefined}>{icon}</CalloutContent>; if (contextProps.title) { children = ( <CalloutHeader> <CalloutTitle id={undefined}>{icon}</CalloutTitle> </CalloutHeader> ); } return { ...boxProps, className, children }; }, { themeKey: 'Callout.IconWrapper' } ); export const CalloutIcon = createComponent<CalloutIconProps>( (props) => { const calloutIconProps = useCalloutIconProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutIconProps, }); }, { attach: { useProps: useCalloutIconProps, displayName: 'Callout.IconWrapper' }, themeKey: 'Callout.IconWrapper', } ); ////////////////////////////// export type LocalCalloutOverlayProps = {}; export type CalloutOverlayProps = CalloutProps & OverlayProps & LocalCalloutOverlayProps; const useCalloutOverlayProps = createHook<CalloutOverlayProps>( (props, { themeKey }) => { const { variant, ...restProps } = props; const { modal } = React.useContext(ModalContext); const calloutProps = Callout.useProps({ onClickClose: restProps.hide || modal.hide, ...restProps, wrapElement: (children) => ( // @ts-ignore <Overlay placement="bottom-end" {...restProps}> {children} </Overlay> ), }); const contextProps = React.useContext(CalloutContext); const className = useClassName({ style: styles.CalloutOverlay, styleProps: { ...contextProps, ...props }, themeKey, prevClassName: calloutProps.className, }); return { ...calloutProps, className }; }, { defaultProps: { showCloseButton: true }, themeKey: 'Callout.Overlay' } ); export const CalloutOverlay = createComponent<CalloutOverlayProps>( (props) => { const calloutOverlayProps = useCalloutOverlayProps(props); return createElement({ children: props.children, component: ReakitBox, use: props.use, htmlProps: calloutOverlayProps, }); }, { attach: { useProps: useCalloutOverlayProps, displayName: 'Callout.Overlay' }, themeKey: 'Callout.Overlay', } );
the_stack
import * as Common from '../../core/common/common.js'; import * as IssuesManager from '../../models/issues_manager/issues_manager.js'; import type * as Protocol from '../../generated/protocol.js'; type AggregationKeyTag = { aggregationKeyTag: undefined, }; /** * An opaque type for the key which we use to aggregate issues. The key must be * chosen such that if two aggregated issues have the same aggregation key, then * they also have the same issue code. */ export type AggregationKey = { toString(): string, }&AggregationKeyTag; /** * An `AggregatedIssue` representes a number of `IssuesManager.Issue.Issue` objects that are displayed together. * Currently only grouping by issue code, is supported. The class provides helpers to support displaying * of all resources that are affected by the aggregated issues. */ export class AggregatedIssue extends IssuesManager.Issue.Issue { private affectedCookies = new Map<string, { cookie: Protocol.Audits.AffectedCookie, hasRequest: boolean, }>(); private affectedRawCookieLines = new Map<string, {rawCookieLine: string, hasRequest: boolean}>(); private affectedRequests = new Map<string, Protocol.Audits.AffectedRequest>(); private affectedLocations = new Map<string, Protocol.Audits.SourceCodeLocation>(); private heavyAdIssues = new Set<IssuesManager.HeavyAdIssue.HeavyAdIssue>(); private blockedByResponseDetails = new Map<string, Protocol.Audits.BlockedByResponseIssueDetails>(); private corsIssues = new Set<IssuesManager.CorsIssue.CorsIssue>(); private cspIssues = new Set<IssuesManager.ContentSecurityPolicyIssue.ContentSecurityPolicyIssue>(); private issueKind = IssuesManager.Issue.IssueKind.Improvement; private lowContrastIssues = new Set<IssuesManager.LowTextContrastIssue.LowTextContrastIssue>(); private mixedContentIssues = new Set<IssuesManager.MixedContentIssue.MixedContentIssue>(); private sharedArrayBufferIssues = new Set<IssuesManager.SharedArrayBufferIssue.SharedArrayBufferIssue>(); private trustedWebActivityIssues = new Set<IssuesManager.TrustedWebActivityIssue.TrustedWebActivityIssue>(); private quirksModeIssues = new Set<IssuesManager.QuirksModeIssue.QuirksModeIssue>(); private attributionReportingIssues = new Set<IssuesManager.AttributionReportingIssue.AttributionReportingIssue>(); private wasmCrossOriginModuleSharingIssues = new Set<IssuesManager.WasmCrossOriginModuleSharingIssue.WasmCrossOriginModuleSharingIssue>(); private genericIssues = new Set<IssuesManager.GenericIssue.GenericIssue>(); private representative?: IssuesManager.Issue.Issue; private aggregatedIssuesCount = 0; private key: AggregationKey; constructor(code: string, aggregationKey: AggregationKey) { super(code); this.key = aggregationKey; } override primaryKey(): string { throw new Error('This should never be called'); } aggregationKey(): AggregationKey { return this.key; } getBlockedByResponseDetails(): Iterable<Protocol.Audits.BlockedByResponseIssueDetails> { return this.blockedByResponseDetails.values(); } cookies(): Iterable<Protocol.Audits.AffectedCookie> { return Array.from(this.affectedCookies.values()).map(x => x.cookie); } getRawCookieLines(): Iterable<{rawCookieLine: string, hasRequest: boolean}> { return this.affectedRawCookieLines.values(); } sources(): Iterable<Protocol.Audits.SourceCodeLocation> { return this.affectedLocations.values(); } cookiesWithRequestIndicator(): Iterable<{ cookie: Protocol.Audits.AffectedCookie, hasRequest: boolean, }> { return this.affectedCookies.values(); } getHeavyAdIssues(): Iterable<IssuesManager.HeavyAdIssue.HeavyAdIssue> { return this.heavyAdIssues; } getMixedContentIssues(): Iterable<IssuesManager.MixedContentIssue.MixedContentIssue> { return this.mixedContentIssues; } getTrustedWebActivityIssues(): Iterable<IssuesManager.TrustedWebActivityIssue.TrustedWebActivityIssue> { return this.trustedWebActivityIssues; } getCorsIssues(): Set<IssuesManager.CorsIssue.CorsIssue> { return this.corsIssues; } getCspIssues(): Iterable<IssuesManager.ContentSecurityPolicyIssue.ContentSecurityPolicyIssue> { return this.cspIssues; } getLowContrastIssues(): Iterable<IssuesManager.LowTextContrastIssue.LowTextContrastIssue> { return this.lowContrastIssues; } requests(): Iterable<Protocol.Audits.AffectedRequest> { return this.affectedRequests.values(); } getSharedArrayBufferIssues(): Iterable<IssuesManager.SharedArrayBufferIssue.SharedArrayBufferIssue> { return this.sharedArrayBufferIssues; } getQuirksModeIssues(): Iterable<IssuesManager.QuirksModeIssue.QuirksModeIssue> { return this.quirksModeIssues; } getAttributionReportingIssues(): ReadonlySet<IssuesManager.AttributionReportingIssue.AttributionReportingIssue> { return this.attributionReportingIssues; } getWasmCrossOriginModuleSharingIssue(): ReadonlySet<IssuesManager.WasmCrossOriginModuleSharingIssue.WasmCrossOriginModuleSharingIssue> { return this.wasmCrossOriginModuleSharingIssues; } getGenericIssues(): ReadonlySet<IssuesManager.GenericIssue.GenericIssue> { return this.genericIssues; } getDescription(): IssuesManager.MarkdownIssueDescription.MarkdownIssueDescription|null { if (this.representative) { return this.representative.getDescription(); } return null; } getCategory(): IssuesManager.Issue.IssueCategory { if (this.representative) { return this.representative.getCategory(); } return IssuesManager.Issue.IssueCategory.Other; } getAggregatedIssuesCount(): number { return this.aggregatedIssuesCount; } /** * Produces a primary key for a cookie. Use this instead of `JSON.stringify` in * case new fields are added to `AffectedCookie`. */ private keyForCookie(cookie: Protocol.Audits.AffectedCookie): string { const {domain, path, name} = cookie; return `${domain};${path};${name}`; } addInstance(issue: IssuesManager.Issue.Issue): void { this.aggregatedIssuesCount++; if (!this.representative) { this.representative = issue; } this.issueKind = IssuesManager.Issue.unionIssueKind(this.issueKind, issue.getKind()); let hasRequest = false; for (const request of issue.requests()) { hasRequest = true; if (!this.affectedRequests.has(request.requestId)) { this.affectedRequests.set(request.requestId, request); } } for (const cookie of issue.cookies()) { const key = this.keyForCookie(cookie); if (!this.affectedCookies.has(key)) { this.affectedCookies.set(key, {cookie, hasRequest}); } } for (const rawCookieLine of issue.rawCookieLines()) { if (!this.affectedRawCookieLines.has(rawCookieLine)) { this.affectedRawCookieLines.set(rawCookieLine, {rawCookieLine, hasRequest}); } } for (const location of issue.sources()) { const key = JSON.stringify(location); if (!this.affectedLocations.has(key)) { this.affectedLocations.set(key, location); } } if (issue instanceof IssuesManager.MixedContentIssue.MixedContentIssue) { this.mixedContentIssues.add(issue); } if (issue instanceof IssuesManager.HeavyAdIssue.HeavyAdIssue) { this.heavyAdIssues.add(issue); } for (const details of issue.getBlockedByResponseDetails()) { const key = JSON.stringify(details, ['parentFrame', 'blockedFrame', 'requestId', 'frameId', 'reason', 'request']); this.blockedByResponseDetails.set(key, details); } if (issue instanceof IssuesManager.TrustedWebActivityIssue.TrustedWebActivityIssue) { this.trustedWebActivityIssues.add(issue); } if (issue instanceof IssuesManager.ContentSecurityPolicyIssue.ContentSecurityPolicyIssue) { this.cspIssues.add(issue); } if (issue instanceof IssuesManager.SharedArrayBufferIssue.SharedArrayBufferIssue) { this.sharedArrayBufferIssues.add(issue); } if (issue instanceof IssuesManager.LowTextContrastIssue.LowTextContrastIssue) { this.lowContrastIssues.add(issue); } if (issue instanceof IssuesManager.CorsIssue.CorsIssue) { this.corsIssues.add(issue); } if (issue instanceof IssuesManager.QuirksModeIssue.QuirksModeIssue) { this.quirksModeIssues.add(issue); } if (issue instanceof IssuesManager.AttributionReportingIssue.AttributionReportingIssue) { this.attributionReportingIssues.add(issue); } if (issue instanceof IssuesManager.WasmCrossOriginModuleSharingIssue.WasmCrossOriginModuleSharingIssue) { this.wasmCrossOriginModuleSharingIssues.add(issue); } if (issue instanceof IssuesManager.GenericIssue.GenericIssue) { this.genericIssues.add(issue); } } getKind(): IssuesManager.Issue.IssueKind { return this.issueKind; } isHidden(): boolean { return this.representative?.isHidden() || false; } setHidden(_value: boolean): void { throw new Error('Should not call setHidden on aggregatedIssue'); } } export class IssueAggregator extends Common.ObjectWrapper.ObjectWrapper<EventTypes> { private readonly aggregatedIssuesByKey = new Map<AggregationKey, AggregatedIssue>(); private readonly hiddenAggregatedIssuesByKey = new Map<AggregationKey, AggregatedIssue>(); constructor(private readonly issuesManager: IssuesManager.IssuesManager.IssuesManager) { super(); this.issuesManager.addEventListener(IssuesManager.IssuesManager.Events.IssueAdded, this.onIssueAdded, this); this.issuesManager.addEventListener( IssuesManager.IssuesManager.Events.FullUpdateRequired, this.onFullUpdateRequired, this); for (const issue of this.issuesManager.issues()) { this.aggregateIssue(issue); } } private onIssueAdded(event: Common.EventTarget.EventTargetEvent<IssuesManager.IssuesManager.IssueAddedEvent>): void { this.aggregateIssue(event.data.issue); } private onFullUpdateRequired(): void { this.aggregatedIssuesByKey.clear(); this.hiddenAggregatedIssuesByKey.clear(); for (const issue of this.issuesManager.issues()) { this.aggregateIssue(issue); } this.dispatchEventToListeners(Events.FullUpdateRequired); } private aggregateIssue(issue: IssuesManager.Issue.Issue): AggregatedIssue { const map = issue.isHidden() ? this.hiddenAggregatedIssuesByKey : this.aggregatedIssuesByKey; const aggregatedIssue = this.aggregateIssueByStatus(map, issue); this.dispatchEventToListeners(Events.AggregatedIssueUpdated, aggregatedIssue); return aggregatedIssue; } private aggregateIssueByStatus( aggregatedIssuesMap: Map<AggregationKey, AggregatedIssue>, issue: IssuesManager.Issue.Issue): AggregatedIssue { const key = issue.code() as unknown as AggregationKey; let aggregatedIssue = aggregatedIssuesMap.get(key); if (!aggregatedIssue) { aggregatedIssue = new AggregatedIssue(issue.code(), key); aggregatedIssuesMap.set(key, aggregatedIssue); } aggregatedIssue.addInstance(issue); return aggregatedIssue; } aggregatedIssues(): Iterable<AggregatedIssue> { return [...this.aggregatedIssuesByKey.values(), ...this.hiddenAggregatedIssuesByKey.values()]; } hiddenAggregatedIssues(): Iterable<AggregatedIssue> { return this.hiddenAggregatedIssuesByKey.values(); } aggregatedIssueCodes(): Set<AggregationKey> { return new Set([...this.aggregatedIssuesByKey.keys(), ...this.hiddenAggregatedIssuesByKey.keys()]); } aggregatedIssueCategories(): Set<IssuesManager.Issue.IssueCategory> { const result = new Set<IssuesManager.Issue.IssueCategory>(); for (const issue of this.aggregatedIssuesByKey.values()) { result.add(issue.getCategory()); } return result; } aggregatedIssueKinds(): Set<IssuesManager.Issue.IssueKind> { const result = new Set<IssuesManager.Issue.IssueKind>(); for (const issue of this.aggregatedIssuesByKey.values()) { result.add(issue.getKind()); } return result; } numberOfAggregatedIssues(): number { return this.aggregatedIssuesByKey.size; } numberOfHiddenAggregatedIssues(): number { return this.hiddenAggregatedIssuesByKey.size; } keyForIssue(issue: IssuesManager.Issue.Issue<string>): AggregationKey { return issue.code() as unknown as AggregationKey; } } export const enum Events { AggregatedIssueUpdated = 'AggregatedIssueUpdated', FullUpdateRequired = 'FullUpdateRequired', } export type EventTypes = { [Events.AggregatedIssueUpdated]: AggregatedIssue, [Events.FullUpdateRequired]: void, };
the_stack
import { Bounds, IEntityBounds, Point } from "../core/interfaces"; import { IRTreeSplitStrategy, NodePair, SplitStrategyLinear, } from "./rTreeSplitStrategies"; /** * The maximum number of children in an r-tree node before we attempt to split. * This must be >= 2. */ const DEFAULT_MAX_NODE_CHILDREN = 5; /** * There are several strategies for splitting nodes that contain overlapping * regions. By default we use `SplitStrategyLinear` which minimizes the change * in node bounding box area. */ const DEFAULT_SPLIT_STRATEGY: IRTreeSplitStrategy = new SplitStrategyLinear(); /** * The return result of predicates used with `RTree.queryNodes`. * * The `PASS_AND_OVERWRITE` value will overwrite previous results * when the predicate finds a more optimal result. */ export enum QueryPredicateResult { PASS, FAIL, PASS_AND_OVERWRITE, } /** * Returns the absolute distance to the nearest point on the edge of bounds or 0 * if the point is in bounds. */ export type IDistanceFunction = (bounds: RTreeBounds, p: Point) => number; /** * Creates a node predicate for use with `RTree.queryNodes` * * @param point - the query point * @param nearFn - an `IDistanceFunction` from the query point to the nearest * point on the node bounds * @param farFn - an `IDistanceFunction` from the query point to the farthest * point on the node bounds */ export function createMinimizingNodePredicate<T>(point: Point, nearFn: IDistanceFunction, farFn: IDistanceFunction) { let nearestLeafDistance = Infinity; let nearestBranchDistance = Infinity; let farthestBranchDistance = Infinity; return (node: RTreeNode<T>) => { const near = nearFn(node.bounds, point); const far = farFn(node.bounds, point); // assumption: node.value indicates that parent is a leaf if (node.value != null) { if (near < nearestLeafDistance) { nearestLeafDistance = near; nearestBranchDistance = near; farthestBranchDistance = far; return QueryPredicateResult.PASS_AND_OVERWRITE; } else if (near === nearestLeafDistance) { return QueryPredicateResult.PASS; } else { return QueryPredicateResult.FAIL; } } else { if (near > farthestBranchDistance) { return QueryPredicateResult.FAIL; } else { nearestBranchDistance = Math.min(near, nearestBranchDistance); farthestBranchDistance = Math.max(far, farthestBranchDistance); return QueryPredicateResult.PASS; } } }; } /** * Create a `Array.sort` function from a query point and a distance function. */ export function createNodeSort<T>(point: Point, distanceFn: IDistanceFunction) { return (a: RTreeNode<T>, b: RTreeNode<T>) => { return distanceFn(b.bounds, point) - distanceFn(a.bounds, point); }; } /** * R-Tree is a multidimensional spatial region tree. It stores entries that have * arbitrarily overlapping bounding boxes and supports efficient point and * bounding box overlap queries. * * Average search time complexity is O(log_M(N)) where M = max children per node * and N is number of values stored in tree. * * It is similar in purpose to a quadtree except quadtrees can only store a * single point per entry. Also, the space-partitioning structure of quadtrees * provides guarantees that any given value has no neighbors closer than its * node's bounds, whereas r-trees provide no such guarantees. */ export class RTree<T> { private root: RTreeNode<T>; private size: number; constructor( private maxNodeChildren = DEFAULT_MAX_NODE_CHILDREN, private splitStrategy = DEFAULT_SPLIT_STRATEGY, ) { this.root = new RTreeNode<T>(true); this.size = 0; } public getRoot() { return this.root; } public clear() { this.root = new RTreeNode<T>(true); this.size = 0; } public insert(bounds: RTreeBounds, value: T) { let node = this.root; // Choose subtree until we find a leaf while (!node.leaf) { node = node.subtree(bounds); } // Insert new value node into leaf node const valueNode = RTreeNode.valueNode<T>(bounds, value); node.insert(valueNode); this.size += 1; // While node overflows, split and walk up while (node.overflow(this.maxNodeChildren)) { node = node.split(this.splitStrategy); if (node.parent == null) { this.root = node; } } return valueNode; } public locate(xy: Point) { return this.query((b) => b.contains(xy)); } /** * Returns an array of `T` values that are the "nearest" to the query point. * * Nearness is measured as the absolute distance from the query point to the * nearest edge of the node bounds. If the node bounds contains the query * point, the distance is 0. */ public locateNearest(xy: Point) { const predicate = createMinimizingNodePredicate( xy, RTreeBounds.distanceSquaredToNearEdge, RTreeBounds.distanceSquaredToFarEdge, ); const nodes = this.queryNodes(predicate); return nodes.map((node) => node.value); } /** * Returns an array of `T` values that are the "nearest" to the query point. * * Nearness is measured as the 1-dimensional absolute distance from the * query's x point to the nearest edge of the node bounds. If the node * bounds contains the query point, the distance is 0. * * The results are sorted by y-coordinate nearness. */ public locateNearestX(xy: Point) { const predicate = createMinimizingNodePredicate( xy, RTreeBounds.absoluteDistanceToNearEdgeX, RTreeBounds.absoluteDistanceToFarEdgeX, ); const nodes = this.queryNodes(predicate); nodes.sort(createNodeSort(xy, RTreeBounds.absoluteDistanceToNearEdgeY)); return nodes.map((node) => node.value); } /** * Returns an array of `T` values that are the "nearest" to the query point. * * Nearness is measured as the 1-dimensional absolute distance from the * query's y point to the nearest edge of the node bounds. If the node * bounds contains the query point, the distance is 0. * * The results are sorted by x-coordinate nearness. */ public locateNearestY(xy: Point) { const predicate = createMinimizingNodePredicate( xy, RTreeBounds.absoluteDistanceToNearEdgeY, RTreeBounds.absoluteDistanceToFarEdgeY, ); const nodes = this.queryNodes(predicate); nodes.sort(createNodeSort(xy, RTreeBounds.absoluteDistanceToNearEdgeX)); return nodes.map((node) => node.value); } public intersect(bounds: RTreeBounds) { return this.query((b) => RTreeBounds.isBoundsOverlapBounds(b, bounds)); } public intersectX(bounds: RTreeBounds) { return this.query((b) => RTreeBounds.isBoundsOverlapX(b, bounds)); } public intersectY(bounds: RTreeBounds) { return this.query((b) => RTreeBounds.isBoundsOverlapY(b, bounds)); } public query(predicate: (b: RTreeBounds) => boolean) { const results: T[] = []; if (this.root.bounds != null && !predicate(this.root.bounds)) { return results; } const candidates = [this.root]; while (candidates.length > 0) { const candidate = candidates.shift(); for (let i = 0; i < candidate.entries.length; i++) { const entry = candidate.entries[i]; if (predicate(entry.bounds)) { if (candidate.leaf) { results.push(entry.value); } else { candidates.push(entry); } } } } return results; } public queryNodes(predicate: (b: RTreeNode<T>) => QueryPredicateResult) { let results: RTreeNode<T>[] = []; if (this.root.bounds != null && predicate(this.root) === QueryPredicateResult.FAIL) { return results; } const candidates = [this.root]; while (candidates.length > 0) { const candidate = candidates.shift(); for (let i = 0; i < candidate.entries.length; i++) { const entry = candidate.entries[i]; const p = predicate(entry); if (p === QueryPredicateResult.PASS_AND_OVERWRITE) { results = []; } if (p === QueryPredicateResult.PASS || p === QueryPredicateResult.PASS_AND_OVERWRITE) { if (candidate.leaf) { results.push(entry); } else { candidates.push(entry); } } } } return results; } } export class RTreeNode<T> { public static valueNode<T>(bounds: RTreeBounds, value: T) { const node = new RTreeNode<T>(true); node.bounds = bounds; node.value = value; return node; } public bounds: RTreeBounds = null; public entries: RTreeNode<T>[] = []; public parent: RTreeNode<T> = null; public value: T = null; constructor( public leaf: boolean, ) {} /** * Returns `true` iff this node has more children than the `maxNodeChildren` * parameter. */ public overflow(maxNodeChildren: number) { return this.entries.length > maxNodeChildren; } /** * Inserts a child node and updates the ancestry bounds. */ public insert(node: RTreeNode<T>) { this.entries.push(node); node.parent = this; // Update ancestor bounds let ancestor: RTreeNode<T> = this; while (ancestor != null) { ancestor.bounds = RTreeBounds.unionAll([ancestor.bounds, node.bounds]); ancestor = ancestor.parent; } return this; } /** * Removes a child node and updates the ancestry bounds. * * If the node argument is not a child, do nothing. */ public remove(node: RTreeNode<T>) { const i = this.entries.indexOf(node); if (i >= 0) { this.entries.splice(i, 1); // Update ancestor bounds let ancestor: RTreeNode<T> = this; while (ancestor != null) { ancestor.bounds = RTreeBounds.unionAll(ancestor.entries.map((e) => e.bounds)); ancestor = ancestor.parent; } } return this; } /** * Chooses an node from then entries that minimizes the area difference that * adding the bounds the each entry would cause. */ public subtree(bounds: RTreeBounds) { const minDiff = Infinity; let minEntry = null; // choose entry for which the addition least increases the entry's area for (let i = 0; i < this.entries.length; i++) { const entry = this.entries[i]; const diffArea = entry.unionAreaDifference(bounds); if (diffArea < minDiff || ( // break ties to node with fewest children diffArea === minDiff && minEntry != null && entry.entries.length < minEntry.entries.length ) ) { minEntry = entry; } } return minEntry; } /** * Splits this node by creating two new nodes and dividing the this node's * children between them. This node is removed from its parent and the two * new nodes are added. * * If this node is the root, a new parent node is created. * * Returns the parent node. */ public split(strategy: IRTreeSplitStrategy): RTreeNode<T> { // Remove self from parent. if (this.parent != null) { this.parent.remove(this); } // Create children from split const children: NodePair<T> = [ new RTreeNode<T>(this.leaf), new RTreeNode<T>(this.leaf), ]; strategy.split(this.entries, children); // Add new nodes to parent // If root, create new non-leaf node as parent. const parent = this.parent != null ? this.parent : new RTreeNode<T>(false); parent.insert(children[0]); parent.insert(children[1]); // Always make the parent a non-leaf after split parent.leaf = false; return parent; } /** * Returns the difference in area that adding an entry `bounds` to the node * would cause. */ public unionAreaDifference(bounds: RTreeBounds) { return Math.abs(RTreeBounds.union(this.bounds, bounds).area() - this.bounds.area()); } /** * Returns the depth from this node to the deepest leaf descendant. */ public maxDepth(): number { if (this.leaf) return 1; return 1 + this.entries.map((e) => e.maxDepth()).reduce((a, b) => Math.max(a, b)); } } export class RTreeBounds { public static xywh(x: number, y: number, w: number, h: number) { return new RTreeBounds(x, y, x + w, y + h); } public static entityBounds(bounds: IEntityBounds) { return new RTreeBounds( bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height, ); } public static bounds(bounds: Bounds) { return RTreeBounds.pointPair( bounds.topLeft, bounds.bottomRight, ); } public static pointPair(p0: Point, p1: Point) { return new RTreeBounds( Math.min(p0.x, p1.x), Math.min(p0.y, p1.y), Math.max(p0.x, p1.x), Math.max(p0.y, p1.y), ); } public static points(points: Point[]) { if (points.length < 2) { throw new Error("need at least 2 points to create bounds"); } const xs: number[] = points.map((p) => p.x); const ys: number[] = points.map((p) => p.y); return new RTreeBounds( xs.reduce((a, b) => Math.min(a, b)), ys.reduce((a, b) => Math.min(a, b)), xs.reduce((a, b) => Math.max(a, b)), ys.reduce((a, b) => Math.max(a, b)), ); } public static union(b0: RTreeBounds, b1: RTreeBounds) { return new RTreeBounds( Math.min(b0.xl, b1.xl), Math.min(b0.yl, b1.yl), Math.max(b0.xh, b1.xh), Math.max(b0.yh, b1.yh), ); } public static unionAll(bounds: RTreeBounds[]) { bounds = bounds.filter((b) => b != null); if (bounds.length === 0) { return null; } return bounds.reduce((b0, b1) => RTreeBounds.union(b0, b1)); } /** * Returns true if `a` overlaps `b` in the x and y axes. * * Touching counts as overlap. */ public static isBoundsOverlapBounds(a: RTreeBounds, b: RTreeBounds) { return RTreeBounds.isBoundsOverlapX(a, b) && RTreeBounds.isBoundsOverlapY(a, b); } /** * Returns true if `a` overlaps `b` in the x axis only. * * Touching counts as overlap. */ public static isBoundsOverlapX(a: RTreeBounds, b: RTreeBounds) { return !(a.xh < b.xl) && !(a.xl > b.xh); } /** * Returns true if `a` overlaps `b` in the y axis only. * * Touching counts as overlap. */ public static isBoundsOverlapY(a: RTreeBounds, b: RTreeBounds) { return !(a.yh < b.yl) && !(a.yl > b.yh); } /** * Returns the orthogonal absolute distance in the x-dimension from point * `p` to the nearest edge of `bounds`. * * If `p.x` is inside the bounds returns `0`. */ public static absoluteDistanceToNearEdgeX(bounds: RTreeBounds, p: Point) { const half = bounds.width / 2; const mid = bounds.xl + half; return Math.max(Math.abs(p.x - mid) - half, 0); } /** * Returns the orthogonal absolute distance in the y-dimension from point * `p` to the nearest edge of `bounds`. * * If `p.y` is inside the bounds returns `0`. */ public static absoluteDistanceToNearEdgeY(bounds: RTreeBounds, p: Point) { const half = bounds.height / 2; const mid = bounds.yl + half; return Math.max(Math.abs(p.y - mid) - half, 0); } /** * Returns the orthogonal absolute distance in the x-dimension from point * `p` to the farthest edge of `bounds`. * * If `p.x` is inside the bounds returns `0`. */ public static absoluteDistanceToFarEdgeX(bounds: RTreeBounds, p: Point) { const near = RTreeBounds.absoluteDistanceToNearEdgeX(bounds, p); return near === 0 ? 0 : near + bounds.width; } /** * Returns the orthogonal absolute distance in the y-dimension from point * `p` to the farthest edge of `bounds`. * * If `p.y` is inside the bounds returns `0`. */ public static absoluteDistanceToFarEdgeY(bounds: RTreeBounds, p: Point) { const near = RTreeBounds.absoluteDistanceToNearEdgeY(bounds, p); return near === 0 ? 0 : near + bounds.height; } /** * Returns the distance squared from `p` to the nearest edge of `bounds`. If * the point touches or is inside the bounds, returns `0`; * * https://gamedev.stackexchange.com/questions/44483/how-do-i-calculate-distance-between-a-point-and-an-axis-aligned-rectangle */ public static distanceSquaredToNearEdge(bounds: RTreeBounds, p: Point) { const dx = RTreeBounds.absoluteDistanceToNearEdgeX(bounds, p); const dy = RTreeBounds.absoluteDistanceToNearEdgeY(bounds, p); return dx * dx + dy * dy; } public static distanceSquaredToFarEdge(bounds: RTreeBounds, p: Point) { const dx = RTreeBounds.absoluteDistanceToFarEdgeX(bounds, p); const dy = RTreeBounds.absoluteDistanceToFarEdgeY(bounds, p); return dx * dx + dy * dy; } public width: number; public height: number; private areaCached: number; constructor( public xl: number, public yl: number, public xh: number, public yh: number, ) { this.width = this.xh - this.xl; this.height = this.yh - this.yl; } public area() { if (this.areaCached == null) { this.areaCached = (this.xh - this.xl) * (this.yh - this.yl); } return this.areaCached; } public contains(xy: Point) { return this.xl <= xy.x && this.xh >= xy.x && this.yl <= xy.y && this.yh >= xy.y; } }
the_stack
import EditorUI = require("../../EditorUI"); import CreateComponentButton = require("./CreateComponentButton"); import ScriptWidget = require("ui/ScriptWidget"); import SerializableEditType = require("./SerializableEditType"); import SelectionSection = require("./SelectionSection"); import SelectionPrefabWidget = require("./SelectionPrefabWidget"); import AttributeInfoEdit = require("./AttributeInfoEdit"); class NodeSection extends SelectionSection { prefabWidget: SelectionPrefabWidget; transformEdits: AttributeInfoEdit[] = []; updateDelta: number = 0.0; constructor(editType: SerializableEditType) { super(editType); this.prefabWidget = new SelectionPrefabWidget(); this.attrLayout.addChild(this.prefabWidget); this.transformEdits.push(this.attrEdits["Position"]); this.transformEdits.push(this.attrEdits["Rotation"]); this.transformEdits.push(this.attrEdits["Scale"]); this.subscribeToEvent(Atomic.UpdateEvent((ev) => this.handleUpdate(ev))); } handleUpdate(ev) { this.updateDelta -= ev.timeStep; if (this.updateDelta < 0.0) { this.updateDelta = 0.1; Atomic.ui.blockChangedEvents = true; for (var i in this.transformEdits) { this.transformEdits[i].refresh(); } Atomic.ui.blockChangedEvents = false; } } } class ComponentSection extends SelectionSection { constructor(editType: SerializableEditType, inspector: SelectionInspector) { super(editType); var deleteButton = new Atomic.UIButton(); deleteButton.text = "Delete Component"; deleteButton.fontDescription = SelectionSection.fontDesc; deleteButton.onClick = () => { inspector.onComponentDelete(editType); return true; }; var copyButton = new Atomic.UIButton(); copyButton.text = "Copy Settings"; copyButton.onClick = () => { inspector.onComponentCopy(editType); return true; }; var pasteButton = new Atomic.UIButton(); pasteButton.text = "Paste Settings"; pasteButton.onClick = () => { inspector.onComponentPaste(editType); return true; }; this.attrLayout.addChild(deleteButton); this.attrLayout.addChild(copyButton); this.attrLayout.addChild(pasteButton); } } class SceneSection extends SelectionSection { constructor(editType: SerializableEditType) { super(editType); } } class JSComponentSection extends ComponentSection { constructor(editType: SerializableEditType, inspector: SelectionInspector) { super(editType, inspector); this.hasDynamicAttr = true; this.subscribeToEvent(this, Editor.AttributeEditResourceChangedEvent((ev) => this.handleAttributeEditResourceChanged(ev))); this.updateTitleFromComponentClass(); } private handleAttributeEditResourceChanged(ev: Editor.AttributeEditResourceChangedEvent) { var jsc = <Atomic.JSComponent>this.editType.getFirstObject(); if (!jsc) return; var attrInfos = jsc.getAttributes(); this.updateDynamicAttrInfos(attrInfos); this.updateTitleFromComponentClass(); } private updateTitleFromComponentClass() { this.text = this.editType.typeName; let jsc = this.editType.getFirstObject() as Atomic.JSComponent; if (jsc && jsc.componentFile) { this.text = jsc.componentFile.name.split("/").pop(); let jscf = <Atomic.JSComponentFile> jsc.componentFile; if (jscf.typeScriptClass) { this.text = this.text.replace(".js", ".ts"); } } } } class CSComponentSection extends ComponentSection { constructor(editType: SerializableEditType, inspector: SelectionInspector) { super(editType, inspector); this.updateTextFromClassAttr(); this.hasDynamicAttr = true; this.subscribeToEvent(this, Editor.AttributeEditResourceChangedEvent((ev) => this.handleAttributeEditResourceChanged(ev))); this.subscribeToEvent(AtomicNETScript.CSComponentAssemblyChangedEvent((ev) => this.handleCSComponentAssemblyChanged(ev))); this.subscribeToEvent(AtomicNETScript.CSComponentClassChangedEvent((ev) => this.handleCSComponentClassChanged(ev))); } private handleCSComponentAssemblyChanged(ev) { var csc = <AtomicNETScript.CSComponent>this.editType.getFirstObject(); if (!csc) return; if (csc.componentFile == <Atomic.ScriptComponentFile> ev.resource) { var attrInfos = csc.getAttributes(); this.updateDynamicAttrInfos(attrInfos); this.updateTextFromClassAttr(); } } private handleCSComponentClassChanged(ev) { var csc = <AtomicNETScript.CSComponent>this.editType.getFirstObject(); if (!csc) return; var attrInfos = csc.getAttributes(); this.updateDynamicAttrInfos(attrInfos); this.updateTextFromClassAttr(); } private handleAttributeEditResourceChanged(ev: Editor.AttributeEditResourceChangedEvent) { var csc = <AtomicNETScript.CSComponent>this.editType.getFirstObject(); if (!csc) return; var attrInfos = csc.getAttributes(); this.updateDynamicAttrInfos(attrInfos); } private updateTextFromClassAttr() { this.text = this.editType.typeName; var object = this.editType.getFirstObject(); if (object) { var value = object.getAttribute("Class"); if (value) this.text = value + " - C#"; } } } // Node Inspector + Component Inspectors class SelectionInspector extends ScriptWidget { component: Atomic.Component; constructor(sceneEditor: Editor.SceneEditor3D) { super(); this.sceneEditor = sceneEditor; var mainLayout = this.mainLayout = new Atomic.UILayout(); mainLayout.spacing = 4; var lp = new Atomic.UILayoutParams(); lp.width = 304; mainLayout.layoutDistribution = Atomic.UI_LAYOUT_DISTRIBUTION.UI_LAYOUT_DISTRIBUTION_GRAVITY; mainLayout.layoutPosition = Atomic.UI_LAYOUT_POSITION.UI_LAYOUT_POSITION_LEFT_TOP; mainLayout.layoutParams = lp; mainLayout.axis = Atomic.UI_AXIS.UI_AXIS_Y; this.addChild(mainLayout); var noticeLayout = this.multipleSelectNotice = new Atomic.UILayout(); noticeLayout.axis = Atomic.UI_AXIS.UI_AXIS_Y; noticeLayout.layoutParams = lp; var noticeText = new Atomic.UITextField(); noticeText.textAlign = Atomic.UI_TEXT_ALIGN.UI_TEXT_ALIGN_CENTER; noticeText.skinBg = "InspectorTextAttrName"; noticeText.text = "Multiple Selection - Some components are hidden"; noticeText.fontDescription = SelectionSection.fontDesc; noticeText.gravity = Atomic.UI_GRAVITY.UI_GRAVITY_LEFT_RIGHT; noticeText.layoutParams = lp; noticeLayout.addChild(noticeText); noticeLayout.visibility = Atomic.UI_WIDGET_VISIBILITY.UI_WIDGET_VISIBILITY_GONE; mainLayout.addChild(noticeLayout); this.createComponentButton = new CreateComponentButton(); mainLayout.addChild(this.createComponentButton); this.subscribeToEvent(sceneEditor.scene, Editor.SceneEditStateChangesBeginEvent((data) => this.handleSceneEditStateChangesBeginEvent())); this.subscribeToEvent(Editor.SceneEditStateChangeEvent((data) => this.handleSceneEditStateChangeEvent(data))); this.subscribeToEvent(sceneEditor.scene, Editor.SceneEditStateChangesEndEvent((data) => this.handleSceneEditStateChangesEndEvent())); this.subscribeToEvent(sceneEditor.scene, Editor.SceneEditNodeRemovedEvent((ev: Editor.SceneEditNodeRemovedEvent) => this.handleSceneEditNodeRemoved(ev))); this.subscribeToEvent(sceneEditor.scene, Editor.SceneEditComponentAddedRemovedEvent((ev) => this.handleSceneEditComponentAddedRemovedEvent(ev))); this.subscribeToEvent(this.createComponentButton, Editor.SelectionCreateComponentEvent((data) => this.handleSelectionCreateComponent(data))); } pruneSections() { var remove: SelectionSection[] = []; for (var i in this.sections) { var section = this.sections[i]; var editType = section.editType; if (editType.typeName == "Node") { continue; } if (editType.typeName == "Scene") { var gotone = false; for (var j in this.nodes) { if (this.nodes[j].typeName == "Scene") { gotone = true; break; } } if (gotone) continue; } if (!editType.nodes.length) { remove.push(section); } } if (remove.length) { for (var i in remove) { var section = remove[i]; this.removeSection(section); } this.suppressSections(); } } suppressSections() { this.multipleSelectNotice.visibility = Atomic.UI_WIDGET_VISIBILITY.UI_WIDGET_VISIBILITY_GONE; for (var i in this.sections) { var section = this.sections[i]; var editType = section.editType; if (editType.typeName == "Node" || editType.typeName == "Scene") { continue; } var suppressed = false; for (var j in this.nodes) { if (editType.nodes.indexOf(this.nodes[j]) == -1) { suppressed = true; break; } } if (suppressed) this.multipleSelectNotice.visibility = Atomic.UI_WIDGET_VISIBILITY.UI_WIDGET_VISIBILITY_VISIBLE; section.suppress(suppressed); } } refresh() { Atomic.ui.blockChangedEvents = true; this.pruneSections(); this.suppressSections(); for (var i in this.sections) { this.sections[i].refresh(); } if (this.nodeSection) { this.nodeSection.prefabWidget.updateSelection(this.nodes); } Atomic.ui.blockChangedEvents = false; } addSection(editType: SerializableEditType) { var section: SelectionSection; if (editType.typeName == "Node") { this.nodeSection = new NodeSection(editType); section = this.nodeSection; } else if (editType.typeName == "Scene") { section = new SceneSection(editType); } else if (editType.typeName == "JSComponent") { section = new JSComponentSection(editType, this); } else if (editType.typeName == "CSComponent") { section = new CSComponentSection(editType, this); } else { section = new ComponentSection(editType, this); } section.value = SelectionInspector.sectionStates[editType.typeName] ? 1 : 0; this.mainLayout.removeChild(this.createComponentButton, false); this.mainLayout.removeChild(this.multipleSelectNotice, false); // sort it in alphabetically this.sections.push(section); this.sections.sort(function(a, b) { if (a.editType.typeName == "Node" && b.editType.typeName == "Scene") return -1; if (a.editType.typeName == "Scene" && b.editType.typeName == "Node") return 1; if (a.editType.typeName == "Node" || a.editType.typeName == "Scene") return -1; if (b.editType.typeName == "Node" || b.editType.typeName == "Scene") return 1; return a.editType.typeName.localeCompare(b.editType.typeName); }); var idx = this.sections.indexOf(section); if (idx == 0) { if (this.sections.length == 1) { this.mainLayout.addChild(section); } else { this.mainLayout.addChildBefore(section, this.sections[1]); } } else if (idx == this.sections.length - 1) { this.mainLayout.addChild(section); } else { this.mainLayout.addChildAfter(section, this.sections[idx - 1]); } // move the create component button down this.mainLayout.addChild(this.multipleSelectNotice); this.mainLayout.addChild(this.createComponentButton); } removeSection(section: SelectionSection) { SelectionInspector.sectionStates[section.editType.typeName] = section.value ? true : false; var index = this.sections.indexOf(section); this.sections.splice(index, 1); this.mainLayout.removeChild(section); } removeSerializable(serial: Atomic.Serializable) { for (var i in this.sections) { var section = this.sections[i]; var e = section.editType; var index = e.objects.indexOf(serial); if (index != -1) { e.objects.splice(index, 1); } if (serial.typeName == "Node") { index = e.nodes.indexOf(<Atomic.Node>serial); if (index != -1) { e.nodes.splice(index, 1); } } } } addSerializable(serial: Atomic.Serializable): SerializableEditType { var editType = this.getEditType(serial); // does it already exist? for (var i in this.sections) { var section = this.sections[i]; var e = section.editType; if (e.compareTypes(editType, this.nodes.length > 1)) { e.addSerializable(serial); return e; } } this.addSection(editType); return editType; } getEditType(serial: Atomic.Serializable): SerializableEditType { var typeName = serial.typeName; if (SelectionInspector._editTypes[typeName]) { return new SelectionInspector._editTypes[typeName](serial); } return new SerializableEditType(serial); } addNode(node: Atomic.Node) { var index = this.nodes.indexOf(node); if (index == -1) { this.nodes.push(node); this.addSerializable(node); var components = node.getComponents(); for (var i in components) { if (this.filterComponent(components[i])) continue; var editType = this.addSerializable(components[i]); editType.addNode(node); } this.refresh(); } } removeNode(node: Atomic.Node) { var index = this.nodes.indexOf(node); if (index != -1) { this.nodes.splice(index, 1); this.removeSerializable(node); var components = node.getComponents(); for (var i in components) { if (this.filterComponent(components[i])) continue; this.removeSerializable(components[i]); } this.refresh(); } // save node section state if (!this.nodes.length && this.nodeSection) SelectionInspector.sectionStates["Node"] = this.nodeSection.value ? true : false; } handleSceneEditStateChangesBeginEvent() { this.stateChangesInProgress = true; } handleSceneEditNodeRemoved(ev: Editor.SceneEditNodeRemovedEvent) { this.removeNode(ev.node); } handleSceneEditComponentAddedRemovedEvent(ev: Editor.SceneEditComponentAddedRemovedEvent) { if (this.filterComponent(ev.component)) { // still refresh as may affect UI (for example PrefabComponents) this.refresh(); return; } var editType; if (!ev.removed) { editType = this.addSerializable(ev.component); editType.addNode(ev.node); } else { for (var i in this.sections) { var section = this.sections[i]; editType = section.editType; var index = editType.objects.indexOf(ev.component); if (index != -1) { editType.objects.splice(index, 1); index = editType.nodes.indexOf(ev.node); if (index != -1) { editType.nodes.splice(index, 1); } break; } } } this.refresh(); } onComponentDelete(editType: SerializableEditType) { var removed: Atomic.Component[] = []; for (var i in editType.objects) { var c = <Atomic.Component>editType.objects[i]; removed.push(c); } for (var i in removed) { var c = removed[i]; var node = c.node; c.remove(); this.removeSerializable(removed[i]); var index = editType.nodes.indexOf(node); if (index != -1) { editType.nodes.splice(index, 1); } } if (removed.length) { this.sceneEditor.scene.sendEvent(Editor.SceneEditEndEventType); this.refresh(); } } onComponentCopy(editType: SerializableEditType) { var copy: Atomic.Component[] = []; for (var i in editType.objects) { var c = <Atomic.Component>editType.objects[i]; copy.push(c); } for (var i in copy) { var c = copy[i]; this.component = c; this.sceneEditor.scene.sendEvent(Editor.SceneEditComponentCopyEventData({ component: this.component })); this.refresh(); } } onComponentPaste(editType: SerializableEditType) { var paste: Atomic.Component[] = []; for (var i in editType.objects) { var c = <Atomic.Component>editType.objects[i]; paste.push(c); } for (var i in paste) { var c = paste[i]; this.component = c; this.sceneEditor.scene.sendEvent(Editor.SceneEditComponentPasteEventData({ component: this.component , end: false})); this.refresh(); } } handleSelectionCreateComponent(ev) { var valid = true; if (ev.componentTypeName != "JSComponent" && ev.componentTypeName != "CSComponent") { for (var i in this.nodes) { var node = this.nodes[i]; if (node.getComponent(ev.componentTypeName, false)) { valid = false; break; } } } if (!valid) { EditorUI.showModalError("Component Create", "Unable to create component, a node with an existing " + ev.componentTypeName + " component is selected"); return; } for (var i in this.nodes) { var node = this.nodes[i]; var c = node.createComponent(ev.componentTypeName); if (!c) { console.log("ERROR: unable to create component ", ev.componentTypeName); return; } var editType = this.addSerializable(c); editType.addNode(node); for (var i in this.sections) { if (this.sections[i].editType == editType) { this.sections[i].value = 1; break; } } } this.refresh(); } handleSceneEditStateChangeEvent(ev: Editor.SceneEditStateChangeEvent) { if (!this.stateChangesInProgress) return; if (this.stateChanges.indexOf(ev.serializable) == -1) { this.stateChanges.push(ev.serializable); } } getPrefabComponent(node: Atomic.Node): Atomic.PrefabComponent { if (node.getComponent("PrefabComponent")) return <Atomic.PrefabComponent>node.getComponent("PrefabComponent"); if (node.parent) return this.getPrefabComponent(node.parent); return null; } filterComponent(component: Atomic.Component): boolean { if (component.typeName == "PrefabComponent") { return true; } return false; } handleSceneEditStateChangesEndEvent() { Atomic.ui.blockChangedEvents = true; var sections: SelectionSection[] = []; for (var i in this.stateChanges) { var serial = this.stateChanges[i]; for (var j in this.sections) { var section = this.sections[j]; if (sections.indexOf(section) != -1) continue; if (section.editType.objects.indexOf(serial) != -1) { sections.push(section); if (section.hasDynamicAttr) { var object = section.editType.getFirstObject(); if (object) { var attrInfos = object.getAttributes(); section.updateDynamicAttrInfos(attrInfos); } } section.refresh(); } } } Atomic.ui.blockChangedEvents = false; this.stateChanges = []; this.stateChangesInProgress = false; } mainLayout: Atomic.UILayout; multipleSelectNotice: Atomic.UILayout; sceneEditor: Editor.SceneEditor3D; nodes: Atomic.Node[] = []; sections: SelectionSection[] = []; createComponentButton: CreateComponentButton; nodeSection: NodeSection; stateChangesInProgress: boolean = false; stateChanges: Atomic.Serializable[] = []; // ------------------------------------ static registerEditType(typeName: string, type: typeof SerializableEditType) { SelectionInspector._editTypes[typeName] = type; } private static sectionStates: { [typeName: string]: boolean } = {}; private static _editTypes: { [typeName: string]: typeof SerializableEditType } = {}; private static Ctor = (() => { SelectionInspector.sectionStates["Node"] = true; })(); } export = SelectionInspector;
the_stack
import { Component, ElementRef, OnInit, AfterViewChecked, EventEmitter } from '@angular/core'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import { DomSanitizer } from '@angular/platform-browser/'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { User } from '../common/user'; import { JobTitle } from '../../job-title'; import { UserService } from '../common/user.service'; import { FormConstantsService } from '../../_services/form-constants.service'; import { AuthService } from '../../auth.service'; import { SkillService } from '../../skill/common/skill.service'; import { MaterializeAction } from 'angular2-materialize'; import { ExtFileHandlerService } from '../../_services/extfilehandler.service'; import { ValidationService } from '../../_services/validation.service'; declare var Materialize: any; @Component({ selector: 'my-edit-user', templateUrl: 'user-edit.component.html', styleUrls: ['user-edit.component.scss'] }) export class UserEditComponent implements OnInit, AfterViewChecked { currentUserId: String; public countries: any[]; public userId; public userEmail; public userRole; public userFirstName; public userLastName; public user: User; public jobTitlesArray: JobTitle[] = []; public loadedFile: any; public userSkillsArray: string[] = []; public skillsArray: string[] = []; public skill = ''; public skillCounter = 0; public inputValue = ''; public avatar: any = ''; public isVolunteer = false; public isOrganization = false; public checkPublish = false; public checkNotify = false; public isSkillExists = false; public isSkillLimit = false; // public isNew = false; public isUserInfoIncomplete = false; public introMaxLength: number = this.validationService.introMaxLength; public introMaxLengthEntered = false; public introValueLength: number; public introFieldFocused = false; public descMaxLength = 255; public userForm: FormGroup; public formPlaceholder: { [key: string]: any } = {}; public globalActions = new EventEmitter<string|MaterializeAction>(); public modalActions = new EventEmitter<string|MaterializeAction>(); constructor( public fb: FormBuilder, private userService: UserService, private auth: AuthService, public constantsService: FormConstantsService, private el: ElementRef, private sanitizer: DomSanitizer, private route: ActivatedRoute, private router: Router, private skillService: SkillService, private extfilehandler: ExtFileHandlerService, private validationService: ValidationService ) { } ngOnInit(): void { this.currentUserId = this.auth.getCurrentUserId(); this.getFormConstants(); this.initForm(); if (this.auth.isOrganization()) { this.isOrganization = true; } else if (this.auth.isVolunteer()) { this.isVolunteer = true; } this.skillService.getSkills() .subscribe( res => { res.map((obj) => { this.skillsArray.push(obj.skillName); }); }, error => console.log(error) ); // this.route.params.subscribe(params => { // this.userId = +params['userId']; this.userService.getAllJobTitles() .subscribe( res => { this.jobTitlesArray = res; }, error => console.log(error) ); if (this.currentUserId === null) { this.fillForm(); } else { this.route.params.subscribe(params => { this.userId = +params['userId']; // Populate user this.populateUser(); // Populate skills list this.skillService.getSkillsForUser(this.userId) .subscribe( res => { this.userSkillsArray = res; }, error => console.log(error) ); }); } } private populateUser(): void { this.userService.getUser(this.userId) .subscribe( res => { this.user = res; this.avatar = this.user.avatarUrl; if (this.user === null || this.user === undefined) { this.isUserInfoIncomplete = true; } else { if (this.user.userName === null || this.user.userName === '' || this.user.firstName === null || this.user.firstName === '' || this.user.lastName === null || this.user.lastName === '' || this.user.country === null || this.user.country === '' || this.user.title === null || this.user.title === '') { this.isUserInfoIncomplete = true; } } /* if (this.user.status === 'N') { this.isNew = true; } */ if (this.user.publishFlag === 'Y') { this.checkPublish = true; } else { this.checkPublish = false; } if (this.user.notifyFlag === 'Y' ) { this.checkNotify = true; } else { this.checkNotify = false; } this.fillForm(); }, error => console.log(error) ); } private getFormConstants(): void { this.countries = this.constantsService.getCountries(); } private initForm(): void { this.userForm = this.fb.group({ 'email': ['', []], 'jobTitleId': ['', []], 'userName': ['', []], 'firstName': ['', []], 'lastName': ['', []], 'state': ['', []], 'country': [this.countries, []], 'phone': ['', []], 'title': ['', []], 'introduction': ['', []], 'linkedinUrl': ['', []], 'personalUrl': ['', []], 'githubUrl': ['', []], 'chatUsername': ['', []], 'publishFlag': ['', []], 'notifyFlag': ['', []] }); } private fillForm(): void { if (this.user === null || this.user === undefined) { this.checkPublish = true; this.checkNotify = true; this.userForm = this.fb.group({ 'email': [localStorage.getItem('currentUserEmail') || '', [Validators.required]], 'firstName': [localStorage.getItem('currentUserFName') || '', [Validators.required]], 'lastName': [localStorage.getItem('currentUserLName') || '', [Validators.required]], 'userName': ['', [Validators.required]], 'title': ['', [Validators.required]], 'introduction': [ '', [Validators.compose([Validators.maxLength(1000)])]], 'jobTitleId': ['', []], 'state': ['', []], 'country': [this.countries, []], 'phone': ['', []], 'linkedinUrl': ['', []], 'personalUrl': ['', []], 'githubUrl': ['', []], 'chatUsername': ['', []], 'publishFlag': [this.checkPublish, []], 'notifyFlag': [this.checkNotify, []] }); } else { this.userForm = this.fb.group({ 'email': [this.user.email || '', [Validators.required]], 'jobTitleId': [this.user.jobTitleId || '', []], 'userName': [this.user.userName || '', [Validators.required]], 'firstName': [this.user.firstName || '', [Validators.required]], 'lastName': [this.user.lastName || '', [Validators.required]], 'state': [this.user.state || '', []], 'country': [this.user.country || '', []], // validation on country cause red line shown, ignore validation 'phone': [this.user.phone || '', []], 'title': [this.user.title || '', [Validators.required]], 'introduction': [this.user.introduction || '', [Validators.compose([Validators.maxLength(10000)])]], 'linkedinUrl': [this.user.linkedinUrl || '', []], 'personalUrl': [this.user.personalUrl || '', []], 'githubUrl': [this.user.githubUrl || '', []], 'chatUsername': [this.user.chatUsername || '', []], 'publishFlag': [this.checkPublish || '', []], 'notifyFlag': [this.checkNotify || '', []] }); } } onSubmit(updatedData: any, event): void { event.preventDefault(); event.stopPropagation(); this.currentUserId = this.auth.getCurrentUserId(); this.userService.getUser(Number(this.currentUserId)) .subscribe( res => { this.user = res; this.user.email = this.userForm.value.email; this.user.userName = this.userForm.value.userName; this.user.firstName = this.userForm.value.firstName; this.user.lastName = this.userForm.value.lastName; this.user.title = this.userForm.value.title; this.user.introduction = this.userForm.value.introduction; this.user.state = this.userForm.value.state; this.user.country = this.userForm.value.country; this.user.phone = this.userForm.value.phone; this.user.linkedinUrl = this.userForm.value.linkedinUrl; this.user.personalUrl = this.userForm.value.personalUrl; this.user.githubUrl = this.userForm.value.githubUrl; this.user.chatUsername = this.userForm.value.chatUsername; this.user.jobTitleId = this.userForm.value.jobTitleId; if (this.userForm.value.publishFlag === true || this.userForm.value.publishFlag === 'Y' ) { this.user.publishFlag = 'Y'; } else { this.user.publishFlag = 'N'; } if (this.userForm.value.notifyFlag === true || this.userForm.value.notifyFlag === 'Y' ) { this.user.notifyFlag = 'Y'; } else { this.user.notifyFlag = 'N'; } if (this.isOrganization === true) { this.user.publishFlag = 'N'; this.user.notifyFlag = 'N'; } if (this.user.status === 'N') { // For new user, set status from 'N' (New) to 'A' (Active) this.user.status = 'A'; // this.isNew = false; } this.user.avatarUrl = this.avatar; this.userService.update(this.user) .subscribe(() => { Materialize.toast('Your account is saved', 4000); this.router.navigate(['/user/view', this.user.id]); }, err => { console.error(err, 'An error occurred'); } ); if (this.userSkillsArray.length > 0) { // Update skills for user this.skillService.updateUserSkills(this.userSkillsArray, this.user.id) .subscribe( res1 => { }, err => { console.error(err, 'An error occurred'); } ); } }); } onDeleteSkill(skillToDelete) { this.userSkillsArray = this.userSkillsArray.filter((projectSkill) => { return projectSkill !== skillToDelete; }); } onAddListedSkill(optionValue) { this.skillCounter = this.userSkillsArray.length; console.log(optionValue.target.value); this.checkSkillList (optionValue.target.value); if (!this.isSkillExists && !this.isSkillLimit) { this.userSkillsArray.push(optionValue.target.value); } } onAddOwnSkill(inputSkill) { this.skillCounter = this.userSkillsArray.length; console.log(inputSkill.value); if (inputSkill.value && inputSkill.value.trim()) { this.checkSkillList (inputSkill.value); if (!this.isSkillExists && !this.isSkillLimit) { this.userSkillsArray.push(inputSkill.value); this.inputValue = ''; } } } checkSkillList(selectedSkill) { this.isSkillExists = false; this.isSkillLimit = false; this.skillCounter = this.skillCounter + 1; if ( this.skillCounter > 10 ) { this.isSkillLimit = true; this.globalActions.emit({action: 'toast', params: ['Skill list exceeds limit 10', 4000]}); } if (!this.isSkillLimit) { for ( this.skill of this.userSkillsArray ) { if (selectedSkill === this.skill) { this.isSkillExists = true; this.globalActions.emit({action: 'toast', params: ['Selected skill already in the list', 4000]}); } } } } // Count chars in introduction field onCountCharIntro() { this.introValueLength = this.userForm.value.introduction.length; if (this.userForm.controls.introduction.invalid) { this.introMaxLengthEntered = true; } else { this.introMaxLengthEntered = false; } } onFocusIntro() { this.introFieldFocused = true; this.onCountCharIntro(); } onBlurIntro() { if (!this.userForm.controls.introduction.invalid) { this.introFieldFocused = false; } } // Orchestrates the avatar image upload sequence of steps onUploadAvatar(fileInput: any): void { if (fileInput.target.files[0].size < this.constantsService.maxFileSize) { if (this.user === null || this.user === undefined) { this.currentUserId = this.auth.getCurrentUserId(); } else { this.currentUserId = String(this.user.id); } // this.auth.getCurrentUserId(); // Function call to upload the file to AWS S3 const upload$ = this.extfilehandler.uploadFile(fileInput, Number(this.currentUserId), 'image'); // Calls the function to save the avatar image url to the user's row upload$.switchMap((res) => this.userService.saveAvatarImg(Number(this.currentUserId), res), (outerValue, innerValue, outerIndex, innerIndex) => ({ outerValue, innerValue, outerIndex, innerIndex })) .subscribe(res => { if (res.innerValue.text() === '') { this.avatar = res.outerValue; // this.user.avatarUrl = this.avatar; } else { console.error('Saving user avatar: Not expecting a response body'); } }, (e) => { console.error('Avatar not saved. Not expecting a response body'); }); } else { Materialize.toast('Maximum image size allowed is 1MB', 4000); } } deleteImage(): void { this.avatar = ''; this.userService.saveAvatarImg(this.userId, this.avatar) .subscribe(res => { this.user.avatarUrl = this.avatar; }, (error) => { console.log('Image not deleted successfully'); } ); } onDelete() { this.userService.delete(this.userId) .subscribe(() => { Materialize.toast('The user is deleted', 4000); this.auth.logout(); this.router.navigate(['/']); }, err => { console.error(err, 'An error occurred'); Materialize.toast('Error deleting the user', 4000); } ); } openModal() { this.modalActions.emit({action: 'modal', params: ['open']}); } closeModal() { this.modalActions.emit({action: 'modal', params: ['close']}); } ngAfterViewChecked(): void { // Activate the labels so that the text does not overlap // User edit page is customized based on user role, need to check element existance first if (document.getElementById('username-label') != null) { document.getElementById('username-label').classList.add('active'); } if (document.getElementById('email-label') != null) { document.getElementById('email-label').classList.add('active'); } if (document.getElementById('firstname-label') != null) { document.getElementById('firstname-label').classList.add('active'); } if (document.getElementById('lastname-label') != null) { document.getElementById('lastname-label').classList.add('active'); } if (document.getElementById('state-label') != null) { document.getElementById('state-label').classList.add('active'); } if (document.getElementById('title-label') != null) { document.getElementById('title-label').classList.add('active'); } if (document.getElementById('summary-label') != null) { document.getElementById('summary-label').classList.add('active'); } if (document.getElementById('linkedin-label') != null) { document.getElementById('linkedin-label').classList.add('active'); } if (document.getElementById('github-label') != null) { document.getElementById('github-label').classList.add('active'); } if (document.getElementById('personal-label') != null) { document.getElementById('personal-label').classList.add('active'); } if (document.getElementById('slack-label') != null) { document.getElementById('slack-label').classList.add('active'); } if (document.getElementById('phone-label') != null) { document.getElementById('phone-label').classList.add('active'); } if (Materialize && Materialize.updateTextFields) { Materialize.updateTextFields(); } } }
the_stack
import * as path from 'path'; import { logErrorMessage } from '../logger'; import type * as dfd from 'danfojs-node'; import type { Configs } from 'danfojs-node/types/config/config'; import { sendMessage } from '../comms'; import { DanfoNodePlotter } from './danforPlotter'; import { DisplayData } from '../types'; export class DanfoJsFormatter { static _instance: DanfoJsFormatter; private isLoaded?: boolean; private failedToInject?: boolean; private danfoJs?: typeof dfd; public static requestId: string = ''; public static get instance() { if (DanfoJsFormatter._instance) { return DanfoJsFormatter._instance; } DanfoJsFormatter._instance = new DanfoJsFormatter(); return DanfoJsFormatter._instance; } public static initialize(danfoModule: typeof dfd) { DanfoJsFormatter.instance.inject(danfoModule); } public canFormatAsDanfo(value: unknown) { if ((!value && typeof value !== 'object') || !this.danfoJs) { return false; } if (value instanceof this.danfoJs.Series) { return true; } if (value instanceof this.danfoJs.DataFrame) { return true; } return false; } public formatDanfoObject(value: unknown): DisplayData { if (this.canFormatAsDanfo(value) && this.danfoJs) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const { html } = value instanceof this.danfoJs?.Series ? seriesToHtmlJson(value) : frameToHtmlJson(value as any); return { type: 'multi-mime', value: [ { type: 'html', value: html, requestId: DanfoJsFormatter.requestId }, // { // type: 'json', // value: json // }, { type: 'text', value: (value as any).toString(), requestId: DanfoJsFormatter.requestId } ], requestId: DanfoJsFormatter.requestId }; } else { return { type: 'json', value, requestId: DanfoJsFormatter.requestId }; } } public inject(danfoModule: typeof dfd) { if (this.isLoaded || this.failedToInject) { return; } let config: Configs | undefined; if (danfoModule) { this.danfoJs = danfoModule; try { config = new (danfoModule as any).Configs(); } catch { // } } // eslint-disable-next-line @typescript-eslint/no-var-requires const loadedModules = Object.keys(require('module')._cache); const modulePath = path.join('node_modules', 'danfojs-node'); if (!loadedModules.some((item) => item.includes(modulePath))) { return; } this.isLoaded = true; try { // Get an instance of the danfo module (load it within the context of the VM, not in our code). if (this.danfoJs) { hijackSeriesPrint(this.danfoJs, config); hijackNDFramePrint(this.danfoJs, config); } // codeRunner("require('danfojs-node')").then((result) => { // this.danfoJs = result as typeof dfd; // hijackSeriesPrint(this.danfoJs); // hijackNDFramePrint(this.danfoJs); // }); } catch (ex) { this.failedToInject = true; logErrorMessage(`Failed to load danfojs-node`, ex); } } } function hijackSeriesPrint(danfoJs: typeof dfd, config?: Configs) { danfoJs.Series.prototype.print = function (this: dfd.Series) { // Always print the old format (this way user has text output & html). const rawText: string = this.toString(); const { html } = seriesToHtmlJson(this, config); sendMessage({ type: 'output', requestId: DanfoJsFormatter.requestId, data: { type: 'multi-mime', requestId: DanfoJsFormatter.requestId, value: [ { type: 'html', value: html, requestId: DanfoJsFormatter.requestId }, // { // type: 'json', // value: json // }, { type: 'text', value: rawText, requestId: DanfoJsFormatter.requestId } ] } }); }; danfoJs.Series.prototype.plot = function (this: dfd.Series, div: string) { const plotter = new DanfoNodePlotter(this, danfoJs, div); return plotter; }; } function hijackNDFramePrint(danfoJs: typeof dfd, config?: Configs) { danfoJs.DataFrame.prototype.print = function (this: dfd.DataFrame) { // Always print the old format (this way user has text output & html). const rawText: string = this.toString(); const { html } = frameToHtmlJson(this, config); sendMessage({ type: 'output', requestId: DanfoJsFormatter.requestId, data: { type: 'multi-mime', requestId: DanfoJsFormatter.requestId, value: [ { type: 'html', value: html, requestId: DanfoJsFormatter.requestId }, // { // type: 'json', // value: json // }, { type: 'text', value: rawText, requestId: DanfoJsFormatter.requestId } ] } }); }; danfoJs.DataFrame.prototype.plot = function (this: dfd.Series, div: string) { const plotter = new DanfoNodePlotter(this, danfoJs, div); return plotter; }; } function seriesToHtmlJson(series: dfd.Series, config?: Configs): { html: string; json: any[] } { const max_row = Math.max(config?.table_max_row || 100, 100); //config.get_max_row; // eslint-disable-next-line @typescript-eslint/no-explicit-any const data_arr: any[] = []; const header = [''].concat(series.columns); let idx, data; if (series.values.length > max_row) { //slice Object to show a max of [max_rows] data = series.values.slice(0, max_row); idx = series.index.slice(0, max_row); } else { data = series.values; idx = series.index; } const rowsHtml: string[] = []; const rowsJson: any[] = []; idx.forEach((val, i) => { const rowJson = {}; const row = [val].concat(data[i]); data_arr.push(row); const rowHtml = row .map((item, i) => { try { rowJson[header[i]] = item; } catch { // } return `<td>${item}</td>`; }) .join(''); rowsJson.push(rowJson); rowsHtml.push(`<tr>${rowHtml}</tr>`); }); const headers = header.map((item) => `<th>${item}</th>`); const html = `<table><thead><tr>${headers.join('')}</tr><tbody>${rowsHtml.join('')}</tbody>`; return { html, json: rowsJson }; } function frameToHtmlJson(df: dfd.DataFrame, config?: Configs): { html: string; json: any[] } { const max_col_in_console = Math.max(config?.get_max_col_in_console || 100, 100); const max_row = Math.max(config?.get_max_row || 100, 100); // let data; type Row = string[]; const data_arr: Row[] = []; // let idx = this.index const col_len = df.columns.length; // let row_len = this.values.length - 1 let header: string[] = []; if (col_len > max_col_in_console) { //truncate displayed columns to fit in the console const first_4_cols = df.columns.slice(0, 4); const last_3_cols = df.columns.slice(col_len - 4); //join columns with truncate ellipse in the middle header = [''].concat(first_4_cols).concat(['...']).concat(last_3_cols); let sub_idx, values_1, value_2; if (df.values.length > max_row) { //slice Object to show [max_rows] const df_subset_1 = df.iloc({ rows: [`0:${max_row}`], columns: ['0:4'] }); const df_subset_2 = df.iloc({ rows: [`0:${max_row}`], columns: [`${col_len - 4}:`] }); sub_idx = df.index.slice(0, max_row); values_1 = df_subset_1.values; value_2 = df_subset_2.values; } else { const df_subset_1 = df.iloc({ rows: ['0:'], columns: ['0:4'] }); const df_subset_2 = df.iloc({ rows: ['0:'], columns: [`${col_len - 4}:`] }); sub_idx = df.index.slice(0, max_row); values_1 = df_subset_1.values; value_2 = df_subset_2.values; } // merge dfs sub_idx.map((val, i) => { const row = [val].concat(values_1[i]).concat(['...']).concat(value_2[i]); data_arr.push(row); }); } else { //display all columns header = [''].concat(df.columns); let idx, values; if (df.values.length > max_row) { //slice Object to show a max of [max_rows] const data = df.loc({ rows: [`0:${max_row}`], columns: df.columns }); idx = data.index; values = data.values; } else { values = df.values; idx = df.index; } // merge cols idx.forEach((val, i) => { const row = [val].concat(values[i]); data_arr.push(row); }); } const rowsHtml: string[] = []; const rowsJson: any[] = []; data_arr.forEach((row) => { const rowJson = {}; const rowCellsHtml = row .map((item, i) => { try { rowJson[header[i]] = item; } catch { // } return `<td>${item}</td>`; }) .join(''); rowsJson.push(rowJson); rowsHtml.push(`<tr>${rowCellsHtml}</tr>`); }); const headers = header.map((item) => `<th>${item}</th>`); const html = `<table><thead><tr>${headers.join('')}</tr><tbody>${rowsHtml.join('')}</tbody>`; return { html, json: rowsJson }; }
the_stack
import {Component, ElementRef, Injector, Input, OnDestroy, OnInit} from '@angular/core'; import {UIOption} from '@common/component/chart/option/ui-option'; import * as _ from 'lodash'; import { BarMarkType, ChartType, DataLabelPosition, UIChartDataLabelDisplayType, UIOrient, UIPosition } from '@common/component/chart/option/define/common'; import {Pivot} from '@domain/workbook/configurations/pivot'; import {LabelBaseOptionComponent} from './labelbase-option.component'; import {LabelOptionConverter} from '@common/component/chart/option/converter/label-option-converter'; @Component({ selector: 'datalabel-option', templateUrl: './datalabel-option.component.html' }) export class DataLabelOptionComponent extends LabelBaseOptionComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 선반값 public pivot: Pivot; // 위치설정 Bar 세로형인경우 public positionBarVerticalList: object[] = [ { name: this.translateService.instant('msg.page.chart.datalabel.position.outside.top'), value: DataLabelPosition.OUTSIDE_TOP }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.top'), value: DataLabelPosition.INSIDE_TOP }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.bottom'), value: DataLabelPosition.INSIDE_BOTTOM }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.center'), value: DataLabelPosition.CENTER } ]; // 위치설정 Bar 가로형인경우 public positionBarHorizontalList: object[] = [ { name: this.translateService.instant('msg.page.chart.datalabel.position.outside.right'), value: DataLabelPosition.OUTSIDE_RIGHT }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.right'), value: DataLabelPosition.INSIDE_RIGHT }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.left'), value: DataLabelPosition.INSIDE_LEFT }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.center'), value: DataLabelPosition.CENTER } ]; // 위치설정 Gauge형인경우 public positionGaugeList: object[] = [ { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.top'), value: DataLabelPosition.INSIDE_TOP }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.bottom'), value: DataLabelPosition.INSIDE_BOTTOM }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.center'), value: DataLabelPosition.CENTER } ]; // 위치설정 Gauge 가로형인경우 public positionGaugeHorizontalList: object[] = [ { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.right'), value: DataLabelPosition.INSIDE_RIGHT }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.left'), value: DataLabelPosition.INSIDE_LEFT }, { name: this.translateService.instant('msg.page.chart.datalabel.position.inside.center'), value: DataLabelPosition.CENTER } ]; // 위치설정 Line 세로형인경우 public positionLineVerticalList: object[] = [ {name: this.translateService.instant('msg.page.chart.datalabel.position.top'), value: DataLabelPosition.TOP}, {name: this.translateService.instant('msg.page.chart.datalabel.position.bottom'), value: DataLabelPosition.BOTTOM}, {name: this.translateService.instant('msg.page.chart.datalabel.position.center'), value: DataLabelPosition.CENTER} ]; // 위치설정 Line 가로형인경우 public positionLineHorizontalList: object[] = [ {name: this.translateService.instant('msg.page.chart.datalabel.position.right'), value: DataLabelPosition.RIGHT}, {name: this.translateService.instant('msg.page.chart.datalabel.position.left'), value: DataLabelPosition.LEFT}, {name: this.translateService.instant('msg.page.chart.datalabel.position.center'), value: DataLabelPosition.CENTER} ]; // 위치설정 Box형인경우 public positionBoxList: object[] = [ {name: this.translateService.instant('msg.page.chart.datalabel.position.top'), value: DataLabelPosition.TOP}, {name: this.translateService.instant('msg.page.chart.datalabel.position.bottom'), value: DataLabelPosition.BOTTOM} ]; // 빈값을 제거한 displayTypes public displayTypes: UIChartDataLabelDisplayType[] = []; public get uiChartDataLabelDisplayType(): typeof UIChartDataLabelDisplayType{ return UIChartDataLabelDisplayType; } public get chartType(): typeof ChartType{ return ChartType; } public get uiPosition(): typeof UIPosition{ return UIPosition; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input('uiOption') public set setUiOption(uiOption: UIOption) { if (!uiOption.dataLabel) { uiOption.dataLabel = {}; uiOption.dataLabel.showValue = false; } // displayTypes가 없으면서 showValue가 true인 경우 displayTypes 설정 if (true === uiOption.dataLabel.showValue && !uiOption.dataLabel.displayTypes) { uiOption.dataLabel.displayTypes = this.setDisplayTypes(uiOption.type); } // pos값이 없을때 초기설정 if (!uiOption.dataLabel.pos) { const positionList = this.getPositionList(uiOption); if (positionList && positionList.length > 0) uiOption.dataLabel.pos = positionList[positionList.length - 1]['value']; } // treemap 차트일때 if (ChartType.TREEMAP === uiOption.type && !uiOption.dataLabel.hAlign) { uiOption.dataLabel.hAlign = UIPosition.CENTER; } if (ChartType.TREEMAP === uiOption.type && !uiOption.dataLabel.vAlign) { uiOption.dataLabel.vAlign = UIPosition.CENTER; } uiOption.dataLabel.previewList = LabelOptionConverter.setDataLabelPreviewList(uiOption); if (uiOption.dataLabel && uiOption.dataLabel.displayTypes) { // remove empty datas in displayTypes this.displayTypes = _.cloneDeep(uiOption.dataLabel.displayTypes.filter(Boolean)); } // useDefaultFormat이 없는경우 if (typeof uiOption.dataLabel.useDefaultFormat === 'undefined') uiOption.dataLabel.useDefaultFormat = true; // Set this.uiOption = uiOption; } @Input('pivot') public set setPivot(pivot: Pivot) { this.pivot = pivot; // 바차트의 중첩일때 dataLabel.pos값을 변경 if (ChartType.BAR === this.uiOption.type && BarMarkType.STACKED === this.uiOption['mark']) { const positionList = this.getPositionList(this.uiOption); if (positionList && positionList.length > 0) this.uiOption.dataLabel.pos = positionList[positionList.length - 1]['value']; } } // Init public ngOnInit() { // Init super.ngOnInit(); } // Destory public ngOnDestroy() { // Destory super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 수치값 표시 여부 * @param show */ public showValueLabel(show: boolean): void { this.uiOption.dataLabel.showValue = show; // showValue가 true인 경우 displayTypes 설정 if (true === this.uiOption.dataLabel.showValue) { // displayTypes가 없는경우 차트에 따라서 기본 displayTypes설정 if (!this.uiOption.dataLabel.displayTypes) { this.uiOption.dataLabel.displayTypes = this.setDisplayTypes(this.uiOption.type); // 빈값을 제외한 displayTypes this.displayTypes = _.cloneDeep(this.uiOption.dataLabel.displayTypes.filter(Boolean)); } } else { // 기본값으로 초기화 this.uiOption.dataLabel.displayTypes = this.setDisplayTypes(this.uiOption.type); this.displayTypes = _.cloneDeep(this.uiOption.dataLabel.displayTypes.filter(Boolean)); } this.apply(); } /** * 표시 레이블 선택 토글 * @param displayType * @param typeIndex */ public toggleDisplayType(displayType: UIChartDataLabelDisplayType, typeIndex: number): void { // 값이 없을경우 기화 if (!this.uiOption.dataLabel.displayTypes) { this.uiOption.dataLabel.displayTypes = []; } // 이미 체크된 상태라면 제거 let isFind = false; _.each(this.uiOption.dataLabel.displayTypes, (type, index) => { if (_.eq(type, displayType)) { isFind = true; this.uiOption.dataLabel.displayTypes[index] = null; } }); // 체크되지 않은 상태라면 추가 if (!isFind) { this.uiOption.dataLabel.displayTypes[typeIndex] = displayType; } // 빈값을 제외한 displayTypes this.displayTypes = _.cloneDeep(this.uiOption.dataLabel.displayTypes.filter(Boolean)); // preview 설정 this.uiOption.dataLabel.previewList = LabelOptionConverter.setDataLabelPreviewList(this.uiOption); // 적용 this.apply(); } /** * 차트 및 옵션에 따른 위치설정 목록을 반환한다. */ public getPositionList(uiOption: UIOption, chartSecondType?: ChartType): object[] { if (!uiOption) return; // 바형태 가로 / 세로형 차트일 경우, 결합차트의 바차트부분인경우 if (_.eq(uiOption.type, ChartType.BAR)) { // 가로형 if (_.eq(uiOption['align'], UIOrient.HORIZONTAL)) { return BarMarkType.STACKED === uiOption['mark'] ? this.positionGaugeHorizontalList : this.positionBarHorizontalList; } // 세로형 else { return BarMarkType.STACKED === uiOption['mark'] ? this.positionGaugeList : this.positionBarVerticalList; } } else if (_.eq(uiOption.type, ChartType.WATERFALL) || (_.eq(uiOption.type, ChartType.COMBINE) && _.eq(chartSecondType, ChartType.BAR))) { // 가로형 if (_.eq(uiOption['align'], UIOrient.HORIZONTAL)) { return this.positionBarHorizontalList; } // 세로형 else { return this.positionBarVerticalList; } } // 라인형태 가로 / 세로형 차트일 경우 else if (_.eq(uiOption.type, ChartType.LINE) || _.eq(uiOption.type, ChartType.SCATTER) || _.eq(uiOption.type, ChartType.SCATTER) || _.eq(uiOption.type, ChartType.COMBINE) || _.eq(uiOption.type, ChartType.RADAR) || _.eq(uiOption.type, ChartType.NETWORK) || _.eq(uiOption.type, ChartType.CONTROL)) { // 가로형 if (_.eq(uiOption['align'], UIOrient.HORIZONTAL)) { return this.positionLineHorizontalList; } // 세로형 else { return this.positionLineVerticalList; } } // 박스형태 차트일 경우 else if (_.eq(uiOption.type, ChartType.BOXPLOT)) { return this.positionBoxList; } // 게이지형태 차트일 경우 else if (_.eq(uiOption.type, ChartType.GAUGE)) { return this.positionGaugeList; } return []; } /** * 위치설정 인덱스를 반환한다. */ public getPositionIndex(pos: DataLabelPosition): number { // 반환 인덱스 let index: number = 0; // 목록 const positionList: object[] = this.getPositionList(this.uiOption); // 인덱스 찾음 _.each(positionList, (item, idx) => { if (_.eq(item['value'], pos)) { index = idx; return; } }); return index; } /** * 위치설정 변경 */ public changePosition(position: object): void { // 적용 this.uiOption.dataLabel.pos = position['value']; this.apply(); } /** * 결합차트 - line 차트부분 위치설정 변경 */ public changeLinePosition(position: object): void { // 적용 this.uiOption.dataLabel.secondaryPos = position['value']; this.apply(); } /** * 회전 가능여부 * @param lotation */ public changeRotation(lotation: boolean): void { // 적용 this.uiOption.dataLabel.enableRotation = lotation; this.apply(); } /** * 배경색 On / Off */ public changeBackgroundColor(): void { if (!this.uiOption.dataLabel.textBackgroundColor) { // this.uiOption.dataLabel.textBackgroundColor = "transparent"; this.uiOption.dataLabel.textBackgroundColor = '#000000'; } else { delete this.uiOption.dataLabel.textBackgroundColor; } this.apply(); } /** * 아웃라인 On / Off */ public changeTextOutlineColor(): void { if (!this.uiOption.dataLabel.textOutlineColor) { // this.uiOption.dataLabel.textOutlineColor = "transparent"; this.uiOption.dataLabel.textOutlineColor = '#000000'; } else { delete this.uiOption.dataLabel.textOutlineColor; } this.apply(); } /** * 정렬변경 */ public changeTextAlign(align: UIPosition): void { // 파이차트의 showOutside상태가 true인 경우 textAlign 적용하지 않음 if (this.uiOption['dataLabel']['showOutside']) return; // 적용 this.uiOption.dataLabel.textAlign = align; this.apply(); } /** * 기본포멧 사용여부 */ public changeUseDefaultFormat(): void { this.uiOption.dataLabel.useDefaultFormat = !this.uiOption.dataLabel.useDefaultFormat; this.apply(); } /** * 적용 */ public apply(): void { // 옵션 적용 this.uiOption = (_.extend({}, this.uiOption, {dataLabel: this.uiOption.dataLabel}) as UIOption); this.update(); } /** * use outside Label 변경 */ public toggleOutsideLabel(showOutside: boolean): void { const dataLabel = this.uiOption.dataLabel; dataLabel.showOutside = showOutside; // when set outside label, delete text align delete dataLabel.textAlign; this.uiOption = (_.extend({}, this.uiOption, {dataLabel: this.uiOption.dataLabel}) as UIOption); this.update(); } /** * text color setting auto / manual 설정 */ public showColorSetting(): void { // text color가 있는경우 => manual if (this.uiOption.dataLabel && this.uiOption.dataLabel.textColor) { // 색상 설정 제거 delete this.uiOption.dataLabel.textColor; delete this.uiOption.dataLabel.textBackgroundColor; delete this.uiOption.dataLabel.textOutlineColor; // text color가 없는경우 => 기본값 설정 } else { // 빈값 설정 // this.uiOption.dataLabel.textColor = ' '; this.uiOption.dataLabel.textColor = '#FFFFFF'; } this.uiOption = (_.extend({}, this.uiOption, {dataLabel: this.uiOption.dataLabel}) as UIOption); this.update(); } /** * treemap - 가로정렬 변경 */ public changeHAlign(hAlign: UIPosition): void { this.uiOption.dataLabel.hAlign = hAlign; this.uiOption = (_.extend({}, this.uiOption, {dataLabel: this.uiOption.dataLabel}) as UIOption); this.update(); } /** * treemap - 세로정렬 변경 */ public changeVAlign(vAlign: UIPosition): void { this.uiOption.dataLabel.vAlign = vAlign; this.uiOption = (_.extend({}, this.uiOption, {dataLabel: this.uiOption.dataLabel}) as UIOption); this.update(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 차트별 displayTypes 기본값 설정 */ private setDisplayTypes(chartType: ChartType): UIChartDataLabelDisplayType[] { const displayTypes = []; switch (chartType) { case ChartType.BAR: case ChartType.LINE: case ChartType.COMBINE: // when bar, line chart has single series if ((chartType === ChartType.BAR && this.pivot.aggregations.length <= 1 && this.pivot.rows.length < 1) || ((chartType === ChartType.LINE || chartType === ChartType.COMBINE) && this.pivot.aggregations.length <= 1)) { displayTypes[0] = UIChartDataLabelDisplayType.CATEGORY_NAME; displayTypes[1] = UIChartDataLabelDisplayType.CATEGORY_VALUE; // when bar, line, combine chart has multi series } else { displayTypes[3] = UIChartDataLabelDisplayType.SERIES_NAME; displayTypes[4] = UIChartDataLabelDisplayType.SERIES_VALUE; } break; case ChartType.CONTROL: case ChartType.WATERFALL: displayTypes[0] = UIChartDataLabelDisplayType.CATEGORY_NAME; displayTypes[1] = UIChartDataLabelDisplayType.CATEGORY_VALUE; break; case ChartType.HEATMAP: case ChartType.GAUGE: displayTypes[0] = UIChartDataLabelDisplayType.CATEGORY_NAME; displayTypes[3] = UIChartDataLabelDisplayType.SERIES_NAME; break; case ChartType.SCATTER: case ChartType.PIE: case ChartType.TREEMAP: displayTypes[3] = UIChartDataLabelDisplayType.SERIES_NAME; break; case ChartType.RADAR: displayTypes[8] = UIChartDataLabelDisplayType.VALUE; break; case ChartType.SANKEY: case ChartType.NETWORK: displayTypes[9] = UIChartDataLabelDisplayType.NODE_NAME; break; } return displayTypes; } }
the_stack
import { Engineers } from "./worlds/engineer"; import { World } from "./world"; import { Utils, Unlocable } from "./utils"; import { Base } from "./units/base"; import { Cost } from "./cost"; import { TypeList } from "./typeList"; import { Action, Research } from "./units/action"; import { Production } from "./production"; import { Map } from "rxjs/util/Map"; import { Unit } from "./units/unit"; import * as LZString from "lz-string"; import { BaseWorld } from "./worlds/baseWorld"; import { WorldInterface } from "./worlds/worldInterface"; import { Machine } from "./worlds/machine"; import { Bee } from "./worlds/bee"; import { Forest } from "./worlds/forest"; import { Beach } from "./worlds/beach"; import { Frozen } from "./worlds/frozen"; import { Researchs } from "./worlds/researchs"; import { Prestige } from "./worlds/prestige"; import { Infestation } from "./worlds/inferstation"; import { Science } from "./worlds/science"; import { Options } from "./options"; export class GameModel { isChanged = true; timeToEnd = Number.POSITIVE_INFINITY; gameVersion = "0.3.3"; hideSaveNotification = false; options: Options = new Options(); buyMulti = 1; //#region // Cost buyExp = new Decimal(1.1); buyExpUnit = new Decimal(1); scienceCost1 = new Decimal(100); scienceCost2 = new Decimal(1e3); scienceCost3 = new Decimal(1e4); scienceCost4 = new Decimal(1e5); upgradeScienceExp = new Decimal(4); upgradeScienceHireExp = new Decimal(6); actionList = new Array<Action>(); // Worlds baseWorld: BaseWorld; science: Science; machines: Machine; engineers: Engineers; bee: Bee; forest: Forest; beach: Beach; frozen: Frozen; infestation: Infestation; research: Researchs; prestige: Prestige; // Research resList = Array<Research>(); worldList = Array<WorldInterface>(); unitMap: Map<string, Unit> = new Map(); all: Array<Unit>; unl: Array<Unit>; allBase: Array<Base>; lists = new Array<TypeList>(); uiLists = new Array<TypeList>(); unitWithUp = new Array<Unit>(); // Prestige currentEarning = new Decimal(0); lifeEarning = new Decimal(0); world: World; nextWorlds: World[]; prestigeDone = new Decimal(0); maxLevel = new Decimal(0); worldTabAv = false; expTabAv = false; homeTabAv = false; minUser = 0; maxUser = 1; maxMax = 1; // ui stuff isLab = false; activeUnit: Unit; pause = false; actMin: Action; actHour: Action; timeModalOpened = false; unitLists = new Array<TypeList>(); skip = false; //#endregion constructor() { this.initialize(); } initialize() { this.currentEarning = new Decimal(0); this.allBase = []; this.unitMap = new Map(); this.lists = new Array<TypeList>(); this.worldList = Array<WorldInterface>(); this.baseWorld = new BaseWorld(this); this.science = new Science(this); this.machines = new Machine(this); this.engineers = new Engineers(this); this.bee = new Bee(this); this.forest = new Forest(this); this.beach = new Beach(this); this.frozen = new Frozen(this); this.infestation = new Infestation(this); this.research = new Researchs(this); this.prestige = new Prestige(this); this.worldList.push(this.baseWorld); this.worldList.push(this.science); this.worldList.push(this.machines); this.worldList.push(this.engineers); this.worldList.push(this.forest); this.worldList.push(this.bee); this.worldList.push(this.beach); this.worldList.push(this.frozen); this.worldList.push(this.infestation); this.worldList.push(this.prestige); this.worldList.push(this.research); this.worldList.forEach(w => w.declareStuff()); this.worldList.forEach(w => w.initStuff()); this.worldList.forEach(w => w.addWorld()); this.all = Array.from(this.unitMap.values()).filter(u => !u.neverEnding); this.all.forEach(u => { if (u.buyAction) u.buyAction.showBuyMenu = true; if (u.upHire) u.upHire.showHide = true; if (u.upAction) u.upAction.showHide = true; if (u.upSpecial) u.upSpecial.showHide = true; }); this.world = World.getBaseWorld(this); this.generateRandomWorld(); this.setInitialStat(); this.prestige.expLists.forEach(v => v.reload()); // console.log("prefix: " + World.worldPrefix.length) // console.log("type: " + World.worldTypes.length) // console.log("suff: " + World.worldSuffix.length) } setInitialStat() { this.all.forEach(u => { u.initialize(); u.actions.forEach(a => a.initialize()); }); this.resList.forEach(r => r.initialize()); this.baseWorld.food.unlocked = true; this.baseWorld.littleAnt.unlocked = true; this.baseWorld.littleAnt.buyAction.unlocked = true; this.research.rDirt.unlocked = true; this.unitWithUp = new Array<Unit>(); this.unitWithUp.push(this.baseWorld.littleAnt); this.baseWorld.food.quantity = this.baseWorld.food.quantity.plus(100); this.unlockUnits(this.all.filter(u => u.quantity.greaterThan(0)))(); this.unl = this.all.filter(u => u.unlocked); this.reloadProduction(); this.reloadLists(); // this.reloadList() } setMaxLevel() { this.maxMax = Decimal.min(this.maxLevel.div(12), 10000) .floor() .toNumber(); this.maxUser = Decimal.min(this.maxUser, this.maxMax) .floor() .toNumber(); } getProduction( prod: Production, level: decimal.Decimal, factorial: decimal.Decimal, fraction: decimal.Decimal, previous = new Decimal(1) ): decimal.Decimal { let ret = new Decimal(0); const production = prod.prodPerSec; if (prod.isActive()) ret = Decimal.pow(fraction, level) // exponential .times(prod.unit.quantity) // time .times(production) // efficenty .div(factorial) .times(previous); const prod2 = prod.unit.producedBy.filter(p => p.isActive()); for (const p2 of prod2) ret = ret.plus( this.getProduction( p2, level.plus(1), factorial.times(level.plus(1)), fraction, production.times(previous) ) ); return ret; } /** * Perform an update taking care of negative production. * If a resource end all consumer will be stopped and the function will be called again. * Can handle only 3 level of producer/consumer (it solve equation un to cubic) * * @param dif time elapsed in millisecond */ longUpdate(dif: number, forceUp = false) { let maxTime = dif; let unitZero: Unit = null; // Infestation fix 2 if ( this.infestation.poisonousPlant.unlocked && this.infestation.poisonousPlant.quantity.lessThan(1) ) this.infestation.poisonousPlant2.quantity = new Decimal(0); this.all.forEach(u => u.produces.forEach(p => p.reload())); this.isChanged = true; // console.log(this.timeToEnd + " " + dif) // reload max time this.timeToEnd = Number.POSITIVE_INFINITY; this.lists.forEach(l => (l.isEnding = false)); this.all.filter(u => u.quantity.lessThan(1)).forEach(res => { res.producedBy .filter(p => p.efficiency.lessThan(0)) .forEach(p => (p.unit.percentage = 0)); }); this.all.forEach(a => (a.endIn = Number.POSITIVE_INFINITY)); for (const res of this.unl) { res.a = new Decimal(0); res.b = new Decimal(0); res.c = new Decimal(0); const d = res.quantity; for (const prod1 of res.producedBy.filter( r => r.isActive() && r.unit.unlocked )) { // x const prodX = prod1.prodPerSec; res.c = res.c.plus(prodX.times(prod1.unit.quantity)); for (const prod2 of prod1.unit.producedBy.filter( r2 => r2.isActive() && r2.unit.unlocked )) { // x^2 const prodX2 = prod2.prodPerSec.times(prodX); res.b = res.b.plus(prodX2.times(prod2.unit.quantity)); for (const prod3 of prod2.unit.producedBy.filter( r3 => r3.isActive() && r3.unit.unlocked )) { // x^3 const prodX3 = prod3.prodPerSec.times(prodX2); res.a = res.a.plus(prodX3.times(prod3.unit.quantity)); } } } res.a = res.a.div(6); res.b = res.b.div(2); if ( res.a.lessThan(0) || res.b.lessThan(0) || res.c.lessThan(0) || d.lessThan(0) ) { const solution = Utils.solveCubic(res.a, res.b, res.c, d).filter(s => s.greaterThan(0) ); if (d.lessThan(Number.EPSILON)) { res.quantity = new Decimal(0); } for (const s of solution) { if (maxTime > s.toNumber() * 1000) { maxTime = s.toNumber() * 1000; unitZero = res; } res.endIn = Math.min(s.times(1000).toNumber(), res.endIn); this.timeToEnd = Math.min(this.timeToEnd, res.endIn); // console.log("End " + this.timeToEnd) } } } // console.log("long end") this.isChanged = false; this.unl.filter(u => u.endIn > 0).forEach(u => (u.endIn = u.endIn - dif)); // Update resource if (!this.pause || forceUp) { if (maxTime > Number.EPSILON) this.update2(new Decimal(maxTime).div(1000)); if (unitZero) { unitZero.producedBy .filter(p => p.efficiency.lessThan(0)) .forEach(p => (p.unit.percentage = 0)); // fix for infestatiion world if (unitZero === this.infestation.poisonousPlant) { this.infestation.poisonousPlant2.quantity = new Decimal(0); } } const remaning = dif - maxTime; if (remaning > Number.EPSILON) { this.isChanged = true; this.reloadProduction(); this.longUpdate(remaning); } } // this.reloadProduction() } /** * Called when update end, adjust some values. */ postUpdate() { this.all .filter(u => u.quantity.lessThan(Number.EPSILON)) .forEach(u => (u.quantity = new Decimal(0))); this.lists.forEach(l => (l.isEnding = !!l.uiList.find(u => u.isEnding()))); this.all.filter(un => un.unlocked).forEach(u => { u.reloadUiPerSec(); }); if (this.isLab) this.checkResearch(); if (this.activeUnit) this.activeUnit.reloadAtcMaxBuy(); // if (this.timeModalOpened) { this.prestige.time.reloadAtcMaxBuy(); // } } /** * Perform an update without handling negative quantity number, can result in negative quantity. * * @param dif time elapsed in millisecond */ // update(dif: number) { // const fraction = new Decimal(dif / 1000) // const all = Array.from(this.unitMap.values()) // for (const res of all) // for (const prod of res.producedBy.filter(p => p.isActive() && p.unit.unlocked)) // res.toAdd = res.toAdd.plus(this.getProduction(prod, new Decimal(1), new Decimal(1), fraction)) // // all.forEach(u => { // // u.quantity = u.quantity.plus(u.toAdd) // // u.toAdd = new Decimal(0) // // }) // for (const u of all) { // u.quantity = u.quantity.plus(u.toAdd) // u.toAdd = new Decimal(0) // } // } update2(dif: decimal.Decimal) { this.unl.forEach(u => { u.quantity = u.quantity .plus(u.a.times(Decimal.pow(dif, 3))) .plus(u.b.times(Decimal.pow(dif, 2))) .plus(u.c.times(dif)); }); } /** * Unlock units and recheck dependencies. */ unlockUnits(units: Unlocable[]) { return () => { let ok = false; units.filter(u => u.avabileThisWorld).forEach(u => { ok = ok || !u.unlocked; u.unlocked = true; if (u instanceof Unit) if (u.buyAction) u.buyAction.unlocked = true; }); this.all .filter(u => u.unlocked) .forEach(u2 => u2.produces.forEach( p => (p.product.unlocked = p.product.avabileThisWorld) ) ); if (ok) { this.unitWithUp = this.all.filter( u => u.unlocked && (u.upHire || u.upSpecial || u.upAction) ); this.unl = this.all.filter(u => u.unlocked); this.reloadLists(); } // if (ok) // this.reloadList() return ok; }; } /** * Initialize 3 random world */ generateRandomWorld(force: boolean = false) { this.setMaxLevel(); if (!this.nextWorlds || force) { this.nextWorlds = [ World.getRandomWorld(this), World.getRandomWorld(this), World.getRandomWorld(this) ]; } else { for (let i = 0; i < 3; i++) { if (!this.nextWorlds[i].keep) this.nextWorlds[i] = World.getRandomWorld(this); } } for (let i = 0; i < 3; i++) { this.nextWorlds[i].id = "" + i; } } /** * Get a savegame */ getSave(): string { const save: any = {}; save.list = Array.from(this.unitMap.entries()).map(v => v[1].getData()); save.last = Date.now(); save.cur = this.currentEarning; save.life = this.lifeEarning; save.w = this.world.getData(); save.nw = this.nextWorlds.map(w => w.getData()); // save.pre = this.prestige.allPrestigeUp.map(p => p.getData()) save.res = this.resList.map(r => r.getData()); save.pd = this.prestigeDone; save.worldTabAv = this.worldTabAv; save.expTabAv = this.expTabAv; save.ml = this.maxLevel; save.htv = this.homeTabAv; save.pause = this.pause; save.hsn = this.hideSaveNotification; save.gameVers = this.gameVersion; save.opti = this.options; return LZString.compressToBase64(JSON.stringify(save)); } /** * Load a savegame * @param saveRaw */ load(saveRaw: string): number { this.isChanged = true; if (saveRaw) { this.setInitialStat(); saveRaw = LZString.decompressFromBase64(saveRaw); const save = JSON.parse(saveRaw); // console.log(saveRaw) this.currentEarning = new Decimal(save.cur); this.lifeEarning = new Decimal(save.life); this.world.restore(save.w, true); this.maxLevel = new Decimal(save.ml); for (const s of save.list) { const unit = this.unitMap.get(s.id); if (unit) unit.restore(s); } this.nextWorlds[0].restore(save.nw[0]); this.nextWorlds[1].restore(save.nw[1]); this.nextWorlds[2].restore(save.nw[2]); for (const s of save.res) { const res = this.resList.find(p => p.id === s.id); if (res) res.restore(s); } if (save.pd) this.prestigeDone = new Decimal(save.pd); if (save.worldTabAv) this.worldTabAv = save.worldTabAv; if (save.expTabAv) this.expTabAv = save.expTabAv; if (save.htv) this.homeTabAv = save.htv; this.reloadProduction(); // Fixes for older savegame, corrupted... this.science.science1Production.unlocked = true; this.resList .filter(r => r.owned()) .forEach(r => r.toUnlock .filter(t => t instanceof Research && !t.owned()) .forEach(t2 => (t2.unlocked = true)) ); this.unitWithUp = this.all.filter( u => u.unlocked && (u.upHire || u.upSpecial || u.upAction) ); // fixing for old version if (save.gameVers && save.gameVers === "0.0.1") { const linear = 1 / 4; const toUnlockMultiplier = Decimal.pow(1.0005, this.world.level) .times(this.world.level + 1 / linear) .times(linear); this.world.toUnlock.forEach(tu => { if ( tu.unit === this.baseWorld.nestAnt || tu.unit === this.bee.hiveBee || tu.unit === this.forest.beetleNest ) { tu.basePrice = new Decimal(30).times(toUnlockMultiplier).floor(); } if (tu.unit === this.bee.hiveBee) { tu.basePrice = tu.basePrice.div(2); } }); } if (save.pause) this.pause = true; if (save.hsn) this.hideSaveNotification = save.hsn; if (save.opti) { this.options.load(save.opti); this.options.apply(); } this.reloadProduction(); this.unitLists.splice(0, this.unitLists.length); this.reloadLists(); this.unl = this.all.filter(u => u.unlocked); if (this.research.r2.owned()) this.unlockUnits(this.research.r2.toUnlock)(); if (this.research.r4.owned()) { this.unlockUnits(this.research.r4.toUnlock)(); this.research.r4.unlocked = false; if (this.research.upCombined.quantity.greaterThan(0)) this.research.upCombined.unlocked = false; } return save.last; } return null; } reloadProduction() { this.all.filter(un => un.unlocked).forEach(u => { u.loadProduction(); }); this.actionList.forEach(a => a.reload()); // console.log("reloadProduction") } getCost(data: any): Cost { return new Cost( this.all.find(u => u.id === data.u), new Decimal(data.b), new Decimal(data.g) ); } getExperience(): decimal.Decimal { return new Decimal(this.world.experience); } reloadUpIcons() { this.unitWithUp.forEach(u => u.checkUp()); } checkResearch() { this.resList .filter(r => r.unlocked && r.avabileThisWorld) .forEach(res => res.setMaxBuy()); } reloadLists() { this.lists.forEach(v => v.reload()); this.uiLists = this.lists.filter(u => u.uiList && u.uiList.length > 0); } }
the_stack
import type { CorePluginList } from './generated/CorePluginList' import type { DefaultColors } from './generated/colors' // Helpers type Expand<T> = T extends object ? T extends infer O ? { [K in keyof O]: Expand<O[K]> } : never : T type KeyValuePair<K extends keyof any = string, V = string> = Record<K, V> interface RecursiveKeyValuePair<K extends keyof any = string, V = string> { [key: string]: V | RecursiveKeyValuePair<K, V> } type ResolvableTo<T> = T | ((utils: PluginUtils) => T) interface PluginUtils { colors: DefaultColors theme(path: string, defaultValue?: unknown): any breakpoints<I = Record<string, unknown>, O = I>(arg: I): O rgb(arg: string): (arg: Partial<{ opacityVariable: string; opacityValue: number }>) => string hsl(arg: string): (arg: Partial<{ opacityVariable: string; opacityValue: number }>) => string } // Content related config type FilePath = string type RawFile = { raw: string; extension?: string } type ExtractorFn = (content: string) => string[] type TransformerFn = (content: string) => string type ContentConfig = | (FilePath | RawFile)[] | { files: (FilePath | RawFile)[] extract?: ExtractorFn | { [extension: string]: ExtractorFn } transform?: TransformerFn | { [extension: string]: TransformerFn } } // Important related config type ImportantConfig = boolean | string // Prefix related config type PrefixConfig = string // Separator related config type SeparatorConfig = string // Safelist related config type SafelistConfig = | string[] | { pattern: RegExp variants: string[] }[] // Presets related config type PresetsConfig = Config[] // Future related config type FutureConfigValues = never // Replace with 'future-feature-1' | 'future-feature-2' type FutureConfig = Expand<'all' | Partial<Record<FutureConfigValues, boolean>>> | [] // Experimental related config type ExperimentalConfigValues = 'optimizeUniversalDefaults' // Replace with 'experimental-feature-1' | 'experimental-feature-2' type ExperimentalConfig = Expand<'all' | Partial<Record<ExperimentalConfigValues, boolean>>> | [] // DarkMode related config type DarkModeConfig = // Use the `media` query strategy. | 'media' // Use the `class` stategy, which requires a `.dark` class on the `html`. | 'class' // Use the `class` stategy with a custom class instead of `.dark`. | ['class', string] type Screen = { raw: string } | { min: string } | { max: string } | { min: string; max: string } type ScreensConfig = string[] | KeyValuePair<string, string | Screen | Screen[]> // Theme related config interface ThemeConfig { // Responsiveness screens: ResolvableTo<ScreensConfig> // Reusable base configs colors: ResolvableTo<RecursiveKeyValuePair> spacing: ResolvableTo<KeyValuePair> // Components container: ResolvableTo< Partial<{ screens: ScreensConfig center: boolean padding: string | Record<string, string> }> > // Utilities inset: ThemeConfig['spacing'] zIndex: ResolvableTo<KeyValuePair> order: ResolvableTo<KeyValuePair> gridColumn: ResolvableTo<KeyValuePair> gridColumnStart: ResolvableTo<KeyValuePair> gridColumnEnd: ResolvableTo<KeyValuePair> gridRow: ResolvableTo<KeyValuePair> gridRowStart: ResolvableTo<KeyValuePair> gridRowEnd: ResolvableTo<KeyValuePair> margin: ThemeConfig['spacing'] aspectRatio: ResolvableTo<KeyValuePair> height: ThemeConfig['spacing'] maxHeight: ThemeConfig['spacing'] minHeight: ResolvableTo<KeyValuePair> width: ThemeConfig['spacing'] maxWidth: ResolvableTo<KeyValuePair> minWidth: ResolvableTo<KeyValuePair> flex: ResolvableTo<KeyValuePair> flexShrink: ResolvableTo<KeyValuePair> flexGrow: ResolvableTo<KeyValuePair> flexBasis: ThemeConfig['spacing'] borderSpacing: ThemeConfig['spacing'] transformOrigin: ResolvableTo<KeyValuePair> translate: ThemeConfig['spacing'] rotate: ResolvableTo<KeyValuePair> skew: ResolvableTo<KeyValuePair> scale: ResolvableTo<KeyValuePair> animation: ResolvableTo<KeyValuePair> keyframes: ResolvableTo<KeyValuePair<string, KeyValuePair<string, KeyValuePair>>> cursor: ResolvableTo<KeyValuePair> scrollMargin: ThemeConfig['spacing'] scrollPadding: ThemeConfig['spacing'] listStyleType: ResolvableTo<KeyValuePair> columns: ResolvableTo<KeyValuePair> gridAutoColumns: ResolvableTo<KeyValuePair> gridAutoRows: ResolvableTo<KeyValuePair> gridTemplateColumns: ResolvableTo<KeyValuePair> gridTemplateRows: ResolvableTo<KeyValuePair> gap: ThemeConfig['spacing'] space: ThemeConfig['spacing'] divideWidth: ThemeConfig['borderWidth'] divideColor: ThemeConfig['borderColor'] divideOpacity: ThemeConfig['borderOpacity'] borderRadius: ResolvableTo<KeyValuePair> borderWidth: ResolvableTo<KeyValuePair> borderColor: ThemeConfig['colors'] borderOpacity: ThemeConfig['opacity'] backgroundColor: ThemeConfig['colors'] backgroundOpacity: ThemeConfig['opacity'] backgroundImage: ResolvableTo<KeyValuePair> gradientColorStops: ThemeConfig['colors'] backgroundSize: ResolvableTo<KeyValuePair> backgroundPosition: ResolvableTo<KeyValuePair> fill: ThemeConfig['colors'] stroke: ThemeConfig['colors'] strokeWidth: ResolvableTo<KeyValuePair> objectPosition: ResolvableTo<KeyValuePair> padding: ThemeConfig['spacing'] textIndent: ThemeConfig['spacing'] fontFamily: ResolvableTo<KeyValuePair<string, string[]>> fontSize: ResolvableTo< KeyValuePair< string, | string | [fontSize: string, lineHeight: string] | [ fontSize: string, configuration: Partial<{ lineHeight: string letterSpacing: string }> ] > > fontWeight: ResolvableTo<KeyValuePair> lineHeight: ResolvableTo<KeyValuePair> letterSpacing: ResolvableTo<KeyValuePair> textColor: ThemeConfig['colors'] textOpacity: ThemeConfig['opacity'] textDecorationColor: ThemeConfig['colors'] textDecorationThickness: ResolvableTo<KeyValuePair> textUnderlineOffset: ResolvableTo<KeyValuePair> placeholderColor: ThemeConfig['colors'] placeholderOpacity: ThemeConfig['opacity'] caretColor: ThemeConfig['colors'] accentColor: ThemeConfig['colors'] opacity: ResolvableTo<KeyValuePair> boxShadow: ResolvableTo<KeyValuePair> boxShadowColor: ThemeConfig['colors'] outlineWidth: ResolvableTo<KeyValuePair> outlineOffset: ResolvableTo<KeyValuePair> outlineColor: ThemeConfig['colors'] ringWidth: ResolvableTo<KeyValuePair> ringColor: ThemeConfig['colors'] ringOpacity: ThemeConfig['opacity'] ringOffsetWidth: ResolvableTo<KeyValuePair> ringOffsetColor: ThemeConfig['colors'] blur: ResolvableTo<KeyValuePair> brightness: ResolvableTo<KeyValuePair> contrast: ResolvableTo<KeyValuePair> dropShadow: ResolvableTo<KeyValuePair> grayscale: ResolvableTo<KeyValuePair> hueRotate: ResolvableTo<KeyValuePair> invert: ResolvableTo<KeyValuePair> saturate: ResolvableTo<KeyValuePair> sepia: ResolvableTo<KeyValuePair> backdropBlur: ThemeConfig['blur'] backdropBrightness: ThemeConfig['brightness'] backdropContrast: ThemeConfig['contrast'] backdropGrayscale: ThemeConfig['grayscale'] backdropHueRotate: ThemeConfig['hueRotate'] backdropInvert: ThemeConfig['invert'] backdropOpacity: ThemeConfig['opacity'] backdropSaturate: ThemeConfig['saturate'] backdropSepia: ThemeConfig['sepia'] transitionProperty: ResolvableTo<KeyValuePair> transitionTimingFunction: ResolvableTo<KeyValuePair> transitionDelay: ResolvableTo<KeyValuePair> transitionDuration: ResolvableTo<KeyValuePair> willChange: ResolvableTo<KeyValuePair> content: ResolvableTo<KeyValuePair> // Custom [key: string]: any } // Core plugins related config type CorePluginsConfig = CorePluginList[] | Expand<Partial<Record<CorePluginList, boolean>>> // Plugins related config type ValueType = | 'any' | 'color' | 'url' | 'image' | 'length' | 'percentage' | 'position' | 'lookup' | 'generic-name' | 'family-name' | 'number' | 'line-width' | 'absolute-size' | 'relative-size' | 'shadow' export interface PluginAPI { // for registering new static utility styles addUtilities( utilities: RecursiveKeyValuePair | RecursiveKeyValuePair[], options?: Partial<{ respectPrefix: boolean respectImportant: boolean }> ): void // for registering new dynamic utility styles matchUtilities<T>( utilities: KeyValuePair<string, (value: T) => RecursiveKeyValuePair>, options?: Partial<{ respectPrefix: boolean respectImportant: boolean type: ValueType | ValueType[] values: KeyValuePair<string, T> supportsNegativeValues: boolean }> ): void // for registering new static component styles addComponents( components: RecursiveKeyValuePair | RecursiveKeyValuePair[], options?: Partial<{ respectPrefix: boolean respectImportant: boolean }> ): void // for registering new dynamic component styles matchComponents<T>( components: KeyValuePair<string, (value: T) => RecursiveKeyValuePair>, options?: Partial<{ respectPrefix: boolean respectImportant: boolean type: ValueType | ValueType[] values: KeyValuePair<string, T> supportsNegativeValues: boolean }> ): void // for registering new base styles addBase(base: RecursiveKeyValuePair | RecursiveKeyValuePair[]): void // for registering custom variants addVariant(name: string, definition: string | string[] | (() => string) | (() => string)[]): void // for looking up values in the user’s theme configuration theme: <TDefaultValue = Config['theme']>( path?: string, defaultValue?: TDefaultValue ) => TDefaultValue // for looking up values in the user’s Tailwind configuration config: <TDefaultValue = Config>(path?: string, defaultValue?: TDefaultValue) => TDefaultValue // for checking if a core plugin is enabled corePlugins(path: string): boolean // for manually escaping strings meant to be used in class names e: (className: string) => string } export type PluginCreator = (api: PluginAPI) => void export type PluginsConfig = ( | PluginCreator | { handler: PluginCreator; config?: Config } | { (options: any): { handler: PluginCreator; config?: Config }; __isOptionsFunction: true } )[] // Top level config related interface RequiredConfig { content: ContentConfig } interface OptionalConfig { important: Partial<ImportantConfig> prefix: Partial<PrefixConfig> separator: Partial<SeparatorConfig> safelist: Partial<SafelistConfig> presets: Partial<PresetsConfig> future: Partial<FutureConfig> experimental: Partial<ExperimentalConfig> darkMode: Partial<DarkModeConfig> theme: Partial<ThemeConfig & { extend: Partial<ThemeConfig> }> corePlugins: Partial<CorePluginsConfig> plugins: Partial<PluginsConfig> // Custom [key: string]: any } export type Config = RequiredConfig & Partial<OptionalConfig>
the_stack
import { defineComponent, ref, PropType, onMounted, watch, onUpdated } from 'vue' import classNames from 'classnames' import marked from './lib/helpers/marked' import keydownListen from './lib/helpers/keydownListen' import ToolbarLeft from './components/toolbar-left' import ToolbarRight from './components/toolbar-right' import { insertText } from './lib/helpers/function' import 'highlight.js/styles/tomorrow-night-blue.css' import 'highlight.js/styles/tomorrow-night-bright.css' import './lib/fonts/iconfont.css' import './lib/css/index.less' import { CONFIG } from './lib' export interface IToolbar { h1?: boolean h2?: boolean h3?: boolean h4?: boolean img?: boolean link?: boolean code?: boolean preview?: boolean expand?: boolean undo?: boolean redo?: boolean save?: boolean subfield?: boolean } export interface IWords { placeholder?: string h1?: string h2?: string h3?: string h4?: string undo?: string redo?: string img?: string link?: string code?: string save?: string preview?: string singleColumn?: string doubleColumn?: string fullscreenOn?: string fullscreenOff?: string addImgLink?: string addImg?: string } export interface ILeft { prefix: string subfix: string str: string } export default defineComponent({ emits: ['update:value'], props: { value: { type: String, default: '' }, lineNum: { type: Boolean, default: true }, onChange: { type: Function as PropType<(value: string) => void>, default: () => {} // eslint-disable-line }, onSave: { type: Function as PropType<(value: string) => void>, default: () => {} // eslint-disable-line }, placeholder: { type: String, default: '' }, fontSize: { type: String, default: '14px' }, disabled: { type: Boolean, default: false }, style: { type: Object, default: () => ({}) }, height: { type: String, default: '' }, preview: { type: Boolean, default: true }, expand: { type: Boolean, default: false }, subfield: { type: Boolean, default: true }, toolbar: { type: Object as PropType<IToolbar>, default: CONFIG.toolbar }, language: { type: String, default: 'zh-CN' }, addImg: { type: Function as PropType<(file: File, index: number) => void>, default: () => {} // eslint-disable-line } }, setup(props, { emit }) { const preview = ref(props.preview) const expand = ref(props.expand) const subfield = ref(props.subfield) const history = ref<string[]>([]) const historyIndex = ref(0) const lineIndex = ref(0) // const value = ref(props.value) const words = ref<IWords>({}) const $vm = ref<HTMLTextAreaElement>() const $scrollEdit = ref<HTMLDivElement>() const $scrollPreview = ref<HTMLDivElement>() const $blockEdit = ref<HTMLDivElement>() const $blockPreview = ref<HTMLDivElement>() const currentTimeout = ref(0) onMounted(() => { if ($vm.value) { keydownListen($vm.value, (type: string) => { toolBarLeftClick(type) // eslint-disable-line }) } if (props.value) { reLineNum(props.value) // eslint-disable-line } initLanguage() // eslint-disable-line }) onUpdated(() => { if (props.value !== history.value[historyIndex.value]) { clearTimeout(currentTimeout.value) currentTimeout.value = window.setTimeout(() => { props.value && saveHistory(props.value) // eslint-disable-line }, 500) } }) watch( () => props.value, val => { if (val) { reLineNum(val) // eslint-disable-line } } ) watch( () => props.subfield, val => { if (val !== subfield.value) { subfield.value = props.subfield } } ) watch( () => props.preview, val => { if (val !== preview.value) { preview.value = props.preview } } ) watch( () => props.expand, val => { if (val !== expand.value) { expand.value = props.expand } } ) function initLanguage() { const lang = CONFIG.langList.indexOf(props.language) >= 0 ? props.language : 'zh-CN' words.value = CONFIG.language[lang] } function handleChange(e: Event) { const target = e.target as HTMLInputElement // props.onChange(target.value) emit('update:value', target.value) } // 保存记录 function saveHistory(value: string) { // 撤销后修改,删除当前以后记录 history.value.splice(historyIndex.value + 1, history.value.length) if (history.value.length >= 20) { history.value.shift() } // 记录当前位置 historyIndex.value = history.value.length history.value.push(value) } // 重新计算行号 function reLineNum(value: string) { lineIndex.value = value ? value.split('\n').length : 1 } function save() { props.onSave($vm.value!.value) // eslint-disable-line } function undo() { if (historyIndex.value < 0) { return } // props.onChange(history.value[historyIndex.value]) emit('update:value', history.value[historyIndex.value]) historyIndex.value = historyIndex.value - 1 } function redo() { if (historyIndex.value >= history.value.length) { return } // props.onChange(history.value[historyIndex.value]) emit('update:value', history.value[historyIndex.value]) historyIndex.value = historyIndex.value + 1 } function toolBarLeftClick(type: string) { const insertTextObj: any = { h1: { prefix: '# ', subfix: '', str: words.value.h1 }, h2: { prefix: '## ', subfix: '', str: words.value.h2 }, h3: { prefix: '### ', subfix: '', str: words.value.h3 }, h4: { prefix: '#### ', subfix: '', str: words.value.h4 }, img: { prefix: '![alt](', subfix: ')', str: 'url' }, link: { prefix: '[title](', subfix: ')', str: 'url' }, code: { prefix: '```', subfix: '\n\n```', str: 'language' }, tab: { prefix: ' ', subfix: '', str: '' } } if (Object.prototype.hasOwnProperty.call(insertTextObj, type)) { if ($vm.value) { const value = insertText($vm.value, insertTextObj[type]) // props.onChange(value) emit('update:value', value) } } const otherLeftClick: any = { undo, redo, save } if (Object.prototype.hasOwnProperty.call(otherLeftClick, type)) { otherLeftClick[type]() } } function addImg(file: File, index: number) { props.addImg(file, index) } // function $img2Url(name: string, url: string) { // if ($vm.value) { // const value = insertText($vm.value, { // prefix: `![${name}](${url})`, // subfix: '', // str: '' // }) // // props.onChange(value) // emit('update:value', value) // } // } function toolBarRightClick(type: string) { const toolbarRightPreviewClick = () => { preview.value = !preview.value } const toolbarRightExpandClick = () => { expand.value = !expand.value } const toolbarRightSubfieldClick = () => { if (preview.value) { if (subfield.value) { subfield.value = false preview.value = false } else { subfield.value = true } } else { if (subfield.value) { subfield.value = false } else { subfield.value = true preview.value = true } } } const rightClick: any = { preview: toolbarRightPreviewClick, expand: toolbarRightExpandClick, subfield: toolbarRightSubfieldClick } if (Object.prototype.hasOwnProperty.call(rightClick, type)) { rightClick[type]() } } function focusText() { $vm.value!.focus() // eslint-disable-line } function handleScoll(e: Event) { const currentTarget = e.currentTarget as HTMLDivElement /* eslint-disable @typescript-eslint/no-non-null-assertion */ const radio = $blockEdit.value!.scrollTop / ($scrollEdit.value!.scrollHeight - currentTarget.offsetHeight) $blockPreview.value!.scrollTop = ($scrollPreview.value!.scrollHeight - $blockPreview.value!.offsetHeight) * radio } return () => { const { placeholder, fontSize, disabled, height, style, toolbar } = props const editorClass = classNames({ 'for-editor-edit': true, 'for-panel': true, 'for-active': preview.value && subfield.value, 'for-edit-preview': preview.value && !subfield.value }) const previewClass = classNames({ 'for-panel': true, 'for-editor-preview': true, 'for-active': preview.value && subfield.value }) const fullscreen = classNames({ 'for-container': true, 'for-fullscreen': expand.value }) const lineNumClass = classNames({ 'for-line-num': true, hidden: !props.lineNum }) // 行号 function lineNum() { const list = [] for (let i = 0; i < lineIndex.value; i++) { list.push(<li key={i + 1}>{i + 1}</li>) } return <ul class={lineNumClass}>{list}</ul> } return ( <div class={fullscreen} style={{ height, ...style }}> {/* 菜单栏 */} {!!Object.keys(toolbar).length && ( <div class="for-toolbar"> <ToolbarLeft {...props} toolbar={toolbar} words={words.value} onClick={toolBarLeftClick} addImg={addImg} /> <ToolbarRight toolbar={toolbar} words={words.value} preview={preview.value} expand={expand.value} subfield={subfield.value} onClick={toolBarRightClick} /> </div> )} {/* 内容区 */} <div class="for-editor" style={{ fontSize }}> {/* 编辑区 */} <div class={editorClass} ref={$blockEdit} onScroll={handleScoll} onClick={focusText}> <div class="for-editor-block" ref={$scrollEdit}> {lineNum()} <div class="for-editor-content"> <pre>{props.value} </pre> <textarea ref={$vm} value={props.value} disabled={disabled} onInput={handleChange} placeholder={placeholder || words.value.placeholder} /> </div> </div> </div> {/* 预览区 */} <div class={previewClass} ref={$blockPreview}> <div ref={$scrollPreview} class="for-preview for-markdown-preview" innerHTML={marked(props.value as string)} ></div> </div> </div> </div> ) } } })
the_stack
const NbSubSegmentPerSegment: number = 10; const Epsilon: number = 0.1; // 1/NBSubSegmentPerSegment const MinimumKnotNb: number = 4; // 猜测0号点是CatmullRom算法辅助点,1号点是真正线段开始,2号点是第一个线段的结束 // 假如存在subsegment(拐点信息),应该存入这个线段的末尾 const FirstSegmentKnotIndex: number = 2; export class SubKnot { distanceFromStart: number; // 距离路径开始的距离 position: cc.Vec2; // ?? tangent: cc.Vec2; // 切线单位向量 } export enum SplineParameterization { Uniform = 0, Centripetal = 1, // https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline } export class Knot { public distanceFromStart: number = -1.0; public subKnots: SubKnot[] = null; public position: cc.Vec2 = cc.Vec2.ZERO; public emitTime: number = 0; // 节点加入时间 constructor(position: cc.Vec2, emitTime: number = cc.director.getTotalTime()) { this.subKnots = new Array<SubKnot>(NbSubSegmentPerSegment+1); this.position.set(position); this.emitTime = emitTime; } public Invalidate() { this.distanceFromStart = -1.0; } } export class Marker { segmentIndex: number; subKnotAIndex: number; subKnotBIndex: number; lerpRatio: number; } export class CatmullRomSpline { public splineParam: SplineParameterization = SplineParameterization.Centripetal; // public algo: SplineAlgorithm = SplineAlgorithm.UNIFORM; public knots: Knot[] = []; // Catmull-Rom算法的有效控制点数是总点数-2,有效线段数是有效控制点数-1。所以这里-3 public get NbSegments(): number { return Math.max(0, this.knots.length - 3); } public FindPositionFromDistance(distance: number, out?: cc.Vec2): cc.Vec2 { let tangent = out || cc.Vec2.ZERO; let result = new Marker; let foundSegment: boolean = this.PlaceMarker(result, distance); if (foundSegment) { tangent = this.GetPosition(result, tangent); } return tangent; } public FindTangentFromDistance(distance: number, out?: cc.Vec2): cc.Vec2 { let tangent = out || cc.Vec2.ZERO; let result = new Marker; let foundSegment = this.PlaceMarker(result, distance); if (foundSegment) { tangent = this.GetTangent(result, tangent); } return tangent; } public static ComputeBinormal(tangent: cc.Vec2, dummy: cc.Vec2, out?: cc.Vec2): cc.Vec2 { out = out || new cc.Vec2; out.x = tangent.y; out.y = -tangent.x; return out; // return cc.v2(tangent.y, -tangent.x); } public Length(): number { if (this.NbSegments === 0) return 0; return Math.max(0, this.GetSegmentDistanceFromStart(this.NbSegments-1)); } public Clear(): void { this.knots.length = 0; } public MoveMarker(marker: Marker, distance: number): void { // TODO: distance是Unity Units,需要转换 this.PlaceMarker(marker, distance, marker); } public GetPosition(marker: Marker, out?: cc.Vec2): cc.Vec2 { let pos = out || cc.Vec2.ZERO; if (this.NbSegments === 0) return pos; let subKnots = this.GetSegmentSubKnots(marker.segmentIndex); pos.x = cc.misc.lerp( subKnots[marker.subKnotAIndex].position.x, subKnots[marker.subKnotBIndex].position.x, marker.lerpRatio); pos.y = cc.misc.lerp( subKnots[marker.subKnotAIndex].position.y, subKnots[marker.subKnotBIndex].position.y, marker.lerpRatio); return pos; } public GetTangent(marker: Marker, out?: cc.Vec2): cc.Vec2 { let tangent = out || cc.Vec2.ZERO; if (this.NbSegments === 0) return tangent; let subKnots = this.GetSegmentSubKnots(marker.segmentIndex); tangent.x = cc.misc.lerp( subKnots[marker.subKnotAIndex].tangent.x, subKnots[marker.subKnotBIndex].tangent.x, marker.lerpRatio); tangent.y = cc.misc.lerp( subKnots[marker.subKnotAIndex].tangent.y, subKnots[marker.subKnotBIndex].tangent.y, marker.lerpRatio); return tangent; } protected GetSegmentSubKnots(i: number): SubKnot[] { return this.knots[FirstSegmentKnotIndex+i].subKnots; } protected GetSegmentDistanceFromStart(i: number): number { return this.knots[FirstSegmentKnotIndex+i].distanceFromStart; } // 计算线段和分线段的距离 // 注意线段的index和顶点的index是错位的 // segmentIndex=0的线段结束点对应vertexIndex=2 public Parametrize(fromSegmentIndex: number, toSegmentIndex: number) { if (this.knots.length < MinimumKnotNb) return; let nbSegments: number = Math.min(toSegmentIndex+1, this.NbSegments); fromSegmentIndex = Math.max(0, fromSegmentIndex); let totalDistance: number = 0; if (fromSegmentIndex > 0) { // 这条线段之前的线段长度总和 totalDistance = this.GetSegmentDistanceFromStart(fromSegmentIndex-1); } let knots = this.knots; for (let i=fromSegmentIndex; i<nbSegments; ++i) { let subKnots = this.GetSegmentSubKnots(i); // subknot固定11个,对应10个线段(挺浪费的,蛮多顶点都是重叠的) for (let j=0; j<subKnots.length; j++) { let sk = new SubKnot; sk.distanceFromStart = totalDistance += this.ComputeLengthOfSegment(i, (j-1)*Epsilon, j*Epsilon); sk.position = this.GetPositionOnSegment(i, j*Epsilon); // new cc.Vec sk.tangent = this.GetTangentOnSegment(i, j*Epsilon); // new cc.Vec subKnots[j] = sk; } knots[FirstSegmentKnotIndex+i].distanceFromStart = totalDistance; } } public PlaceMarker(result: Marker, distance: number, from: Marker = null): boolean { let nbSegments = this.NbSegments; if (nbSegments === 0) return false; if (distance <= 0) { result.segmentIndex = 0; result.subKnotAIndex = 0; result.subKnotBIndex = 1; result.lerpRatio = 0; return true; } else if (distance >= this.Length()) { let subKnots = this.GetSegmentSubKnots(nbSegments-1); result.segmentIndex = nbSegments-1; result.subKnotAIndex = subKnots.length-2; result.subKnotBIndex = subKnots.length-1; result.lerpRatio = 1; return true; } let fromSegmentIndex = 0; let fromSubKnotIndex = 1; if (from != null) { fromSegmentIndex = from.segmentIndex; } for (let i=fromSegmentIndex; i<nbSegments; ++i) { if (distance > this.GetSegmentDistanceFromStart(i)) continue; let subKnots = this.GetSegmentSubKnots(i); for (let j=fromSubKnotIndex; j<subKnots.length; j++) { let sk: SubKnot = subKnots[j]; if (distance > sk.distanceFromStart) continue; result.segmentIndex = i; result.subKnotAIndex = j-1; result.subKnotBIndex = j; result.lerpRatio = 1 - ((sk.distanceFromStart - distance) / (sk.distanceFromStart - subKnots[j-1].distanceFromStart)); break; } break; } return true; } protected ComputeLength(): number { if(this.knots.length < 4) return 0; let length: number = 0; let nbSegments = this.NbSegments; for (let i=0; i<nbSegments; ++i) { length += this.ComputeLengthOfSegment(i, 0, 1); } return length; } // 计算线段[from, to]区间的长度 // 这里看似在分段累加,实际上有时候from和to刚好相差一个Epsilon。这里叫Epsilon也不合适,应该叫Delta protected _prePoint = new cc.Vec2; protected _curPoint = new cc.Vec2; protected ComputeLengthOfSegment(segmentIndex: number, from: number, to: number): number { let length: number = 0; from = cc.misc.clamp01(from); to = cc.misc.clamp01(to); let lastPoint = this.GetPositionOnSegment(segmentIndex, from, this._prePoint); let point = this._curPoint; for (let j=from+Epsilon, n=to+Epsilon/2; j<n; j+=Epsilon) { this.GetPositionOnSegment(segmentIndex, j, this._curPoint); length += cc.Vec2.distance(point, lastPoint); lastPoint.set(point); } return length; } protected GetPositionOnSegment(segmentIndex: number, t: number, out?: cc.Vec2): cc.Vec2 { // 真正代表segmentIndex线段的点是segmentIndex+2,所以要注意FirstSegmentKnotIndex = 2实际是hardcode的,不能修改 let knots = this.knots; return CatmullRomSpline.FindSplinePoint(knots[segmentIndex].position, knots[segmentIndex+1].position, knots[segmentIndex+2].position, knots[segmentIndex+3].position, t, this.splineParam, out || new cc.Vec2); } protected GetTangentOnSegment(segmentIndex: number, t: number, out?: cc.Vec2): cc.Vec2 { // 真正代表segmentIndex线段的点是segmentIndex+2,所以要注意FirstSegmentKnotIndex = 2实际是hardcode的,不能修改 let knots = this.knots; let result = CatmullRomSpline.FindSplineTangent(knots[segmentIndex].position, knots[segmentIndex+1].position, knots[segmentIndex+2].position, knots[segmentIndex+3].position, t, this.splineParam, out || new cc.Vec2); result.normalizeSelf(); return result; } protected static _tmpVec2 = cc.v2(0, 0); protected static GetT(t: number, alpha: number, p0: cc.Vec2, p1: cc.Vec2): number { let tmpVec2 = CatmullRomSpline._tmpVec2; let d = p1.sub(p0, tmpVec2); let a = d.dot(d); let b = Math.pow(a, alpha * .5); return b + t; } // 曲线在t点采样 protected static FindSplinePoint(p0: cc.Vec2, p1: cc.Vec2, p2: cc.Vec2, p3: cc.Vec2, t: number, splineParam: SplineParameterization, out?: cc.Vec2): cc.Vec2 { let ret = out || new cc.Vec2; if (splineParam === SplineParameterization.Uniform) { let t2 = t * t; let t3 = t2 * t; ret.x = 0.5 * ((2.0 * p1.x) + (-p0.x + p2.x) * t + (2.0 * p0.x - 5.0 * p1.x + 4 * p2.x - p3.x) * t2 + (-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t3); ret.y = 0.5 * ((2.0 * p1.y) + (-p0.y + p2.y) * t + (2.0 * p0.y - 5.0 * p1.y + 4 * p2.y - p3.y) * t2 + (-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t3); return ret; } else { // Centripetal模式插值 let alpha = 0.5; let t0 = 0.0; let t1 = CatmullRomSpline.GetT(t0, alpha, p0, p1); let t2 = CatmullRomSpline.GetT(t1, alpha, p1, p2); let t3 = CatmullRomSpline.GetT(t2, alpha, p2, p3); t = cc.misc.lerp(t1, t2, t); let t1_0 = 1./(t1-t0); let t2_1 = 1./(t2-t1); let t3_2 = 1./(t3-t2); let t2_0 = 1./(t2-t0); let t3_1 = 1./(t3-t1); let A1 = (t1-t)*t1_0*p0.x + (t-t0)*t1_0*p1.x; let A2 = (t2-t)*t2_1*p1.x + (t-t1)*t2_1*p2.x; let A3 = (t3-t)*t3_2*p2.x + (t-t2)*t3_2*p3.x; let B1 = (t2-t)*t2_0*A1 + (t-t0)*t2_0*A2; let B2 = (t3-t)*t3_1*A2 + (t-t1)*t3_1*A3; let C = (t2-t)*t2_1*B1 + (t-t1)*t2_1*B2; ret.x = C; A1 = (t1-t)*t1_0*p0.y + (t-t0)*t1_0*p1.y; A2 = (t2-t)*t2_1*p1.y + (t-t1)*t2_1*p2.y; A3 = (t3-t)*t3_2*p2.y + (t-t2)*t3_2*p3.y; B1 = (t2-t)*t2_0*A1 + (t-t0)*t2_0*A2; B2 = (t3-t)*t3_1*A2 + (t-t1)*t3_1*A3; C = (t2-t)*t2_1*B1 + (t-t1)*t2_1*B2; ret.y = C; return ret; } } // protected static GetT(t: number, alpha: number, p0: cc.Vec2, p1: cc.Vec2): number { protected static GetDT(p0: cc.Vec2, p1: cc.Vec2, alpha: number): number { let tmpVec2 = CatmullRomSpline._tmpVec2; let d = p1.sub(p0, tmpVec2); let a = d.dot(d); let b = Math.pow(a, alpha * .5); return b; } // 获得曲线在t处的切线向量(非归一化) // 返回后再外部归一化 // 对Spline插值公式求导得到 protected static FindSplineTangent(p0: cc.Vec2, p1: cc.Vec2, p2: cc.Vec2, p3: cc.Vec2, t: number, splineParam: SplineParameterization, out?: cc.Vec2): cc.Vec2 { let ret = out || new cc.Vec2; if (splineParam === SplineParameterization.Uniform) { let t2 = t * t; ret.x = 0.5 * (-p0.x + p2.x) + (2.0 * p0.x - 5.0 * p1.x + 4 * p2.x - p3.x) * t + (-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t2 * 1.5; ret.y = 0.5 * (-p0.y + p2.y) + (2.0 * p0.y - 5.0 * p1.y + 4 * p2.y - p3.y) * t + (-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t2 * 1.5; return ret; } else { // Centripetal模式求切线 // quick answer: // https://math.stackexchange.com/questions/843595/how-can-i-calculate-the-derivative-of-a-catmull-rom-spline-with-nonuniform-param // https://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/23980479#23980479 // parper: // http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf let alpha = 0.5; let t0 = 0.0; let t1 = CatmullRomSpline.GetT(t0, alpha, p0, p1); let t2 = CatmullRomSpline.GetT(t1, alpha, p1, p2); let t3 = CatmullRomSpline.GetT(t2, alpha, p2, p3); t = cc.misc.lerp(t1, t2, t); let t1_0 = 1./(t1-t0); let t2_0 = 1./(t2-t0); let t2_1 = 1./(t2-t1); let t3_1 = 1./(t3-t1); let t3_2 = 1./(t3-t2); let tan1x = (p1.x-p0.x) * t1_0 - (p2.x-p0.x) * t2_0 + (p2.x-p1.x) * t2_1; let tan1y = (p1.y-p0.y) * t1_0 - (p2.y-p0.y) * t2_0 + (p2.y-p1.y) * t2_1; let tan2x = (p2.x-p1.x) * t2_1 - (p3.x-p1.x) * t3_1 + (p3.x-p2.x) * t3_2; let tan2y = (p2.y-p1.y) * t2_1 - (p3.y-p1.y) * t3_1 + (p3.y-p2.y) * t3_2; const inv3 = (t2-t1)/3; let R1x = p1.x + inv3 * tan1x; let R1y = p1.y + inv3 * tan1y; let R2x = p2.x - inv3 * tan2x; let R2y = p2.y - inv3 * tan2y; let u = (t-t1)*t2_1; let n = 1-u; let dCdtx = 3*(n*n*(R1x-p1.x) + 2*u*n*(R2x-R1x) + u*u*(p2.x-R2x)) * t2_1; let dCdty = 3*(n*n*(R1y-p1.y) + 2*u*n*(R2y-R1y) + u*u*(p2.y-R2y)) * t2_1; ret.x = dCdtx; ret.y = dCdty; return ret; } } }
the_stack
import 'styling/_QuerySummary'; import { escape } from 'underscore'; import { IQuerySuccessEventArgs, QueryEvents } from '../../events/QueryEvents'; import { QuerySummaryEvents } from '../../events/QuerySummaryEvents'; import { exportGlobally } from '../../GlobalExports'; import { Assert } from '../../misc/Assert'; import { QueryStateModel } from '../../models/QueryStateModel'; import { l } from '../../strings/Strings'; import { $$ } from '../../utils/Dom'; import { QuerySummaryUtils } from '../../utils/QuerySummaryUtils'; import { analyticsActionCauseList, IAnalyticsNoMeta } from '../Analytics/AnalyticsActionListMeta'; import { Component } from '../Base/Component'; import { IComponentBindings } from '../Base/ComponentBindings'; import { ComponentOptions } from '../Base/ComponentOptions'; import { Initialization } from '../Base/Initialization'; import { AccessibleButton } from '../../utils/AccessibleButton'; export interface IQuerySummaryOptions { onlyDisplaySearchTips?: boolean; enableNoResultsFoundMessage?: boolean; noResultsFoundMessage?: string; enableCancelLastAction?: boolean; enableSearchTips?: boolean; } export const noResultsCssClass: string = 'coveo-show-if-no-results'; /** * The QuerySummary component can display information about the currently displayed range of results (e.g., "Results * 1-10 of 123"). * * When the query does not match any items, the QuerySummary component can instead display information to the end users. * * The information displayed to the end user is customizable through this component. */ export class QuerySummary extends Component { static ID = 'QuerySummary'; static doExport = () => { exportGlobally({ QuerySummary: QuerySummary }); }; /** * Options for the component * @componentOptions */ static options: IQuerySummaryOptions = { /** * Specifies whether to hide the number of returned results. * * When this option is set to true, the number of returned results will be hidden from the page, meaning that your end users will not know how many results were returned for their query. * * Default value is `false`. */ onlyDisplaySearchTips: ComponentOptions.buildBooleanOption({ defaultValue: false }), /** * Specifies whether to display the {@link QuerySummary.options.noResultsFoundMessage} message when there are no search results. * * Default value is `true`. * * @availablesince [August 2018 Release (v2.4609.6)](https://docs.coveo.com/410/#august-2018-release-v246096) */ enableNoResultsFoundMessage: ComponentOptions.buildBooleanOption({ defaultValue: true }), /** * Specifies a custom message to display when there are no search results. * * You can refer to the query the end user has entered using the `${query}` query tag. * * **Example** * > For the `noResultFoundMessage` option, you enter `There were no results found for "${query}"`. * > Your end user searches for `query without results`, which does not return any result. * > On your page, they see this message: `There were no results found for "query without results"`. * * Default value is `No results for ${query}`. * * **Note** * > If there is no query, the value will fallback to `No results`. * * @availablesince [August 2018 Release (v2.4609.6)](https://docs.coveo.com/410/#august-2018-release-v246096) */ noResultsFoundMessage: ComponentOptions.buildLocalizedStringOption({ localizedString: () => l('noResultFor', '${query}'), depend: 'enableNoResultsFoundMessage', postProcessing: (value: string) => { return escape(value); } }), /** * Specifies whether to display the `Cancel last action` link when there are no search results. * * When clicked, the link restores the previous query that contained results. * * Default value is `true`. */ enableCancelLastAction: ComponentOptions.buildBooleanOption({ defaultValue: true }), /** * Specifies whether to display search tips when there are no search results. * * Default value is `true`. */ enableSearchTips: ComponentOptions.buildBooleanOption({ defaultValue: true }) }; private textContainer: HTMLElement; private lastKnownGoodState: any; private noResultsSnapshot: string; /** * Creates a new QuerySummary component. * @param element The HTMLElement on which to instantiate the component. * @param options The options for the QuerySummary component. * @param bindings The bindings that the component requires to function normally. If not set, these will be * automatically resolved (with a slower execution time). */ constructor(public element: HTMLElement, public options?: IQuerySummaryOptions, bindings?: IComponentBindings) { super(element, QuerySummary.ID, bindings); this.options = ComponentOptions.initComponentOptions(element, QuerySummary, options); this.bind.onRootElement(QueryEvents.querySuccess, (data: IQuerySuccessEventArgs) => this.handleQuerySuccess(data)); this.bind.onRootElement(QueryEvents.queryError, () => this.hide()); this.hide(); this.textContainer = $$('span').el; $$(this.element).prepend(this.textContainer); } private hide() { $$(this.element).addClass('coveo-hidden'); } private show() { $$(this.element).removeClass('coveo-hidden'); } private render(data: IQuerySuccessEventArgs) { $$(this.textContainer).empty(); this.show(); this.updateNoResultsSnapshot(); this.hideNoResultsPage(); if (!this.options.onlyDisplaySearchTips) { this.updateSummaryIfResultsWereReceived(data); } const queryResults = data.results; if (queryResults.exception != null && queryResults.exception.code != null) { const code: string = ('QueryException' + queryResults.exception.code).toLocaleString(); this.textContainer.innerHTML = l('QueryException', code); } else if (queryResults.results.length == 0) { this.updateQueryTagsInNoResultsContainer(); this.displayInfoOnNoResults(); } else { this.lastKnownGoodState = this.queryStateModel.getAttributes(); } } private handleQuerySuccess(data: IQuerySuccessEventArgs) { Assert.exists(data); this.render(data); } private updateSummaryIfResultsWereReceived(data: IQuerySuccessEventArgs) { if (!data.results.results.length) { return; } const message = QuerySummaryUtils.htmlMessage(this.root, data); this.textContainer.innerHTML = message; } private updateNoResultsSnapshot() { const noResultsContainer = this.getNoResultsContainer(); if (this.noResultsSnapshot == null && noResultsContainer) { this.noResultsSnapshot = noResultsContainer.innerHTML; } } private updateQueryTagsInNoResultsContainer() { const noResultsContainer = this.getNoResultsContainer(); if (noResultsContainer) { noResultsContainer.innerHTML = this.replaceQueryTagsWithHighlightedQuery(this.noResultsSnapshot); } } private replaceQueryTagsWithHighlightedQuery(template: string) { const highlightedQuery = `<span class="coveo-highlight">${this.sanitizedQuery}</span>`; return QuerySummaryUtils.replaceQueryTags(template, highlightedQuery); } private get sanitizedQuery() { return escape(this.queryStateModel.get(QueryStateModel.attributesEnum.q)); } private displayInfoOnNoResults() { this.showNoResultsPage(); if (this.options.enableNoResultsFoundMessage) { const noResultsFoundMessage = this.getNoResultsFoundMessageElement(); this.textContainer.appendChild(noResultsFoundMessage.el); } if (this.options.enableCancelLastAction) { const cancelLastAction = this.getCancelLastActionElement(); this.textContainer.appendChild(cancelLastAction.el); } if (this.options.enableSearchTips) { const searchTipsTitle = this.getSearchTipsTitleElement(); const searchTipsList = this.getSearchTipsListElement(); this.textContainer.appendChild(searchTipsTitle.el); this.textContainer.appendChild(searchTipsList.el); } } private hideNoResultsPage() { const noResultsContainers = this.getAllNoResultsContainer(); noResultsContainers.forEach(noResultsContainer => { $$(noResultsContainer).removeClass('coveo-no-results'); }); } private showNoResultsPage() { const noResultsContainers = this.getAllNoResultsContainer(); noResultsContainers.forEach(noResultsContainer => { $$(noResultsContainer).addClass('coveo-no-results'); }); } private getNoResultsContainer(): HTMLElement { return $$(this.element).find(`.${noResultsCssClass}`); } private getAllNoResultsContainer(): HTMLElement[] { return $$(this.element).findAll(`.${noResultsCssClass}`); } private get parsedNoResultsFoundMessage() { if (this.sanitizedQuery.trim() === '') { return l('noResult'); } return this.replaceQueryTagsWithHighlightedQuery(this.options.noResultsFoundMessage); } private getNoResultsFoundMessageElement() { const noResultsFoundMessage = $$( 'div', { className: 'coveo-query-summary-no-results-string' }, this.parsedNoResultsFoundMessage ); return noResultsFoundMessage; } private getCancelLastActionElement() { const cancelLastAction = $$( 'div', { className: 'coveo-query-summary-cancel-last' }, l('CancelLastAction') ); new AccessibleButton() .withLabel(l('CancelLastAction')) .withElement(cancelLastAction) .withSelectAction(() => { this.usageAnalytics.logCustomEvent<IAnalyticsNoMeta>(analyticsActionCauseList.noResultsBack, {}, this.root); this.usageAnalytics.logSearchEvent<IAnalyticsNoMeta>(analyticsActionCauseList.noResultsBack, {}); if (this.lastKnownGoodState) { this.queryStateModel.reset(); this.queryStateModel.setMultiple(this.lastKnownGoodState); $$(this.root).trigger(QuerySummaryEvents.cancelLastAction); this.queryController.executeQuery(); } else { history.back(); } }) .build(); return cancelLastAction; } private getSearchTipsTitleElement() { const searchTipsInfo = $$('div', { className: 'coveo-query-summary-search-tips-info' }); searchTipsInfo.text(l('SearchTips')); return searchTipsInfo; } private getSearchTipsListElement() { const searchTips = $$('ul'); const checkSpelling = $$('li'); checkSpelling.text(l('CheckSpelling')); const fewerKeywords = $$('li'); fewerKeywords.text(l('TryUsingFewerKeywords')); searchTips.el.appendChild(checkSpelling.el); searchTips.el.appendChild(fewerKeywords.el); if (this.queryStateModel.atLeastOneFacetIsActive()) { const fewerFilter = $$('li'); fewerFilter.text(l('SelectFewerFilters')); searchTips.el.appendChild(fewerFilter.el); } return searchTips; } } Initialization.registerAutoCreateComponent(QuerySummary);
the_stack
import { ClusterOutlined, InfoCircleOutlined } from '@ant-design/icons'; import parse from 'html-react-parser'; import { Button, Card, Input, Select, Tooltip } from 'antd'; import Modal from 'antd/lib/modal/Modal'; import React, { useEffect, useState, useMemo, lazy } from 'react'; import { useCallback } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Dispatch, RootState } from '~/redux/store'; import { ArgumentsItem, ArgumentsNumber, ArgumentsString, } from '~/types/appData'; import s from './ArgumentsSetting.module.less'; import ArrayArguments from './ArrayArguments'; import BooleanArguments from './BooleanArguments'; import ObjectArguments from './ObjectArguments'; import RunningTimesModal from '~/components/MiniDashboard/RunningTimesModal'; import HtmlSuffix from './HtmlSuffix'; import classNames from 'classnames'; import MixedArguments from './MixedArguments'; interface Props { /** * 显示参数面板 */ visible: boolean; /** * 确认时回调 */ onOk?: (data: ArgumentsItem[]) => void; /** * 参数数据 */ argumentsData?: ArgumentsItem[]; /** * 组件导出事件的初始化参数数据 */ initArgumentData?: ArgumentsItem[]; /** * 取消时回调 */ onCancel?: () => void; /** * 头部可自定义 */ headerFlexible?: boolean; /** * 数据可自定义,默认false固定不变 */ dataFlexible?: boolean; /** * title */ title?: string; /* * forceUpdate */ forceUpdate?: boolean; } const ArgumentsSetting: React.FC<Props> = ({ visible, argumentsData, initArgumentData, onOk, onCancel, title, dataFlexible = false, headerFlexible = false, forceUpdate, }) => { const runningTimes = useSelector((state: RootState) => state.runningTimes); const [argumentState, setArgumentState] = useState<ArgumentsItem[]>([]); const [showRunningTimes, setShowRunningTimes] = useState(false); const forceUpdateByStateTag = useDispatch<Dispatch>().controller.forceUpdateByStateTag; // 将argument数据接管 useEffect(() => { let data: ArgumentsItem[] = [...(argumentsData || [])]; // 不可自定义参数且数据为空时,使用组件初始数据 if (data.length === 0) { data = [...(initArgumentData || [])]; } setArgumentState(data); }, [argumentsData, headerFlexible, initArgumentData]); // 弹窗确定收集编辑完毕的argument数据 const onModalOk = useCallback(() => { if (onOk instanceof Function) { // todo 确定页面为何强制更新?? if (forceUpdate) { forceUpdateByStateTag(); } onOk(argumentState); } }, [onOk, forceUpdateByStateTag, argumentState, forceUpdate]); // number const onChangeInput = useCallback( (index: number, isSelect?: boolean) => (e: any) => { const result = [...argumentState]; result[index].data = isSelect ? e : e.target.value; setArgumentState(result); }, [argumentState], ); const onChangeRunningTime = useCallback( (index: number) => (e: any) => { const result = [...argumentState]; result[index].data = e; setArgumentState(result); }, [argumentState], ); const onChangeObjType = useCallback( (index: number) => (data: ArgumentsItem) => { const result = [...argumentState]; result[index] = data; setArgumentState(result); }, [argumentState], ); const onChangeFieldName = useCallback( (index: number) => (e: any) => { const result = [...argumentState]; result[index].fieldName = e.target.value; result[index].name = e.target.value; setArgumentState(result); }, [argumentState], ); const onChangeDescribe = useCallback( (index: number) => (e: any) => { const result = [...argumentState]; result[index].describe = e.target.value; setArgumentState(result); }, [argumentState], ); // 移除字段 const onRemove = useCallback( (index: number) => () => { let result = [...argumentState]; result = result.filter((_, i) => i !== index); setArgumentState(result); }, [argumentState], ); // 新增字段 const onAddField = useCallback(() => { const result = [...argumentState]; result.push({ describe: undefined, name: '未命名', fieldName: '', type: 'string', data: '', }); setArgumentState(result); }, [argumentState]); // 修改字段类型 const onChangeArgType = useCallback( (index: number) => (e: any) => { const result = [...argumentState]; result[index].type = e; switch (e) { case 'runningTime': case 'string': case 'number': result[index].data = ''; break; case 'array': result[index].data = []; break; case 'object': result[index].data = {}; break; case 'boolean': result[index].data = { comparableAverageA: null, comparableAverageB: null, method: '===', }; break; default: break; } setArgumentState(result); }, [argumentState], ); const onClickShowGloabVar = useCallback(() => { console.log(runningTimes); }, [runningTimes]); const renderNumberString = ( item: ArgumentsString | ArgumentsNumber, index: number, ) => { // 下拉选择形式 if (item?.select) { const { select } = item; const keys = Object.keys(select); console.log('select', select); console.log('keys', keys); return ( <Select onChange={onChangeInput(index, true)} value={item.data} className={s.select} placeholder={`请输入值,${item.describe || ''}`} > {keys.map((value) => ( <Select.Option key={value} value={value}> {select[value]} </Select.Option> ))} </Select> ); } // 输入框形式 return ( <Input onChange={onChangeInput(index)} placeholder={`请输入值,${item.describe || ''}`} value={item.data} type="text" suffix={!!item.html ? <HtmlSuffix /> : null} /> ); }; return ( <> <Modal title={ <div className={s.title}> <h4> {title}{' '} <Button type="text" onClick={onClickShowGloabVar} icon={ <Tooltip title="查看全局发布变量"> <ClusterOutlined onClick={() => setShowRunningTimes(true)} /> </Tooltip> } /> </h4> <div className={s.right}> {headerFlexible ? ( <Button onClick={onAddField}>新增</Button> ) : null} </div> </div> } visible={visible} onOk={onModalOk} onCancel={onCancel} bodyStyle={{ padding: '10px' }} okText="确定" cancelText="取消" > {argumentState.map((item, index) => { const initItem = initArgumentData?.length ? initArgumentData[index] : undefined; return ( <Card className={classNames(s.card, { [s.mixedcard]: item.type === 'mixed', })} key={`${index}`} title={ <div className={s.cardtitle}> <div className={s.cardtitleinfo}> {!headerFlexible ? ( <> <span className={s.label}>名称:</span> {item.name || initItem?.name || ''} &nbsp; <Tooltip title={parse( item.describe || initItem?.describe || '', )} > <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)', }} /> </Tooltip> </> ) : ( <> <span className={s.label}>字段:</span> <Input className={s.title} value={item.fieldName || initItem?.fieldName || ''} placeholder="限数字或字母" onChange={onChangeFieldName(index)} suffix={ <Tooltip title={ <Input className={s.desc} placeholder="新增字段描述" value={item.describe} style={{ width: '200px', }} onChange={onChangeDescribe(index)} /> } > <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)', }} /> </Tooltip> } /> </> )} <span className={s.divide} /> <span className={s.label}>类型:</span> {headerFlexible ? ( <Select className={s.type} value={item.type} onChange={onChangeArgType(index)} > <Select.Option value="string">string</Select.Option> <Select.Option value="number">number</Select.Option> <Select.Option value="boolean">boolean</Select.Option> <Select.Option value="object">object</Select.Option> <Select.Option value="array">array</Select.Option> <Select.Option value="mixed">mixed</Select.Option> <Select.Option value="runningTime"> runningTime </Select.Option> </Select> ) : ( item.type )} </div> <div> {headerFlexible ? ( <Button onClick={onRemove(index)}>移除</Button> ) : null} </div> </div> } > <div> {item.type === 'number' || item.type === 'string' ? renderNumberString(item, index) : null} {item.type === 'runningTime' ? ( <Select className={s.select} placeholder="请选择" showSearch value={item.data} optionFilterProp="children" filterOption={ (input, option) => { const str = option?.children.join('').toLowerCase(); if (str.indexOf(input) !== -1) { return true; } return false; } // option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } onChange={onChangeRunningTime(index)} > {Object.keys(runningTimes)?.map( (optionsIitem, optionsIitemIndex) => ( <Select.Option key={optionsIitemIndex} value={optionsIitem} > {optionsIitem} </Select.Option> ), )} </Select> ) : null} {item.type === 'object' ? ( <ObjectArguments describe={item.describe} htmlInput={!!item.html} onChange={onChangeObjType(index)} typeArguments={item} flexible={!!dataFlexible} /> ) : null} {item.type === 'array' ? ( <ArrayArguments htmlInput={!!item.html} describe={item.describe} onChange={onChangeObjType(index)} typeArguments={item} flexible={!!dataFlexible} /> ) : null} {item.type === 'boolean' ? ( <BooleanArguments onChange={onChangeObjType(index)} typeArguments={item} flexible={!!dataFlexible} /> ) : null} {item.type === 'mixed' ? ( <MixedArguments onChange={onChangeObjType(index)} typeArguments={item} flexible={!!dataFlexible} /> ) : null} </div> </Card> ); })} </Modal> <RunningTimesModal visible={showRunningTimes} data={runningTimes} onCancel={() => setShowRunningTimes(false)} /> </> ); }; export default ArgumentsSetting;
the_stack
import URL from "url"; import nunjucks from "nunjucks"; import parser from "./bash-parser.js"; import type { Parser } from "./bash-parser.js"; const env = nunjucks.configure(["templates/"], { // set folders with templates autoescape: false, }); env.addFilter("isArr", (something: any): boolean => Array.isArray(something)); env.addFilter( "isString", (something: any): boolean => typeof something === "string" ); // TODO: this type doesn't work. function has<T, K extends PropertyKey>( obj: T, prop: K ): obj is T & Record<K, unknown> { return Object.prototype.hasOwnProperty.call(obj, prop); } export class CCError extends Error {} function pushProp<Type>( obj: { [key: string]: Type[] }, prop: string, value: Type ) { if (!has(obj, prop)) { // TODO: I have no idea what // Type 'never[]' is not assignable to type 'never'. // means (obj[prop] as Type[]) = []; } obj[prop].push(value); return obj; } interface _LongShort { name?: string; // added dynamically type: "string" | "number" | "bool"; expand?: boolean; removed?: string; } interface LongShort { name: string; type: "string" | "number" | "bool"; expand?: boolean; removed?: string; } interface _LongOpts { [key: string]: _LongShort; } interface LongOpts { [key: string]: LongShort | null; } interface ShortOpts { [key: string]: string; } type Query = Array<[string, string | null]>; interface QueryDict { [key: string]: string | null | Array<string | null>; } type Headers = Array<[string, string | null]>; type Cookie = [string, string]; type Cookies = Array<Cookie>; type FormParam = { value: string; type: "string" | "form" }; interface ParsedArguments { request?: string; // the HTTP method data?: string[]; "data-binary"?: string[]; "data-ascii"?: string[]; "data-raw"?: string[]; "data-urlencode"?: string[]; json?: string[]; form?: FormParam[]; [key: string]: any; } type Warnings = [string, string][]; function pushArgValue(obj: ParsedArguments, argName: string, value: string) { if (argName === "form-string") { return pushProp(obj, "form", { value, type: "string" }); } else if (argName === "form") { return pushProp(obj, "form", { value, type: "form" }); } // TODO: --data-* return pushProp(obj, argName, value); } interface Request { url: string; urlWithoutQuery: string; query?: Query; queryDict?: QueryDict; method: string; headers?: Headers; stdin?: string; input?: string; multipartUploads?: ({ name: string; } & ({ content: string } | { contentFile: string; filename?: string }))[]; auth?: [string, string]; cookies?: Cookies; cookieFiles?: string[]; cookieJar?: string; compressed?: boolean; isDataBinary?: boolean; isDataRaw?: boolean; digest?: boolean; dataArray?: string[]; data?: string; uploadFile?: string; insecure?: boolean; cert?: string | [string, string]; cacert?: string; capath?: string; proxy?: string; proxyAuth?: string; timeout?: string; followRedirects?: boolean; output?: string; http2?: boolean; http3?: boolean; } // BEGIN GENERATED CURL OPTIONS const _curlLongOpts: _LongOpts = { url: { type: "string" }, "dns-ipv4-addr": { type: "string" }, "dns-ipv6-addr": { type: "string" }, "random-file": { type: "string" }, "egd-file": { type: "string" }, "oauth2-bearer": { type: "string" }, "connect-timeout": { type: "string" }, "doh-url": { type: "string" }, ciphers: { type: "string" }, "dns-interface": { type: "string" }, "disable-epsv": { type: "bool", name: "epsv" }, "no-disable-epsv": { type: "bool", name: "epsv", expand: false }, "disallow-username-in-url": { type: "bool" }, "no-disallow-username-in-url": { type: "bool", name: "disallow-username-in-url", expand: false, }, epsv: { type: "bool" }, "no-epsv": { type: "bool", name: "epsv", expand: false }, "dns-servers": { type: "string" }, trace: { type: "string" }, npn: { type: "bool" }, "no-npn": { type: "bool", name: "npn", expand: false }, "trace-ascii": { type: "string" }, alpn: { type: "bool" }, "no-alpn": { type: "bool", name: "alpn", expand: false }, "limit-rate": { type: "string" }, compressed: { type: "bool" }, "no-compressed": { type: "bool", name: "compressed", expand: false }, "tr-encoding": { type: "bool" }, "no-tr-encoding": { type: "bool", name: "tr-encoding", expand: false }, digest: { type: "bool" }, "no-digest": { type: "bool", name: "digest", expand: false }, negotiate: { type: "bool" }, "no-negotiate": { type: "bool", name: "negotiate", expand: false }, ntlm: { type: "bool" }, "no-ntlm": { type: "bool", name: "ntlm", expand: false }, "ntlm-wb": { type: "bool" }, "no-ntlm-wb": { type: "bool", name: "ntlm-wb", expand: false }, basic: { type: "bool" }, "no-basic": { type: "bool", name: "basic", expand: false }, anyauth: { type: "bool" }, "no-anyauth": { type: "bool", name: "anyauth", expand: false }, wdebug: { type: "bool" }, "no-wdebug": { type: "bool", name: "wdebug", expand: false }, "ftp-create-dirs": { type: "bool" }, "no-ftp-create-dirs": { type: "bool", name: "ftp-create-dirs", expand: false, }, "create-dirs": { type: "bool" }, "no-create-dirs": { type: "bool", name: "create-dirs", expand: false }, "create-file-mode": { type: "string" }, "max-redirs": { type: "string" }, "proxy-ntlm": { type: "bool" }, "no-proxy-ntlm": { type: "bool", name: "proxy-ntlm", expand: false }, crlf: { type: "bool" }, "no-crlf": { type: "bool", name: "crlf", expand: false }, stderr: { type: "string" }, "aws-sigv4": { type: "string" }, interface: { type: "string" }, krb: { type: "string" }, krb4: { type: "string", name: "krb" }, "haproxy-protocol": { type: "bool" }, "no-haproxy-protocol": { type: "bool", name: "haproxy-protocol", expand: false, }, "max-filesize": { type: "string" }, "disable-eprt": { type: "bool", name: "eprt" }, "no-disable-eprt": { type: "bool", name: "eprt", expand: false }, eprt: { type: "bool" }, "no-eprt": { type: "bool", name: "eprt", expand: false }, xattr: { type: "bool" }, "no-xattr": { type: "bool", name: "xattr", expand: false }, "ftp-ssl": { type: "bool", name: "ssl" }, "no-ftp-ssl": { type: "bool", name: "ssl", expand: false }, ssl: { type: "bool" }, "no-ssl": { type: "bool", name: "ssl", expand: false }, "ftp-pasv": { type: "bool" }, "no-ftp-pasv": { type: "bool", name: "ftp-pasv", expand: false }, socks5: { type: "string" }, "tcp-nodelay": { type: "bool" }, "no-tcp-nodelay": { type: "bool", name: "tcp-nodelay", expand: false }, "proxy-digest": { type: "bool" }, "no-proxy-digest": { type: "bool", name: "proxy-digest", expand: false }, "proxy-basic": { type: "bool" }, "no-proxy-basic": { type: "bool", name: "proxy-basic", expand: false }, retry: { type: "string" }, "retry-connrefused": { type: "bool" }, "no-retry-connrefused": { type: "bool", name: "retry-connrefused", expand: false, }, "retry-delay": { type: "string" }, "retry-max-time": { type: "string" }, "proxy-negotiate": { type: "bool" }, "no-proxy-negotiate": { type: "bool", name: "proxy-negotiate", expand: false, }, "form-escape": { type: "bool" }, "no-form-escape": { type: "bool", name: "form-escape", expand: false }, "ftp-account": { type: "string" }, "proxy-anyauth": { type: "bool" }, "no-proxy-anyauth": { type: "bool", name: "proxy-anyauth", expand: false }, "trace-time": { type: "bool" }, "no-trace-time": { type: "bool", name: "trace-time", expand: false }, "ignore-content-length": { type: "bool" }, "no-ignore-content-length": { type: "bool", name: "ignore-content-length", expand: false, }, "ftp-skip-pasv-ip": { type: "bool" }, "no-ftp-skip-pasv-ip": { type: "bool", name: "ftp-skip-pasv-ip", expand: false, }, "ftp-method": { type: "string" }, "local-port": { type: "string" }, socks4: { type: "string" }, socks4a: { type: "string" }, "ftp-alternative-to-user": { type: "string" }, "ftp-ssl-reqd": { type: "bool", name: "ssl-reqd" }, "no-ftp-ssl-reqd": { type: "bool", name: "ssl-reqd", expand: false }, "ssl-reqd": { type: "bool" }, "no-ssl-reqd": { type: "bool", name: "ssl-reqd", expand: false }, sessionid: { type: "bool" }, "no-sessionid": { type: "bool", name: "sessionid", expand: false }, "ftp-ssl-control": { type: "bool" }, "no-ftp-ssl-control": { type: "bool", name: "ftp-ssl-control", expand: false, }, "ftp-ssl-ccc": { type: "bool" }, "no-ftp-ssl-ccc": { type: "bool", name: "ftp-ssl-ccc", expand: false }, "ftp-ssl-ccc-mode": { type: "string" }, libcurl: { type: "string" }, raw: { type: "bool" }, "no-raw": { type: "bool", name: "raw", expand: false }, post301: { type: "bool" }, "no-post301": { type: "bool", name: "post301", expand: false }, keepalive: { type: "bool" }, "no-keepalive": { type: "bool", name: "keepalive", expand: false }, "socks5-hostname": { type: "string" }, "keepalive-time": { type: "string" }, post302: { type: "bool" }, "no-post302": { type: "bool", name: "post302", expand: false }, noproxy: { type: "string" }, "socks5-gssapi-nec": { type: "bool" }, "no-socks5-gssapi-nec": { type: "bool", name: "socks5-gssapi-nec", expand: false, }, "proxy1.0": { type: "string" }, "tftp-blksize": { type: "string" }, "mail-from": { type: "string" }, "mail-rcpt": { type: "string" }, "ftp-pret": { type: "bool" }, "no-ftp-pret": { type: "bool", name: "ftp-pret", expand: false }, proto: { type: "string" }, "proto-redir": { type: "string" }, resolve: { type: "string" }, delegation: { type: "string" }, "mail-auth": { type: "string" }, post303: { type: "bool" }, "no-post303": { type: "bool", name: "post303", expand: false }, metalink: { type: "bool" }, "no-metalink": { type: "bool", name: "metalink", expand: false }, "sasl-authzid": { type: "string" }, "sasl-ir": { type: "bool" }, "no-sasl-ir": { type: "bool", name: "sasl-ir", expand: false }, "test-event": { type: "bool" }, "no-test-event": { type: "bool", name: "test-event", expand: false }, "unix-socket": { type: "string" }, "path-as-is": { type: "bool" }, "no-path-as-is": { type: "bool", name: "path-as-is", expand: false }, "socks5-gssapi-service": { type: "string", name: "proxy-service-name" }, "proxy-service-name": { type: "string" }, "service-name": { type: "string" }, "proto-default": { type: "string" }, "expect100-timeout": { type: "string" }, "tftp-no-options": { type: "bool" }, "no-tftp-no-options": { type: "bool", name: "tftp-no-options", expand: false, }, "connect-to": { type: "string" }, "abstract-unix-socket": { type: "string" }, "tls-max": { type: "string" }, "suppress-connect-headers": { type: "bool" }, "no-suppress-connect-headers": { type: "bool", name: "suppress-connect-headers", expand: false, }, "compressed-ssh": { type: "bool" }, "no-compressed-ssh": { type: "bool", name: "compressed-ssh", expand: false }, "happy-eyeballs-timeout-ms": { type: "string" }, "retry-all-errors": { type: "bool" }, "no-retry-all-errors": { type: "bool", name: "retry-all-errors", expand: false, }, "http1.0": { type: "bool" }, "http1.1": { type: "bool" }, http2: { type: "bool" }, "http2-prior-knowledge": { type: "bool" }, http3: { type: "bool" }, "http0.9": { type: "bool" }, "no-http0.9": { type: "bool", name: "http0.9", expand: false }, tlsv1: { type: "bool" }, "tlsv1.0": { type: "bool" }, "tlsv1.1": { type: "bool" }, "tlsv1.2": { type: "bool" }, "tlsv1.3": { type: "bool" }, "tls13-ciphers": { type: "string" }, "proxy-tls13-ciphers": { type: "string" }, sslv2: { type: "bool" }, sslv3: { type: "bool" }, ipv4: { type: "bool" }, ipv6: { type: "bool" }, append: { type: "bool" }, "no-append": { type: "bool", name: "append", expand: false }, "user-agent": { type: "string" }, cookie: { type: "string" }, "alt-svc": { type: "string" }, hsts: { type: "string" }, "use-ascii": { type: "bool" }, "no-use-ascii": { type: "bool", name: "use-ascii", expand: false }, "cookie-jar": { type: "string" }, "continue-at": { type: "string" }, data: { type: "string" }, "data-raw": { type: "string" }, "data-ascii": { type: "string" }, "data-binary": { type: "string" }, "data-urlencode": { type: "string" }, json: { type: "string" }, "dump-header": { type: "string" }, referer: { type: "string" }, cert: { type: "string" }, cacert: { type: "string" }, "cert-type": { type: "string" }, key: { type: "string" }, "key-type": { type: "string" }, pass: { type: "string" }, engine: { type: "string" }, capath: { type: "string" }, pubkey: { type: "string" }, hostpubmd5: { type: "string" }, hostpubsha256: { type: "string" }, crlfile: { type: "string" }, tlsuser: { type: "string" }, tlspassword: { type: "string" }, tlsauthtype: { type: "string" }, "ssl-allow-beast": { type: "bool" }, "no-ssl-allow-beast": { type: "bool", name: "ssl-allow-beast", expand: false, }, "ssl-auto-client-cert": { type: "bool" }, "no-ssl-auto-client-cert": { type: "bool", name: "ssl-auto-client-cert", expand: false, }, "proxy-ssl-auto-client-cert": { type: "bool" }, "no-proxy-ssl-auto-client-cert": { type: "bool", name: "proxy-ssl-auto-client-cert", expand: false, }, pinnedpubkey: { type: "string" }, "proxy-pinnedpubkey": { type: "string" }, "cert-status": { type: "bool" }, "no-cert-status": { type: "bool", name: "cert-status", expand: false }, "doh-cert-status": { type: "bool" }, "no-doh-cert-status": { type: "bool", name: "doh-cert-status", expand: false, }, "false-start": { type: "bool" }, "no-false-start": { type: "bool", name: "false-start", expand: false }, "ssl-no-revoke": { type: "bool" }, "no-ssl-no-revoke": { type: "bool", name: "ssl-no-revoke", expand: false }, "ssl-revoke-best-effort": { type: "bool" }, "no-ssl-revoke-best-effort": { type: "bool", name: "ssl-revoke-best-effort", expand: false, }, "tcp-fastopen": { type: "bool" }, "no-tcp-fastopen": { type: "bool", name: "tcp-fastopen", expand: false }, "proxy-tlsuser": { type: "string" }, "proxy-tlspassword": { type: "string" }, "proxy-tlsauthtype": { type: "string" }, "proxy-cert": { type: "string" }, "proxy-cert-type": { type: "string" }, "proxy-key": { type: "string" }, "proxy-key-type": { type: "string" }, "proxy-pass": { type: "string" }, "proxy-ciphers": { type: "string" }, "proxy-crlfile": { type: "string" }, "proxy-ssl-allow-beast": { type: "bool" }, "no-proxy-ssl-allow-beast": { type: "bool", name: "proxy-ssl-allow-beast", expand: false, }, "login-options": { type: "string" }, "proxy-cacert": { type: "string" }, "proxy-capath": { type: "string" }, "proxy-insecure": { type: "bool" }, "no-proxy-insecure": { type: "bool", name: "proxy-insecure", expand: false }, "proxy-tlsv1": { type: "bool" }, "socks5-basic": { type: "bool" }, "no-socks5-basic": { type: "bool", name: "socks5-basic", expand: false }, "socks5-gssapi": { type: "bool" }, "no-socks5-gssapi": { type: "bool", name: "socks5-gssapi", expand: false }, "etag-save": { type: "string" }, "etag-compare": { type: "string" }, curves: { type: "string" }, fail: { type: "bool" }, "no-fail": { type: "bool", name: "fail", expand: false }, "fail-early": { type: "bool" }, "no-fail-early": { type: "bool", name: "fail-early", expand: false }, "styled-output": { type: "bool" }, "no-styled-output": { type: "bool", name: "styled-output", expand: false }, "mail-rcpt-allowfails": { type: "bool" }, "no-mail-rcpt-allowfails": { type: "bool", name: "mail-rcpt-allowfails", expand: false, }, "fail-with-body": { type: "bool" }, "no-fail-with-body": { type: "bool", name: "fail-with-body", expand: false }, form: { type: "string" }, "form-string": { type: "string" }, globoff: { type: "bool" }, "no-globoff": { type: "bool", name: "globoff", expand: false }, get: { type: "bool" }, "request-target": { type: "string" }, help: { type: "bool" }, "no-help": { type: "bool", name: "help", expand: false }, header: { type: "string" }, "proxy-header": { type: "string" }, include: { type: "bool" }, "no-include": { type: "bool", name: "include", expand: false }, head: { type: "bool" }, "no-head": { type: "bool", name: "head", expand: false }, "junk-session-cookies": { type: "bool" }, "no-junk-session-cookies": { type: "bool", name: "junk-session-cookies", expand: false, }, "remote-header-name": { type: "bool" }, "no-remote-header-name": { type: "bool", name: "remote-header-name", expand: false, }, insecure: { type: "bool" }, "no-insecure": { type: "bool", name: "insecure", expand: false }, "doh-insecure": { type: "bool" }, "no-doh-insecure": { type: "bool", name: "doh-insecure", expand: false }, config: { type: "string" }, "list-only": { type: "bool" }, "no-list-only": { type: "bool", name: "list-only", expand: false }, location: { type: "bool" }, "no-location": { type: "bool", name: "location", expand: false }, "location-trusted": { type: "bool" }, "no-location-trusted": { type: "bool", name: "location-trusted", expand: false, }, "max-time": { type: "string" }, manual: { type: "bool" }, "no-manual": { type: "bool", name: "manual", expand: false }, netrc: { type: "bool" }, "no-netrc": { type: "bool", name: "netrc", expand: false }, "netrc-optional": { type: "bool" }, "no-netrc-optional": { type: "bool", name: "netrc-optional", expand: false }, "netrc-file": { type: "string" }, buffer: { type: "bool" }, "no-buffer": { type: "bool", name: "buffer", expand: false }, output: { type: "string" }, "remote-name": { type: "bool" }, "remote-name-all": { type: "bool" }, "no-remote-name-all": { type: "bool", name: "remote-name-all", expand: false, }, "output-dir": { type: "string" }, proxytunnel: { type: "bool" }, "no-proxytunnel": { type: "bool", name: "proxytunnel", expand: false }, "ftp-port": { type: "string" }, disable: { type: "bool" }, "no-disable": { type: "bool", name: "disable", expand: false }, quote: { type: "string" }, range: { type: "string" }, "remote-time": { type: "bool" }, "no-remote-time": { type: "bool", name: "remote-time", expand: false }, silent: { type: "bool" }, "no-silent": { type: "bool", name: "silent", expand: false }, "show-error": { type: "bool" }, "no-show-error": { type: "bool", name: "show-error", expand: false }, "telnet-option": { type: "string" }, "upload-file": { type: "string" }, user: { type: "string" }, "proxy-user": { type: "string" }, verbose: { type: "bool" }, "no-verbose": { type: "bool", name: "verbose", expand: false }, version: { type: "bool" }, "no-version": { type: "bool", name: "version", expand: false }, "write-out": { type: "string" }, proxy: { type: "string" }, preproxy: { type: "string" }, request: { type: "string" }, "speed-limit": { type: "string" }, "speed-time": { type: "string" }, "time-cond": { type: "string" }, parallel: { type: "bool" }, "no-parallel": { type: "bool", name: "parallel", expand: false }, "parallel-max": { type: "string" }, "parallel-immediate": { type: "bool" }, "no-parallel-immediate": { type: "bool", name: "parallel-immediate", expand: false, }, "progress-bar": { type: "bool" }, "no-progress-bar": { type: "bool", name: "progress-bar", expand: false }, "progress-meter": { type: "bool" }, "no-progress-meter": { type: "bool", name: "progress-meter", expand: false }, next: { type: "bool" }, }; const curlShortOpts: ShortOpts = { 0: "http1.0", 1: "tlsv1", 2: "sslv2", 3: "sslv3", 4: "ipv4", 6: "ipv6", a: "append", A: "user-agent", b: "cookie", B: "use-ascii", c: "cookie-jar", C: "continue-at", d: "data", D: "dump-header", e: "referer", E: "cert", f: "fail", F: "form", g: "globoff", G: "get", h: "help", H: "header", i: "include", I: "head", j: "junk-session-cookies", J: "remote-header-name", k: "insecure", K: "config", l: "list-only", L: "location", m: "max-time", M: "manual", n: "netrc", N: "no-buffer", o: "output", O: "remote-name", p: "proxytunnel", P: "ftp-port", q: "disable", Q: "quote", r: "range", R: "remote-time", s: "silent", S: "show-error", t: "telnet-option", T: "upload-file", u: "user", U: "proxy-user", v: "verbose", V: "version", w: "write-out", x: "proxy", X: "request", Y: "speed-limit", y: "speed-time", z: "time-cond", Z: "parallel", "#": "progress-bar", ":": "next", }; // END GENERATED CURL OPTIONS // These are options that curl used to have. // Those that don't conflict with the current options are supported by curlconverter. // TODO: curl's --long-options can be shortened. // For example if curl used to only have a single option, "--blah" then // "--bla" "--bl" and "--b" all used to be valid options as well. If later // "--blaz" was added, suddenly those 3 shortened options are removed (because // they are now ambiguous). // https://github.com/curlconverter/curlconverter/pull/280#issuecomment-931241328 const _removedLongOpts: { [key: string]: _LongShort } = { "ftp-ascii": { type: "bool", name: "use-ascii", removed: "7.10.7" }, port: { type: "string", removed: "7.3" }, upload: { type: "bool", removed: "7.7" }, continue: { type: "bool", removed: "7.9" }, "3p-url": { type: "string", removed: "7.16.0" }, "3p-user": { type: "string", removed: "7.16.0" }, "3p-quote": { type: "string", removed: "7.16.0" }, "http2.0": { type: "bool", name: "http2", removed: "7.36.0" }, "no-http2.0": { type: "bool", name: "http2", removed: "7.36.0" }, "telnet-options": { type: "string", name: "telnet-option", removed: "7.49.0", }, "http-request": { type: "string", name: "request", removed: "7.49.0" }, socks: { type: "string", name: "socks5", removed: "7.49.0" }, "capath ": { type: "string", name: "capath", removed: "7.49.0" }, // trailing space ftpport: { type: "string", name: "ftp-port", removed: "7.49.0" }, environment: { type: "bool", removed: "7.54.1" }, // These --no-<option> flags were automatically generated and never had any effect "no-tlsv1": { type: "bool", name: "tlsv1", removed: "7.54.1" }, "no-tlsv1.2": { type: "bool", name: "tlsv1.2", removed: "7.54.1" }, "no-http2-prior-knowledge": { type: "bool", name: "http2-prior-knowledge", removed: "7.54.1", }, "no-ipv6": { type: "bool", name: "ipv6", removed: "7.54.1" }, "no-ipv4": { type: "bool", name: "ipv4", removed: "7.54.1" }, "no-sslv2": { type: "bool", name: "sslv2", removed: "7.54.1" }, "no-tlsv1.0": { type: "bool", name: "tlsv1.0", removed: "7.54.1" }, "no-tlsv1.1": { type: "bool", name: "tlsv1.1", removed: "7.54.1" }, "no-remote-name": { type: "bool", name: "remote-name", removed: "7.54.1" }, "no-sslv3": { type: "bool", name: "sslv3", removed: "7.54.1" }, "no-get": { type: "bool", name: "get", removed: "7.54.1" }, "no-http1.0": { type: "bool", name: "http1.0", removed: "7.54.1" }, "no-next": { type: "bool", name: "next", removed: "7.54.1" }, "no-tlsv1.3": { type: "bool", name: "tlsv1.3", removed: "7.54.1" }, "no-environment": { type: "bool", name: "environment", removed: "7.54.1" }, "no-http1.1": { type: "bool", name: "http1.1", removed: "7.54.1" }, "no-proxy-tlsv1": { type: "bool", name: "proxy-tlsv1", removed: "7.54.1" }, "no-http2": { type: "bool", name: "http2", removed: "7.54.1" }, }; for (const [opt, val] of Object.entries(_removedLongOpts)) { if (!has(val, "name")) { val.name = opt; } } const removedLongOpts = _removedLongOpts as LongOpts; // could be stricter, there's no null values // TODO: use this to warn users when they specify a short option that // used to be for something else? const changedShortOpts: { [key: string]: string } = { p: "used to be short for --port <port> (a since-deleted flag) until curl 7.3", // TODO: some of these might be renamed options t: "used to be short for --upload (a since-deleted boolean flag) until curl 7.7", c: "used to be short for --continue (a since-deleted boolean flag) until curl 7.9", // TODO: did -@ actually work? "@": "used to be short for --create-dirs until curl 7.10.7", Z: "used to be short for --max-redirs <num> until curl 7.10.7", 9: "used to be short for --crlf until curl 7.10.8", 8: "used to be short for --stderr <file> until curl 7.10.8", 7: "used to be short for --interface <name> until curl 7.10.8", 6: "used to be short for --krb <level> (which itself used to be --krb4 <level>) until curl 7.10.8", // TODO: did these short options ever actually work? 5: "used to be another way to specify the url until curl 7.10.8", "*": "used to be another way to specify the url until curl 7.49.0", "~": "used to be short for --xattr until curl 7.49.0", }; // These are args that users wouldn't expect to be warned about const ignoredArgs = new Set([ "help", "no-help", "silent", "no-silent", "verbose", "no-verbose", "version", "no-version", "progress-bar", "no-progress-bar", "progress-meter", "no-progress-meter", "show-error", "no-show-error", ]); // These options can be specified more than once, they // are always returned as a list. // Normally, if you specify some option more than once, // curl will just take the last one. // TODO: extract this from curl's source code? const canBeList = new Set([ // TODO: unlike curl, we don't support multiple // URLs and just take the last one. "url", "header", "proxy-header", "form", "data", "data-binary", "data-ascii", "data-raw", "data-urlencode", "json", "mail-rcpt", "resolve", "connect-to", "cookie", "quote", "telnet-option", ]); const shortened: { [key: string]: LongShort[] } = {}; for (const [opt, val] of Object.entries(_curlLongOpts)) { if (!has(val, "name")) { val.name = opt; } } const curlLongOpts = _curlLongOpts as LongOpts; for (const [opt, val] of Object.entries(_curlLongOpts)) { // curl lets you not type the full argument as long as it's unambiguous. // So --sil instead of --silent is okay, --s is not. // This doesn't apply to options starting with --no- // Default 'expand' to true if not specified const shouldExpand = !has(val, "expand") || val.expand; delete val.expand; if (shouldExpand) { for (let i = 1; i < opt.length; i++) { const shortenedOpt = opt.slice(0, i); pushProp(shortened, shortenedOpt, val); } } } for (const [shortenedOpt, vals] of Object.entries(shortened)) { if (!has(curlLongOpts, shortenedOpt)) { if (vals.length === 1) { (curlLongOpts[shortenedOpt] as LongShort | null) = vals[0]; } else if (vals.length > 1) { // More than one option shortens to this, it's ambiguous (curlLongOpts[shortenedOpt] as LongShort | null) = null; } } } for (const [removedOpt, val] of Object.entries(removedLongOpts)) { if (!has(curlLongOpts, removedOpt)) { (curlLongOpts[removedOpt] as LongShort | null) = val; } else if (curlLongOpts[removedOpt] === null) { // This happens with --socks because it became --socks5 and there are multiple options // that start with "--socks" // console.error("couldn't add removed option --" + removedOpt + " to curlLongOpts because it's already ambiguous") // TODO: do we want to do this? // curlLongOpts[removedOpt] = val } else { // Almost certainly a shortened form of a still-existing option // This happens with --continue (now short for --continue-at) // and --upload (now short for --upload-file) // console.error("couldn't add removed option --" + removedOpt + ' to curlLongOpts because it already exists') } } function toBoolean(opt: string): boolean { if (opt.startsWith("no-disable-")) { return true; } if (opt.startsWith("disable-") || opt.startsWith("no-")) { return false; } return true; } const parseWord = (str: string): string => { const BACKSLASHES = /\\./gs; const unescapeChar = (m: string) => (m.charAt(1) === "\n" ? "" : m.charAt(1)); return str.replace(BACKSLASHES, unescapeChar); }; const parseSingleQuoteString = (str: string): string => { const BACKSLASHES = /\\(\n|')/gs; const unescapeChar = (m: string) => (m.charAt(1) === "\n" ? "" : m.charAt(1)); return str.slice(1, -1).replace(BACKSLASHES, unescapeChar); }; const parseDoubleQuoteString = (str: string): string => { const BACKSLASHES = /\\(\n|\\|")/gs; const unescapeChar = (m: string) => (m.charAt(1) === "\n" ? "" : m.charAt(1)); return str.slice(1, -1).replace(BACKSLASHES, unescapeChar); }; const parseTranslatedString = (str: string): string => { return parseDoubleQuoteString(str.slice(1)); }; // ANSI-C quoted strings look $'like this'. // Not all shells have them but bash does // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html // // https://git.savannah.gnu.org/cgit/bash.git/tree/lib/sh/strtrans.c const parseAnsiCString = (str: string): string => { const ANSI_BACKSLASHES = /\\(\\|a|b|e|E|f|n|r|t|v|'|"|\?|[0-7]{1,3}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|c.)/gs; const unescapeChar = (m: string) => { switch (m.charAt(1)) { case "\\": return "\\"; case "a": return "\x07"; case "b": return "\b"; case "e": case "E": return "\x1B"; case "f": return "\f"; case "n": return "\n"; case "r": return "\r"; case "t": return "\t"; case "v": return "\v"; case "'": return "'"; case '"': return '"'; case "?": return "?"; case "c": // bash handles all characters by considering the first byte // of its UTF-8 input and can produce invalid UTF-8, whereas // JavaScript stores strings in UTF-16 if (m.codePointAt(2)! > 127) { throw new CCError( "non-ASCII control character in ANSI-C quoted string: '\\u{" + m.codePointAt(2)!.toString(16) + "}'" ); } // If this produces a 0x00 (null) character, it will cause bash to // terminate the string at that character, but we return the null // character in the result. return m[2] === "?" ? "\x7F" : String.fromCodePoint( m[2].toUpperCase().codePointAt(0)! & 0b00011111 ); case "x": case "u": case "U": // Hexadecimal character literal // Unlike bash, this will error if the the code point is greater than 10FFFF return String.fromCodePoint(parseInt(m.slice(2), 16)); case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": // Octal character literal return String.fromCodePoint(parseInt(m.slice(1), 8) % 256); default: // There must be a mis-match between ANSI_BACKSLASHES and the switch statement throw new CCError( "unhandled character in ANSI-C escape code: " + JSON.stringify(m) ); } }; return str.slice(2, -1).replace(ANSI_BACKSLASHES, unescapeChar); }; const underlineBadNode = ( curlCommand: string, node: Parser.SyntaxNode ): string => { // TODO: is this exactly how tree-sitter splits lines? const line = curlCommand.split("\n")[node.startPosition.row]; const onOneLine = node.endPosition.row === node.startPosition.row; const end = onOneLine ? node.endPosition.column : line.length; return ( `${line}\n` + " ".repeat(node.startPosition.column) + "^".repeat(end - node.startPosition.column) + (onOneLine ? "" : "^") // TODO: something else? ); }; function toVal(node: Parser.SyntaxNode, curlCommand: string): string { switch (node.type) { case "word": case "simple_expansion": // TODO: handle variables properly downstream return parseWord(node.text); case "string": return parseDoubleQuoteString(node.text); case "raw_string": return parseSingleQuoteString(node.text); case "ansii_c_string": return parseAnsiCString(node.text); case "string_expansion": return parseTranslatedString(node.text); case "concatenation": // item[]=1 turns into item=1 if we don't do this // https://github.com/tree-sitter/tree-sitter-bash/issues/104 if (node.children.every((n) => n.type === "word")) { return node.text; } return node.children.map((c) => toVal(c, curlCommand)).join(""); default: // console.error(curlCommand) // console.error(curlArgs.rootNode.toString()) throw new CCError( "unexpected argument type " + JSON.stringify(node.type) + '. Must be one of "word", "string", "raw_string", "ascii_c_string", "simple_expansion" or "concatenation"\n' + underlineBadNode(curlCommand, node) ); } } interface TokenizeResult { cmdName: string; args: string[]; stdin?: string; input?: string; } const tokenize = ( curlCommand: string, warnings: Warnings = [] ): TokenizeResult => { const curlArgs = parser.parse(curlCommand); // The AST must be in a nice format, i.e. // (program // (command // name: (command_name (word)) // argument+: ( // word | // string ('') | // raw_string ("") | // ansii_c_string ($'') | // simple_expansion (variable_name)))) // // TODO: support strings with variable expansions inside // TODO: support prefixed variables, e.g. "MY_VAR=hello curl example.com" // TODO: get only named children? if (curlArgs.rootNode.type !== "program") { // TODO: better error message. throw new CCError( "expected a 'program' top-level AST node, got " + curlArgs.rootNode.type + " instead" ); } if (curlArgs.rootNode.childCount < 1 || !curlArgs.rootNode.children) { // TODO: better error message. throw new CCError('empty "program" node'); } // Get the curl call AST node. Skip comments let command, stdin, input; for (const n of curlArgs.rootNode.children) { if (n.type === "comment") { continue; } else if (n.type === "command") { command = n; // TODO: if there are more `command` nodes, // warn that everything after the first one is ignored break; } else if (n.type === "redirected_statement") { if (!n.childCount) { throw new CCError("got empty 'redirected_statement' AST node"); } let redirect; [command, redirect] = n.children; if (command.type !== "command") { throw new CCError( "got 'redirected_statement' AST node whose first child is not a 'command', got " + command.type + " instead\n" + underlineBadNode(curlCommand, command) ); } if (n.childCount < 2) { throw new CCError( "got 'redirected_statement' AST node with only one child - no redirect" ); } if (redirect.type === "file_redirect") { stdin = toVal(redirect.namedChildren[0], curlCommand); } else if (redirect.type === "heredoc_redirect") { // heredoc bodies are children of the parent program node // https://github.com/tree-sitter/tree-sitter-bash/issues/118 if (redirect.namedChildCount < 1) { throw new CCError( "got 'redirected_statement' AST node with heredoc but no heredoc start" ); } const heredocStart = redirect.namedChildren[0].text; const heredocBody = n.nextNamedSibling; if (!heredocBody) { throw new CCError( "got 'redirected_statement' AST node with no heredoc body" ); } // TODO: herestrings and heredocs are different if (heredocBody.type !== "heredoc_body") { throw new CCError( "got 'redirected_statement' AST node with heredoc but no heredoc body, got " + heredocBody.type + " instead" ); } // TODO: heredocs do variable expansion and stuff if (heredocStart.length) { input = heredocBody.text.slice(0, -heredocStart.length); } else { // this shouldn't happen input = heredocBody.text; } // Curl removes newlines when you pass any @filename including @- for stdin input = input.replace(/\n/g, ""); } else if (redirect.type === "herestring_redirect") { if (redirect.namedChildCount < 1 || !redirect.firstNamedChild) { throw new CCError( "got 'redirected_statement' AST node with empty herestring" ); } // TODO: this just converts bash code to text input = redirect.firstNamedChild.text; } else { throw new CCError( "got 'redirected_statement' AST node whose second child is not one of 'file_redirect', 'heredoc_redirect' or 'herestring_redirect', got " + command.type + " instead" ); } break; } else if (n.type === "ERROR") { throw new CCError( `Bash parsing error on line ${n.startPosition.row + 1}:\n` + underlineBadNode(curlCommand, n) ); } else { // TODO: better error message. throw new CCError( "expected a 'command' or 'redirected_statement' AST node, instead got " + curlArgs.rootNode.children[0].type + "\n" + underlineBadNode(curlCommand, curlArgs.rootNode.children[0]) ); } } if (!command) { // NOTE: if you add more node types in the `for` loop above, this error needs to be updated. // We would probably need to keep track of the node types we've seen. throw new CCError( "expected a 'command' or 'redirected_statement' AST node, only found 'comment' nodes" ); } for (const n of curlArgs.rootNode.children) { if (n.type === "ERROR") { warnings.push([ "bash", `Bash parsing error on line ${n.startPosition.row + 1}:\n` + underlineBadNode(curlCommand, n), ]); } } if (command.childCount < 1) { // TODO: better error message. throw new CCError('empty "command" node'); } // TODO: add childrenForFieldName to tree-sitter node/web bindings and then // use that here instead // TODO: you can have variable_assignment before the actual command // MY_VAR=foo curl example.com const [cmdName, ...args] = command.children; if (cmdName.type !== "command_name") { // TODO: better error message. throw new CCError( "expected a 'command_name' AST node, got " + cmdName.type + " instead\n" + underlineBadNode(curlCommand, cmdName) ); } return { cmdName: cmdName.text.trim(), args: args.map((a) => toVal(a, curlCommand)), stdin, input, }; }; const checkLongOpt = ( lookup: string, longArgName: string, supportedOpts: Set<string>, warnings: Warnings ) => { if (!supportedOpts.has(longArgName) && !ignoredArgs.has(longArgName)) { // TODO: better message. include generator name? warnings.push([longArgName, "--" + lookup + " is not a supported option"]); } }; const checkShortOpt = ( lookup: string, longArgName: string, supportedOpts: Set<string>, warnings: Warnings ) => { if (!supportedOpts.has(longArgName) && !ignoredArgs.has(longArgName)) { // TODO: better message. include generator name? warnings.push([longArgName, "-" + lookup + " is not a supported option"]); } }; const parseArgs = ( args: string[], longOpts: LongOpts, shortOpts: ShortOpts, supportedOpts?: Set<string>, warnings: Warnings = [] ): ParsedArguments => { const parsedArguments: ParsedArguments = {}; for (let i = 0, stillflags = true; i < args.length; i++) { let arg: string | string[] = args[i]; let argRepr = arg; if (stillflags && arg.startsWith("-")) { if (arg === "--") { /* This indicates the end of the flags and thus enables the following (URL) argument to start with -. */ stillflags = false; } else if (arg.startsWith("--")) { const lookup = arg.slice(2); const longArg = longOpts[lookup]; if (longArg === null) { throw new CCError("option " + arg + ": is ambiguous"); } if (typeof longArg === "undefined") { // TODO: extract a list of deleted arguments to check here throw new CCError("option " + arg + ": is unknown"); } if (longArg.type === "string") { if (i + 1 < args.length) { i++; pushArgValue(parsedArguments, longArg.name, args[i]); } else { throw new CCError("option " + arg + ": requires parameter"); } } else { parsedArguments[longArg.name] = toBoolean(arg.slice(2)); // TODO: all shortened args work correctly? } if (supportedOpts) { checkLongOpt(lookup, longArg.name, supportedOpts, warnings); } } else { // Short option. These can look like // -X POST -> {request: 'POST'} // or // -XPOST -> {request: 'POST'} // or multiple options // -ABCX POST // -> {A: true, B: true, C: true, request: 'POST'} // or multiple options and a value for the last one // -ABCXPOST // -> {A: true, B: true, C: true, request: 'POST'} // "-" passed to curl as an argument raises an error, // curlconverter's command line uses it to read from stdin if (arg.length === 1) { if (has(shortOpts, "")) { arg = ["-", ""]; argRepr = "-"; } else { throw new CCError("option " + argRepr + ": is unknown"); } } for (let j = 1; j < arg.length; j++) { if (!has(shortOpts, arg[j])) { if (has(changedShortOpts, arg[j])) { throw new CCError( "option " + argRepr + ": " + changedShortOpts[arg[j]] ); } // TODO: there are a few deleted short options we could report throw new CCError("option " + argRepr + ": is unknown"); } const lookup = arg[j]; const shortFor = shortOpts[lookup]; const longArg = longOpts[shortFor]; if (longArg === null) { // This could happen if curlShortOpts points to a renamed option or has a typo throw new CCError("ambiguous short option -" + arg[j]); } if (longArg.type === "string") { let val; if (j + 1 < arg.length) { // treat -XPOST as -X POST val = arg.slice(j + 1); j = arg.length; } else if (i + 1 < args.length) { i++; val = args[i]; } else { throw new CCError("option " + argRepr + ": requires parameter"); } pushArgValue(parsedArguments, longArg.name, val as string); } else { // Use shortFor because -N is short for --no-buffer // and we want to end up with {buffer: false} parsedArguments[longArg.name] = toBoolean(shortFor); } if (supportedOpts && lookup) { checkShortOpt(lookup, longArg.name, supportedOpts, warnings); } } } } else { pushArgValue(parsedArguments, "url", arg); } } for (const [arg, values] of Object.entries(parsedArguments)) { if (Array.isArray(values) && !canBeList.has(arg)) { parsedArguments[arg] = values[values.length - 1]; } } return parsedArguments; }; export function parseQueryString( s: string | null ): [Query | null, QueryDict | null] { // if url is 'example.com?' => s is '' // if url is 'example.com' => s is null if (!s) { return [null, null]; } const asList: Query = []; for (const param of s.split("&")) { const [key, _val] = param.split(/=(.*)/s, 2); const val = _val === undefined ? null : _val; let decodedKey; let decodedVal; try { // https://url.spec.whatwg.org/#urlencoded-parsing recommends replacing + with space // before decoding. decodedKey = decodeURIComponent(key.replace(/\+/g, " ")); decodedVal = val === null ? null : decodeURIComponent(val.replace(/\+/g, " ")); } catch (e) { if (e instanceof URIError) { // Query string contains invalid percent encoded characters, // we cannot properly convert it. return [null, null]; } throw e; } try { // If the query string doesn't round-trip, we cannot properly convert it. // TODO: this is too strict. Ideally we want to check how each runtime/library // percent encodes query strings. For example, a %27 character in the input query // string will be decoded to a ' but won't be re-encoded into a %27 by encodeURIComponent const percentEncodeChar = (c: string): string => "%" + c.charCodeAt(0).toString(16).padStart(2, "0").toUpperCase(); // Match Python's urllib.parse.quote() behavior // https://stackoverflow.com/questions/946170/equivalent-javascript-functions-for-pythons-urllib-parse-quote-and-urllib-par const percentEncode = (s: string): string => encodeURIComponent(s).replace(/[()*!']/g, percentEncodeChar); // .replace('%20', '+') const roundTripKey = percentEncode(decodedKey); const roundTripVal = decodedVal === null ? null : percentEncode(decodedVal); // If the original data used %20 instead of + (what requests will send), that's close enough if ( (roundTripKey !== key && roundTripKey.replace(/%20/g, "+") !== key) || (roundTripVal !== null && roundTripVal !== val && roundTripVal.replace(/%20/g, "+") !== val) ) { return [null, null]; } } catch (e) { if (e instanceof URIError) { return [null, null]; } throw e; } asList.push([decodedKey, decodedVal]); } // Group keys const asDict: QueryDict = {}; let prevKey = null; for (const [key, val] of asList) { if (prevKey === key) { (asDict[key] as Array<string | null>).push(val); } else { if (!has(asDict, key)) { (asDict[key] as Array<string | null>) = [val]; } else { // If there's a repeated key with a different key between // one of its repetitions, there is no way to represent // this query string as a dictionary. return [asList, null]; } } prevKey = key; } // Convert lists with 1 element to the element for (const [key, val] of Object.entries(asDict)) { if ((val as Array<string | null>).length === 1) { asDict[key] = (val as Array<string | null>)[0]; } } return [asList, asDict]; } function buildRequest( parsedArguments: ParsedArguments, warnings: Warnings = [] ): Request { // TODO: handle multiple URLs if (!parsedArguments.url || !parsedArguments.url.length) { // TODO: better error message (could be parsing fail) throw new CCError("no URL specified!"); } let url = parsedArguments.url[parsedArguments.url.length - 1]; const headers: Headers = []; if (parsedArguments.header) { for (const header of parsedArguments.header) { if (header.includes(":")) { const [name, value] = header.split(/:(.*)/s, 2); if (!value.trim()) { headers.push([name, null]); } else { headers.push([name, value.replace(/^ /, "")]); } } else if (header.includes(";")) { const [name] = header.split(/;(.*)/s, 2); headers.push([name, ""]); } } } const lowercase = headers.length > 0 && headers.every((h) => h[0] === h[0].toLowerCase()); let cookies; const cookieFiles: string[] = []; const cookieHeaders = headers.filter((h) => h[0].toLowerCase() === "cookie"); if (cookieHeaders.length === 1 && cookieHeaders[0][1] !== null) { const parsedCookies = parseCookiesStrict(cookieHeaders[0][1]); if (parsedCookies) { cookies = parsedCookies; } } else if (cookieHeaders.length === 0 && parsedArguments.cookie) { // If there is a Cookie header, --cookies is ignored const cookieStrings: string[] = []; for (const c of parsedArguments.cookie) { // a --cookie without a = character reads from it as a filename if (c.includes("=")) { cookieStrings.push(c); } else { cookieFiles.push(c); } } if (cookieStrings.length) { const cookieString = parsedArguments.cookie.join(";"); _setHeaderIfMissing(headers, "Cookie", cookieString, lowercase); cookies = parseCookies(cookieString); } } if (parsedArguments["user-agent"]) { _setHeaderIfMissing( headers, "User-Agent", parsedArguments["user-agent"], lowercase ); } if (parsedArguments.referer) { // referer can be ";auto" or followed by ";auto", we ignore that. const referer = parsedArguments.referer.replace(/;auto$/, ""); if (referer) { _setHeaderIfMissing(headers, "Referer", referer, lowercase); } } // curl expects you to uppercase methods always. If you do -X PoSt, that's what it // will send, but most APIs will helpfully uppercase what you pass in as the method. // TODO: read curl's source to figure out precedence rules. let method = "GET"; if (parsedArguments.head) { method = "HEAD"; } else if ( has(parsedArguments, "request") && parsedArguments.request !== "null" ) { // Safari adds `-Xnull` if it can't determine the request type method = parsedArguments.request as string; } else if (parsedArguments["upload-file"]) { // --upload-file '' doesn't do anything. method = "PUT"; } else if ( (has(parsedArguments, "data") || has(parsedArguments, "data-ascii") || has(parsedArguments, "data-binary") || has(parsedArguments, "data-raw") || has(parsedArguments, "form") || has(parsedArguments, "json")) && !parsedArguments.get ) { method = "POST"; } // curl automatically prepends 'http' if the scheme is missing, // but many libraries fail if your URL doesn't have it, // we tack it on here to mimic curl // // RFC 3986 3.1 says // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) // but curl will accept a digit/plus/minus/dot in the first character // curl will also accept a url with one / like http:/localhost const schemeMatch = url.match(/^([a-zA-Z0-9+-.]*):\/\/?/); if (schemeMatch) { const scheme = schemeMatch[1].toLowerCase(); if (scheme !== "http" && scheme !== "https") { warnings.push(["bad-scheme", `Protocol "${scheme}" not supported`]); } url = scheme + "://" + url.slice(schemeMatch[0].length); } else { // curl's default scheme is actually https:// // but we don't do that because, unlike curl, most libraries won't downgrade to http if you ask for https url = "http://" + url; } let urlObject = URL.parse(url); // eslint-disable-line if (parsedArguments["upload-file"]) { // TODO: it's more complicated if ((!urlObject.path || urlObject.path === "/") && !urlObject.hash) { url += "/" + parsedArguments["upload-file"]; } else if (url.endsWith("/")) { url += parsedArguments["upload-file"]; } urlObject = URL.parse(url); // eslint-disable-line } // if GET request with data, convert data to query string // NB: the -G flag does not change the http verb. It just moves the data into the url. // TODO: this probably has a lot of mismatches with curl if (parsedArguments.get) { urlObject.query = urlObject.query ? urlObject.query : ""; if (has(parsedArguments, "data") && parsedArguments.data !== undefined) { let urlQueryString = ""; if (url.indexOf("?") < 0) { url += "?"; } else { urlQueryString += "&"; } urlQueryString += parsedArguments.data.join("&"); urlObject.query += urlQueryString; // TODO: url and urlObject will be different if url has an #id url += urlQueryString; delete parsedArguments.data; } } if (urlObject.query && urlObject.query.endsWith("&")) { urlObject.query = urlObject.query.slice(0, -1); } const [queryAsList, queryAsDict] = parseQueryString(urlObject.query); const useParsedQuery = queryAsList && queryAsList.length && queryAsList.every((p) => p[1] !== null); // Most software libraries don't let you distinguish between a=&b= and a&b, // so if we get an `a&b`-type query string, don't bother. let urlWithoutQuery; if (useParsedQuery) { urlObject.search = null; // Clean out the search/query portion. urlWithoutQuery = URL.format(urlObject); } else { urlWithoutQuery = url; // TODO: rename? } const request: Request = { url, method, urlWithoutQuery }; if (useParsedQuery) { request.query = queryAsList; if (queryAsDict) { request.queryDict = queryAsDict; } } if (cookies) { // generators that use .cookies need to do // deleteHeader(request, 'cookie') request.cookies = cookies; } // TODO: most generators support passing cookies with --cookie but don't // support reading cookies from a file. We need to somehow warn users // when that is the case. if (cookieFiles.length) { request.cookieFiles = cookieFiles; } if (parsedArguments["cookie-jar"]) { request.cookieJar = parsedArguments["cookie-jar"]; } if (parsedArguments.compressed) { request.compressed = true; } if (parsedArguments["upload-file"]) { request.uploadFile = parsedArguments["upload-file"]; } // TODO: all of these could be specified in the same command. // They also need to maintain order. // TODO: do all of these allow @file? let data; if (parsedArguments.data) { data = parsedArguments.data; _setHeaderIfMissing( headers, "Content-Type", "application/x-www-form-urlencoded", lowercase ); } else if (parsedArguments["data-binary"]) { data = parsedArguments["data-binary"]; request.isDataBinary = true; _setHeaderIfMissing( headers, "Content-Type", "application/x-www-form-urlencoded", lowercase ); } else if (parsedArguments["data-ascii"]) { data = parsedArguments["data-ascii"]; _setHeaderIfMissing( headers, "Content-Type", "application/x-www-form-urlencoded", lowercase ); } else if (parsedArguments["data-raw"]) { data = parsedArguments["data-raw"]; request.isDataRaw = true; _setHeaderIfMissing( headers, "Content-Type", "application/x-www-form-urlencoded", lowercase ); } else if (parsedArguments["data-urlencode"]) { // TODO: this doesn't exactly match curl // all '&' and all but the first '=' need to be escaped data = parsedArguments["data-urlencode"]; _setHeaderIfMissing( headers, "Content-Type", "application/x-www-form-urlencoded", lowercase ); } else if (parsedArguments.json) { data = parsedArguments.json; _setHeaderIfMissing(headers, "Content-Type", "application/json", lowercase); _setHeaderIfMissing(headers, "Accept", "application/json", lowercase); } else if (parsedArguments.form) { request.multipartUploads = []; for (const multipartArgument of parsedArguments.form) { // TODO: https://curl.se/docs/manpage.html#-F // -F is the most complicated option, we only handle // name=value and name=@file and name=<file const [name, value] = multipartArgument.value.split(/=(.*)/s, 2); const isString = multipartArgument.type === "string"; if (!isString && value.charAt(0) === "@") { const contentFile = value.slice(1); const filename = contentFile; request.multipartUploads.push({ name, contentFile, filename }); } else if (!isString && value.charAt(0) === "<") { const contentFile = value.slice(1); request.multipartUploads.push({ name, contentFile }); } else { const content = value; request.multipartUploads.push({ name, content }); } } } if (headers.length > 0) { for (let i = headers.length - 1; i >= 0; i--) { if (headers[i][1] === null) { // TODO: ideally we should generate code that explicitly unsets the header too headers.splice(i, 1); } } request.headers = headers; } if (parsedArguments.user) { const [user, pass] = parsedArguments.user.split(/:(.*)/s, 2); request.auth = [user, pass || ""]; } if (parsedArguments.digest) { request.digest = parsedArguments.digest; } if (data) { if (data.length > 1) { request.dataArray = data; request.data = data.join(parsedArguments.json ? "" : "&"); } else { request.data = data[0]; } } if (parsedArguments.insecure) { request.insecure = true; } // TODO: if the URL doesn't start with https://, curl doesn't verify // certificates, etc. if (parsedArguments.cert) { // --key has no effect if --cert isn't passed request.cert = parsedArguments.key ? [parsedArguments.cert, parsedArguments.key] : parsedArguments.cert; } if (parsedArguments.cacert) { request.cacert = parsedArguments.cacert; } if (parsedArguments.capath) { request.capath = parsedArguments.capath; } if (parsedArguments.proxy) { // https://github.com/curl/curl/blob/e498a9b1fe5964a18eb2a3a99dc52160d2768261/lib/url.c#L2388-L2390 request.proxy = parsedArguments.proxy; if (parsedArguments["proxy-user"]) { request.proxyAuth = parsedArguments["proxy-user"]; } } if (parsedArguments["max-time"]) { request.timeout = parsedArguments["max-time"]; } if (parsedArguments.location) { request.followRedirects = true; } if (parsedArguments.output) { request.output = parsedArguments.output; } if (parsedArguments.http2) { request.http2 = parsedArguments.http2; } if (parsedArguments.http3) { request.http3 = parsedArguments.http3; } return request; } function parseCurlCommand( curlCommand: string | string[], supportedArgs?: Set<string>, warnings: Warnings = [] ): Request { let cmdName: string, args: string[], stdin: undefined | string, input: undefined | string; if (Array.isArray(curlCommand)) { [cmdName, ...args] = curlCommand; if (typeof cmdName === "undefined") { throw new CCError("no arguments provided"); } } else { ({ cmdName, args, stdin, input } = tokenize(curlCommand, warnings)); if (typeof cmdName === "undefined") { throw new CCError("failed to parse input"); } } if (cmdName.trim() !== "curl") { const shortenedCmdName = cmdName.length > 30 ? cmdName.slice(0, 27) + "..." : cmdName; if (cmdName.startsWith("curl ")) { throw new CCError( 'command should begin with a single token "curl" but instead begins with ' + JSON.stringify(shortenedCmdName) ); } else { throw new CCError( 'command should begin with "curl" but instead begins with ' + JSON.stringify(shortenedCmdName) ); } } const parsedArguments = parseArgs( args, curlLongOpts, curlShortOpts, supportedArgs, warnings ); const request = buildRequest(parsedArguments, warnings); if (stdin) { request.stdin = stdin; } if (input) { request.input = input; } return request; } // Gets the first header, matching case-insensitively const getHeader = ( request: Request, header: string ): string | null | undefined => { if (!request.headers) { return undefined; } const lookup = header.toLowerCase(); for (const [h, v] of request.headers) { if (h.toLowerCase() === lookup) { return v; } } return undefined; }; const getContentType = (request: Request): string | null | undefined => { if (!request.headers) { return undefined; } const contentTypeHeader = getHeader(request, "content-type"); if (!contentTypeHeader) { return contentTypeHeader; } return contentTypeHeader.split(";")[0].trim(); }; const _hasHeader = (headers: Headers, header: string): boolean => { const lookup = header.toLowerCase(); for (const h of headers) { if (h[0].toLowerCase() === lookup) { return true; } } return false; }; const hasHeader = (request: Request, header: string): boolean | undefined => { if (!request.headers) { return; } return _hasHeader(request.headers, header); }; const _setHeaderIfMissing = ( headers: Headers, header: string, value: string, lowercase: boolean | number = false ): boolean => { if (_hasHeader(headers, header)) { return false; } headers.push([lowercase ? header.toLowerCase() : header, value]); return true; }; const setHeaderIfMissing = ( request: Request, header: string, value: string, lowercase: boolean | number = false ) => { if (!request.headers) { return; } return _setHeaderIfMissing(request.headers, header, value, lowercase); }; const _deleteHeader = (headers: Headers, header: string) => { const lookup = header.toLowerCase(); for (let i = headers.length - 1; i >= 0; i--) { if (headers[i][0].toLowerCase() === lookup) { headers.splice(i, 1); } } }; const deleteHeader = (request: Request, header: string) => { if (!request.headers) { return; } return _deleteHeader(request.headers, header); }; const countHeader = (request: Request, header: string) => { let count = 0; const lookup = header.toLowerCase(); for (const h of request.headers || []) { if (h[0].toLowerCase() === lookup) { count += 1; } } return count; }; const parseCookiesStrict = (cookieString: string): Cookies | null => { const cookies: Cookies = []; for (let cookie of cookieString.split(";")) { cookie = cookie.replace(/^ /, ""); const [name, value] = cookie.split(/=(.*)/s, 2); if (value === undefined) { return null; } cookies.push([name, value]); } return cookies; }; const parseCookies = (cookieString: string): Cookies => { const cookies: Cookies = []; for (let cookie of cookieString.split(";")) { cookie = cookie.trim(); if (!cookie) { continue; } const [name, value] = cookie.split(/=(.*)/s, 2); cookies.push([name, value || ""]); } return cookies; }; export { curlLongOpts, curlShortOpts, parseCurlCommand, parseArgs, buildRequest, getHeader, getContentType, hasHeader, countHeader, setHeaderIfMissing, deleteHeader, has, }; export type { LongOpts, ShortOpts, Request, Cookie, Cookies, Query, QueryDict, Warnings, };
the_stack
import { assert } from 'chai'; import { Component, Fragment, VNode } from 'preact'; import * as preact from 'preact'; import { NodeType, RSTNode } from 'enzyme'; import { getNode, rstNodeFromElement } from '../src/preact10-rst'; import { getType } from '../src/util'; import { render } from '../src/compat'; function Child({ label }: any) { return <div>{label}</div>; } function Parent({ label }: any) { return <Child label={label} />; } function Section({ children }: any) { return <section>{...children}</section>; } class ClassComponent extends Component<{ label: string }> { render() { return <span>{this.props.label}</span>; } } function FunctionComponent({ label }: any) { return <div>{label}</div>; } const ArrowFunctionComponent = ({ label }: any) => <div>{label}</div>; function NumberComponent({ value }: { value: number }) { return <div>{value}</div>; } function EmptyComponent() { return null; } function functionNode({ type, rendered, props = {}, key = null, ref = null, }: any) { return { nodeType: 'function' as NodeType, type, rendered: rendered || [], props, key, ref, instance: type.name, }; } function classNode({ type, rendered = [], props = {}, key = null, ref = null, }: any) { return { nodeType: 'class' as NodeType, type, rendered, props, key, ref, instance: type.name, }; } function getConstructorName(name: string) { const el = document.createElement(name); return el.constructor.name; } function hostNode({ type, rendered = [], props = {}, key = null, ref = null, }: any) { return { nodeType: 'host' as NodeType, type, rendered, props, key, ref, instance: getConstructorName(type), }; } function filterNode(node: RSTNode | null) { if (!node) { return node; } // Ignore `children` prop during comparisons. const props = { ...node.props }; delete props.children; node.props = props; // Convert instance from an object reference to a string indicating the // object type, which is easier to test against. if (node.instance._constructor) { node.instance = node.instance._constructor.name; } else { node.instance = getType(node.instance); } // Process rendered output. node.rendered.forEach(node => { if (node && typeof node !== 'string' && node.nodeType) { filterNode(node); } }); return node; } const testRef = () => {}; const treeCases = [ { description: 'simple DOM element', element: <div>Hello</div>, expectedTree: hostNode({ type: 'div', rendered: ['Hello'] }), }, { description: 'DOM element with children', element: ( <div> <span /> <br /> </div> ), expectedTree: hostNode({ type: 'div', rendered: [hostNode({ type: 'span' }), hostNode({ type: 'br' })], }), }, { description: 'DOM element with props', element: <img alt="Image label" />, expectedTree: hostNode({ type: 'img', rendered: [], props: { alt: 'Image label' }, }), }, { description: 'function component', element: <FunctionComponent label="Hello" />, expectedTree: functionNode({ type: FunctionComponent, rendered: [hostNode({ type: 'div', rendered: ['Hello'] })], props: { label: 'Hello' }, }), }, { description: 'function component (arrow function)', element: <ArrowFunctionComponent label="Hello" />, expectedTree: functionNode({ type: ArrowFunctionComponent, rendered: [hostNode({ type: 'div', rendered: ['Hello'] })], props: { label: 'Hello' }, }), }, { description: 'numeric child (nonzero number)', element: <NumberComponent value={42} />, expectedTree: functionNode({ type: NumberComponent, rendered: [hostNode({ type: 'div', rendered: ['42'] })], props: { value: 42 }, }), }, { description: 'numeric child (zero number)', element: <NumberComponent value={0} />, expectedTree: functionNode({ type: NumberComponent, rendered: [hostNode({ type: 'div', rendered: ['0'] })], props: { value: 0 }, }), }, { description: 'class component', element: <ClassComponent label="Hello" />, expectedTree: classNode({ type: ClassComponent, rendered: [hostNode({ type: 'span', rendered: ['Hello'] })], props: { label: 'Hello' }, }), }, { description: 'component that renders another component', element: <Parent label="Hello" />, expectedTree: functionNode({ type: Parent, rendered: [ functionNode({ type: Child, rendered: [hostNode({ type: 'div', rendered: ['Hello'] })], props: { label: 'Hello' }, }), ], props: { label: 'Hello' }, }), }, { description: 'component that renders children', element: ( <Section> <p>Section content</p> </Section> ), expectedTree: functionNode({ type: Section, rendered: [ hostNode({ type: 'section', rendered: [hostNode({ type: 'p', rendered: ['Section content'] })], }), ], props: {}, }), }, { description: 'component that has a key', element: <Child label="test" key="a-key" />, expectedTree: functionNode({ type: Child, key: 'a-key', props: { label: 'test' }, rendered: [hostNode({ type: 'div', rendered: ['test'] })], }), }, { description: 'DOM element that has a key', element: <div key="a-key" />, expectedTree: hostNode({ type: 'div', key: 'a-key', }), }, { description: 'component that has a ref', element: <ClassComponent label="test" ref={testRef} />, expectedTree: classNode({ type: ClassComponent, ref: testRef, rendered: [hostNode({ type: 'span', rendered: ['test'] })], props: { label: 'test' }, }), }, { description: 'DOM element that has a ref', element: <div ref={testRef} />, expectedTree: hostNode({ type: 'div', ref: testRef, }), }, { description: 'component that renders `null`', element: <EmptyComponent />, expectedTree: functionNode({ type: EmptyComponent, rendered: [], }), }, ]; function renderToRST(el: VNode, container?: HTMLElement): RSTNode | null { if (!container) { container = document.createElement('div'); } render(el, container); const rootNode = getNode(container); return filterNode(rootNode); } describe('preact10-rst', () => { let container: HTMLElement; beforeEach(() => { container = document.createElement('div'); }); afterEach(() => { container.remove(); }); describe('getNode', () => { treeCases.forEach(({ description, element, expectedTree }) => { it(`returns expected RST node (${description})`, () => { assert.deepEqual(renderToRST(element), expectedTree); }); }); it('ignores fragments in result', () => { const el = ( <ul> <Fragment> <li>1</li> <li>2</li> </Fragment> <Fragment> <li>3</li> <li>4</li> </Fragment> </ul> ); const expectedTree = hostNode({ type: 'ul', rendered: [ hostNode({ type: 'li', rendered: ['1'] }), hostNode({ type: 'li', rendered: ['2'] }), hostNode({ type: 'li', rendered: ['3'] }), hostNode({ type: 'li', rendered: ['4'] }), ], }); assert.deepEqual(renderToRST(el), expectedTree); }); it('flattens nested fragments', () => { const el = ( <ul> <Fragment> <li>1</li> <Fragment> <li>2</li> <li>3</li> </Fragment> <li>4</li> </Fragment> </ul> ); const expectedTree = hostNode({ type: 'ul', rendered: [ hostNode({ type: 'li', rendered: ['1'] }), hostNode({ type: 'li', rendered: ['2'] }), hostNode({ type: 'li', rendered: ['3'] }), hostNode({ type: 'li', rendered: ['4'] }), ], }); assert.deepEqual(renderToRST(el), expectedTree); }); it('supports components that return fragments', () => { function ListItems({ items }: { items: number[] }) { return ( <Fragment> {items.map(item => ( <li>{item}</li> ))} </Fragment> ); } const el = ( <ul> <ListItems items={[1, 2]} /> <ListItems items={[3, 4]} /> </ul> ); const expectedTree = hostNode({ type: 'ul', rendered: [ functionNode({ type: ListItems, props: { items: [1, 2] }, rendered: [ hostNode({ type: 'li', rendered: ['1'] }), hostNode({ type: 'li', rendered: ['2'] }), ], }), functionNode({ type: ListItems, props: { items: [3, 4] }, rendered: [ hostNode({ type: 'li', rendered: ['3'] }), hostNode({ type: 'li', rendered: ['4'] }), ], }), ], }); assert.deepEqual(renderToRST(el), expectedTree); }); it('throws an error if the root node renders multiple children', () => { const el = ( <Fragment> <li>1</li> <li>2</li> </Fragment> ); assert.throws(() => { renderToRST(el); }, 'Root element must not be a fragment with multiple children'); }); it('converts components with text children to RST nodes', () => { function TestComponent() { return 'some text' as any; } const rstNode = renderToRST(<TestComponent />, container)!; assert.deepEqual(rstNode.rendered, ['some text']); }); it('converts Preact prop names to RST prop names', () => { function TestComponent() { return <div class="widget" />; } const rstNode = filterNode(renderToRST(<TestComponent />, container))!; assert.equal(rstNode.rendered.length, 1); assert.deepEqual((rstNode.rendered[0] as RSTNode).props, { className: 'widget', }); }); }); describe('rstNodeFromElement', () => { function stripInstances(node: RSTNode | string | null) { if (node == null || typeof node === 'string') { return node; } node.instance = null; node.rendered.forEach(child => { stripInstances(child); }); return node; } [ { description: 'function component', element: <FunctionComponent />, expectedNode: functionNode({ type: FunctionComponent, }), }, { description: 'class component', element: <ClassComponent label="test" />, expectedNode: classNode({ type: ClassComponent, props: { label: 'test' }, }), }, { description: 'host node', element: <div />, expectedNode: hostNode({ type: 'div' }), }, { description: 'host node with props', element: <img alt="test" class="foo" />, expectedNode: hostNode({ type: 'img', props: { alt: 'test', className: 'foo' }, }), }, { description: 'component with props', element: <FunctionComponent class="foo" />, expectedNode: functionNode({ type: FunctionComponent, props: { class: 'foo' }, }), }, { description: 'element with key', element: <li key="foo" />, expectedNode: hostNode({ type: 'li', key: 'foo' }), }, { description: 'element with ref', element: <li ref={testRef} />, expectedNode: hostNode({ type: 'li', ref: testRef }), }, { description: 'element with children', element: ( <ul> <li>item</li> </ul> ), expectedNode: hostNode({ type: 'ul', rendered: [hostNode({ type: 'li', rendered: ['item'] })], }), }, ].forEach(({ description, element, expectedNode }) => { it(`converts node to element (${description})`, () => { const rstNode = rstNodeFromElement(element); assert.deepEqual(rstNode, stripInstances(expectedNode)); }); }); }); });
the_stack
import { DdRumErrorTracking } from '../../../rum/instrumentation/DdRumErrorTracking' import { DdRum } from '../../../index'; jest.useFakeTimers() jest.mock('../../../foundation', () => { return { DdRum: { // eslint-disable-next-line @typescript-eslint/no-empty-function addError: jest.fn().mockImplementation(() => { return Promise.resolve(); }) }, }; }); let baseErrorHandlerCalled = false; let baseErrorHandler = (error: any, isFatal?: boolean) => { baseErrorHandlerCalled = true }; let originalErrorHandler = undefined; let baseConsoleErrorCalled = false; let baseConsoleError = (...params: unknown) => { baseConsoleErrorCalled = true } let originalConsoleError = undefined const flushPromises = () => new Promise(setImmediate); beforeEach(() => { DdRum.addError.mockClear(); baseErrorHandlerCalled = false; originalErrorHandler = ErrorUtils.getGlobalHandler(); ErrorUtils.setGlobalHandler(baseErrorHandler); originalConsoleError = console.error; console.error = baseConsoleError; jest.setTimeout(20000) }) afterEach(() => { DdRumErrorTracking['isTracking'] = false ErrorUtils.setGlobalHandler(originalErrorHandler) console.error = originalConsoleError }) it('M intercept and send a RUM event W onGlobalError() {no message}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { stack: ["doSomething() at ./path/to/file.js:67:3"] }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe(String(error)); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {empty stack trace}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe(""); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {Error object}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = new Error('Something bad happened'); // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toContain("Error: Something bad happened"); expect(DdRum.addError.mock.calls[0][2]).toContain("/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {with source file info}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { sourceURL: "./path/to/file.js", line: 1038, column: 57, message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("at ./path/to/file.js:1038:57"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {with component stack}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { componentStack: ["doSomething() at ./path/to/file.js:67:3", "nestedCall() at ./path/to/file.js:1064:9", "root() at ./path/to/index.js:10:1"], message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3,nestedCall() at ./path/to/file.js:1064:9,root() at ./path/to/index.js:10:1"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {with stack}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { stack: ["doSomething() at ./path/to/file.js:67:3", "nestedCall() at ./path/to/file.js:1064:9", "root() at ./path/to/index.js:10:1"], message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3,nestedCall() at ./path/to/file.js:1064:9,root() at ./path/to/index.js:10:1"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onGlobalError() {with stacktrace}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { stacktrace: ["doSomething() at ./path/to/file.js:67:3", "nestedCall() at ./path/to/file.js:1064:9", "root() at ./path/to/index.js:10:1"], message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3,nestedCall() at ./path/to/file.js:1064:9,root() at ./path/to/index.js:10:1"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(baseErrorHandlerCalled).toStrictEqual(true); }) it('M not report error in console handler W onGlobalError() {with console reporting handler}', async () => { // GIVEN const consoleReportingErrorHandler = jest.fn((error, isFatal)=> { console.error(error.message); baseErrorHandler(error, isFatal); }); ErrorUtils.setGlobalHandler(consoleReportingErrorHandler); DdRumErrorTracking.startTracking(); const is_fatal = Math.random() < 0.5; const error = { componentStack: ["doSomething() at ./path/to/file.js:67:3", "nestedCall() at ./path/to/file.js:1064:9", "root() at ./path/to/index.js:10:1"], message: "Something bad happened" }; // WHEN DdRumErrorTracking.onGlobalError(error, is_fatal); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("SOURCE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3,nestedCall() at ./path/to/file.js:1064:9,root() at ./path/to/index.js:10:1"); const attributes = DdRum.addError.mock.calls[0][3]; expect(attributes["_dd.error.raw"]).toStrictEqual(error); expect(attributes["_dd.error.is_crash"]).toStrictEqual(is_fatal); expect(consoleReportingErrorHandler).toBeCalledTimes(1); expect(baseConsoleErrorCalled).toStrictEqual(false); }) it('M intercept and send a RUM event W onConsole() {Error with source file info}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const message= "Oops I did it again!"; const error = { sourceURL: "./path/to/file.js", line: 1038, column: 57, message: "Something bad happened" }; // WHEN DdRumErrorTracking.onConsoleError(message, error); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Oops I did it again! Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("CONSOLE"); expect(DdRum.addError.mock.calls[0][2]).toBe("at ./path/to/file.js:1038:57"); expect(DdRum.addError.mock.calls[0][3]).toBeUndefined() expect(baseConsoleErrorCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onConsole() {Error with component stack}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const message= "Oops I did it again!"; const error = { componentStack: ["doSomething() at ./path/to/file.js:67:3", "nestedCall() at ./path/to/file.js:1064:9", "root() at ./path/to/index.js:10:1"], message: "Something bad happened" }; // WHEN DdRumErrorTracking.onConsoleError(message, error); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe("Oops I did it again! Something bad happened"); expect(DdRum.addError.mock.calls[0][1]).toBe("CONSOLE"); expect(DdRum.addError.mock.calls[0][2]).toBe("doSomething() at ./path/to/file.js:67:3,nestedCall() at ./path/to/file.js:1064:9,root() at ./path/to/index.js:10:1"); expect(DdRum.addError.mock.calls[0][3]).toBeUndefined() expect(baseConsoleErrorCalled).toStrictEqual(true); }) it('M intercept and send a RUM event W onConsole() {message only}', async () => { // GIVEN DdRumErrorTracking.startTracking(); const message= "Something bad happened"; // WHEN DdRumErrorTracking.onConsoleError(message); await flushPromises(); // THEN expect(DdRum.addError.mock.calls.length).toBe(1); expect(DdRum.addError.mock.calls[0][0]).toBe(message); expect(DdRum.addError.mock.calls[0][1]).toBe("CONSOLE"); expect(DdRum.addError.mock.calls[0][2]).toBe(""); expect(DdRum.addError.mock.calls[0][3]).toBeUndefined() expect(baseConsoleErrorCalled).toStrictEqual(true); })
the_stack
import utils = require("../common/utils"); import styles = require("./styles/styles"); import React = require("react"); import ReactDOMServer = require("react-dom/server"); import * as csx from './base/csx'; import {BaseComponent} from "./ui"; import * as ui from "./ui"; import {cast,server} from "../socket/socketClient"; import * as commands from "./commands/commands"; import * as types from "../common/types"; import {AvailableProjectConfig} from "../common/types"; import {Clipboard} from "./components/clipboard"; import {PendingRequestsIndicator} from "./pendingRequestsIndicator"; import {Icon} from "./components/icon"; import {tabState,tabStateChanged} from "./tabs/v2/appTabsContainer"; import {Progress} from "./components/progress"; import {connect} from "react-redux"; import {StoreState,expandErrors,collapseErrors} from "./state/state"; import * as state from "./state/state"; import {errorsCache} from "./globalErrorCacheClient"; import {testResultsCache} from "./clientTestResultsCache"; let notificationKeyboardStyle = { border: '2px solid', borderRadius: '6px', display: 'inline-block', padding: '5px', background: 'grey', } const ouputStatusStyle = csx.extend(styles.noSelect, {fontSize:'.6rem'}); const activeProjectContainerStyle = csx.extend( styles.statusBarSection, styles.hand, styles.noSelect, { border: '1px solid grey', paddingTop: '2px', paddingBottom: '2px', paddingLeft: '4px', paddingRight: '4px', fontSize: '.7rem', marginTop: '1px', } ); export interface Props { // from react-redux ... connected below errorsExpanded?: boolean; activeProject?: AvailableProjectConfig; activeProjectFiles?: { [filePath: string]: boolean }; socketConnected?: boolean; outputStatusCache?: types.JSOutputStatusCache; liveBuildResults?: types.LiveBuildResults; fileTreeShown?: boolean; errorsDisplayMode?: types.ErrorsDisplayMode; errorsFilter?: string; tsWorking?: types.Working; testedWorking?: types.Working; } export interface State { } const projectTipKeboard = ReactDOMServer.renderToString(<div style={notificationKeyboardStyle}>Alt+Shift+P</div>); /** * The singleton status bar */ export var statusBar: StatusBar; @connect((state: StoreState): Props => { return { errorsExpanded: state.errorsExpanded, activeProject: state.activeProject, activeProjectFiles: state.activeProjectFilePathTruthTable, socketConnected: state.socketConnected, outputStatusCache: state.outputStatusCache, liveBuildResults: state.liveBuildResults, fileTreeShown: state.fileTreeShown, errorsDisplayMode: state.errorsDisplayMode, errorsFilter: state.errorsFilter, tsWorking: state.tsWorking, testedWorking: state.testedWorking, }; }) export class StatusBar extends BaseComponent<Props, State>{ constructor(props:Props){ super(props); this.state = { } } componentDidMount() { statusBar = this; tabStateChanged.on(()=>this.forceUpdate()); errorsCache.errorsDelta.on(() => this.forceUpdate()); testResultsCache.testResultsDelta.on(() => this.forceUpdate()); } render() { let tab = tabState.getSelectedTab(); let filePath = tab && utils.getFilePathFromUrl(tab.url); let protocol = tab && utils.getFilePathAndProtocolFromUrl(tab.url).protocol; const activeProjectDetails = this.props.activeProject ?<span className="hint--top-right" data-hint="Active Project path. Click to open project file" style={activeProjectContainerStyle} onClick={()=>{ this.openFile(this.props.activeProject.tsconfigFilePath); ui.notifyInfoNormalDisappear(`TIP : You can change the active project using project search <br/> <br/> ${projectTipKeboard}`, { onClick: () => commands.omniSelectProject.emit({}) }); }}> <span style={csx.extend(styles.noSelect,styles.statusBarSuccess,styles.hand,{marginRight: '5px'})}> <Icon name="heartbeat"/> </span> {this.props.activeProject.isVirtual && <span style={csx.extend(styles.noSelect,styles.statusBarSuccess,styles.hand,{marginRight: '5px'})}> <Icon name="blind"/> </span>} {this.props.activeProject.name} </span> :<span className="hint--top-right" style={csx.extend(styles.statusBarSection, styles.noSelect,styles.statusBarError,styles.hand)} onClick={() => ui.notifyWarningNormalDisappear(`There is no active project. Please select from the available ones <br/> <br/> ${projectTipKeboard}`, { onClick: () => commands.omniSelectProject.emit({}) }) } data-hint="There is no active TypeScript project. Robots deactivated."> <Icon name="heartbeat"/> </span>; let inActiveProjectSection = !tab ? '' : <span style={styles.statusBarSection}> {state.inActiveProjectUrl(tab.url) ?<span className="hint--top-right hint--success" style={csx.extend(styles.noSelect,styles.statusBarSuccess, styles.hand)} onClick={()=>ui.notifySuccessNormalDisappear(`The file is a part of the currently active TypeScript project and we are actively providing code intelligence`)} data-hint="File is part of the currently active project. 💻 providing code intelligence."> <Icon name="eye"/> </span> :<span className="hint--top-right" style={csx.extend(styles.noSelect,styles.statusBarError,styles.hand)} onClick={() => ui.notifyWarningNormalDisappear(`The file is not a part of the currently active TypeScript project <br/> <br/> ${projectTipKeboard}`, { onClick: () => commands.omniSelectProject.emit({}) }) } data-hint="File is not a part of the currently active project. Robots deactivated."> <Icon name="eye-slash"/> </span>} </span>; const fileOutput = protocol !== 'file' ? null : !this.props.outputStatusCache[filePath] ? null : this.props.outputStatusCache[filePath] const fileOutputState = fileOutput && fileOutput.state; const openOutputJSFile = () => { commands.doToggleFileTab.emit({ filePath: fileOutput.outputFilePath }); } const fileOutputStateRendered = !!fileOutputState && <span style={styles.statusBarSection}> <span style={csx.extend(ouputStatusStyle)}> { fileOutputState === types.JSOutputState.NoJSFile ? null : fileOutputState === types.JSOutputState.JSOutOfDate ? <span style={csx.extend(styles.statusBarError,{transition: 'color .5s', cursor:'pointer'})} onClick={openOutputJSFile}>❌ JS Outdated</span> : <span style={csx.extend(styles.statusBarSuccess,{transition: 'color .5s', cursor:'pointer'})} onClick={openOutputJSFile}>✓ JS Current</span> } </span> </span>; const fileTreeToggleRendered = <span style={csx.extend(styles.statusBarSection, styles.noSelect, styles.hand)} onClick={this.toggleFileTree} className="hint--top-right" data-hint={`Click to toggle the file tree 🌲`}> <span style={csx.extend(this.props.fileTreeShown?{color:'white'}:{color:'grey'},{transition: 'color .4s'})}> <Icon name="tree"/> </span> </span>; const updateRendered = serverState.update && <span style={csx.extend(styles.statusBarSection) }> <span className="hint--left hint--error" data-hint={ `Update ${serverState.update.latest} available (current: ${serverState.update.current})` + ". Please run `npm i -g alm`"}> <Icon style={{ color: styles.errorColor, cursor: 'pointer' }} name="wrench" onClick={this.whatsNew}/> </span> </span>; const errorsUpdate = errorsCache.getErrorsLimited(); const errorFilteringActive = this.props.errorsDisplayMode !== types.ErrorsDisplayMode.all || this.props.errorsFilter.trim(); const errorsFilteredCount = tabState.errorsByFilePathFiltered().errorsFlattened.length; /** Tested */ const testResultsStats = testResultsCache.getStats(); const failing = !!testResultsStats.failCount; const totalThatRan = testResultsStats.passCount + testResultsStats.failCount; const testStatsRendered = !!testResultsStats.testCount && <span className="hint--top-right" data-hint={`Test Total: ${testResultsStats.testCount}, Pass: ${testResultsStats.passCount}, Fail: ${testResultsStats.failCount}, Skip: ${testResultsStats.skipCount}, Duration: ${utils.formatMilliseconds(testResultsStats.durationMs)}`} style={csx.extend(activeProjectContainerStyle)} onClick={()=>{ commands.doOpenTestResultsView.emit({}); }}> <span style={csx.extend( styles.noSelect, failing ? styles.statusBarError : styles.statusBarSuccess, styles.hand, { marginRight: '5px', transition: '.4s color, .4s opacity', opacity: this.props.testedWorking.working ? 1 : 0.5, } )}> <Icon name={styles.icons.tested} spin={this.props.testedWorking.working}/> </span> { failing ? <span style={{ color: styles.errorColor, fontWeight: 'bold'}}>{testResultsStats.failCount}/{totalThatRan} fail</span> : <span style={{ color: styles.successColor, fontWeight: 'bold'}}>{testResultsStats.passCount}/{totalThatRan} pass</span> } </span> return ( <div> <div style={csx.extend(styles.statusBar,csx.horizontal,csx.center, styles.noWrap)}> {/* Left sections */} <span style={csx.extend(styles.statusBarSection, styles.noSelect, styles.hand)} onClick={this.toggleErrors} className="hint--top-right" data-hint={`${errorsUpdate.totalCount} errors. Click to toggle message panel.`}> <span style={csx.extend(errorsUpdate.totalCount?styles.statusBarError:styles.statusBarSuccess,{transition: 'color .4s'})}> {errorsUpdate.totalCount} <Icon name="times-circle"/> {errorFilteringActive && ' '} {errorFilteringActive && <span>( {errorsFilteredCount} <Icon name="filter"/>)</span>} </span> </span> <span style={csx.extend(styles.statusBarSection, styles.noSelect, styles.hand) }> <span className={this.props.tsWorking.working ? "hint--right hint--success" : "hint--right"} data-hint={this.props.tsWorking.working ? "TS Worker Busy" : "TS Worker Idle"} style={{ color: this.props.tsWorking.working ? 'white' : 'grey', transition: 'color .4s' }}> <Icon name="rocket"/> </span> </span> {testStatsRendered} {fileTreeToggleRendered} {activeProjectDetails} {inActiveProjectSection} {filePath ?<span className="hint--top-right" data-hint="Click to copy the file path to clipboard" data-clipboard-text={filePath.replace(/\//g,commands.windows?'\\':'/')} onClick={()=>ui.notifyInfoQuickDisappear("File path copied to clipboard")} style={csx.extend(styles.statusBarSection,styles.noSelect,styles.hand)}> {filePath} </span> :''} {fileOutputStateRendered} {/* seperator */} <span style={csx.flex}></span> {/* Right sections */} <span style={csx.extend(styles.statusBarSection)}> <PendingRequestsIndicator /> </span> { this.props.liveBuildResults.builtCount !== this.props.liveBuildResults.totalCount && <span style={csx.extend(styles.statusBarSection)}> <Progress current={this.props.liveBuildResults.builtCount} total={this.props.liveBuildResults.totalCount}> {this.props.liveBuildResults.builtCount} / {this.props.liveBuildResults.totalCount} </Progress> </span> } <span style={csx.extend(styles.statusBarSection)}> {this.props.socketConnected? <span className="hint--left hint--success" data-hint="Connected to server"> <Icon style={{color:styles.successColor, cursor:'pointer'}} name="flash" onClick={()=>ui.notifySuccessNormalDisappear("Connected to alm server")}/></span> :<span className="hint--left hint--error" data-hint="Disconnected from server"> <Icon style={{color:styles.errorColor, cursor:'pointer'}} name="spinner" spin={true} onClick={()=>ui.notifyWarningNormalDisappear("Disconneted from alm server")}/></span>} </span> <span style={csx.extend(styles.statusBarSection, styles.noSelect, styles.hand)}> <span style={{paddingRight: '2px'} as any} onClick={this.giveStar} className="hint--left" data-hint={`If you like it then you should have put a star on it 🌟. Also, go here for support. Version: ${serverState.version}, TypeScript version: ${serverState.typescriptVersion}`}>🌟</span> <span onClick={this.giveRose} className="hint--left" data-hint="Your love keep this rose alive 🌹">🌹</span> </span> {updateRendered} </div> </div> ); } toggleErrors = () => { if (this.props.errorsExpanded){ collapseErrors({}); } else{ expandErrors({}); } } toggleFileTree = () => { if (this.props.fileTreeShown) { state.collapseFileTree({}); } else { state.expandFileTree({}); } } openErrorLocation = (error: types.CodeError) => { commands.doOpenOrFocusFile.emit({ filePath: error.filePath, position: error.from }); } openFile = (filePath: string) => { commands.doOpenOrFocusFile.emit({ filePath }); } giveStar = () => { window.open('https://github.com/alm-tools/alm') } giveRose = () => { window.open('https://twitter.com/basarat') } whatsNew = () => { /** We currently show the diff. Once we have semantic releases we will show release notes */ const update = serverState.update; window.open(`https://github.com/alm-tools/alm/compare/v${update.current}...v${update.latest}`); } }
the_stack
import 'mocha'; import sinon, { SinonSpy } from 'sinon'; import { assert } from 'chai'; import rewiremock from 'rewiremock'; import { Logger, LogLevel } from '@slack/logger'; import { EventEmitter } from 'events'; import { IncomingMessage, ServerResponse } from 'http'; import { InstallProvider } from '@slack/oauth'; import { SocketModeClient } from '@slack/socket-mode'; import { Override, mergeOverrides } from '../test-helpers'; import { CustomRouteInitializationError, AppInitializationError } from '../errors'; // Fakes class FakeServer extends EventEmitter { public on = sinon.fake(); public listen = sinon.fake(() => { if (this.listeningFailure !== undefined) { this.emit('error', this.listeningFailure); } }); public close = sinon.fake((...args: any[]) => { setImmediate(() => { this.emit('close'); setImmediate(() => { args[0](); }); }); }); public constructor(private listeningFailure?: Error) { super(); } } describe('SocketModeReceiver', function () { beforeEach(function () { this.listener = (_req: any, _res: any) => {}; this.fakeServer = new FakeServer(); // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; this.fakeCreateServer = sinon.fake(function (handler: (req: any, res: any) => void) { that.listener = handler; // pick up the socket listener method so we can assert on its behaviour return that.fakeServer as FakeServer; }); }); const noopLogger: Logger = { debug(..._msg: any[]): void { /* noop */ }, info(..._msg: any[]): void { /* noop */ }, warn(..._msg: any[]): void { /* noop */ }, error(..._msg: any[]): void { /* noop */ }, setLevel(_level: LogLevel): void { /* noop */ }, getLevel(): LogLevel { return LogLevel.DEBUG; }, setName(_name: string): void { /* noop */ }, }; describe('constructor', function () { // NOTE: it would be more informative to test known valid combinations of options, as well as invalid combinations it('should accept supported arguments and use default arguments when not provided', async function () { // Arrange const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes: ['channels:read'], installerOptions: { authVersion: 'v2', userScopes: ['chat:write'], }, }); assert.isNotNull(receiver); assert.isOk(this.fakeServer.listen.calledWith(3000)); }); it('should allow for customizing port the socket listens on', async function () { // Arrange const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const customPort = 1337; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes: ['channels:read'], installerOptions: { authVersion: 'v2', userScopes: ['chat:write'], port: customPort, }, }); assert.isNotNull(receiver); assert.isOk(this.fakeServer.listen.calledWith(customPort)); }); it('should throw an error if redirect uri options supplied invalid or incomplete', async function () { const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const clientId = 'my-clientId'; const clientSecret = 'my-clientSecret'; const stateSecret = 'my-stateSecret'; const scopes = ['chat:write']; const appToken = 'my-secret'; const redirectUri = 'http://example.com/heyo'; const installerOptions = { redirectUriPath: '/heyo', }; // correct format with full redirect options supplied const receiver = new SocketModeReceiver({ appToken, clientId, clientSecret, stateSecret, scopes, redirectUri, installerOptions, }); assert.isNotNull(receiver); // redirectUri supplied, but no redirectUriPath assert.throws(() => new SocketModeReceiver({ appToken, clientId, clientSecret, stateSecret, scopes, redirectUri, }), AppInitializationError); // inconsistent redirectUriPath assert.throws(() => new SocketModeReceiver({ appToken, clientId: 'my-clientId', clientSecret, stateSecret, scopes, redirectUri, installerOptions: { redirectUriPath: '/hiya', }, }), AppInitializationError); // inconsistent redirectUri assert.throws(() => new SocketModeReceiver({ appToken, clientId: 'my-clientId', clientSecret, stateSecret, scopes, redirectUri: 'http://example.com/hiya', installerOptions, }), AppInitializationError); }); }); describe('request handling', function () { describe('handleInstallPathRequest()', function () { it('should invoke installer generateInstallUrl if a request comes into the install path', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const metadata = 'this is bat country'; const scopes = ['channels:read']; const userScopes = ['chat:write']; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes, installerOptions: { authVersion: 'v2', installPath: '/hiya', metadata, userScopes, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq = { url: '/hiya', method: 'GET', }; const fakeRes = { writeHead: sinon.fake(), end: sinon.fake(), }; await this.listener(fakeReq, fakeRes); assert(installProviderStub.generateInstallUrl.calledWith(sinon.match({ metadata, scopes, userScopes }))); assert(fakeRes.writeHead.calledWith(200, sinon.match.object)); assert(fakeRes.end.called); }); it('should use a custom HTML renderer for the install path webpage', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const metadata = 'this is bat country'; const scopes = ['channels:read']; const userScopes = ['chat:write']; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes, installerOptions: { authVersion: 'v2', installPath: '/hiya', renderHtmlForInstallPath: (_) => 'Hello world!', metadata, userScopes, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq = { url: '/hiya', method: 'GET', }; const fakeRes = { writeHead: sinon.fake(), end: sinon.fake(), }; await this.listener(fakeReq, fakeRes); assert(installProviderStub.generateInstallUrl.calledWith(sinon.match({ metadata, scopes, userScopes }))); assert(fakeRes.writeHead.calledWith(200, sinon.match.object)); assert(fakeRes.end.called); assert.isTrue(fakeRes.end.calledWith('Hello world!')); }); it('should redirect installers if directInstall is true', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const metadata = 'this is bat country'; const scopes = ['channels:read']; const userScopes = ['chat:write']; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes, installerOptions: { authVersion: 'v2', installPath: '/hiya', directInstall: true, metadata, userScopes, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq = { url: '/hiya', method: 'GET', }; const fakeRes = { writeHead: sinon.fake(), end: sinon.fake(), }; /* eslint-disable-next-line @typescript-eslint/await-thenable */ await this.listener(fakeReq, fakeRes); assert(installProviderStub.generateInstallUrl.calledWith(sinon.match({ metadata, scopes, userScopes }))); assert(fakeRes.writeHead.calledWith(302, sinon.match.object)); assert(fakeRes.end.called); }); }); describe('handleInstallRedirectRequest()', function () { it('should invoke installer handleCallback if a request comes into the redirect URI path', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const callbackOptions = { failure: () => {}, success: () => {}, }; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes: ['channels:read'], redirectUri: 'http://example.com/heyo', installerOptions: { stateVerification: true, authVersion: 'v2', userScopes: ['chat:write'], redirectUriPath: '/heyo', callbackOptions, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq = { url: '/heyo', method: 'GET', }; const fakeRes = null; await this.listener(fakeReq, fakeRes); assert( installProviderStub.handleCallback.calledWith( fakeReq as IncomingMessage, fakeRes as unknown as ServerResponse, callbackOptions, ), ); }); it('should invoke handleCallback with installURLoptions as params if state verification is off', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const metadata = 'this is bat country'; const scopes = ['channels:read']; const redirectUri = 'http://example.com/heyo'; const userScopes = ['chat:write']; const callbackOptions = { failure: () => {}, success: () => {}, }; const installUrlOptions = { scopes, metadata, userScopes, redirectUri, }; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes, redirectUri, installerOptions: { stateVerification: false, authVersion: 'v2', redirectUriPath: '/heyo', callbackOptions, userScopes: ['chat:write'], metadata, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq: IncomingMessage = sinon.createStubInstance(IncomingMessage) as IncomingMessage; fakeReq.url = '/heyo'; fakeReq.headers = { host: 'localhost' }; fakeReq.method = 'GET'; const fakeRes: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; fakeRes.writeHead = sinon.fake(); fakeRes.end = sinon.fake(); await this.listener(fakeReq, fakeRes); sinon.assert.calledWith( installProviderStub.handleCallback, fakeReq as IncomingMessage, fakeRes as unknown as ServerResponse, callbackOptions, installUrlOptions, ); }); }); describe('custom route handling', function () { it('should call custom route handler only if request matches route path and method', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const customRoutes = [{ path: '/test', method: ['get', 'POST'], handler: sinon.fake() }]; const receiver = new SocketModeReceiver({ appToken: 'my-secret', customRoutes, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq: IncomingMessage = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const fakeRes = { writeHead: sinon.fake(), end: sinon.fake() }; fakeReq.url = '/test'; fakeReq.headers = { host: 'localhost' }; fakeReq.method = 'GET'; await this.listener(fakeReq, fakeRes); assert(customRoutes[0].handler.calledWith(fakeReq, fakeRes)); fakeReq.method = 'POST'; await this.listener(fakeReq, fakeRes); assert(customRoutes[0].handler.calledWith(fakeReq, fakeRes)); fakeReq.method = 'UNHANDLED_METHOD'; await this.listener(fakeReq, fakeRes); assert(fakeRes.writeHead.calledWith(404, sinon.match.object)); assert(fakeRes.end.called); }); it("should throw an error if customRoutes don't have the required keys", async function () { // Arrange const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const customRoutes = [{ handler: sinon.fake() }] as any; assert.throws(() => new SocketModeReceiver({ appToken: 'my-secret', customRoutes }), CustomRouteInitializationError); }); }); it('should return a 404 if a request passes the install path, redirect URI path and custom routes', async function () { // Arrange const installProviderStub = sinon.createStubInstance(InstallProvider); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const metadata = 'this is bat country'; const scopes = ['channels:read']; const userScopes = ['chat:write']; const customRoutes = [{ path: '/test', method: ['get', 'POST'], handler: sinon.fake() }]; const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes, customRoutes, redirectUri: 'http://example.com/heyo', installerOptions: { authVersion: 'v2', installPath: '/hiya', redirectUriPath: '/heyo', metadata, userScopes, }, }); assert.isNotNull(receiver); receiver.installer = installProviderStub as unknown as InstallProvider; const fakeReq = { url: '/nope', method: 'GET', }; const fakeRes = { writeHead: sinon.fake(), end: sinon.fake(), }; await this.listener(fakeReq, fakeRes); assert(fakeRes.writeHead.calledWith(404, sinon.match.object)); assert(fakeRes.end.calledOnce); }); }); describe('#start()', function () { it('should invoke the SocketModeClient start method', async function () { // Arrange const clientStub = sinon.createStubInstance(SocketModeClient); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes: ['channels:read'], installerOptions: { authVersion: 'v2', userScopes: ['chat:write'], }, }); assert.isNotNull(receiver); receiver.client = clientStub as unknown as SocketModeClient; await receiver.start(); assert(clientStub.start.called); }); }); describe('#stop()', function () { it('should invoke the SocketModeClient disconnect method', async function () { // Arrange const clientStub = sinon.createStubInstance(SocketModeClient); const overrides = mergeOverrides( withHttpCreateServer(this.fakeCreateServer), withHttpsCreateServer(sinon.fake.throws('Should not be used.')), ); const SocketModeReceiver = await importSocketModeReceiver(overrides); const receiver = new SocketModeReceiver({ appToken: 'my-secret', logger: noopLogger, clientId: 'my-clientId', clientSecret: 'my-client-secret', stateSecret: 'state-secret', scopes: ['channels:read'], installerOptions: { authVersion: 'v2', userScopes: ['chat:write'], }, }); assert.isNotNull(receiver); receiver.client = clientStub as unknown as SocketModeClient; await receiver.stop(); assert(clientStub.disconnect.called); }); }); }); /* Testing Harness */ // Loading the system under test using overrides async function importSocketModeReceiver( overrides: Override = {}, ): Promise<typeof import('./SocketModeReceiver').default> { return (await rewiremock.module(() => import('./SocketModeReceiver'), overrides)).default; } // Composable overrides function withHttpCreateServer(spy: SinonSpy): Override { return { http: { createServer: spy, }, }; } function withHttpsCreateServer(spy: SinonSpy): Override { return { https: { createServer: spy, }, }; }
the_stack
import debug from "debug"; import { Panel } from "@lumino/widgets"; import { DisposableDelegate, IDisposable } from "@lumino/disposable"; import type { JupyterFrontEndPlugin } from "@jupyterlab/application"; import type { DocumentRegistry } from "@jupyterlab/docregistry"; import type { INotebookModel, NotebookPanel } from "@jupyterlab/notebook"; import type { IRenderMime } from "@jupyterlab/rendermime"; import type { Kernel } from "@jupyterlab/services"; import WebIO from "@webio/webio"; const log = debug("WebIO:jupyter-lab"); const MIME_TYPE = "application/vnd.webio.node+json"; const COMM_TARGET = "webio_comm"; const WEBIO_METADATA_KEY = "@webio"; const WEBIO_OLD_KERNEL_MESSAGE = "This WebIO widget was rendered for a Jupyter kernel that is no longer running. " + "Re-run this cell to regenerate this widget."; /** * In order to know when (and how) to resume connections (after a refresh, for * example), we store information about the last-used kernel and the last-used * comm. This data is stored in the notebook's metadata. */ interface WebIONotebookMetadata { lastKernelId?: string; lastCommId?: string; } interface WebIOOutputMetadata { kernelId?: string; } /* * The rank of a renderer determines the order in which renderers are invoked. * A lower rank means that the Renderer has a higher priority. * * It shouldn't actually mean anything since there shouldn't(?) be any other * renderers that try to render the WebIO MIME type. */ const RENDERER_RANK = 0; /** * A Jupyter renderer class that mounts a WebIO node. * * The JupyterLab machinery creates an instance of this class every time WebIO * data is displayed in the notebook. It is passed a {@link WebIO} instance by * the renderer-factory which is set up in * {@link WebIONotebookExtension#createNew}. The {@link WebIO} instance is also * managed by a {@link WebIONotebookManager} but that is handles outside of this * class (_i.e._ this class just gets a WebIO instance which may or may not be * connected to the Julia kernel yet). */ class WebIORenderer extends Panel implements IRenderMime.IRenderer, IDisposable { private get webIO() { return this.webIOManager.webIO; } constructor( options: IRenderMime.IRendererOptions, private webIOManager: WebIONotebookManager, ) { super(); log("WebIORenderer¬constructor", options, webIOManager); } async renderModel(model: IRenderMime.IMimeModel): Promise<void> { // const metadata = model.metadata as WebIOOutputMetadata; // if (!metadata.kernelId) { // // Do nothing; we set the model metadata which triggers a re-render. // return this.setModelMetadata(model); // } log("WebIORenderer¬renderModel"); const { kernelId } = this.getModelMetadata(model); if (!kernelId) { return this.setModelMetadata(model); } const currentKernelId = (await this.webIOManager.getKernel()).id; if (kernelId !== currentKernelId) { log( `WebIORenderer¬renderModel: output was generated for kernelId "${kernelId}", ` + `but we're currently running using kernel "${currentKernelId}".`, ); const div = document.createElement("div"); const p = document.createElement("p"); const strong = document.createElement("strong"); strong.innerText = WEBIO_OLD_KERNEL_MESSAGE; p.appendChild(strong); div.appendChild(p); this.node.appendChild(div); return; } (window as any).lastWebIORenderer = this; log("WebIORenderer¬renderModel", model.data[MIME_TYPE]); const data = model.data[MIME_TYPE]; if (!data) { console.error("WebIORenderer created for unsupported model:", model); return; } this.webIO.mount(this.node, model.data[MIME_TYPE] as any); return; } private getModelMetadata(model: IRenderMime.IMimeModel) { return (model.metadata[WEBIO_METADATA_KEY] || {}) as WebIOOutputMetadata; } private async setModelMetadata(model: IRenderMime.IMimeModel) { model.setData({ metadata: { ...model.metadata, [WEBIO_METADATA_KEY]: { kernelId: (await this.webIOManager.getKernel()).id, } as WebIOOutputMetadata, } as any, }); } } /** * A manager that is responsible for maintaining the WebIO instance for a single * notebook panel. * * An instance of this class exists for every notebook open in the JupyterLab * session (i.e. for every notebook tab). * * This class is necessary to facilitate lazy-initialization. We could just * create a new {@link WebIO} instance in {@link WebIONotebookExtension#createNew} * but we won't be sure that WebIO has been loaded on the kernel side yet (i.e. * we try to open the comm before `using WebIO` has been executed); even if * WebIO is initialized on the kernel later, the comm will never connect. */ class WebIONotebookManager { private readonly _webIO = new WebIO(); private comm?: Kernel.IComm; /** * We lazy-connect WebIO. This ensures that we don't try to connect to WebIO * before the kernel is ready. * * IMPORTANT: This also depends upon how the WebIORenderer won't try to render * WebIO nodes that were created for a different kernel; because we know that * the node was generated using the current kernel, we're sure that it's ready * for comm connections (since it's already been answering code execution * requests). */ get webIO() { this.connect(); return this._webIO; } constructor( private notebook: NotebookPanel, private context: DocumentRegistry.IContext<INotebookModel>, ) { (window as any).webIONotebookManager = this; log("WebIONotebookManager¬constructor"); } async getKernel() { log("WebIONotebookManager¬getKernel"); await this.context.sessionContext.ready; const session = this.context.sessionContext.session; if (!session) { throw new Error("Kernel is not available!"); } const kernel = session.kernel; if (!kernel) { throw new Error("Session is ready but kernel isn't available!"); } log( `WebIONotebookManager¬connect: Notebook kernel is ready; status is ${kernel.status}.`, ); return kernel; } /** * Connect to the Julia side of WebIO using a comm. * * This function is idempotent (_i.e._ calling it multiple times shouldn't * result on an error and it should only connect on the first call). */ async connect() { log("WebIONotebookManager¬connect"); const kernel = await this.getKernel(); // It's important that everything below this is synchronous to avoid race // conditions. if (this.comm) { log("WebIONotebookManager¬connect: WebIO is already connected."); return; } const { lastKernelId, lastCommId } = this.getWebIOMetadata(); const shouldReuseCommId = // To re-use the comm id, we need to be using the same kernel. lastKernelId === kernel.id && // We need to know what the last comm id *was* !!lastCommId; log( `WebIONotebookManager¬connect: Last WebIO connection was for kernelId="${lastKernelId}", commId="${lastCommId}".`, ); log( `WebIONotebookManager¬connect: We're ${ shouldReuseCommId ? "definitely" : "not" } re-using the old commId.`, ); this.comm = kernel.createComm( COMM_TARGET, shouldReuseCommId ? lastCommId : undefined, ); this.comm.open(); this._webIO.setSendCallback((msg: any) => this.comm!.send(msg)); this.comm.onMsg = (msg: any) => { log("Received WebIO comm message:", msg); this._webIO.dispatch(msg.content.data); }; this.setWebIOMetadata(kernel.id, this.comm.commId); } private getWebIOMetadata(): WebIONotebookMetadata { if (!this.notebook.model) { throw new Error("Notebook model is not available!"); } return (this.notebook.model.metadata.get(WEBIO_METADATA_KEY) || {}) as any; } private setWebIOMetadata(kernelId: string, commId: string) { const metadata: WebIONotebookMetadata = { lastKernelId: kernelId, lastCommId: commId, }; log("Setting WebIO notebook metadata.", metadata); if (!this.notebook.model) { throw new Error("Notebook model is not available!"); } this.notebook.model.metadata.set(WEBIO_METADATA_KEY, metadata as any); } } /** * The JupyterLab WebIO notebook extension. * * Essentially, every time a new {@link NotebookPanel} instance is created * (_i.e._ when a new notebook tab is opened), JupyterLab will call the * {@link WebIONotebookExtension#createNew} method which creates a new * {@link WebIO} instance (specific to the new notebook) and hooks up the * {@link WebIORenderer} using this notebook-specific instance of {@link WebIO}. */ class WebIONotebookExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> { createNew( notebook: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>, ): IDisposable { log("WebIONotebookExtension¬createNew", notebook, context); const webIONotebookManager = new WebIONotebookManager(notebook, context); log(`Registering rendermime factory for MIME: ${MIME_TYPE}.`); const { rendermime } = notebook.content; rendermime.addFactory( { safe: true, mimeTypes: [MIME_TYPE], createRenderer: (options) => { log("Creating WebIO renderer..."); webIONotebookManager.connect(); return new WebIORenderer(options, webIONotebookManager); }, }, RENDERER_RANK, ); return new DisposableDelegate(() => { log("Unregistering WebIO MIME renderer..."); rendermime.removeMimeType(MIME_TYPE); }); } } const extension: JupyterFrontEndPlugin<void> = { id: "@webio/jupyter-lab-provider:plugin", activate: (app) => { log("Activating WebIO JupyterLab plugin."); app.docRegistry.addWidgetExtension( "Notebook", new WebIONotebookExtension(), ); }, autoStart: true, }; export default extension;
the_stack
import { huge as INFINITY } from "@wowts/math"; import { kpairs, tonumber } from "@wowts/lua"; import aceEvent, { AceEvent } from "@wowts/ace_event-3.0"; import { GetSpellCount, IsSpellInRange, IsUsableItem, IsUsableSpell, SpellId, UnitIsFriend, } from "@wowts/wow-mock"; import { isNumber } from "../tools/tools"; import { OvaleSpellBookClass } from "./SpellBook"; import { AceModule } from "@wowts/tsaddon"; import { OvaleClass } from "../Ovale"; import { Tracer, DebugTools } from "../engine/debug"; import { OvaleDataClass } from "../engine/data"; import { StateModule } from "../engine/state"; import { NamedParametersOf, AstActionNode } from "../engine/ast"; import { OvalePowerClass, PowerType } from "./Power"; import { OvaleRunesClass } from "./Runes"; import { SpellActivationGlow } from "./spellactivationglow"; const warriorInterceptSpellId = SpellId.intercept; const warriorHeroicThrowSpellId = SpellId.heroic_throw; export class OvaleSpellsClass implements StateModule { private module: AceModule & AceEvent; private tracer: Tracer; constructor( private spellBook: OvaleSpellBookClass, ovale: OvaleClass, ovaleDebug: DebugTools, private ovaleData: OvaleDataClass, private power: OvalePowerClass, private runes: OvaleRunesClass, private spellActivationGlow: SpellActivationGlow ) { this.module = ovale.createModule( "OvaleSpells", this.handleInitialize, this.handleDisable, aceEvent ); this.tracer = ovaleDebug.create(this.module.GetName()); } private handleInitialize = (): void => {}; private handleDisable = (): void => {}; getCastTime(spellId: number): number | undefined { if (spellId) { let [name, , , castTime] = this.spellBook.getSpellInfo(spellId); if (name) { if (castTime) { castTime = castTime / 1000; } else { castTime = 0; } } else { return undefined; } return castTime; } } getSpellCount(spellId: number): number { const [index, bookType] = this.spellBook.getSpellBookIndex(spellId); if (index && bookType) { const spellCount = GetSpellCount(index, bookType); this.tracer.debug( "GetSpellCount: index=%s bookType=%s for spellId=%s ==> spellCount=%s", index, bookType, spellId, spellCount ); return spellCount; } else { const spellName = this.spellBook.getSpellName(spellId); if (spellName) { const spellCount = GetSpellCount(spellName); this.tracer.debug( "GetSpellCount: spellName=%s for spellId=%s ==> spellCount=%s", spellName, spellId, spellCount ); return spellCount; } return 0; } } isSpellInRange(spellId: number, unitId: string): boolean | undefined { const [index, bookType] = this.spellBook.getSpellBookIndex(spellId); let returnValue; if (index && bookType) { returnValue = IsSpellInRange(index, bookType, unitId); } else if (this.spellBook.isKnownSpell(spellId)) { const name = this.spellBook.getSpellName(spellId); if (name) returnValue = IsSpellInRange(name, unitId); } if (returnValue == 1 && spellId == warriorInterceptSpellId) { return ( UnitIsFriend("player", unitId) || this.isSpellInRange(warriorHeroicThrowSpellId, unitId) ); } if (returnValue === 1) return true; if (returnValue === 0) return false; return undefined; } cleanState(): void {} initializeState(): void {} resetState(): void {} isUsableItem(itemId: number, atTime: number): boolean { let isUsable = IsUsableItem(itemId); const ii = this.ovaleData.getItemInfo(itemId); if (ii) { if (isUsable) { const unusable = this.ovaleData.getItemInfoProperty( itemId, atTime, "unusable" ); if (unusable && unusable > 0) { this.tracer.log( "Item ID '%s' is flagged as unusable.", itemId ); isUsable = false; } } } return isUsable; } isUsableSpell( spellId: number, atTime: number, targetGUID: string | undefined ): [boolean, boolean] { let [isUsable, noMana] = [false, false]; const isKnown = this.spellBook.isKnownSpell(spellId); const si = this.ovaleData.spellInfo[spellId]; if (!isKnown) { this.tracer.log("Spell ID '%s' is not known.", spellId); [isUsable, noMana] = [false, false]; } else if (si !== undefined) { const unusable = this.ovaleData.getSpellInfoProperty( spellId, atTime, "unusable", targetGUID ); if (unusable !== undefined && tonumber(unusable) > 0) { this.tracer.log( "Spell ID '%s' is flagged as unusable.", spellId ); [isUsable, noMana] = [false, false]; } else { const seconds = this.timeToPowerForSpell( spellId, atTime, targetGUID, undefined ); if (seconds > 0) { this.tracer.log( "Spell ID '%s' does not have enough power.", spellId ); [isUsable, noMana] = [false, true]; } else { this.tracer.log( "Spell ID '%s' meets power requirements.", spellId ); [isUsable, noMana] = [true, false]; } } // if we have a spell activation glow we force the spell as being usable anyway. if ( !isUsable && this.spellActivationGlow.hasSpellActivationGlow(spellId) ) { this.tracer.log( "Spell ID '%s' has spell activation glow. Force it as usable.", spellId ); isUsable = true; } } else { [isUsable, noMana] = IsUsableSpell(spellId); } return [isUsable, noMana]; } timeToPowerForSpell( spellId: number, atTime: number, targetGUID: string | undefined, powerType: PowerType | undefined, extraPower?: NamedParametersOf<AstActionNode> ): number { let timeToPower = 0; const si = this.ovaleData.spellInfo[spellId]; if (si) { for (const [, powerInfo] of kpairs(this.power.powerInfos)) { const pType = powerInfo.type; if (powerType == undefined || powerType == pType) { let [cost] = this.power.powerCost( spellId, pType, atTime, targetGUID ); if (cost > 0) { if (extraPower) { let extraAmount; if (pType == "energy") { extraAmount = extraPower.extra_energy; } else if (pType == "focus") { extraAmount = extraPower.extra_focus; } if (isNumber(extraAmount)) { this.tracer.log( " Spell ID '%d' has cost of %d (+%d) %s", spellId, cost, extraAmount, pType ); cost = cost + <number>extraAmount; } } else { this.tracer.log( " spell ID '%d' has cost of %d %s", spellId, cost, pType ); } const seconds = this.power.getTimeToPowerAt( this.power.next, cost, pType, atTime ); this.tracer.log( " spell ID '%d' requires %f seconds for %d %s", spellId, seconds, cost, pType ); if (timeToPower < seconds) { timeToPower = seconds; } if (timeToPower == INFINITY) { this.tracer.log( " short-circuiting checks for other power requirements" ); break; } } } } if (timeToPower != INFINITY) { // Check runes, implemented as a separate module. const runes = this.ovaleData.getSpellInfoProperty( spellId, atTime, "runes", targetGUID ); if (runes) { const seconds = this.runes.getRunesCooldown( atTime, <number>runes ); this.tracer.log( " spell ID '%d' requires %f seconds for %d runes", spellId, seconds, runes ); if (timeToPower < seconds) { timeToPower = seconds; } } } } this.tracer.log( "Spell ID '%d' requires %f seconds for power requirements.", spellId, timeToPower ); return timeToPower; } /* GetTimeToSpell(spellId: number, atTime: number, targetGUID: string, extraPower?: number) { if (type(atTime) == "string" && !targetGUID) { [atTime, targetGUID] = [undefined, atTime]; } let timeToSpell = 0; { let [start, duration] = OvaleCooldown.GetSpellCooldown(spellId, atTime); let seconds = (duration > 0) && (start + duration - atTime) || 0; if (timeToSpell < seconds) { timeToSpell = seconds; } } { let seconds = OvalePower.TimeToPower(spellId, atTime, targetGUID, undefined, extraPower); if (timeToSpell < seconds) { timeToSpell = seconds; } } { let runes = OvaleData.GetSpellInfoProperty(spellId, atTime, "runes", targetGUID); if (runes) { let seconds = OvaleRunes.GetRunesCooldown(atTime, <number>runes); if (timeToSpell < seconds) { timeToSpell = seconds; } } } return timeToSpell; } */ }
the_stack
import { makeRoot } from "../../root"; import { Task as TaskInterface } from "../../store/interfaces"; import store from "../../store/store"; import Checkbox from "../checkbox/checkbox"; import Controls from "../controls/controls"; import Pin from "../pin/pin"; const FOCUS_SAVE_INTERVAL: number = 5000; export default class Task extends HTMLElement { private controls: Controls; private task: TaskInterface; private checkbox: Checkbox; private tasktext: HTMLSpanElement; private subtasks: HTMLElement; constructor(task: TaskInterface, controls: Controls) { super(); this.task = task; this.controls = controls; const template: HTMLTemplateElement = document.querySelector("#task") as HTMLTemplateElement; const node: DocumentFragment = document.importNode(template.content, true); this.appendChild(node); this.id = task.id; this.subtasks = this.querySelector("footer") as HTMLElement; this.checkbox = new Checkbox(task.id); this.checked = task.checked; this.tasktext = document.createElement("span"); if (task.text) { this.tasktext.innerText = task.text; } this.tasktext.setAttribute("contenteditable", "true"); this.isPinned = task.pinned; const header: HTMLElement = this.querySelector("header") as HTMLElement; header.appendChild(this.checkbox); header.appendChild(this.tasktext); (this.querySelector("header > a:nth-child(1)") as HTMLElement).addEventListener("click", this.onRoot); (this.querySelector("header > a:nth-child(2)") as HTMLElement).addEventListener("click", this.onLinkClick); (this.querySelector("header > a:nth-child(3)") as HTMLElement).addEventListener("click", this.onTryResync); // keypress does not detect tab, backspace and some other keys this.tasktext.addEventListener("keydown", this.onKeyPress); this.tasktext.addEventListener("blur", this.updateTextCache); this.tasktext.addEventListener("focus", this.onFocusText); this.checkbox.addEventListener("change", this.onCheckboxChange); } public connectedCallback(): void { if (this.isPinned) { (document.querySelector(`#pinned-${this.id}`) as Pin).updateLocation(); } } public disconnectedCallback(): void { if (this.isPinned) { const pinElement: HTMLElement|null = document.querySelector(`#pinned-${this.id}`) as HTMLElement; pinElement.remove(); } } get expanded(): boolean { return this.hasAttribute("expanded"); } set expanded(val: boolean) { if (val) { this.setAttribute("expanded", "true"); this.task.collapsed = false; } else { this.removeAttribute("expanded"); this.task.collapsed = true; } } get hasSubtasks(): boolean { return this.hasAttribute("has-subtasks"); } set hasSubtasks(val: boolean) { if (val) { this.setAttribute("has-subtasks", "true"); this.isPinned = false; } else { this.removeAttribute("has-subtasks"); } } get root(): boolean { return this.hasAttribute("root"); } set root(val: boolean) { if (val) { this.setAttribute("root", "true"); } else { this.removeAttribute("root"); } } get ancestor(): boolean { return this.hasAttribute("ancestor"); } set ancestor(val: boolean) { if (val) { this.setAttribute("ancestor", "true"); } else { this.removeAttribute("ancestor"); } } get isPinned(): boolean { return this.hasAttribute("is-pinned"); } set isPinned(val: boolean) { if (val) { this.setAttribute("is-pinned", "true"); this.task.pinned = true; (document.querySelector("#pins") as HTMLElement).appendChild(new Pin(this)); } else { this.removeAttribute("is-pinned"); this.task.pinned = false; const pinElement: HTMLElement|null = document.querySelector(`#pinned-${this.id}`); if (pinElement) { pinElement.remove(); } } } get checked(): boolean { return this.hasAttribute("checked"); } set checked(val: boolean) { if (val) { this.setAttribute("checked", "true"); this.isPinned = false; } else { this.removeAttribute("checked"); } this.checkbox.checked = val; if (this.isConnected) { const parent: Task|null = this.parent(); if (parent) { parent.verifyChecked(); } } } get unsynced(): boolean { return this.hasAttribute("unsynced"); } set unsynced(val: boolean) { if (val) { this.setAttribute("unsynced", "true"); } else { this.removeAttribute("unsynced"); } } get textElement(): HTMLSpanElement { return this.tasktext; } public addSubtask(task: Task): void { task.remove(); this.subtasks.appendChild(task); this.expanded = true; this.hasSubtasks = true; } public freezeText(): void { this.tasktext.removeAttribute("contenteditable"); } public async updateText(text: string): Promise<void> { this.tasktext.innerText = text; await this.updateTextCache(); } public parent(): Task|null { const candidate: HTMLElement | null = (this.parentElement as HTMLElement).parentElement; if (candidate instanceof Task) { return candidate; } return null; } public async toggleChecked(): Promise<void> { this.checked = !this.checked; this.task.checked = this.checked; await store.update(this.task); } public async toggleExpanded(): Promise<void> { this.expanded = !this.expanded; await store.update(this.task); } public async togglePinned(): Promise<void> { this.isPinned = !this.isPinned; await store.update(this.task); } public isShiftable(): boolean { if (this.hasAttribute("root")) { return false; } const prevSibling: Task|null = this.previousSibling as Task|null; if (!prevSibling) { return false; } return true; } public async shift(): Promise<void> { if (this.hasAttribute("root")) { return; } const prevSibling: Task|null = this.previousSibling as Task|null; if (!prevSibling) { return; } const pos: number = this.getCursorPosition(); const parent: Task = this.parent() as Task; parent.removeSubtask(this.task.id); prevSibling.task.children.push(this.task.id); await store.update(prevSibling.task); prevSibling.addSubtask(this); this.tasktext.focus(); this.setCursorPosition(pos); } public isUnshiftable(): boolean { if (this.hasAttribute("root")) { return false; } const parent: Task = this.parent() as Task; const grandParent: Task = parent.parent() as Task; if (!grandParent || !(grandParent instanceof Task)) { return false; } return true; } public async unshift(): Promise<void> { if (this.hasAttribute("root")) { return; } const parent: Task = this.parent() as Task; const grandParent: Task = parent.parent() as Task; if (!grandParent || !(grandParent instanceof Task)) { return; } const pos: number = this.getCursorPosition(); const nextSibling: Task = parent.nextSibling as Task; if (!nextSibling) { grandParent.task.children.push(this.id); grandParent.addSubtask(this); } else { const idx: number = grandParent.task.children.indexOf(nextSibling.id); grandParent.task.children.splice(idx, 0, this.id); grandParent.addSubtaskBefore(this, nextSibling); } await Promise.all([ parent.removeSubtask(this.task.id), store.update(grandParent.task), ]); this.tasktext.focus(); this.setCursorPosition(pos); } public isMovableUpwards(): boolean { const element: Task|null = this.previousSibling as Task|null; if (!element) { return false; } const parent: Task|null = this.parent(); if (!parent) { return false; } if (this.root) { return false; } return true; } public async moveUp(): Promise<void> { const element: Task|null = this.previousSibling as Task|null; if (!element) { return; } const parent: Task|null = this.parent(); if (!parent) { return; } if (this.root) { return; } const cursor: number = this.getCursorPosition(); const idx: number = parent.task.children.indexOf(element.id); parent.task.children[idx] = this.id; parent.task.children[idx + 1] = element.id; parent.addSubtaskBefore(this, element); this.tasktext.focus(); this.setCursorPosition(cursor); await store.update(parent.task); } public isMovableDownwards(): boolean { const element: Task|null = this.nextSibling as Task|null; if (!element) { return false; } const parent: Task|null = this.parent(); if (!parent) { return false; } if (this.root) { return false; } return true; } public async moveDown(): Promise<void> { const element: Task|null = this.nextSibling as Task|null; if (!element) { return; } const parent: Task|null = this.parent(); if (!parent) { return; } if (this.root) { return; } const cursor: number = this.getCursorPosition(); const idx: number = parent.task.children.indexOf(element.id); parent.task.children[idx] = this.id; parent.task.children[idx - 1] = element.id; parent.addSubtaskAfter(this, element); this.tasktext.focus(); this.setCursorPosition(cursor); await store.update(parent.task); } private onCheckboxChange = async (e: Event): Promise<void> => { const newValue: boolean = (e.target as HTMLInputElement).checked; if (newValue !== this.checked) { await this.toggleChecked(); } } private verifyChecked = async (): Promise<void> => { const uncheckedSubtask: HTMLElement|null = this.subtasks.querySelector("x-task:not([checked])"); if ((this.checked && uncheckedSubtask) || (!this.checked && !uncheckedSubtask)) { await this.toggleChecked(); } } private addSubtaskBefore = (task: Task, nextSibling: Task): void => { this.expanded = true; task.remove(); this.subtasks.insertBefore(task, nextSibling); } private addSubtaskAfter = (task: Task, prevSibling: Task): void => { this.expanded = true; task.remove(); const next: Task|null = prevSibling.nextSibling as Task|null; if (next) { this.subtasks.insertBefore(task, next); } else { this.subtasks.appendChild(task); } } private onRoot = (e: Event): void => { e.preventDefault(); makeRoot(this); } private onLinkClick = (e: Event): void => { e.preventDefault(); if (this.hasSubtasks) { this.toggleExpanded(); } else { this.togglePinned(); } } private onTryResync = async (e: Event): Promise<void> => { e.preventDefault(); await store.update(this.task); } private onKeyPress = async (e: KeyboardEvent): Promise<void> => { if (e.shiftKey) { switch (e.keyCode) { case 9: // tab e.preventDefault(); await this.unshift(); break; case 38: // ArrowUp e.preventDefault(); await this.moveUp(); break; case 40: // ArrowDown e.preventDefault(); await this.moveDown(); break; } return; } if (e.ctrlKey) { switch (e.keyCode) { case 8: // backspace e.preventDefault(); await this.drop(); break; case 13: // enter e.preventDefault(); await this.toggleChecked(); break; case 38: // ArrowUp e.preventDefault(); this.expanded = false; break; case 40: // ArrowDown e.preventDefault(); this.expanded = true; break; } return; } switch (e.keyCode) { case 9: // tab e.preventDefault(); await this.shift(); break; case 13: // enter e.preventDefault(); await this.addSibling(); break; case 38: // ArrowUp e.preventDefault(); await this.moveFocusUp(); break; case 40: // ArrowDown e.preventDefault(); await this.moveFocusDown(); break; } } private removeSubtask = async (id: string): Promise<void> => { this.task.children = this.task.children.filter((cid: string): boolean => cid !== id); if (this.task.children.length === 0) { this.hasSubtasks = false; this.expanded = false; } await store.update(this.task); } private drop = async (): Promise<void> => { const parent: Task = this.parent() as Task; this.remove(); await Promise.all([ parent.removeSubtask(this.id), store.remove(this.task), ]); } private addSibling = async (): Promise<void> => { if (this.hasAttribute("root")) { return; } const parent: Task = this.parent() as Task; const nextSibling: Task|null = this.nextSibling as Task|null; if (!nextSibling) { const newTask: TaskInterface = await store.create(parent.task); const newTaskElement: Task = new Task(newTask, this.controls); parent.addSubtask(newTaskElement); (newTaskElement.tasktext as HTMLElement).focus(); } else { const newTask: TaskInterface = await store.createBefore(parent.task, nextSibling.task); const newTaskElement: Task = new Task(newTask, this.controls); parent.addSubtaskBefore(newTaskElement, nextSibling); (newTaskElement.tasktext as HTMLElement).focus(); } } private updateTextCache = async (): Promise<void> => { this.task.text = this.tasktext.innerText; if (this.task.text) { await store.update(this.task); } else { await this.drop(); } this.controls.removeCurrentTask(this); } private onFocusText = (): void => { const update: () => Promise<void> = async (): Promise<void> => { if (this.tasktext !== document.activeElement) { return; } if (this.task.text !== this.tasktext.innerText) { this.task.text = this.tasktext.innerText; await store.update(this.task); } setTimeout(update, FOCUS_SAVE_INTERVAL); }; this.controls.setCurrentTask(this); } private moveFocusUp = async (): Promise<void> => { const element: Task|null = this.previousSibling as Task|null; if (element) { this.moveFocus(element); return; } const parent: Task = this.parent() as Task; if (!parent.root) { this.moveFocus(parent); } } private moveFocusDown = async (): Promise<void> => { const element: Task = this.nextSibling as Task; if (element) { this.moveFocus(element); } } private moveFocus = (task: Task): void => { const pos: number = this.getCursorPosition(); this.tasktext.blur(); task.tasktext.focus(); task.setCursorPosition(pos); } /** * https://developer.mozilla.org/en-US/docs/Web/API/Selection * https://developer.mozilla.org/en-US/docs/Web/API/range */ private getCursorPosition = (): number => { const selection: Selection | null = window.getSelection(); if (!selection) { return 0; } if (selection.rangeCount) { const range: Range = selection.getRangeAt(0); if (range.commonAncestorContainer.parentNode === this.tasktext) { return range.endOffset; } } return 0; } private setCursorPosition = (pos: number): void => { if (!this.tasktext.childNodes || !this.tasktext.childNodes.length) { return; } const range: Range = document.createRange(); range.setStart(this.tasktext.childNodes[0], pos); range.collapse(true); const sel: Selection | null = window.getSelection(); if (!sel) { return; } sel.removeAllRanges(); sel.addRange(range); } } window.customElements.define("x-task", Task);
the_stack
import { validateYaml, validateSchema, checkCodeOwners, checkAutoApproveConfig, } from '../src/check-config.js'; import {describe, it} from 'mocha'; import assert from 'assert'; import * as fs from 'fs'; import nock from 'nock'; import snapshot from 'snap-shot-it'; const {Octokit} = require('@octokit/rest'); const octokit = new Octokit({ auth: 'mypersonalaccesstoken123', }); const CONFIGURATION_FILE_PATH = 'auto-approve.yml'; nock.disableNetConnect(); function getCodeOwnersFile(response: string | undefined, status: number) { return nock('https://api.github.com') .get('/repos/owner/repo/contents/.github%2FCODEOWNERS') .reply( status, response ? {content: Buffer.from(response).toString('base64')} : undefined ); } function getAutoApproveFile(response: string | undefined, status: number) { return nock('https://api.github.com') .get('/repos/owner/repo/contents/.github%2Fauto-approve.yml') .reply( status, response ? {content: Buffer.from(response).toString('base64')} : undefined ); } async function checkForValidSchema( configNum: number, V2: string, invalid: string ) { return await validateSchema( fs.readFileSync( `./test/fixtures/config/${invalid}valid-schemas${V2}/${invalid}valid-schema${configNum}.yml`, 'utf8' ) ); } describe('check for config', () => { describe('whether config is a valid YAML object', () => { it('should return error message if YAML is invalid', () => { const isYamlValid = validateYaml( fs.readFileSync( './test/fixtures/config/invalid-schemas/invalid-yaml-config.yml', 'utf8' ) ); snapshot(isYamlValid); }); it('should return true if YAML is valid', async () => { const isYamlValid = validateYaml( fs.readFileSync( './test/fixtures/config/valid-schemas/valid-schema1.yml', 'utf8' ) ); assert.strictEqual(isYamlValid, ''); }); }); describe('whether YAML file has valid schema', async () => { it('should fail if YAML has any other properties than the ones specified', async () => { //does not have any additional properties const isSchemaValid = await checkForValidSchema(1, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if title does not match first author', async () => { //title does not correspond to author const isSchemaValid = await checkForValidSchema(2, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if title does not match second author', async () => { //title does not correspond to author const isSchemaValid = await checkForValidSchema(3, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if title does not match third author', async () => { //title does not correspond to author const isSchemaValid = await checkForValidSchema(4, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if author is not allowed', async () => { //author is not allowed const isSchemaValid = await checkForValidSchema(5, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if it does not have title property', async () => { //missing 'title' property const isSchemaValid = await checkForValidSchema(6, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if config is empty', async () => { //empty array const isSchemaValid = await checkForValidSchema(7, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if there are duplicate items', async () => { //duplicate items const isSchemaValid = await checkForValidSchema(8, '', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should return empty string if YAML has all of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(1, '', ''); assert.strictEqual(isSchemaValid, ''); }); it('should return empty string if YAML has any one of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(2, '', ''); assert.strictEqual(isSchemaValid, ''); }); it('should return empty string if YAML has some of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(3, '', ''); assert.strictEqual(isSchemaValid, ''); }); }); describe('whether YAML file has valid schema V2', async () => { it('should fail if YAML has any other properties than the ones specified', async () => { const isSchemaValid = await checkForValidSchema(1, 'V2', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if the property is wrong', async () => { const isSchemaValid = await checkForValidSchema(2, 'V2', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if both v1 and v2 schemas are included', async () => { const isSchemaValid = await checkForValidSchema(3, 'V2', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should fail if there are duplicate items', async () => { //duplicate items const isSchemaValid = await checkForValidSchema(4, 'V2', 'in'); snapshot(isSchemaValid ? isSchemaValid : 'undefined'); }); it('should return empty string if YAML has all of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(1, 'V2', ''); assert.strictEqual(isSchemaValid, ''); }); it('should return empty string if YAML has any one of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(2, 'V2', ''); assert.strictEqual(isSchemaValid, ''); }); it('should return empty string if YAML has some of the possible valid options', async () => { const isSchemaValid = await checkForValidSchema(3, 'V2', ''); assert.strictEqual(isSchemaValid, ''); }); }); describe('codeowner file behavior', async () => { it('should ask to change CODEOWNERS, if CODEOWNERS file is not configured properly (and the CODEOWNERS is not in the PR)', async () => { const codeownersFileResponse = fs.readFileSync( './test/fixtures/config/invalid-codeowners/invalid-codeowners1', 'utf8' ); const scopes = getCodeOwnersFile(codeownersFileResponse, 200); const response = await checkCodeOwners( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.strictEqual( response, `You must add this line to the CODEOWNERS file for auto-approve.yml to merge pull requests on this repo: .github/${CONFIGURATION_FILE_PATH} @googleapis/github-automation/` ); }); it('should ask to change codeowners, if codeowners file does not contain proper owners for config path (and the CODEOWNERS is not in the PR)', async () => { const codeownersFileResponse = fs.readFileSync( './test/fixtures/config/invalid-codeowners/invalid-codeowners2', 'utf8' ); const scopes = getCodeOwnersFile(codeownersFileResponse, 200); const response = await checkCodeOwners( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.strictEqual( response, `You must add this line to the CODEOWNERS file for auto-approve.yml to merge pull requests on this repo: .github/${CONFIGURATION_FILE_PATH} @googleapis/github-automation/` ); }); it('should accept a well-configured CODEOWNERS file', async () => { const codeownersFileResponse = fs.readFileSync( './test/fixtures/config/valid-codeowners', 'utf8' ); const scopes = getCodeOwnersFile(codeownersFileResponse, 200); const response = await checkCodeOwners( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.strictEqual(response, ''); }); it('should accept a well-configured CODEOWNERS file in PR', async () => { const response = await checkCodeOwners( octokit, 'owner', 'repo', fs.readFileSync('./test/fixtures/config/valid-codeowners', 'utf8') ); assert.strictEqual(response, ''); }); it('should ask to create a codeowners file if it does not exist', async () => { const scopes = getCodeOwnersFile(undefined, 403); const response = await checkCodeOwners( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.strictEqual( response, `You must create a CODEOWNERS file for the configuration file for auto-approve.yml that lives in .github/CODEWONERS in your repository, and contains this line: .github/${CONFIGURATION_FILE_PATH} @googleapis/github-automation/; please make sure it is accessible publicly.` ); }); it('should ask to change CODEOWNERS file in PR if it is not correctly formatted', async () => { const response = await checkCodeOwners( octokit, 'owner', 'repo', fs.readFileSync( './test/fixtures/config/invalid-codeowners/invalid-codeowners1', 'utf8' ) ); assert.deepStrictEqual( response, `You must add this line to the CODEOWNERS file for auto-approve.yml to merge pull requests on this repo: .github/${CONFIGURATION_FILE_PATH} @googleapis/github-automation/` ); }); }); describe('auto-approve file behavior', async () => { it('should check if auto-approve is on main if it is undefined on PR', async () => { const autoapproveFileResponse = fs.readFileSync( './test/fixtures/config/valid-schemas/valid-schema1.yml', 'utf8' ); const scopes = getAutoApproveFile(autoapproveFileResponse, 200); const response = await checkAutoApproveConfig( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.strictEqual(response, ''); }); it('should throw if autoapprove does not exist on PR or repo', async () => { assert.rejects(async () => { await checkAutoApproveConfig(octokit, 'owner', 'repo', undefined); }, /Auto-Approve config does not exist on repo/); }); it('should return empty string if autoapprove is on PR, but has no issues', async () => { const autoapproveFileResponse = fs.readFileSync( './test/fixtures/config/valid-schemas/valid-schema1.yml', 'utf8' ); const response = await checkAutoApproveConfig( octokit, 'owner', 'repo', autoapproveFileResponse ); assert.strictEqual(response, ''); }); it('should return error messages if autoapprove is on PR and has issues', async () => { const autoapproveFileResponse = fs.readFileSync( './test/fixtures/config/invalid-schemas/invalid-schema1.yml', 'utf8' ); const response = await checkAutoApproveConfig( octokit, 'owner', 'repo', autoapproveFileResponse ); assert.notStrictEqual(response.length, 0); }); it('should return error messages if autoapprove is on repo and has issues', async () => { const autoapproveFileResponse = fs.readFileSync( './test/fixtures/config/invalid-schemas/invalid-schema1.yml', 'utf8' ); const scopes = getAutoApproveFile(autoapproveFileResponse, 200); const response = await checkAutoApproveConfig( octokit, 'owner', 'repo', undefined ); scopes.done(); assert.notStrictEqual(response.length, 0); }); }); });
the_stack
import axios from 'axios' import { Word } from '@/_helpers/record-manager' import { parseCtxText } from '@/_helpers/translateCtx' import { AddConfig, SyncService } from '../../interface' import { getNotebook } from '../../helpers' import { message } from '@/_helpers/browser-api' import { Message } from '@/typings/message' export interface SyncConfig { enable: boolean key: string | null host: string port: string deckName: string noteType: string /** Note tags */ tags: string escapeContext: boolean escapeTrans: boolean escapeNote: boolean /** Sync to AnkiWeb after added */ syncServer: boolean } export class Service extends SyncService<SyncConfig> { static readonly id = 'ankiconnect' static getDefaultConfig(): SyncConfig { return { enable: false, host: '127.0.0.1', port: '8765', key: null, deckName: 'Saladict', noteType: 'Saladict Word', tags: '', escapeContext: true, escapeTrans: true, escapeNote: true, syncServer: false } } noteFileds: string[] | undefined async init() { if (!(await this.isServerUp())) { throw new Error('server') } const decks = await this.request<string[]>('deckNames') if (!decks?.includes(this.config.deckName)) { throw new Error('deck') } const noteTypes = await this.request<string[]>('modelNames') if (!noteTypes?.includes(this.config.noteType)) { throw new Error('notetype') } } handleMessage = (msg: Message) => { switch (msg.type) { case 'ANKI_CONNECT_FIND_WORD': return this.findNote(msg.payload).catch(() => '') case 'ANKI_CONNECT_UPDATE_WORD': return this.updateWord(msg.payload.cardId, msg.payload.word).catch(e => Promise.reject(e) ) } } onStart() { message.addListener(this.handleMessage) } async destroy() { message.removeListener(this.handleMessage) } async findNote(date: number): Promise<number | undefined> { if (!this.noteFileds) { this.noteFileds = await this.getNotefields() } try { const notes = await this.request<number[]>('findNotes', { query: `deck:${this.config.deckName} ${this.noteFileds[0]}:${date}` }) return notes[0] } catch (e) { if (process.env.DEBUG) { console.error(e) } } } async add({ words, force }: AddConfig) { if (!(await this.isServerUp())) { throw new Error('server') } if (force) { words = await getNotebook() } if (!words || words.length <= 0) { return } await Promise.all( words.map(async word => { if (!(await this.findNote(word.date))) { try { await this.addWord(word) } catch (e) { if (process.env.DEBUG) { console.warn(e) } throw new Error('add') } } }) ) if (this.config.syncServer) { try { await this.request('sync') } catch (e) { if (process.env.DEBUG) { console.warn(e) } } } } async addWord(word: Readonly<Word>) { return this.request<number | null>('addNote', { note: { deckName: this.config.deckName, modelName: this.config.noteType, options: { allowDuplicate: false, duplicateScope: 'deck' }, tags: this.extractTags(), fields: await this.wordToFields(word) } }) } async updateWord(noteId: number, word: Readonly<Word>) { return this.request('updateNoteFields', { note: { id: noteId, fields: await this.wordToFields(word) } }) } async addDeck() { return this.request('createDeck', { deck: this.config.deckName }) } async addNoteType() { this.noteFileds = [ 'Date', 'Text', 'Translation', 'Context', 'ContextCloze', 'Note', 'Title', 'Url', 'Favicon', 'Audio' ] await this.request('createModel', { modelName: this.config.noteType, inOrderFields: this.noteFileds, css: cardCss(), cardTemplates: [ { Name: 'Saladict Cloze', Front: cardText(true, this.noteFileds), Back: cardText(false, this.noteFileds) } ] }) // Anki Connect could tranlate the field names // Update again this.noteFileds = await this.getNotefields() await this.request('updateModelTemplates', { model: { name: this.config.noteType, templates: { 'Saladict Cloze': { Front: cardText(true, this.noteFileds), Back: cardText(false, this.noteFileds) } } } }) } async request<R = void>(action: string, params?: any): Promise<R> { const { data } = await axios({ method: 'post', url: `http://${this.config.host}:${this.config.port}`, data: { key: this.config.key || null, version: 6, action, params: params || {} } }) if (process.env.DEBUG) { console.log(`Anki Connect ${action} response`, data) } if (!data || !Object.prototype.hasOwnProperty.call(data, 'result')) { throw new Error('Deprecated Anki Connect version') } if (data.error) { throw new Error(data.error) } return data.result } async wordToFields(word: Readonly<Word>): Promise<{ [k: string]: string }> { if (!this.noteFileds) { this.noteFileds = await this.getNotefields() } return { // Date [this.noteFileds[0]]: `${word.date}`, // Text [this.noteFileds[1]]: word.text || '', // Translation [this.noteFileds[2]]: this.parseTrans( word.trans, this.config.escapeTrans ), // Context [this.noteFileds[3]]: this.multiline( word.context, this.config.escapeContext ), // ContextCloze [this.noteFileds[4]]: this.multiline( word.context.split(word.text).join(`{{c1::${word.text}}}`), this.config.escapeContext ) || `{{c1::${word.text}}}`, // Note [this.noteFileds[5]]: this.multiline(word.note, this.config.escapeNote), // Title [this.noteFileds[6]]: word.title || '', // Url [this.noteFileds[7]]: word.url || '', // Favicon [this.noteFileds[8]]: word.favicon || '', // Audio [this.noteFileds[9]]: '' // @TODO } } async getNotefields(): Promise<string[]> { const nf = await this.request<string[]>('modelFieldNames', { modelName: this.config.noteType }) // Anki connect bug return nf?.includes('Date.') ? [ 'Date.', 'Text.', 'Translation.', 'Context.', 'ContextCloze.', 'Note.', 'Title.', 'Url.', 'Favicon.', 'Audio.' ] : nf?.includes('日期') ? [ '日期', '文字', 'Translation', 'Context', 'ContextCloze', '笔记', 'Title', 'Url', 'Favicon', 'Audio' ] : [ 'Date', 'Text', 'Translation', 'Context', 'ContextCloze', 'Note', 'Title', 'Url', 'Favicon', 'Audio' ] } multiline(text: string, escape: boolean): string { text = text.trim() if (!text) return '' if (escape) { text = this.escapeHTML(text) } return text.trim().replace(/\n/g, '<br/>') } parseTrans(text: string, escape: boolean): string { text = text.trim() if (!text) return '' const ctx = parseCtxText(text) const ids = Object.keys(ctx) if (ids.length <= 0) { return this.multiline(text, escape) } const trans = ids .map( id => `<span class="trans_title">${id}</span><div class="trans_content">${ctx[id]}</div>` ) .join('') return text .split(/\[:: \w+ ::\](?:[\s\S]+?)(?:-{15})/) .map(text => this.multiline(text, escape)) .join(`<div class="trans">${trans}</div>`) } private _div: HTMLElement | undefined escapeHTML(text: string): string { if (!this._div) { this._div = document.createElement('div') this._div.appendChild(document.createTextNode('')) } this._div.firstChild!.nodeValue = text return this._div.innerHTML } extractTags(): string[] { return this.config.tags .split(/,|,/) .map(t => t.trim()) .filter(Boolean) } async isServerUp(): Promise<boolean> { try { return (await this.request<number>('version')) != null } catch (e) { if (process.env.DEBUG) { console.error(e) } return false } } } function cardText(front: boolean, nf: string[]) { return `{{#${nf[4]}}} <section>{{cloze:${nf[4]}}}</section> <section>{{{{type:cloze:${nf[4]}}}</section> {{#${nf[2]}}} <section>{{${nf[2]}}}</section> {{/${nf[2]}}} {{/${nf[4]}}} {{^${nf[4]}}} <h1>{{${nf[1]}}}</h1> {{#${nf[2]}}} <section>{{${nf[2]}}}</section> {{/${nf[2]}}} {{/${nf[4]}}} {{#${nf[5]}}} <section>{{${(front ? 'hint:' : '') + nf[5]}}}</section> {{/${nf[5]}}} {{#${nf[6]}}} <section class="tsource"> <hr /> {{#${nf[8]}}}<img src="{{${nf[8]}}}" />{{/${nf[8]}}} <a href="{{${nf[7]}}}">{{${nf[6]}}}</a> </section> {{/${nf[6]}}} ` } function cardCss() { return `.card { font-family: arial; font-size: 20px; text-align: center; color: #333; background-color: white; } a { color: #5caf9e; } input { border: 1px solid #eee; } section { margin: 1em 0; } .trans { border: 1px solid #eee; padding: 0.5em; } .trans_title { display: block; font-size: 0.9em; font-weight: bold; } .trans_content { margin-bottom: 0.5em; } .cloze { font-weight: bold; color: #f9690e; } .tsource { position: relative; font-size: .8em; } .tsource img { height: .7em; } .tsource a { text-decoration: none; } .typeGood { color: #fff; background: #1EBC61; } .typeBad { color: #fff; background: #F75C4C; } .typeMissed { color: #fff; background: #7C8A99; } ` }
the_stack
'use strict'; import fs = require('../commons/fileSystem'); import FileSystem = require('../main/fileSystem'); import bracketsMock = require('./bracketsMock'); import d = bracketsMock.d; import f = bracketsMock.f; describe('FileSystem', function() { var fileSystem: FileSystem, fileSystemMock: bracketsMock.FileSystem, rootDir: bracketsMock.Directory, projectManager: bracketsMock.ProjectManager; beforeEach(function () { rootDir = d({ name: '/', children : [ f({ name: 'file1.ts', content: 'File1 content' }), f({ name: 'file2.ts', content: 'File2 content' }), d({ name : 'subdir1/', children: [ f({ name: 'file3.ts', content: 'File3 content' }) ] }), d({ name : 'subdir2/', children: [ f({ name: 'file4.ts', content: 'File4 content' }), f({ name: 'file5.ts', content: 'File5 content' }), d({ name : 'subdir3/', children: [ f({ name: 'file6.ts', content: 'File6 content' }), f({ name: 'file7.ts', content: 'File7 content\r\nline2\nline3\r\nline4' }), d({ name: 'subdir4/', children: [] }) ] }) ] }) ] }); fileSystemMock = new bracketsMock.FileSystem(rootDir); projectManager = new bracketsMock.ProjectManager(fileSystemMock); fileSystem = new FileSystem(<any>fileSystemMock, <any>projectManager); }); describe('getProjectFiles', function() { it('should return a list of the project files paths', function () { var files: string[]; fileSystem.getProjectFiles().then(result => files = result); waitsFor(() => !!files, 'files should be set', 20); runs(() => expect(files).toEqual([ '/file1.ts', '/file2.ts', '/subdir1/file3.ts', '/subdir2/file4.ts', '/subdir2/file5.ts', '/subdir2/subdir3/file6.ts', '/subdir2/subdir3/file7.ts' ])); }); }); describe('readFile', function () { it('should return the file content', function () { var content: string; fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { expect(content).toBe('File6 content'); }); }); it('should normalize the file content', function () { var content: string; fileSystem.readFile('/subdir2/subdir3/file7.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { expect(content).toBe('File7 content\nline2\nline3\nline4'); }); }); it('should return an error if underlying file system return an error', function () { var error: string; fileSystem.readFile('/subdir2/subdir3/file8.ts').then(undefined, (e?: string) => error = e); waitsFor(() => !!error, 'error should be set'); runs(() => { expect(error).toBe(bracketsMock.FILE_NOT_FOUND); }); }); it('should return an error if the file is a directory', function () { var error: string; fileSystem.readFile('/subdir2/subdir3').then(undefined, (e?: string) => error = e); waitsFor(() => !!error, 'error should be set'); runs(() => { expect(error).toBe(bracketsMock.FILE_NOT_FOUND); }); }); it('should cache files content', function () { var spy = spyOn(fileSystemMock, 'getFileForPath').andCallThrough(), content: string; fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => !!content, 'file should be read', 20); runs(() => { fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => expect(data).toBe(content)); expect(spy.callCount).toBe(1); expect(content).toBe('File6 content'); }); }); it('should update cached files when they are updated', function () { var content: string; fileSystem.readFile('/subdir2/subdir3/file6.ts'); fileSystemMock.updateFile('/subdir2/subdir3/file6.ts', 'new content'); fileSystem.readFile('/subdir2/subdir3/file6.ts').then(data => content = data); waitsFor(() => content === 'new content', 'file should be read', 20); runs(() => { expect(content).toBe('new content'); }); }); }); describe('change dispatching', function () { var changeSpy = jasmine.createSpy('changeSpy'); beforeEach(() => { fileSystem.projectFilesChanged.add(changeSpy); //initilize the caching fileSystem.getProjectFiles(); }); afterEach(function () { changeSpy.reset(); }); it('should dispatch an event when a file is updated', function () { fileSystemMock.updateFile('/subdir2/file4.ts', 'New content'); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.UPDATE, fileName: '/subdir2/file4.ts' }]); }); }); it('should ispatch an event when a file is deleted', function () { fileSystemMock.deleteEntry('/subdir2/file4.ts'); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' }]); }); }); it('should dispatch an event when a file is added', function () { fileSystemMock.addEntry(f({ name : 'file8.ts', content : 'File8 Content' }, '/subdir2/file8.ts', '/subdir2/')); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.ADD, fileName: '/subdir2/file8.ts' }]); }); }); it('should dispatch an event when a non empty directory is deleted', function () { fileSystemMock.deleteEntry('/subdir2/'); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file5.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' }]); }); }); it('should not dispatch an event when an empty directory is deleted', function () { fileSystemMock.deleteEntry('/subdir2/subdir3/subdir4/'); waits(20); runs(function () { expect(changeSpy.callCount).toBe(0); }); }); it('should dispatch an event when a non empty directory is added', function () { var dir = d({ name: 'subdir5/', children: [ f({ name: 'file8.ts', content: 'File 8 content' }), f({ name: 'file9.ts', content: 'File 9 content' }), d({ name: 'subdir6/', children: [ f({ name: 'file10.ts', content: 'File 10 content' }), d({ name: 'subdir7/', children: [] }) ] }) ] }); dir.setParent(fileSystemMock.getEntryForFile('/subdir1/', 'directory')); fileSystemMock.addEntry(dir); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/file8.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/file9.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir1/subdir5/subdir6/file10.ts' }]); }); }); it('should not dispatch an event when an empty directory is added', function () { var dir = d({ name: 'subdir5/', children: [] }); dir.setParent(fileSystemMock.getEntryForFile('/subdir1/', 'directory')); fileSystemMock.addEntry(dir); waits(20); runs(function () { expect(changeSpy.callCount).toBe(0); }); }); it('should dispatch an event containing all file that have been deleted/added', function () { var file5Content: string, file3Content: string; fileSystem.readFile('/subdir2/file5.ts').then(result => file5Content = result); fileSystem.readFile('/subdir1/file3.ts').then(result => file3Content = result); waitsFor(() => !!file3Content && !!file5Content, 'files should have been read', 20); runs(function () { fileSystemMock.refresh(d({ name: '/', children : [ f({ name: 'file2.ts', content: 'File2 content has changed' }), f({ name: 'file8.ts', content: 'File8 content' }), d({ name : 'subdir1/', children: [ f({ name: 'file3.ts', content: 'File3 content' }) ] }), d({ name : 'subdir2/', children: [ f({ name: 'file4.ts', content: 'File4 content' }), f({ name: 'file5.ts', content: 'File5 content has changed' }) ] }), d({ name : 'subdir3/', children: [ f({ name: 'file6.ts', content: 'File6 content' }), f({ name: 'file7.ts', content: 'File7 content\r\nline2\nline3\r\nline4' }), d({ name: 'subdir4/', children: [] }) ] }) ] })); }); waitsFor(() => changeSpy.callCount !== 0, 'change spy should have been called'); runs(function () { expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/file1.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/file8.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir3/file6.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir3/file7.ts' }, { kind: fs.FileChangeKind.UPDATE, fileName: '/subdir2/file5.ts' }]); }); }); it('should dispatch an event with a delete record and an add record when a file has been renamed', function () { var files: string[]; fileSystemMock.renameFile('/subdir2/file4.ts', '/subdir2/newFile.ts'); expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir2/newFile.ts' }]); fileSystem.getProjectFiles().then(result => files = result); waitsFor(() => !!files, 'files should be set', 20); runs(() => expect(files).toEqual([ '/file1.ts', '/file2.ts', '/subdir1/file3.ts', '/subdir2/file5.ts', '/subdir2/subdir3/file6.ts', '/subdir2/subdir3/file7.ts', '/subdir2/newFile.ts' ])); }); it('should update the cache when a file has been renamed', function () { var spy = spyOn(fileSystemMock, 'getFileForPath').andCallThrough(), content: string, newContent: string; fileSystem.readFile('/subdir2/file4.ts').then(result => content = result); waitsFor(() => !!content, 'file should be read', 20); runs(() => { fileSystemMock.renameFile('/subdir2/file4.ts', '/subdir2/newFile.ts'); }); waits(20); runs(() => { fileSystem.readFile('/subdir2/newFile.ts').then(result => newContent = result); }); waitsFor(() => !!newContent, 'file should be read', 20); runs(() => { expect(spy.callCount).toBe(1); expect(content).toBe(newContent); }); }); it('should dispatch an event with a delete record and an add fo reach file subfile of ' + 'the directory when a directory has been renamed', function () { fileSystemMock.renameFile('/subdir2/', '/subdir4/'); waits(20); runs(function () { expect(changeSpy.callCount).toBe(1); expect(changeSpy).toHaveBeenCalledWith([{ kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file4.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/file4.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/file5.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/file5.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file6.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/subdir3/file6.ts' }, { kind: fs.FileChangeKind.DELETE, fileName: '/subdir2/subdir3/file7.ts' }, { kind: fs.FileChangeKind.ADD, fileName: '/subdir4/subdir3/file7.ts' }]); }); }); }); describe('initilaization stack', function () { it('should cache every call to getProjectFiles/readFile during inialization, and resolve them afterward', function () { projectManager.async = true; fileSystem.reset(); var spy = spyOn(fileSystem, 'resolveInitializationStack').andCallThrough(), files: string[], content: string; fileSystem.getProjectFiles().then(result => files = result); fileSystem.readFile('/file1.ts').then(result => content = result); waitsFor(() => !!files && !!content, 'operation should have been resolved', 100); runs(() => { expect(spy).toHaveBeenCalled(); expect(files).toEqual([ '/file1.ts', '/file2.ts', '/subdir1/file3.ts', '/subdir2/file4.ts', '/subdir2/file5.ts', '/subdir2/subdir3/file6.ts', '/subdir2/subdir3/file7.ts' ]); expect(content).toBe('File1 content'); }); }); }); });
the_stack
import { relative } from 'path'; import type webpack from 'webpack'; import type { Compiler, Module } from 'webpack'; import { parse } from 'semver'; import chalk from 'chalk'; const cwd = process.cwd(); declare module 'webpack' { export interface Module { // абсолютный путь к ресурсу resource: string; } } export interface NMFResult { // описание package.json либы, из которой импортим какой-то модуль resourceResolveData?: { // само описание package.json descriptionFileData?: { // имя либы name?: string; // версия либы version?: string; }; // путь к файлу который импортируем, относительно package.json либы relativePath?: string; }; } export type DeduplicateStrategy = 'equality' | 'semver'; const PLUGIN_NAME = 'DedupePlugin'; export class DedupePlugin { private readonly strategy: DeduplicateStrategy; private readonly ignorePackages?: RegExp[]; private cache: Map<string, Set<string>> = new Map(); private versions: Map<string, string> = new Map(); private logs: Map< string, { name: string; toVersion: string; toPath: string; deduped: Array<{ fromVersion: string; fromPath: string }>; } > = new Map(); constructor(strategy: DeduplicateStrategy, ignorePackages?: RegExp[]) { this.strategy = strategy; this.ignorePackages = ignorePackages; } // функция проверяет находится ли данный модуль в списке исключений isIgnoredModule(result: NMFResult) { if (!this.ignorePackages) { return false; } const name = getResourceName(result); if (!name) { return false; } for (const regexp of this.ignorePackages) { if (regexp.test(name)) { return true; } } return false; } // собираем в один сет модули под одним ключом addToCache(key: string, module: Module) { const id = module.identifier(); if (this.cache.has(key)) { this.cache.get(key).add(id); } else { this.cache.set(key, new Set([id])); } } // нам нужно запомнить версию библиотеки, т.к. в самих модулях эта информация не хранится setVersion(module: Module, version: string) { this.versions.set(module.identifier(), version); } compareModuleVersions(module1: Module, module2: Module) { const version1 = this.versions.get(module1.identifier()); const version2 = this.versions.get(module2.identifier()); return parse(version1).compare(version2); } // из двух модулей выбирает один по следующии принципам // 1. модуль у которого версия выше по семверу // 2. модуль у которого путь к файлу самый короткий // 3. если все выше равно, просто сравниваем через сравнение строк лексикографически pickBetterModule(module1: Module, module2: Module) { const versionCompare = this.compareModuleVersions(module1, module2); if (versionCompare > 0) { return module1; } if (versionCompare < 0) { return module2; } const pathLengthDiff = module1.resource.length - module2.resource.length || module1.resource.localeCompare(module2.resource); if (pathLengthDiff > 0) { return module2; } return module1; } // создать маппинг модуль -> модуль в который должен дедуплицироваться данный модуль deduplicateCache(compilation: webpack.Compilation) { const dedupLinks = new WeakMap<Module, Module>(); for (const [k, v] of this.cache) { if (v.size <= 1) { // игнорируем список где один модуль, т.к. это не дедуплицируется =) continue; } let bestModule: Module; for (const moduleId of v) { const module = compilation.findModule(moduleId); bestModule = bestModule ?? module; bestModule = this.pickBetterModule(bestModule, module); } for (const moduleId of v) { const module = compilation.findModule(moduleId); // для всех модулей в множестве выставляем ссылку на модуль в который все они должны дедуплицироваться if (module !== bestModule) { dedupLinks.set(module, bestModule); // запоминаем выбор лучшего модуля на будущее для логирования this.logDeduplicationInfo(k, module, bestModule); } } } return dedupLinks; } // получить оптимизированный список модулей optimizeModules(compilation: webpack.Compilation) { const { modules, moduleGraph } = compilation; const dedupLinks = this.deduplicateCache(compilation); for (const module of modules) { if (dedupLinks.has(module)) { const deduped = dedupLinks.get(module as Module); // удаляем текущий модуль из компиляции - его место займет deduped modules.delete(module); moduleGraph.moveModuleConnections(module, deduped, (connection) => { // переносим только связи которые идут в дедуплицированный модуль // т.о. все связи будут направлены в один лучший модуль, а отброшенные не будут ни с чем связаны return connection.originModule !== module; }); } } } apply(compiler: Compiler) { let called = false; // этот хук будет вызываться при каждом создании компилятора, но это создает дубли модулей, // с которыми пока непонятно что делать, поэтому просто игнорируем childCompiler compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => { if (called) { return; } called = true; nmf.hooks.module.tap(PLUGIN_NAME, (module: Module, result: NMFResult) => { // игнорируем все что вне node_modules, т.к. вряд-ли это нужно дедуплицировать или если модуль игнорируем if (!module.resource.includes('node_modules') || this.isIgnoredModule(result)) { return; } const cacheKey = createCacheKeyFromNMFResult(result, this.strategy === 'semver'); // что же, на удивление, некоторые пакеты в node_modules не имеют имени или версии в описании // привет, https://github.com/babel/babel/blob/main/packages/babel-runtime/helpers/esm/package.json if (cacheKey) { this.addToCache(cacheKey, module); this.setVersion(module, getResourceVersion(result)); } return module; }); }); // thisCompilation вызывается только один раз, в рутовом компиляторе // а compilation вызывается для каждого компилятора, пока фокусируемся только на рутовом // привет, https://github.com/faceyspacey/extract-css-chunks-webpack-plugin/blob/master/src/loader.js#L82 compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, () => { this.optimizeModules(compilation); }); }); // done также вызывается только в рутовом компиляторе compiler.hooks.done.tap(PLUGIN_NAME, () => { this.flushLogs(); }); } logDeduplicationInfo(cacheKey: string, fromModule: Module, toModule: Module) { const splitted = cacheKey.split('@'); const fromVersion = this.versions.get(fromModule.identifier()); const toVersion = this.versions.get(toModule.identifier()); const fromPath = getRelativePathFromCwd(fromModule.resource); const toPath = getRelativePathFromCwd(toModule.resource); // учитываем scoped пакеты const name = splitted[0] || `@${splitted[1]}`; const key = `${name}@${toVersion}:${toPath}`; let { deduped } = this.logs.get(key) ?? {}; if (!deduped) { deduped = []; this.logs.set(key, { name, toVersion, toPath, deduped, }); } deduped.push({ fromVersion, fromPath, }); } flushLogs() { const keys = [...this.logs.keys()].sort(); let log = `\n${chalk.blue('Deduplicated modules:')}\n`; for (const key of keys) { const { name, toVersion, toPath, deduped } = this.logs.get(key); log += `\tDeduped to ${chalk.cyanBright(name)}@${chalk.green(toVersion)}:${chalk.bgGray( toPath )}\n`; for (const { fromPath, fromVersion } of deduped) { log += `\t\tfrom ${chalk.red(fromVersion)}:${chalk.bgGray(fromPath)}\n`; } log += '\n'; } if (keys.length === 0) { log += ' no duplicates found'; } console.warn(log); } } export function createDedupePlugin(strategy: DeduplicateStrategy, ignorePackages?: RegExp[]) { return new DedupePlugin(strategy, ignorePackages); } export function createCacheKeyFromNMFResult( nmfResult: NMFResult, useSemver = false ): string | null { const name = getResourceName(nmfResult); const version = getResourceVersion(nmfResult); if (!name || !version) { return null; } // если semver то используем только мажорную версию пакета // если нет, то оставляем полную версию const versionForCache = useSemver ? buildCacheVersionFromNMFResult(nmfResult) : version; // ключ = имя + версия + путь к исходному файлу относительно корня либы return `${name}@${versionForCache}:${nmfResult.resourceResolveData.relativePath}`; } /** * Получаем основную версию для зависимости по правилу semver `^version` * * Когда major версия равна 0, считаем что minor версия является мажорной. * Если и minor версия равна 0, считаем что patch версия является мажорной. */ function buildCacheVersionFromNMFResult(nmfResult: NMFResult): string { const version = getResourceVersion(nmfResult); const semver = parse(version); const majorVersion = String(semver.major); const minorVersion = `0.${semver.minor}`; const patchVersion = `0.0.${semver.patch}`; const minor = semver.minor ? minorVersion : patchVersion; return semver.major ? majorVersion : minor; } // получаем поле `name` из package.json function getResourceName(nmfResult: NMFResult) { return nmfResult?.resourceResolveData?.descriptionFileData?.name; } // получаем поле `version` из package.json function getResourceVersion(nmfResult: NMFResult) { return nmfResult?.resourceResolveData?.descriptionFileData?.version; } // получаем относительный путь от корня вместо абсолютного function getRelativePathFromCwd(path: string) { return relative(cwd, path); }
the_stack
import { ChangeDetectorRef, Component, ElementRef, Input, OnInit, Type, ViewChild } from '@angular/core'; import { Graph, Edge, Shape, NodeView, Cell, Color } from '@antv/x6'; import { STColumn, STColumnTag, STComponent, STData } from '@delon/abc/st'; import { SettingsService } from '@delon/theme'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-devicegraph', templateUrl: './devicegraph.component.html', styleUrls: ['./devicegraph.component.less'], }) export class DevicegraphComponent implements OnInit { selectedstyle = { body: { stroke: '#00ff00', strokeWidth: 5, }, }; selcetedDevice: any = { ports: { in: [], }, }; ports: port[] = []; TAG: STColumnTag = { 1: { text: '以太网', color: 'green' }, 2: { text: 'RS232', color: 'blue' }, 3: { text: 'RS485', color: 'orange' }, }; columns: STColumn[] = [ { title: '名称', index: 'portname', render: 'portNameTpl' }, { title: 'IO类型', index: 'iotype', render: 'portTypeTpl' }, { title: '类型', index: 'type', render: 'portPhyTypeTpl', type: 'enum', enum: { 1: '壹', 2: '贰', 3: '叁' }, }, { title: '操作', buttons: [ { text: `修改`, iif: (i) => !i.edit, click: (i) => this.updateEdit(i, true), }, { text: `保存`, iif: (i) => i.edit, click: (i) => { this.submit(i); }, }, { text: `取消`, iif: (i) => i.edit, click: (i) => this.updateEdit(i, false), }, ], }, ]; subscription: Subscription; droppedData: string; @Input() id: Number = -1; @ViewChild('container', { static: true }) private container!: ElementRef; @ViewChild('st') private st: STComponent; //左侧未在设计上的设备和网关的列表数据,自己有时间搞Shape,可以用官方的dnd(https://x6.antv.vision/zh/docs/tutorial/basic/dnd),不然就手动吧 data: Array<DeviceItem> = [ { devicename: '设备1', id: '11', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 1, type: 1, iotype: 1 }], }, }, { devicename: '设备2', id: '22', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 2, type: 1, iotype: 1 }], }, }, { devicename: '设备3', id: '33', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 3, type: 1, iotype: 1 }], }, }, { devicename: '网关1', id: '44', type: 'gateway', logo: 'ungroup', image: './assets/logo.png', remark: '这是一个网关,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [ { portname: 'port11', id: '4', type: 1, iotype: 1 }, { portname: 'port2', id: '5', type: 1, iotype: 1 }, { portname: 'port3', id: '6', type: 1, iotype: 1 }, { portname: 'port4', id: '7', type: 1, iotype: 1 }, { portname: 'port5', id: '8', type: 1, iotype: 1 }, { portname: 'port6', id: '9', type: 1, iotype: 1 }, { portname: 'port7', id: '10', type: 1, iotype: 1 }, ], out: [ { portname: 'port11', id: '11', type: 1, iotype: 1 }, { portname: 'port2', id: '12', type: 1, iotype: 1 }, { portname: 'port3', id: '13', type: 1, iotype: 1 }, { portname: 'port4', id: '14', type: 1, iotype: 1 }, { portname: 'port5', id: '15', type: 1, iotype: 1 }, { portname: 'port6', id: '16', type: 1, iotype: 1 }, { portname: 'port7', id: '17', type: 1, iotype: 1 }, ], }, }, { devicename: '网关2', id: '55', type: 'gateway', logo: 'ungroup', image: './assets/logo.png', remark: '这是一个网关,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [ { portname: 'port1', id: 18, type: 1, iotype: 1 }, { portname: 'port2', id: 19, type: 1, iotype: 1 }, { portname: 'port3', id: 20, type: 1, iotype: 1 }, { portname: 'port4', id: 21, type: 1, iotype: 1 }, { portname: 'port5', id: 22, type: 1, iotype: 1 }, { portname: 'port6', id: 23, type: 1, iotype: 1 }, { portname: 'port7', id: 24, type: 1, iotype: 1 }, ], out: [ { portname: 'port1', id: 25, type: 1, iotype: 1 }, { portname: 'port2', id: 26, type: 1, iotype: 1 }, { portname: 'port3', id: 27, type: 1, iotype: 1 }, { portname: 'port4', id: 28, type: 1, iotype: 1 }, { portname: 'port5', id: 29, type: 1, iotype: 1 }, { portname: 'port6', id: 30, type: 1, iotype: 1 }, { portname: 'port7', id: 31, type: 1, iotype: 1 }, ], }, }, { devicename: '设备4', id: '66', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 32, type: 1, iotype: 1 }] }, }, { devicename: '设备5', id: '77', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 33, type: 1, iotype: 1 }] }, }, { devicename: '设备6', id: '88', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 34, type: 1, iotype: 1 }] }, }, { devicename: '设备7', id: '99', type: 'device', logo: 'control', image: './assets/logo.png', remark: '这是一个设备,拖动它放到设计器上', prop: { GraphStroke: '#d9d9d9', GraphStrokeWidth: 1, GraphTextFill: '', GraphTextFontSize: '', GraphPostionX: '', GraphPostionY: '', GraphFill: '', GraphTextRefX: '', GraphHeight: '', GraphTextRefY: '', GraphTextAnchor: '', GraphTextVerticalAnchor: '', GraphTextFontFamily: '', GraphWidth: '', GraphShape: '', }, ports: { in: [{ portname: 'port1', id: 35, type: 1, iotype: 1 }] }, }, ]; graph!: Graph; magnetAvailabilityHighlighter = { name: 'stroke', args: { attrs: { fill: '#fff', stroke: '#47C769', }, }, }; toolbtnclick = ({ cell }) => { this.data = [...this.data, cell.getProp('Biz')]; //设计器删除的设备返回设备列表 this.graph.removeCell(cell); }; tools: any = [ { name: 'button', args: { markup: [ { tagName: 'circle', selector: 'button', attrs: { r: 14, stroke: '#fe854f', strokeWidth: 2, fill: 'white', cursor: 'pointer', }, }, { tagName: 'text', textContent: '-', selector: 'icon', attrs: { fill: '#fe854f', fontSize: 24, textAnchor: 'middle', pointerEvents: 'none', y: '0.3em', }, }, ], x: '50%', y: '10%', offset: { x: -0, y: -0 }, onClick: this.toolbtnclick, //闭包了哟 }, }, ]; constructor(cdr: ChangeDetectorRef, private settingService: SettingsService) { } newport(id) { this.selcetedDevice.ports.in = [...this.selcetedDevice.ports.in, { id: '0', portname: '新端口', type: 1, iotype: 1 }]; console.log(this.selcetedDevice.ports.in); } private submit(i: STData): void { this.updateEdit(i, false); } private updateEdit(i: STData, edit: boolean): void { this.st.setRow(i, { edit }, { refreshSchema: true }); } ngOnInit(): void { this.graph = new Graph({ background: { color: '' }, autoResize: true, grid: true, container: this.container.nativeElement, height: 800, highlighting: { magnetAvailable: this.magnetAvailabilityHighlighter, magnetAdsorbed: { name: 'stroke', args: { attrs: { fill: '#fff', stroke: '#31d0c6', }, }, }, }, onPortRendered: (args) => { }, connecting: { snap: true, allowBlank: false, allowLoop: false, highlight: true, connector: 'rounded', connectionPoint: 'boundary', router: { name: 'er', args: { direction: 'H', }, }, createEdge() { return new Shape.Edge({ attrs: { line: { stroke: '#a0a0a0', strokeWidth: 1, targetMarker: { name: 'classic', size: 7, }, }, }, }); }, validateConnection({ sourceView, targetView, targetMagnet }) { if (!targetMagnet) { return false; } if (targetMagnet.getAttribute('port-group') !== 'in') { return false; } if (targetView) { const node = targetView.cell; if (node instanceof Device) { const portId = targetMagnet.getAttribute('port'); const usedInPorts = node.getUsedInPorts(this); if (usedInPorts.find((port) => port && port.id === portId)) { return false; } } } return true; }, }, }); this.graph.on('edge:connected', ({ previousView, currentView }) => { if (previousView) { this.update(previousView as NodeView); } if (currentView) { this.update(currentView as NodeView); } }); this.graph.on('blank:mousemove', ({ e }) => { this.dragEndlocation = e; }); this.graph.on('edge:removed', ({ edge, options }) => { if (!options.ui) { return; } const target = edge.getTargetCell(); if (target instanceof Device) { target.updateInPorts(this.graph); } console.log(target); }); this.graph.on('edge:mouseenter', ({ edge }) => { edge.addTools([ 'source-arrowhead', 'target-arrowhead', { name: 'button-remove', args: { distance: -30, }, }, ]); }); this.graph.on('cell:mousedown', ({ cell }) => { // cell.removeTools(); //只读状态下移除Node中的操作按钮 }); this.graph.on('node:click', (e) => { var matadata = e.node.getProp('Biz'); this.graph.getNodes; for (var item of this.graph.getNodes()) { var _matadata = e.node.getProp('Biz'); item.attr({ root: { magnet: false, }, body: { fill: '#eeffee', stroke: _matadata.prop.GraphStroke, strokeWidth: _matadata.prop.GraphStrokeWidth, }, }); } e.cell.attr(this.selectedstyle); this.selcetedDevice = matadata; }); } update(view: NodeView) { const cell = view.cell; if (cell instanceof Device) { cell.getInPorts().forEach((port) => { const portNode = view.findPortElem(port.id!, 'portBody'); view.unhighlight(portNode, { highlighter: this.magnetAvailabilityHighlighter, }); }); cell.updateInPorts(this.graph); } } dragend($event) { } onDrop($event) { switch ($event.dropData.type) { case 'device': var ports = []; if ($event.dropData.ports.in) { for (var item of $event.dropData.ports.in) { var port = { id: item.id, group: 'in', zIndex: 'auto', attrs: { text: { // 标签选择器 text: item.portname, // 标签文本 }, }, }; ports = [...ports, port]; } } if ($event.dropData.ports.out) { for (var item of $event.dropData.ports.out) { var port = { id: item.id, group: 'out', zIndex: 'auto', attrs: { text: { // 标签选择器 text: item.portname, // 标签文本 }, }, }; ports = [...ports, port]; } } var data = { label: $event.dropData.devicename, height: 80, width: 160, tools: this.tools, offsetX: this.dragEndlocation.offsetX, offsetY: this.dragEndlocation.offsetY, Biz: $event.dropData, portdata: { group: { in: { label: { position: 'left', }, position: { name: 'right', }, attrs: { portBody: { magnet: 'passive', r: 6, stroke: '#ff0000', fill: '#fff', strokeWidth: 2, }, }, }, out: { position: { name: 'left', }, label: { position: 'right', }, attrs: { portBody: { magnet: true, r: 6, fill: '#fff', stroke: '#3199FF', strokeWidth: 2, }, }, }, }, ports: ports, }, }; this.createshape(data); break; case 'gateway': // var node = this.graph.addNode( // new GateWay({ // label: $event.dropData.devicename, // tools: this.tools, // }) // .setProp('Biz', $event.dropData) // .resize(160, 200) // .position(this.dragEndlocation.offsetX, this.dragEndlocation.offsetY) // .updateInPorts(this.graph), // ); // node.setPortLabelMarkup; // this.data.splice(this.data.indexOf($event.dropData), 1); var ports = []; for (var item of $event.dropData.ports.in) { var port = { id: item.id, group: 'in', zIndex: 'auto', attrs: { text: { // 标签选择器 text: item.portname, // 标签文本 }, }, }; ports = [...ports, port]; } for (var item of $event.dropData.ports.out) { var port = { id: item.id, group: 'out', zIndex: 'auto', attrs: { text: { // 标签选择器 text: item.portname, // 标签文本 }, }, }; ports = [...ports, port]; } console.log(ports); var data = { label: $event.dropData.devicename, height: 200, width: 160, tools: this.tools, offsetX: this.dragEndlocation.offsetX, offsetY: this.dragEndlocation.offsetY, Biz: $event.dropData, portdata: { group: { in: { label: { position: 'left', }, position: { name: 'right', }, attrs: { portBody: { magnet: 'passive', r: 6, stroke: '#ff0000', fill: '#fff', strokeWidth: 2, }, }, }, out: { position: { name: 'left', }, label: { position: 'right', }, attrs: { portBody: { magnet: true, r: 6, fill: '#fff', stroke: '#3199FF', strokeWidth: 2, }, }, }, }, ports: ports, }, }; this.createshape(data); break; } } createshape(data: any) { var node = this.graph.addNode( new GateWay({ label: data.label, tools: data.tools, }) .setProp('Biz', data.Biz) .resize(data.width, data.height) .position(this.dragEndlocation.offsetX, this.dragEndlocation.offsetY) .initports(data.portdata) .setAttrs({ root: { magnet: false, }, body: { fill: '#eeffee', stroke: data.Biz.prop.GraphStroke, strokeWidth: data.Biz.prop.GraphStrokeWidth, }, }), // .updateInPorts(this.graph), ); node.setPortLabelMarkup; this.data.splice(this.data.indexOf(data.Biz), 1); } dragEnd(event) { } onmove($event) { this.dragEndlocation = $event; } dragEndlocation: any; load() { } savediagram() { var edges = this.graph.getEdges(); var nodes = this.graph.getNodes(); var shapes = []; var mappings = []; for (var item of nodes) { var port = item.ports.items; var incomes = port.filter((x) => x.group === 'in').map((x) => x.id); var outgoings = port.filter((x) => x.group === 'out').map((x) => x.id); var data = item.getProp('Biz'); var dev = { incomes, outgoings, prop: { position: item.getPosition(), size: item.getSize(), body: item.getAttrs().body, text: item.getAttrs().text, }, id: data.id, type: data.type, }; shapes = [...shapes, dev]; } for (var _item of edges) { var edge = { id: _item.id, source: _item.source, target: _item.target, }; mappings = [...mappings, edge]; } var graph = { shapes, mappings, }; console.log(graph); } } export interface DeviceItem { devicename: string; id: string; type: string; logo: string; image: string; remark: string; prop: any; ports: any; } export interface DeviceInfo { Income: string[]; OutGoing: string[]; Label: string; LocationX: number; LocationY: number; Width: number; Height: number; Type: string; } class Device extends Shape.Rect { getInPorts() { return this.getPortsByGroup('in'); } getOutPorts() { return this.getPortsByGroup('out'); } getUsedInPorts(graph: Graph) { const incomingEdges = graph.getIncomingEdges(this) || []; return incomingEdges.map((edge: Edge) => { const portId = edge.getTargetPortId(); return this.getPort(portId!); }); } getNewInPorts(length: number) { return Array.from( { length, }, () => { return { group: 'in', }; }, ); } updateInPorts(graph: Graph) { const minNumberOfPorts = 1; const ports = this.getInPorts(); const usedPorts = this.getUsedInPorts(graph); const newPorts = this.getNewInPorts(Math.max(minNumberOfPorts - usedPorts.length, 1)); if (ports.length === minNumberOfPorts && ports.length - usedPorts.length > 0) { // noop } else if (ports.length === usedPorts.length) { // this.addPorts(newPorts); } else if (ports.length + 1 > usedPorts.length) { this.prop(['ports', 'items'], this.getOutPorts().concat(usedPorts).concat(newPorts), { rewrite: true, }); } return this; } } Device.config({ label: '', attrs: { root: { magnet: false, }, body: { fill: '#eeffee', stroke: '#d9d9d9', strokeWidth: 1, }, }, ports: { groups: { in: { position: { name: 'right', }, attrs: { portBody: { magnet: 'passive', r: 6, stroke: '#ff0000', fill: '#fff', strokeWidth: 2, }, }, }, out: { position: { name: 'left', }, attrs: { portBody: { magnet: true, r: 6, fill: '#fff', stroke: '#3199FF', strokeWidth: 2, }, }, }, }, }, portMarkup: [ { tagName: 'circle', selector: 'portBody', }, ], }); class GateWay extends Shape.Rect { initports(data: any) { const ports = this.getInPorts(); console.log(data); console.log(this.ports); for (var item of data.ports) { this.addPort(item); } return this; } getInPorts() { return this.getPortsByGroup('in'); } getOutPorts() { return this.getPortsByGroup('out'); } getUsedInPorts(graph: Graph) { const incomingEdges = graph.getIncomingEdges(this) || []; return incomingEdges.map((edge: Edge) => { const portId = edge.getTargetPortId(); return this.getPort(portId!); }); } getNewInPorts(length: number) { return Array.from( { length, }, () => { return { group: 'in', }; }, ); } // updateInPorts(graph: Graph) { // const minNumberOfPorts = 8; // const ports = this.getInPorts(); // const usedPorts = this.getUsedInPorts(graph); // const newPorts = this.getNewInPorts(Math.max(minNumberOfPorts - usedPorts.length, 1)); // if (ports.length === minNumberOfPorts && ports.length - usedPorts.length > 0) { // // noop // } else if (ports.length === usedPorts.length) { // this.addPorts(newPorts); // } else if (ports.length + 1 > usedPorts.length) { // this.prop(['ports', 'items'], this.getOutPorts().concat(usedPorts).concat(newPorts), { // rewrite: true, // }); // } // return this; // } } GateWay.config({ attrs: { root: { magnet: false, }, body: { fill: '#ffa940', stroke: '#d9d9d9', strokeWidth: 1, }, }, ports: { groups: { in: { label: { position: 'left', }, position: { name: 'right', }, attrs: { portBody: { magnet: 'passive', r: 6, stroke: '#ff0000', fill: '#fff', strokeWidth: 2, }, }, }, out: { position: { name: 'left', }, label: { position: 'right', }, attrs: { portBody: { magnet: true, r: 6, fill: '#fff', stroke: '#3199FF', strokeWidth: 2, }, }, }, }, }, portMarkup: [ { tagName: 'circle', selector: 'portBody', }, ], }); export interface port { portid: number; portName: string; portType: number; portPhyType: number; }
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { environment } from './../../../../../../../environments/environment'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { UtilsService } from '../../../../../../shared/services/utils.service'; import { LoggerService } from '../../../../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../../../../shared/services/error-handling.service'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/pairwise'; import { WorkflowService } from '../../../../../../core/services/workflow.service'; import { RouterUtilityService } from '../../../../../../shared/services/router-utility.service'; import { AdminService } from '../../../../../services/all-admin.service'; @Component({ selector: 'app-admin-create-update-target-types', templateUrl: './create-update-target-types.component.html', styleUrls: ['./create-update-target-types.component.css'], providers: [ LoggerService, ErrorHandlingService, AdminService ] }) export class CreateUpdateTargetTypesComponent implements OnInit, OnDestroy { pageTitle: String = ''; breadcrumbArray: any = ['Admin', 'Target Types']; breadcrumbLinks: any = ['policies', 'target-types']; breadcrumbPresent: any; outerArr: any = []; filters: any = []; targetTypes: any = { domain: [], category: [], name: '', desc: '', config: '' }; isCreate: boolean = false; successTitle: String = ''; failedTitle: string = ''; successSubTitle: String = ''; isTargetTypeCreationUpdationFailed: boolean = false; isTargetTypeCreationUpdationSuccess: boolean = false; loadingContent: string = ''; targetTypeLoader: boolean = false; targetTypeName: string = ''; paginatorSize: number = 25; isLastPage: boolean; isFirstPage: boolean; totalPages: number; pageNumber: number = 0; showLoader: boolean = true; errorMessage: any; hideContent: boolean = false; filterText: any = {}; errorValue: number = 0; FullQueryParams: any; queryParamsWithoutFilter: any; urlToRedirect: any = ''; mandatory: any; public labels: any; private previousUrl: any = ''; private pageLevel = 0; public backButtonRequired; private routeSubscription: Subscription; private getKeywords: Subscription; private previousUrlSubscription: Subscription; constructor( private router: Router, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private workflowService: WorkflowService, private routerUtilityService: RouterUtilityService, private adminService: AdminService ) { this.routerParam(); this.updateComponent(); } ngOnInit() { this.urlToRedirect = this.router.routerState.snapshot.url; this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently( this.pageLevel ); } nextPage() { try { if (!this.isLastPage) { this.pageNumber++; this.showLoader = true; //this.getPolicyDetails(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } prevPage() { try { if (!this.isFirstPage) { this.pageNumber--; this.showLoader = true; //this.getPolicyDetails(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } selectedTargetTypeName: string = ''; createTargetType(targetTypes) { this.loadingContent = 'creating'; this.hideContent = true; this.targetTypeLoader = true; this.isTargetTypeCreationUpdationFailed = false; this.isTargetTypeCreationUpdationSuccess= false; let url = environment.createTargetType.url; let method = environment.createTargetType.method; this.selectedTargetTypeName = targetTypes.name; let targetTypeDetails = { domain: targetTypes.domain[0].text, category: targetTypes.category[0].text, name: targetTypes.name, desc: targetTypes.desc, config: targetTypes.config, dataSource: 'aws' } this.adminService.executeHttpAction(url, method, targetTypeDetails, {}).subscribe(reponse => { this.successTitle = 'Target type Created'; this.isTargetTypeCreationUpdationSuccess= true; this.targetTypeLoader = false; this.targetTypes = { domain: [], category: [], name: '', desc: '', config: '' }; }, error => { this.failedTitle = 'Creation Failed'; this.targetTypeLoader = false; this.isTargetTypeCreationUpdationFailed = true; }) } updateTargetType(targetTypes) { this.loadingContent = 'updating'; this.hideContent = true; this.targetTypeLoader = true; this.isTargetTypeCreationUpdationFailed = false; this.isTargetTypeCreationUpdationSuccess= false; let url = environment.updateTargetType.url; let method = environment.updateTargetType.method; this.selectedTargetTypeName = targetTypes.name; let targetTypeDetails = { domain: targetTypes.domain[0].text, category: targetTypes.category[0].text, name: targetTypes.name, desc: targetTypes.desc, config: targetTypes.config, dataSource: 'aws' } this.adminService.executeHttpAction(url, method, targetTypeDetails, {}).subscribe(reponse => { this.successTitle = 'Target type Updated'; this.isTargetTypeCreationUpdationSuccess= true; this.targetTypeLoader = false; this.targetTypes = { domain: [], category: [], name: '', desc: '', config: '' }; }, error => { this.failedTitle = 'Updation Failed'; this.targetTypeLoader = false; this.isTargetTypeCreationUpdationFailed = true; }) } closeErrorMessage() { if(this.failedTitle === 'Loading Failed') { this.getDomainAndCategoryDetails(); } else { this.hideContent = false; } this.isTargetTypeCreationUpdationFailed = false; this.isTargetTypeCreationUpdationSuccess = false; } getData() { //this.getAllPolicyIds(); } /* * This function gets the urlparameter and queryObj *based on that different apis are being hit with different queryparams */ routerParam() { try { // this.filterText saves the queryparam let currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root); if (currentQueryParams) { this.FullQueryParams = currentQueryParams; this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams)); this.targetTypeName = this.queryParamsWithoutFilter.targetTypeName; delete this.queryParamsWithoutFilter['filter']; if (this.targetTypeName) { this.pageTitle = 'Edit Target Type'; this.breadcrumbPresent = 'Edit Target Type'; this.isCreate = false; this.getDomainAndCategoryDetails(); } else { this.pageTitle = 'Create New Target Type'; this.breadcrumbPresent = 'Create Target Type'; this.isCreate = true; this.getDomainAndCategoryDetails(); } /** * The below code is added to get URLparameter and queryparameter * when the page loads ,only then this function runs and hits the api with the * filterText obj processed through processFilterObj function */ this.filterText = this.utils.processFilterObj( this.FullQueryParams ); //check for mandatory filters. if (this.FullQueryParams.mandatory) { this.mandatory = this.FullQueryParams.mandatory; } } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } highlightName: string =''; allDomainDetails: any = []; allCategoryDetails: any = []; getDomainAndCategoryDetails() { this.hideContent = true; this.targetTypeLoader = true; this.loadingContent = 'loading'; this.highlightName = 'Domain and Category details' this.isTargetTypeCreationUpdationFailed = false; this.isTargetTypeCreationUpdationSuccess= false; let url = environment.domains.url; let method = environment.domains.method; this.adminService.executeHttpAction(url, method, {}, {}).subscribe(domainsReponse => { this.allDomainDetails = this.deMarshalDomain(domainsReponse[0]); let targetCategoryUrl = environment.getTargetTypesCategories.url; let targetCategoryMethod = environment.getTargetTypesCategories.method; this.adminService.executeHttpAction(targetCategoryUrl, targetCategoryMethod, {}, {}).subscribe(categoryReponse => { this.allCategoryDetails = categoryReponse[0]; if(this.isCreate) { this.hideContent = false; this.targetTypeLoader = false; } else { this.getTargetTypeDetails(this.targetTypeName); } }, error => { this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; this.failedTitle = 'Loading Failed' this.loadingContent = 'Loading'; this.highlightName = 'Domain and Category' this.isTargetTypeCreationUpdationFailed = true; this.targetTypeLoader = false; }) }, error => { this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; this.failedTitle = 'Loading Failed' this.loadingContent = 'Loading'; this.highlightName = 'Domain and Category' this.isTargetTypeCreationUpdationFailed = true; this.targetTypeLoader = false; }) } allSelectedTargettypeDetails: any; getTargetTypeDetails(targetTypeName) { this.hideContent = true; this.targetTypeLoader = true; this.loadingContent = 'loading'; this.highlightName = 'Target Type details' this.isTargetTypeCreationUpdationFailed = false; this.isTargetTypeCreationUpdationSuccess= false; let url = environment.getTargetTypesByName.url; let method = environment.getTargetTypesByName.method; this.adminService.executeHttpAction(url, method, {}, {targetTypeName: targetTypeName}).subscribe(reponse => { this.allSelectedTargettypeDetails = reponse[0]; this.hideContent = false; this.targetTypeLoader = false; this.targetTypes.domain = [{text: this.allSelectedTargettypeDetails.domain, id:this.allSelectedTargettypeDetails.domain}]; this.targetTypes.category = [{text: this.allSelectedTargettypeDetails.category, id:this.allSelectedTargettypeDetails.category}]; this.targetTypes.name = this.allSelectedTargettypeDetails.targetName; this.targetTypes.desc = this.allSelectedTargettypeDetails.targetDesc; this.targetTypes.config = this.allSelectedTargettypeDetails.targetConfig; }, error => { this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; this.failedTitle = 'Loading Failed' this.loadingContent = 'Loading'; this.highlightName = 'Target Type details' this.isTargetTypeCreationUpdationFailed = true; this.targetTypeLoader = false; }) } deMarshalDomain(domainsData) { let fullDomains = []; for (var index = 0; index < domainsData.length; index++) { let domainItem = {}; domainItem['id'] = domainsData[index].domainName; domainItem['text'] = domainsData[index].domainName; fullDomains.push(domainItem); } return fullDomains; } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.showLoader = true; this.errorValue = 0; this.getData(); } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } ngOnDestroy() { try { if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.previousUrlSubscription) { this.previousUrlSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
import { spawn as spawnChildProcess, spawnSync as spawnSyncChildProcess } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { getMutoolExtractionFolder, getTemporaryFile } from '../utils'; import Cache from './CacheLayer'; import logger from './Logger'; export interface Dimensions { width: number; height: number; } const COMMANDS = { MUTOOL: 'mutool', PDF2TXT: ['pdf2txt.py', 'pdf2txt'], IDENTIFY: ['magick', 'identify'], CONVERT: ['magick', 'convert'], PANDOC: 'pandoc', DUMPPDF: ['dumppdf.py', 'dumppdf'], PYTHON: ['python3', 'python'], QPDF: 'qpdf', }; export function run(cmd: string | string[], args: string[], options?: any): Promise<string> { if (!isCommandAvailable(cmd)) { const message = `${cmd.toString()} was not found on the system. Are you sure it is installed and added to PATH?`; logger.warn(message); return new Promise((_resolve, reject) => { return reject({ found: false, error: message, }); }); } if (COMMANDS.PDF2TXT === cmd || COMMANDS.DUMPPDF === cmd) { // Last PdfMiner version requires to be ran --> python /path_to_pdf2txt/pdf2txt.py args return runPythonCommand(cmd, args, options); } else { return runCommand(cmd, args, options); } } export function isCommandAvailable(cmd: string | string[]) { if (Array.isArray(cmd)) { return null != getCommandLocationOnSystem(cmd[0], cmd[1] || '', cmd[2] || ''); } else { return null != getCommandLocationOnSystem(cmd); } } /** * Prepares a command, syncSpawns a child process and returns the object */ export function spawnSync(cmd: string, args: string[], options: any = {}): any { const cmdComponents: string[] = cmd.split(' '); if (cmdComponents.length > 1) { args.unshift(...cmdComponents.splice(1, cmdComponents.length)); } return spawnSyncChildProcess(cmdComponents.join(' '), args, options); } /** * Prepares a command, spawns a child process and returns the object */ export function spawn(cmd: string, args: string[], options: any = {}): any { const cmdComponents: string[] = cmd.split(' '); if (cmdComponents.length > 1) { args.unshift(...cmdComponents.splice(1, cmdComponents.length)); } return spawnChildProcess(cmdComponents.join(' '), args, options); } /** * Repair a pdf using the external qpdf and mutool utilities. * Use qpdf to decrcrypt the pdf to avoid errors due to DRMs. * @param filePath The absolute filename and path of the pdf file to be repaired. */ export async function repairPdf(filePath: string): Promise<string> { try { const decryptedOutput = await qpdfDecrypt(filePath); return mutoolClean(decryptedOutput).catch(() => decryptedOutput); } catch ({ found, error }) { return mutoolClean(filePath).catch(() => filePath); } } export function mutoolExtract(filePath: string): Promise<string> { const outputFolder = getMutoolExtractionFolder(); return run(COMMANDS.MUTOOL, ['extract', '-r', filePath], { cwd: outputFolder, }).then(() => { logger.info(`Mutool extract succeed --> ${outputFolder}`); return outputFolder; }); } export function pandocDocxToHtml(filePath: string): Promise<string> { const assetsFolder = path.dirname(filePath); return run(COMMANDS.PANDOC, [filePath, '--extract-media', assetsFolder, '-t', 'html5']).then( html => { logger.info(`Pandoc docx to html succeed`); return html; }, ); } export function imageCorrection(filePath: string): Promise<string> { const args: string[] = [path.join(__dirname, '../../assets/ImageCorrection.py'), filePath]; return run(COMMANDS.PYTHON, args).then(transformation => { logger.info(`Image optimisation succeed`); return transformation; }); } export function pdfPagesNumber(filePath: string): Promise<string> { const args: string[] = [path.join(__dirname, '../../assets/PdfPageNumber.py'), filePath]; return run(COMMANDS.PYTHON, args).then(transformation => { logger.info(`Pages number extraction succeed`); return transformation; }); } export function pandocMdToPdf(mdFilePath: string, pdfOutputPath: string): Promise<string> { const args: string[] = [ '-f', 'markdown_github+all_symbols_escapable', '--pdf-engine=xelatex', '--quiet', '-s', mdFilePath, '-o', pdfOutputPath, ]; return run(COMMANDS.PANDOC, args, { cwd: process.cwd(), env: process.env, }).then(() => { return pdfOutputPath; }); } export function detectTables( filePath: string, flavor: string, lineScale: string, pages: string, tableAreas: string[], ): Promise<string> { const args: string[] = [ path.join(__dirname, '../../assets/TableDetectionScript.py'), filePath, flavor, lineScale, pages, ]; if (tableAreas.length > 0) { args.push(tableAreas.join(';')); } return run(COMMANDS.PYTHON, args).then(tableData => { logger.info(`Table detection succeed`); return tableData; }); } export function detectTables2(filePath: string, pages: string): Promise<string> { const args: string[] = [ path.join(__dirname, '../../assets/TableDetection2Script.py'), filePath, pages, ]; return run(COMMANDS.PYTHON, args).then(tableData => { logger.info(`Table detection succeed`); return tableData; }); } export function levelPrediction( headings_features: string, ): Promise<string> { const args: string[] = [ path.join(__dirname, '../../assets/HeadingLevelPrediction.py'), headings_features, ]; return run(COMMANDS.PYTHON, args).then(predictions => { return predictions; }); } export function pdfMinerExtract( filePath: string, pages: string, rotationDegrees: number = 0, ): Promise<string> { const xmlOutputFile: string = getTemporaryFile('.xml'); let pdf2txtArguments: string[] = [ '--detect-vertical', '-R', rotationDegrees.toString(), '-c', 'utf-8', '-t', 'xml', '--word-margin', '0.2', '-o', xmlOutputFile, filePath, ]; if (pages != null) { pdf2txtArguments = ['-p', pages].concat(pdf2txtArguments); const from = pages.split(',').shift(); const to = pages.split(',').pop(); logger.info('PdfMiner extracting contents (pages ' + from + ' to ' + to + ')'); } const key = ['pdf2txt', ...pdf2txtArguments].filter(arg => arg !== xmlOutputFile).join(' '); if (Cache.has(key)) { return Promise.resolve(Cache.get(key)); } return run(COMMANDS.PDF2TXT, pdf2txtArguments).then(() => { logger.info(`PdfMiner pdf2txt.py succeed --> ${xmlOutputFile}`); Cache.set(key, xmlOutputFile); return xmlOutputFile; }); } export function dumpPdf(filePath: string): Promise<string> { const xmlOutputFile: string = getTemporaryFile('.xml'); const dumpAarguments = ['-a', '-o', xmlOutputFile, filePath]; const key = `dumppdf -a -o <outfile> ${filePath}`; if (Cache.has(key)) { return Promise.resolve(Cache.get(key)); } return run(COMMANDS.DUMPPDF, dumpAarguments).then(() => { logger.info(`PdfMiner dumppdf.py succeed --> ${xmlOutputFile}`); Cache.set(key, xmlOutputFile); return xmlOutputFile; }); } export function magickImageDimensions(filePath: string): Promise<Dimensions[]> { const args = ['-format', '%[fx:w]x%[fx:h],', filePath]; return run(COMMANDS.IDENTIFY, magickRetroCompatibility(COMMANDS.IDENTIFY, args)).then(data => { const dimensions = data.split(','); const retDimension: Dimensions[] = dimensions.map(dimension => { const [width, height] = dimension.split('x').map(s => parseInt(s, 10)); return { width, height }; }); logger.info(`Magick identify succeed`); return retDimension; }); } export function magickImageToPdf(filePath: string): Promise<string> { const outputFilePath = getTemporaryFile('.pdf'); const args = [filePath, '-units', 'PixelsPerInch', '-density', '96', outputFilePath]; return run(COMMANDS.CONVERT, magickRetroCompatibility(COMMANDS.CONVERT, args)).then(() => { logger.info(`Magick convert Pdf to image succeed --> ${outputFilePath}`); return outputFilePath; }); } export function magickPdfToImages(filePath: string): Promise<string[]> { const folder = path.dirname(filePath).concat('/samples'); try { if (!fs.existsSync(folder)) { fs.mkdirSync(folder); } } catch (e) { Promise.reject(e); } const fileName = 'Sample_' + path.basename(filePath, '.pdf'); const extension = 'jpeg'; const outPutFilePath = folder + '/' + fileName + '_%03d.' + extension; const regExp = new RegExp(fileName + '_(\\d{3}).' + extension); const args = [ '-colorspace', 'RGB', '-density', '300x300', '-compress', 'lzw', '-alpha', 'remove', '-background', 'white', filePath, outPutFilePath, ]; return run(COMMANDS.CONVERT, magickRetroCompatibility(COMMANDS.CONVERT, args)).then(() => { logger.info(`Magick convert Pdf to image succeed --> ${folder}`); return fs .readdirSync(folder) .map(file => path.join(folder, file)) .filter(file => regExp.test(file)); }); } function magickRetroCompatibility(command: string[], args: string[]): string[] { if (isCommandAvailable(command[0]) && command === COMMANDS.CONVERT) { // Magick 7.X --> 'magick convert ' + args // Magick 6.X --> 'convert ' + args args = ['convert'].concat(args); } if (isCommandAvailable(command[0]) && command === COMMANDS.IDENTIFY) { // Magick 7.X --> 'magick identify ' + args // Magick 6.X --> 'identify ' + args args = ['identify'].concat(args); } return args; } function qpdfDecrypt(filePath: string): Promise<string> { const outputFilePath = getTemporaryFile('.pdf'); return run(COMMANDS.QPDF, ['--decrypt', '--no-warn', filePath, outputFilePath]).then(() => { logger.info(`Qpdf repair succeed --> ${outputFilePath}`); return outputFilePath; }); } function mutoolClean(filePath: string): Promise<string> { const outputFilePath = getTemporaryFile('.pdf'); return run(COMMANDS.MUTOOL, ['clean', '-g', filePath, outputFilePath]).then(() => { logger.info(`Mutool clean succeed --> ${outputFilePath}`); return outputFilePath; }); } function runPythonCommand(cmd: string | string[], args: string[], options?: any): Promise<string> { const newArgs = [systemCommandPath(cmd)].concat(args); return runCommand(COMMANDS.PYTHON, newArgs, options); } function runCommand(cmd: string | string[], args: string[], options?: any): Promise<string> { return new Promise((resolve, reject) => { const command = availableCommand(cmd); logger.info(`executing command: ${command} ${args.join(' ')}`); const { stderr, stdout, status } = spawnSync(command, args, options); if (status === 0) { return resolve((stdout || '').toString()); } logger.error(`executing command error: ${(stderr || '').toString()}`); return reject({ found: true, error: (stderr || '').toString() }); }); } /** * returns the location of a command on a system. * @param firstChoice the first choice name of the executable to be located * @param secondChoice the second choice name of the executable to be located * @param thirdChoice the third choice name of the executable to be located */ function getCommandLocationOnSystem( firstChoice: string, secondChoice: string = '', thirdChoice: string = '', ): string { const cmdComponents: string[] = firstChoice.split(' '); const info = spawnSync(getExecLocationCommandOnSystem(), [cmdComponents[0]]); const result = info.status === 0 ? info.stdout.toString().split(os.EOL)[0] : null; if (result === null && secondChoice !== '') { return getCommandLocationOnSystem(secondChoice, thirdChoice); } if (result === null) { return null; } return result; } /** * returns the location of the executable locator command on the current system. * on linux/unix machines, this is 'which', on windows machines, it is 'where'. */ function getExecLocationCommandOnSystem(): string { return os.platform() === 'win32' ? 'where' : 'which'; } function systemCommandPath(cmd: string | string[]) { if (Array.isArray(cmd)) { return getCommandLocationOnSystem(cmd[0], cmd[1] || '', cmd[2] || ''); } else { return getCommandLocationOnSystem(cmd); } } function availableCommand(cmd: string | string[]): string { if (!Array.isArray(cmd)) { return isCommandAvailable(cmd) ? cmd : null; } if (isCommandAvailable(cmd[0])) { return cmd[0]; } else if (cmd[1] && isCommandAvailable(cmd[1])) { return cmd[1]; } else if (cmd[2] && isCommandAvailable(cmd[2])) { return cmd[2]; } return null; }
the_stack
import { Stats } from 'fs' import { getLatestGitRelease } from '../releases' export interface NexeBinary { blobPath: string resources: { [key: string]: number[] } layout: { stat: Stats resourceStart: number contentSize?: number contentStart?: number resourceSize?: number } } let originalFsMethods: any = null let lazyRestoreFs = () => {} // optional Win32 file namespace prefix followed by drive letter and colon const windowsFullPathRegex = /^(\\{2}\?\\)?([a-zA-Z]):/ const upcaseDriveLetter = (s: string): string => s.replace(windowsFullPathRegex, (_match, ns, drive) => `${ns || ''}${drive.toUpperCase()}:`) function shimFs(binary: NexeBinary, fs: any = require('fs')) { if (originalFsMethods !== null) { return } originalFsMethods = Object.assign({}, fs) const { blobPath, resources: manifest } = binary, { resourceStart, stat } = binary.layout, directories: { [key: string]: { [key: string]: boolean } } = {}, notAFile = '!@#$%^&*', isWin = process.platform.startsWith('win'), isString = (x: any): x is string => typeof x === 'string' || x instanceof String, noop = () => {}, path = require('path'), winPath: (key: string) => string = isWin ? upcaseDriveLetter : (s) => s, baseDir = winPath(path.dirname(process.execPath)) let log = (_: string) => true let loggedManifest = false if ((process.env.DEBUG || '').toLowerCase().includes('nexe:require')) { log = (text: string) => { setupManifest() if (!loggedManifest) { process.stderr.write('[nexe] - MANIFEST' + JSON.stringify(manifest, null, 4) + '\n') process.stderr.write('[nexe] - DIRECTORIES' + JSON.stringify(directories, null, 4) + '\n') loggedManifest = true } return process.stderr.write('[nexe] - ' + text + '\n') } } const getKey = function getKey(filepath: string | Buffer | null): string { if (Buffer.isBuffer(filepath)) { filepath = filepath.toString() } if (!isString(filepath)) { return notAFile } let key = path.resolve(baseDir, filepath) return winPath(key) } const statTime = function () { return { atime: new Date(stat.atime), mtime: new Date(stat.mtime), ctime: new Date(stat.ctime), birthtime: new Date(stat.birthtime), } } let BigInt: Function try { BigInt = eval('BigInt') } catch (ignored) {} const minBlocks = Math.max(Math.ceil(stat.blksize / 512), 1) const createStat = function (extensions: any, options: any) { const stat = Object.assign(new fs.Stats(), binary.layout.stat, statTime(), extensions) if ('size' in extensions) { //Assume non adjustable allocation size for file system stat.blocks = Math.ceil(stat.size / stat.blksize) * minBlocks } if (options && options.bigint && typeof BigInt !== 'undefined') { for (const k in stat) { if (Object.prototype.hasOwnProperty.call(stat, k) && typeof stat[k] === 'number') { stat[k] = BigInt(stat[k]) } } } return stat } const ownStat = function (filepath: any, options: any) { setupManifest() const key = getKey(filepath) if (directories[key]) { let mode = binary.layout.stat.mode mode |= fs.constants.S_IFDIR mode &= ~fs.constants.S_IFREG return createStat({ mode, size: 0 }, options) } if (manifest[key]) { return createStat({ size: manifest[key][1] }, options) } } const getStat = function (fn: string) { return function stat(filepath: string | Buffer, options: any, callback: any) { let stat: any if (typeof options === 'function') { callback = options stat = ownStat(filepath, null) } else { stat = ownStat(filepath, options) } if (stat) { process.nextTick(() => { callback(null, stat) }) } else { return originalFsMethods[fn].apply(fs, arguments) } } } function makeLong(filepath: string) { return (path as any)._makeLong && (path as any)._makeLong(filepath) } function fileOpts(options: any) { return !options ? {} : isString(options) ? { encoding: options } : options } let setupManifest = () => { Object.keys(manifest).forEach((filepath) => { const entry = manifest[filepath] const absolutePath = getKey(filepath) const longPath = makeLong(absolutePath) const normalizedPath = winPath(path.normalize(filepath)) if (!manifest[absolutePath]) { manifest[absolutePath] = entry } if (longPath && !manifest[longPath]) { manifest[longPath] = entry } if (!manifest[normalizedPath]) { manifest[normalizedPath] = manifest[filepath] } let currentDir = path.dirname(absolutePath) let prevDir = absolutePath while (currentDir !== prevDir) { directories[currentDir] = directories[currentDir] || {} directories[currentDir][path.basename(prevDir)] = true const longDir = makeLong(currentDir) if (longDir && !directories[longDir]) { directories[longDir] = directories[currentDir] } prevDir = currentDir currentDir = path.dirname(currentDir) } }) ;(manifest[notAFile] as any) = false ;(directories[notAFile] as any) = false setupManifest = noop } //naive patches intended to work for most use cases const nfs: any = { existsSync: function existsSync(filepath: string) { setupManifest() const key = getKey(filepath) if (manifest[key] || directories[key]) { return true } return originalFsMethods.existsSync.apply(fs, arguments) }, realpath: function realpath(filepath: any, options: any, cb: any): void { setupManifest() const key = getKey(filepath) if (isString(filepath) && (manifest[filepath] || manifest[key])) { return process.nextTick(() => cb(null, filepath)) } return originalFsMethods.realpath.call(fs, filepath, options, cb) }, realpathSync: function realpathSync(filepath: any, options: any) { setupManifest() const key = getKey(filepath) if (manifest[key]) { return filepath } return originalFsMethods.realpathSync.call(fs, filepath, options) }, readdir: function readdir(filepath: string | Buffer, options: any, callback: any) { setupManifest() const dir = directories[getKey(filepath)] if (dir) { if ('function' === typeof options) { callback = options options = { encoding: 'utf8' } } process.nextTick(() => callback(null, Object.keys(dir))) } else { return originalFsMethods.readdir.apply(fs, arguments) } }, readdirSync: function readdirSync(filepath: string | Buffer, options: any) { setupManifest() const dir = directories[getKey(filepath)] if (dir) { return Object.keys(dir) } return originalFsMethods.readdirSync.apply(fs, arguments) }, readFile: function readFile(filepath: any, options: any, callback: any) { setupManifest() const entry = manifest[getKey(filepath)] if (!entry) { return originalFsMethods.readFile.apply(fs, arguments) } const [offset, length] = entry const resourceOffset = resourceStart + offset const encoding = fileOpts(options).encoding callback = typeof options === 'function' ? options : callback originalFsMethods.open(blobPath, 'r', function (err: Error, fd: number) { if (err) return callback(err, null) originalFsMethods.read( fd, Buffer.alloc(length), 0, length, resourceOffset, function (error: Error, bytesRead: number, result: Buffer) { if (error) { return originalFsMethods.close(fd, function () { callback(error, null) }) } originalFsMethods.close(fd, function (err: Error) { if (err) { return callback(err, result) } callback(err, encoding ? result.toString(encoding) : result) }) } ) }) }, createReadStream: function createReadStream(filepath: any, options: any) { setupManifest() const entry = manifest[getKey(filepath)] if (!entry) { return originalFsMethods.createReadStream.apply(fs, arguments) } const [offset, length] = entry const resourceOffset = resourceStart + offset const opts = fileOpts(options) return originalFsMethods.createReadStream( blobPath, Object.assign({}, opts, { start: resourceOffset, end: resourceOffset + length - 1, }) ) }, readFileSync: function readFileSync(filepath: any, options: any) { setupManifest() const entry = manifest[getKey(filepath)] if (!entry) { return originalFsMethods.readFileSync.apply(fs, arguments) } const [offset, length] = entry const resourceOffset = resourceStart + offset const encoding = fileOpts(options).encoding const fd = originalFsMethods.openSync(process.execPath, 'r') const result = Buffer.alloc(length) originalFsMethods.readSync(fd, result, 0, length, resourceOffset) originalFsMethods.closeSync(fd) return encoding ? result.toString(encoding) : result }, statSync: function statSync(filepath: string | Buffer, options: any) { const stat = ownStat(filepath, options) if (stat) { return stat } return originalFsMethods.statSync.apply(fs, arguments) }, stat: getStat('stat'), lstat: getStat('lstat'), lstatSync: function statSync(filepath: string | Buffer, options: any) { const stat = ownStat(filepath, options) if (stat) { return stat } return originalFsMethods.lstatSync.apply(fs, arguments) }, } if (typeof fs.exists === 'function') { nfs.exists = function (filepath: string, cb: Function) { cb = cb || noop const exists = nfs.existsSync(filepath) process.nextTick(() => cb(exists)) } } const patches = (process as any).nexe.patches || {} delete (process as any).nexe patches.internalModuleReadFile = function (this: any, original: any, ...args: any[]) { setupManifest() const filepath = getKey(args[0]) if (manifest[filepath]) { log('read (hit) ' + filepath) return nfs.readFileSync(filepath, 'utf-8') } log('read (miss) ' + filepath) return original.call(this, ...args) } let returningArray: boolean patches.internalModuleReadJSON = function (this: any, original: any, ...args: any[]) { if (returningArray == null) returningArray = Array.isArray(original.call(this, '')) const res = patches.internalModuleReadFile.call(this, original, ...args) return returningArray && !Array.isArray(res) ? [res, /"(main|name|type|exports|imports)"/.test(res)] : res } patches.internalModuleStat = function (this: any, original: any, ...args: any[]) { setupManifest() const filepath = getKey(args[0]) if (manifest[filepath]) { log('stat (hit) ' + filepath + ' ' + 0) return 0 } if (directories[filepath]) { log('stat dir (hit) ' + filepath + ' ' + 1) return 1 } const res = original.call(this, ...args) if (res === 0) { log('stat (miss) ' + filepath + ' ' + res) } else if (res === 1) { log('stat dir (miss) ' + filepath + ' ' + res) } else { log('stat (fail) ' + filepath + ' ' + res) } return res } if (typeof fs.exists === 'function') { nfs.exists = function (filepath: string, cb: Function) { cb = cb || noop const exists = nfs.existsSync(filepath) if (!exists) { return originalFsMethods.exists(filepath, cb) } process.nextTick(() => cb(exists)) } } if (typeof fs.copyFile === 'function') { nfs.copyFile = function (filepath: string, dest: string, flags: number, callback: Function) { setupManifest() const entry = manifest[getKey(filepath)] if (!entry) { return originalFsMethods.copyFile.apply(fs, arguments) } if (typeof flags === 'function') { callback = flags flags = 0 } nfs.readFile(filepath, (err: any, buffer: any) => { if (err) { return callback(err) } originalFsMethods.writeFile(dest, buffer, (err: any) => { if (err) { return callback(err) } callback(null) }) }) } nfs.copyFileSync = function (filepath: string, dest: string) { setupManifest() const entry = manifest[getKey(filepath)] if (!entry) { return originalFsMethods.copyFileSync.apply(fs, arguments) } return originalFsMethods.writeFileSync(dest, nfs.readFileSync(filepath)) } } if (typeof fs.realpath.native === 'function') { nfs.realpath.native = function realpathNative(filepath: any, options: any, cb: any): void { setupManifest() const key = getKey(filepath) if (isString(filepath) && (manifest[filepath] || manifest[key])) { return process.nextTick(() => cb(null, filepath)) } return originalFsMethods.realpath.native.call(fs, filepath, options, cb) } nfs.realpathSync.native = function realpathSyncNative(filepath: any, options: any) { setupManifest() const key = getKey(filepath) if (manifest[key]) { return filepath } return originalFsMethods.realpathSync.native.call(fs, filepath, options) } } Object.assign(fs, nfs) lazyRestoreFs = () => { Object.keys(nfs).forEach((key) => { fs[key] = originalFsMethods[key] }) lazyRestoreFs = () => {} } return true } function restoreFs() { lazyRestoreFs() } export { shimFs, restoreFs }
the_stack
const CLIENT: Sfdc.canvas.Client = { oauthToken: 'oauthToken', instanceId: 'instanceId', targetOrigin: 'targetOrigin', }; const APPLICATION: Sfdc.canvas.Application = { applicationId: '06Px000000003ed', authType: Sfdc.canvas.ApplicationAuthType.SIGNED_REQUEST, canvasUrl: 'http://MyDomainName.my.salesforce.com:8080/canvas_app_path/canvas_app.jsp', developerName: 'my_java_app', isInstalledPersonalApp: false, name: 'My Java App', namespace: 'org_namespace', options: [], referenceId: '09HD00000000AUM', samlInitiationMethod: 'None', version: '1.0.0', }; const USER: Sfdc.canvas.User = { accessibilityModeEnabled: false, currencyISOCode: 'USD', email: 'admin@6457617734813492.com', firstName: 'Sean', fullName: 'Sean Forbes', isDefaultNetwork: false, language: 'en_US', lastName: 'Forbes', locale: 'en_US', networkId: '0DBxx000000001r', profileId: '00ex0000000jzpt', profilePhotoUrl: '/profilephoto/005/F', profileThumbnailUrl: '/profilephoto/005/T', roleId: null, siteUrl: 'https://MyDomainName.my.site.com/', siteUrlPrefix: '/mySite', timeZone: 'America/Los_Angeles', userId: '005x0000001SyyEAAS', userName: 'admin@6457617734813492.com', userType: Sfdc.canvas.UserType.STANDARD, }; const ENVIRONMENT: Sfdc.canvas.Environment = { parameters: { complex: { key1: 'value1', key2: 'value2', }, integer: 10, simple: 'This is a simple string.', boolean: true, }, dimensions: { clientHeight: '50px', clientWidth: '70px', height: '900px', width: '800px', maxHeight: '2000px', maxWidth: '1000px', }, record: { attributes: { type: 'Account', url: '/services/data/v52.0/sobjects/Account/001xx000003DGWiAAO', }, Id: '001xx000003DGWiAAO', Phone: '(555) 555-5555', Fax: '(555) 555-5555', BillingCity: 'Seattle', }, displayLocation: Sfdc.canvas.EnvironmentDisplayLocation.CHATTER, locationUrl: 'http://www.salesforce.com/some/path/index.html', subLocation: null, uiTheme: 'Theme3', version: { api: '52.0', season: 'SUMMER', }, }; const ORGANIZATION: Sfdc.canvas.Organization = { currencyIsoCode: 'USD', multicurrencyEnabled: true, name: 'Edge Communications', namespacePrefix: 'org_namespace', organizationId: '00Dx00000001hxyEAA', }; const LINKS: Sfdc.canvas.Links = { chatterFeedItemsUrl: '/services/data/v52.0/chatter/feed-items', chatterFeedsUrl: '/services/data/v52.0/chatter/feeds', chatterGroupsUrl: '/services/data/v52.0/chatter/groups', chatterUsersUrl: '/services/data/v52.0/chatter/users', enterpriseUrl: '/services/Soap/c/52.0/00Dx00000001hxy', loginUrl: 'http://MyDomainName.my.salesforce.com', metadataUrl: '/services/Soap/m/52.0/00Dx00000001hxy', partnerUrl: '/services/Soap/u/52.0/00Dx00000001hxy', queryUrl: '/services/data/v52.0/query/', recentItemsUrl: '/services/data/v52.0/recent/', restUrl: '/services/data/v52.0/', searchUrl: '/services/data/v52.0/search/', sobjectUrl: '/services/data/v52.0/sobjects/', userUrl: '/005x0000001SyyEAAS', }; const CONTEXT: Sfdc.canvas.Context = { application: APPLICATION, user: USER, environment: ENVIRONMENT, organization: ORGANIZATION, links: LINKS, }; // ============================================================================= // Sfdc.canvas // ============================================================================= Sfdc.canvas(() => {}); // $ExpectType void Sfdc.canvas.hasOwn({ a: 1 }, 'a'); // $ExpectType boolean Sfdc.canvas.hasOwn({ a: 1 }, 'b'); // $ExpectType boolean Sfdc.canvas.isUndefined(undefined); // $ExpectType boolean Sfdc.canvas.isUndefined('a'); // $ExpectType boolean Sfdc.canvas.isNil(undefined); // $ExpectType boolean Sfdc.canvas.isNil(null); // $ExpectType boolean Sfdc.canvas.isNil(''); // $ExpectType boolean Sfdc.canvas.isNil('a'); // $ExpectType boolean Sfdc.canvas.isNumber(123); // $ExpectType boolean Sfdc.canvas.isNumber('a'); // $ExpectType boolean Sfdc.canvas.isFunction(() => {}); // $ExpectType boolean Sfdc.canvas.isFunction(''); // $ExpectType boolean Sfdc.canvas.isArray([]); // $ExpectType boolean Sfdc.canvas.isArray({}); // $ExpectType boolean Sfdc.canvas.isArray(''); // $ExpectType boolean Sfdc.canvas.isArguments([]); // $ExpectType boolean Sfdc.canvas.isObject({}); // $ExpectType boolean Sfdc.canvas.isObject([]); // $ExpectType boolean Sfdc.canvas.isString(''); // $ExpectType boolean Sfdc.canvas.isString(1); // $ExpectType boolean Sfdc.canvas.appearsJson('{}'); // $ExpectType boolean Sfdc.canvas.appearsJson(''); // $ExpectType boolean Sfdc.canvas.nop(); // $ExpectType void Sfdc.canvas.invoker(() => {}); // $ExpectType void Sfdc.canvas.identity(1); // $ExpectType 1 Sfdc.canvas.identity('a'); // $ExpectType "a" Sfdc.canvas.identity({}); // $ExpectType {} // $ExpectType void Sfdc.canvas.each(['1', '2', '3'], (item, index, arr) => { item; // $ExpectType string index; // $ExpectType number arr; // $ExpectType string[] }); // $ExpectType void Sfdc.canvas.each({ a: 1, b: 2, c: 3 }, (item, key, obj) => { item; // $ExpectType number key; // $ExpectType string obj; // $ExpectType Record<string, number> }); Sfdc.canvas.each(1, (item, index, arr) => {}); // $ExpectError Sfdc.canvas.startsWithHttp('http://foo', 'http://bar'); // $ExpectType string Sfdc.canvas.startsWithHttp('foo', 'http://bar'); // $ExpectType string // $ExpectError Sfdc.canvas.startsWithHttp(1, 'http://bar'); // $ExpectType number[] Sfdc.canvas.map(['1', '2', '3'], (item, index, arr) => { item; // $ExpectType string index; // $ExpectType number arr; // $ExpectType string[] return parseInt(item, 10); }); // $ExpectType string[] Sfdc.canvas.map({ a: 1, b: 2, c: 3 }, (item, index, obj) => { item; // $ExpectType number index; // $ExpectType string obj; // $ExpectType Record<string, number> return String(item); }); Sfdc.canvas.map(1, (item, index, arr) => {}); // $ExpectError Sfdc.canvas.values([1, 2, 3, 4]); // $ExpectType number[] Sfdc.canvas.values({ a: 1, b: 2, c: 3 }); // $ExpectType number[] Sfdc.canvas.values(1); // $ExpectError Sfdc.canvas.slice([1, 2, 3, 4]); // $ExpectType number[] Sfdc.canvas.slice([1, 2, 3, 4], 0); // $ExpectType number[] Sfdc.canvas.slice([1, 2, 3, 4], 0, 1); // $ExpectType number[] Sfdc.canvas.slice(0, 0, 0); // $ExpectError Sfdc.canvas.toArray(undefined); // $ExpectType [] Sfdc.canvas.toArray(null); // $ExpectType [] Sfdc.canvas.toArray([1, 2, 3, 4]); // $ExpectType number[] Sfdc.canvas.toArray({ a: 1, b: 2, c: 3 }); // $ExpectType number[] Sfdc.canvas.toArray(1); // $ExpectError Sfdc.canvas.size(undefined); // $ExpectType number Sfdc.canvas.size(null); // $ExpectType number Sfdc.canvas.size([1, 2, 3, 4]); // $ExpectType number Sfdc.canvas.size({ a: 1, b: 2, c: 3 }); // $ExpectType number Sfdc.canvas.size(1); // $ExpectError Sfdc.canvas.indexOf([1, 2, 3, 4], 3); // $ExpectType number Sfdc.canvas.indexOf([1, 2, 3, 4], 'a'); // $ExpectError Sfdc.canvas.isEmpty(null); // $ExpectType boolean Sfdc.canvas.isEmpty(''); // $ExpectType boolean Sfdc.canvas.isEmpty(1); // $ExpectType boolean Sfdc.canvas.isEmpty([]); // $ExpectType boolean Sfdc.canvas.isEmpty('test'); // $ExpectType boolean Sfdc.canvas.isEmpty(['a']); // $ExpectType boolean Sfdc.canvas.remove([1, 2, 3, 4], 3); // $ExpectType number[] Sfdc.canvas.remove([1, 2, 3, 4], 'a'); // $ExpectError Sfdc.canvas.param([1, 2, 3, 4], true); // $ExpectType string Sfdc.canvas.param([1, 2, 3, 4]); // $ExpectType string Sfdc.canvas.param({ a: 1, b: 2, c: 3 }, true); // $ExpectType string Sfdc.canvas.param({ a: 1, b: 2, c: 3 }); // $ExpectType string Sfdc.canvas.param(1); // $ExpectError Sfdc.canvas.objectify('a=1&b=2'); // $ExpectType Record<string, string> Sfdc.canvas.objectify(1); // $ExpectError Sfdc.canvas.stripUrl('http://foo'); // $ExpectType string Sfdc.canvas.stripUrl(1); // $ExpectError Sfdc.canvas.query('http://foo', 'a=1&b=2'); // $ExpectType string // $ExpectError Sfdc.canvas.query('http://foo', 1); // $ExpectError Sfdc.canvas.query(1, 'a=1&b=2'); Sfdc.canvas.extend({ a: 1 }, { b: 2 }); // $ExpectType { a: number; } & { b: number; } Sfdc.canvas.extend({ a: 1 }, { b: 2 }, { c: 3 }); // $ExpectType { a: number; } & { b: number; } & { c: number; } Sfdc.canvas.extend({ a: 1 }, 'a'); // $ExpectError Sfdc.canvas.extend({ a: 1 }); // $ExpectError Sfdc.canvas.endsWith('hello world', 'world'); // $ExpectType boolean Sfdc.canvas.endsWith('hello world', 'foo'); // $ExpectType boolean Sfdc.canvas.endsWith('hello world', 1); // $ExpectError Sfdc.canvas.capitalize('hello world'); // $ExpectType string Sfdc.canvas.capitalize(1); // $ExpectError Sfdc.canvas.uncapitalize('hello world'); // $ExpectType string Sfdc.canvas.uncapitalize(1); // $ExpectError Sfdc.canvas.decode('abcedf'); // $ExpectType string Sfdc.canvas.decode(1); // $ExpectError Sfdc.canvas.escapeToUTF8('abcedf'); // $ExpectType string Sfdc.canvas.escapeToUTF8(1); // $ExpectError Sfdc.canvas.validEventName('abcedf', 'foo'); // $ExpectType number Sfdc.canvas.validEventName('abcedf', ['foo']); // $ExpectType number Sfdc.canvas.validEventName(1, 'foo'); // $ExpectError Sfdc.canvas.validEventName('abcedf', 1); // $ExpectError Sfdc.canvas.prototypeOf(1); // $ExpectType object | null Sfdc.canvas.module('foo', { a: 1 }); // $ExpectType typeof canvas Sfdc.canvas.module(1, { a: 1 }); // $ExpectError Sfdc.canvas.document(); // $ExpectType Document Sfdc.canvas.byId('foo'); // $ExpectType HTMLElement Sfdc.canvas.byId(1); // $ExpectError Sfdc.canvas.byClass('foo'); // $ExpectType HTMLElement Sfdc.canvas.byClass(1); // $ExpectError const el = document.createElement('div'); Sfdc.canvas.attr(el, 'foo'); // $ExpectType string Sfdc.canvas.attr(el, 1); // $ExpectError Sfdc.canvas.attr(1, 'foo'); // $ExpectError Sfdc.canvas.onReady(() => {}); // $ExpectType void // ============================================================================= // Sfdc.Sfdc.canvas.client // ============================================================================= // $ExpectType void Sfdc.canvas.client.ctx(response => { response; // $ExpectType Response<string | Context> }, CLIENT); // $ExpectType void Sfdc.canvas.client.ajax('/foo', { client: CLIENT, success: (data: Sfdc.canvas.Response<unknown>) => { data; // $ExpectType Response<unknown> }, }); // $ExpectType void Sfdc.canvas.client.ajax('/foo', { client: CLIENT, method: 'POST', async: true, contentType: 'text/html', headers: { foo: 'bar' }, data: JSON.stringify({ hello: 'world' }), success: (data: Sfdc.canvas.Response<unknown>) => { data; // $ExpectType Response<unknown> }, }); Sfdc.canvas.client.token(); // $ExpectType string | null Sfdc.canvas.client.token('foo'); // $ExpectType string | null Sfdc.canvas.client.token(null); // $ExpectType string | null Sfdc.canvas.client.token(123); // $ExpectError Sfdc.canvas.client.version(); // $ExpectType Version Sfdc.canvas.client.resize(CLIENT); // $ExpectType void Sfdc.canvas.client.resize(CLIENT, { width: '5px', height: '5px' }); // $ExpectType void Sfdc.canvas.client.resize(CLIENT, {}); // $ExpectError Sfdc.canvas.client.size(); // $ExpectType Size Sfdc.canvas.client.autogrow(CLIENT); // $ExpectType void Sfdc.canvas.client.autogrow(CLIENT, true); // $ExpectType void Sfdc.canvas.client.autogrow(CLIENT, false); // $ExpectType void Sfdc.canvas.client.autogrow(CLIENT, true, 500); // $ExpectType void Sfdc.canvas.client.autogrow(CLIENT, 500); // $ExpectError // $ExpectType void Sfdc.canvas.client.subscribe(CLIENT, { name: 'foo.bar', onData: (event: unknown) => { event; // $ExpectType unknown }, }); // $ExpectType void Sfdc.canvas.client.subscribe(CLIENT, [ { name: 'foo.bar', onData: (event: unknown) => { event; // $ExpectType unknown }, }, ]); // $ExpectError Sfdc.canvas.client.subscribe(CLIENT, { name: 'sfdc.streamingapi', params: {}, onData: (event: unknown) => { event; // $ExpectType unknown }, onComplete: (event: unknown) => { event; // $ExpectType unknown }, }); // $ExpectType void Sfdc.canvas.client.subscribe(CLIENT, { name: 'sfdc.streamingapi', params: { topic: 'foo.bar', }, onData: (event: unknown) => { event; // $ExpectType unknown }, onComplete: (event: unknown) => { event; // $ExpectType unknown }, }); // $ExpectType void Sfdc.canvas.client.subscribe(CLIENT, [ { name: 'foo.bar', onData: (event: unknown) => { event; // $ExpectType unknown }, }, { name: 'sfdc.streamingapi', params: { topic: 'foo.bar', }, onData: (event: unknown) => { event; // $ExpectType unknown }, onComplete: (event: unknown) => { event; // $ExpectType unknown }, }, ]); Sfdc.canvas.client.unsubscribe(CLIENT, 'foo.bar'); // $ExpectType void // $ExpectType void Sfdc.canvas.client.unsubscribe(CLIENT, { name: 'foo.bar', }); // $ExpectType void Sfdc.canvas.client.unsubscribe(CLIENT, { name: 'sfdc.streamingapi', params: { topic: 'foo.bar', }, }); // $ExpectError Sfdc.canvas.client.unsubscribe(CLIENT, { name: 'sfdc.streamingapi', params: {}, }); // $ExpectType void Sfdc.canvas.client.unsubscribe(CLIENT, [ 'foo.bar', { name: 'foo.bar', }, { name: 'sfdc.streamingapi', params: { topic: 'foo.bar', }, }, ]); // $ExpectType void Sfdc.canvas.client.publish(CLIENT, { name: 'foo', payload: { hello: 'world' }, }); // $ExpectError Sfdc.canvas.client.publish(CLIENT, { name: 'foo', }); Sfdc.canvas.client.signedrequest(); // $ExpectType SignedRequest // $ExpectType SignedRequest Sfdc.canvas.client.signedrequest({ context: CONTEXT, client: CLIENT, algorithm: 'HMACSHA256', userId: '005x0000001SyyEAAS', issuedAt: null, }); // $ExpectType void Sfdc.canvas.client.refreshSignedRequest(data => { data; // $ExpectType Response<{ response: string; }> }); Sfdc.canvas.client.repost(); // $ExpectType void Sfdc.canvas.client.repost(true); // $ExpectType void Sfdc.canvas.client.repost(false); // $ExpectType void // ============================================================================= // Sfdc.Sfdc.canvas.console // ============================================================================= Sfdc.canvas.console.enable(); // $ExpectType void Sfdc.canvas.console.disable(); // $ExpectType void Sfdc.canvas.console.log('hello'); // $ExpectType void Sfdc.canvas.console.log('hello', 'world'); // $ExpectType void Sfdc.canvas.console.log(['hello', 'world']); // $ExpectType void Sfdc.canvas.console.log({ hello: 'world' }); // $ExpectType void Sfdc.canvas.console.log(12345); // $ExpectType void Sfdc.canvas.console.error(new Error('hello')); // $ExpectType void Sfdc.canvas.console.error('hello'); // $ExpectType void Sfdc.canvas.console.error('hello', 'world'); // $ExpectType void Sfdc.canvas.console.error(['hello', 'world']); // $ExpectType void Sfdc.canvas.console.error({ hello: 'world' }); // $ExpectType void Sfdc.canvas.console.error(12345); // $ExpectType void // ============================================================================= // Sfdc.Sfdc.canvas.cookies // ============================================================================= Sfdc.canvas.cookies.set('foo', 'bar'); // $ExpectType void Sfdc.canvas.cookies.set('foo', 'bar', 300); // $ExpectType void Sfdc.canvas.cookies.set('foo', 300); // $ExpectError Sfdc.canvas.cookies.get('foo'); // $ExpectType string Sfdc.canvas.cookies.get(1); // $ExpectError Sfdc.canvas.cookies.remove('foo'); // $ExpectType void Sfdc.canvas.cookies.remove(1); // $ExpectError // ============================================================================= // Sfdc.Sfdc.canvas.oauth // ============================================================================= Sfdc.canvas.oauth.init(); // $ExpectType void // $ExpectType void Sfdc.canvas.oauth.login({ uri: Sfdc.canvas.oauth.loginUrl(), params: { response_type: 'token', client_id: 'foo', redirect_uri: encodeURIComponent('https://foo/callback.html'), }, }); // $ExpectType void Sfdc.canvas.oauth.login({ uri: Sfdc.canvas.oauth.loginUrl(), params: { response_type: 'token', client_id: 'foo', redirect_uri: encodeURIComponent('https://foo/callback.html'), scope: 'foo bar', }, }); Sfdc.canvas.oauth.logout(); // $ExpectType void Sfdc.canvas.oauth.loggedin(); // $ExpectType boolean Sfdc.canvas.oauth.loginUrl(); // $ExpectType string Sfdc.canvas.oauth.token(); // $ExpectType string | null Sfdc.canvas.oauth.token(null); // $ExpectType string | null Sfdc.canvas.oauth.token('foo'); // $ExpectType string | null Sfdc.canvas.oauth.token(1); // $ExpectError Sfdc.canvas.oauth.instance(); // $ExpectType string | null Sfdc.canvas.oauth.instance(null); // $ExpectType string | null Sfdc.canvas.oauth.instance('foo'); // $ExpectType string | null Sfdc.canvas.oauth.instance(1); // $ExpectError Sfdc.canvas.oauth.client(); // $ExpectType Client Sfdc.canvas.oauth.checkChildWindowStatus(); // $ExpectType void Sfdc.canvas.oauth.childWindowUnloadNotification('foo'); // $ExpectType void // ============================================================================= // Sfdc.Sfdc.canvas.xd // ============================================================================= Sfdc.canvas.xd.post('foo', 'http://test'); // $ExpectType void Sfdc.canvas.xd.post('foo', 'http://test', window); // $ExpectType void // $ExpectError Sfdc.canvas.xd.post({}, 'http://test', window); Sfdc.canvas.xd.receive((data: unknown) => {}); // $ExpectType void Sfdc.canvas.xd.receive((data: unknown) => {}, 'origin'); // $ExpectType void Sfdc.canvas.xd.remove(); // $ExpectType void
the_stack
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { UsersAPIClientInterface } from './users-api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from '../../types'; import * as models from '../../models'; export const USE_DOMAIN = new InjectionToken<string>('UsersAPIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('UsersAPIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class UsersAPIClient implements UsersAPIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://api.github.com`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Get all users. * This provides a dump of every user, in the order that they signed up for GitHub. * Note: Pagination is powered exclusively by the since parameter. Use the Link * header to get the URL for the next page of users. * * Response generated for [ 200 ] HTTP response code. */ getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getUsers( args: UsersAPIClientInterface['getUsersParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/users`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('since' in args) { options.params = options.params.set('since', String(args.since)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * Get a single user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/users/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events. * Response generated for [ default ] HTTP response code. */ getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/events`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * This is the user's organization dashboard. You must be authenticated as the user to view this. * Response generated for [ default ] HTTP response code. */ getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/events/orgs/${args.org}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * List a user's followers * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/users/${args.username}/followers`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * Check if one user follows another. * Response generated for [ 204 ] HTTP response code. */ getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/following/${args.targetUser}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * List a users gists. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gists>; getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gists>>; getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gists>>; getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gists | HttpResponse<models.Gists> | HttpEvent<models.Gists>> { const path = `/users/${args.username}/gists`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('since' in args) { options.params = options.params.set('since', String(args.since)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gists>(`${this.domain}${path}`, options); } /** * List public keys for a user. * Lists the verified public keys for a user. This is accessible by anyone. * * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> { const path = `/users/${args.username}/keys`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gitignore>(`${this.domain}${path}`, options); } /** * List all public organizations for a user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> { const path = `/users/${args.username}/orgs`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gitignore>(`${this.domain}${path}`, options); } /** * These are events that you'll only see public events. * Response generated for [ default ] HTTP response code. */ getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/received_events`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * List public events that a user has received * Response generated for [ default ] HTTP response code. */ getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/received_events/public`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * List public repositories for the specified user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> { const path = `/users/${args.username}/repos`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('type' in args) { options.params = options.params.set('type', String(args.type)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Repos>(`${this.domain}${path}`, options); } /** * List repositories being starred by a user. * Response generated for [ default ] HTTP response code. */ getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/starred`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * List repositories being watched by a user. * Response generated for [ default ] HTTP response code. */ getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/users/${args.username}/subscriptions`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } }
the_stack
import plugin from "tailwindcss/plugin"; import type { PluginTools, TailwindCSSConfig } from "@navith/tailwindcss-plugin-author-types"; import type { ObjectOfNestedStrings, SemanticUtility, ThisPluginOptions, ThisPluginTheme, } from "./types"; import { addParent } from "./selectors"; const DEFAULT = "DEFAULT"; type FlattenedSemantics = Record<string, Record<string, Map<string, string>>>; const flattenSemantics = (allThemes: [string, ThisPluginTheme][]): FlattenedSemantics => { const semanticsAccumulating = {} as FlattenedSemantics; for (const [themeName, themeConfiguration] of allThemes) { for (const [utilityName, utilityValues] of Object.entries(themeConfiguration.semantics ?? {})) { if (!semanticsAccumulating[utilityName]) { semanticsAccumulating[utilityName] = {}; } for (const [rootName, rootValue] of Object.entries(utilityValues ?? {})) { const thing = semanticsAccumulating[utilityName]; const flatten = (name: string, value: string | ObjectOfNestedStrings) => { if (typeof value === "string") { const computedName = name === DEFAULT ? rootName : `${rootName}-${name}`; if (!thing[computedName]) { // Use Maps to guarantee order matches theme order thing[computedName] = new Map(); } thing[computedName].set(themeName, value); } else { for (const [nestedName, nestedValue] of Object.entries(value)) { const computedName = nestedName === DEFAULT ? name : `${name}-${nestedName}`; flatten(computedName, nestedValue); } } }; if (typeof rootValue === "string") { flatten(DEFAULT, rootValue); } else { for (const [name, value] of Object.entries(rootValue)) { flatten(name, value); } } } } } return semanticsAccumulating; }; const thisPlugin = plugin.withOptions(({ themes, baseSelector: passedBaseSelector, fallback = false, utilities = {}, }: ThisPluginOptions) => ({ addBase, addVariant, e, postcss, theme: lookupTheme, }: PluginTools): void => { const allThemes = Object.entries(themes ?? {}); if (allThemes.length === 0) console.warn("tailwindcss-theme-variants: no themes were given in this plugin's configuration under the `themes` key, so no variants can be generated. this can be fixed by specifying a theme like `light: { selector: '.light' }` in `themes` of this plugin's configuration. see the README for more information"); const firstTheme = allThemes[0][0]; // Implicitly disable `baseSelector` on behalf of the person only using media queries to set their themes // Otherwise use :root as the default `baseSelector` const usesAnySelectors = allThemes.some(([_name, { selector }]) => selector); const baseSelector = passedBaseSelector ?? (usesAnySelectors ? ":root" : ""); if (fallback) { if (allThemes.length === 1) { if (baseSelector === "") { console.warn(`tailwindcss-theme-variants: the "${firstTheme}" theme was selected for fallback, but it is the only one available, so it will always be active, which is unusual. this can be "fixed" by adding another theme to \`themes\` in this plugin's configuration, disabling \`fallback\` in this plugin's configuration, or setting a \`baseSelector\` in this plugin's configuration (there is no way to silence this warning)`); } else { console.warn(`tailwindcss-theme-variants: the "${firstTheme}" theme was selected for fallback, but it is the only one available, so it will always be active as long as \`${baseSelector}\` exists. this is an unusual pattern, so if you meant not to do this, it can be "fixed" by adding another theme to \`themes\` in this plugin's configuration, disabling \`fallback\` in this plugin's configuration, or changing \`baseSelector\` to \`""\` and setting this theme's \`selector\` to the current value of \`baseSelector\` (there is no way to silence this warning)`); } } if (usesAnySelectors && baseSelector === "") { console.warn(`tailwindcss-theme-variants: the "${firstTheme}" theme was selected for fallback, but you specified \`baseSelector: ""\` even though you use theme(s) that need a selector to activate, which will result in confusing and erroneous behavior of when themes activate. this can be fixed by disabling \`fallback\` in this plugin's configuration, or setting a \`baseSelector\` in this plugin's configuration (there is no way to silence this warning)`); } } // Begin variants logic for (const [themeName, { mediaQuery, selector }] of allThemes) { addVariant(themeName, ({ container, separator }) => { const originalContainer = container.clone(); // Remove the pre-existing (provided by Tailwind's core) CSS so that we don't duplicate it container.removeAll(); const nameSelector = (ruleSelector: string): string => `${(`.${e(`${themeName}${separator}`)}${ruleSelector.slice(1)}`)}`; if (fallback && themeName === firstTheme) { const containerFallBack = originalContainer.clone(); containerFallBack.walkRules((rule) => { const namedSelector = nameSelector(rule.selector); rule.selector = addParent(namedSelector, baseSelector); }); container.append(containerFallBack); } else { if (mediaQuery) { const queryAtRule = postcss.parse(mediaQuery).first; // Nest the utilities inside the given media query const queryContainer = originalContainer.clone(); queryContainer.walkRules((rule) => { const namedSelector = nameSelector(rule.selector); if (fallback && baseSelector !== "") { const inactiveThemes = selector ? allThemes.map(([_themeName, { selector: otherSelector }]) => ((selector === otherSelector) ? "" : `:not(${otherSelector})`)) : []; rule.selector = addParent(namedSelector, `${baseSelector}${inactiveThemes.join("")}`); } else { rule.selector = namedSelector; } }); if (queryAtRule?.type === "atrule") { if (queryContainer.nodes) { queryAtRule.append(queryContainer.nodes); } container.append(queryAtRule); } else { throw new TypeError(`tailwindcss-theme-variants: the media query passed to ${themeName}'s \`mediaQuery\` option (\`${mediaQuery}\`) is not a valid media query. this can be fixed by passing a valid media query there instead (lol)`); } } if (selector) { const normalContainer = originalContainer.clone(); normalContainer.walkRules((rule) => { const namedSelector = nameSelector(rule.selector); const activator = `${baseSelector}${selector}`; rule.selector = addParent(namedSelector, activator); }); container.append(normalContainer); } } }); } // End variants logic // Begin semantics logic const someSemantics = Object.values(themes).some((theme) => theme.semantics); const everySemantics = Object.values(themes).every((theme) => theme.semantics); if (everySemantics) { const semantics = flattenSemantics(allThemes); const behavior = utilities; for (const [themeName, { mediaQuery, selector }] of allThemes) { const fixedBaseSelector = baseSelector || ":root"; const semanticVariables: Record<string, string> = {}; for (const [utilityName, utilityConfig] of Object.entries(semantics ?? {})) { for (const [variable, valueMap] of Object.entries(utilityConfig ?? {})) { if (semanticVariables[variable]) { throw new TypeError(`tailwindcss-theme-variants: you duplicated a semantic variable name "${variable}" across your utilities in ${themeName}'s semantics configuration (found in ${utilityName} and at least one other place). this can be fixed by using a different name for one of them`); } const referenceValue = valueMap.get(themeName); if (!referenceValue) { throw new TypeError(`tailwindcss-theme-variants: the semantic variable "${variable}" was expected to have an initial ("constant") value for the "${themeName}" theme, but it is undefined. this can be fixed by specifying a value for "${variable}" in any utility's configuration in the "semantics" object under the "${themeName}" theme's configuration`); } const { themeValueToVariableValue = (x) => x.toString() } = behavior[utilityName] ?? ({} as SemanticUtility); const realValue = lookupTheme(`${utilityName}.${referenceValue}`, undefined); if (!realValue) throw new TypeError(`tailwindcss-theme-variants: the initial / constant value for the semantic variable named "${variable}" for the "${themeName}" theme couldn't be found; it should be named "${referenceValue}" ${referenceValue.includes(".") || referenceValue.includes("-") ? "(maybe with . in place of -?) " : ""}in \`theme.${utilityName}\`. this can be fixed by making sure the value you referenced (${referenceValue}) is in your Tailwind CSS \`theme\` configuration under \`${utilityName}\`.\nthere could be a mistake here; please create an issue if it actually does exist: https://github.com/JakeNavith/tailwindcss-theme-variants/issues`); semanticVariables[`--${variable}`] = themeValueToVariableValue(realValue.toString()); } } if (fallback && themeName === firstTheme) { addBase({ [fixedBaseSelector]: semanticVariables, }); } else { if (mediaQuery) { if (fallback) { let selectorWithCustomProperties = fixedBaseSelector; if (baseSelector !== "") { const inactiveThemes = selector ? allThemes.map(([_themeName, { selector: otherSelector }]) => ((selector === otherSelector) ? "" : `:not(${otherSelector})`)) : []; selectorWithCustomProperties = `${fixedBaseSelector}${inactiveThemes.join("")}`; } addBase({ [mediaQuery]: { [selectorWithCustomProperties]: semanticVariables, }, }); } else { addBase({ [mediaQuery]: { [fixedBaseSelector]: semanticVariables, }, }); } } if (selector) { addBase({ [`${fixedBaseSelector}${selector}`]: semanticVariables, }); } } } } else if (someSemantics) { throw new TypeError("tailwindcss-theme-variants: either all themes must define `semantics` or none do. this can be fixed by TODO"); } // End semantics logic }, ({ themes, utilities }: ThisPluginOptions) => { const everySemantics = Object.values(themes).every((theme) => theme.semantics); const extendedConfig: TailwindCSSConfig & { theme: { extend: NonNullable<TailwindCSSConfig["theme"]> } } = { theme: { extend: {}, }, }; if (everySemantics) { const behavior = { ...utilities }; const allThemes = Object.entries(themes ?? {}); const semantics = flattenSemantics(allThemes); for (const [configKey, themeMaps] of Object.entries(semantics)) { extendedConfig.theme.extend[configKey] = {}; const { variableValueToThemeValue = (x) => x } = behavior[configKey] ?? ({} as SemanticUtility); for (const semanticName of Object.keys(themeMaps)) { const variableValueToThemeValued = variableValueToThemeValue(`var(--${semanticName})`); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error it's typed wrong extendedConfig.theme.extend[configKey][semanticName] = variableValueToThemeValued; } } } return extendedConfig; }); export const themeVariants = thisPlugin; export * from "./media-queries"; export * from "./supports";
the_stack
'use strict'; import * as nls from 'vs/nls'; import { IPickOpenEntry } from 'vs/platform/quickOpen/common/quickOpen'; export interface TaskEntry extends IPickOpenEntry { sort?: string; autoDetect: boolean; content: string; } /* const gulp: TaskEntry = { id: 'gulp', label: 'Gulp', autoDetect: true, content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "gulp",', '\t"isShellCommand": true,', '\t"args": ["--no-color"],', '\t"showOutput": "always"', '}' ].join('\n') }; const grunt: TaskEntry = { id: 'grunt', label: 'Grunt', autoDetect: true, content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "grunt",', '\t"isShellCommand": true,', '\t"args": ["--no-color"],', '\t"showOutput": "always"', '}' ].join('\n') }; const npm: TaskEntry = { id: 'npm', label: 'npm', sort: 'NPM', autoDetect: false, content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "npm",', '\t"isShellCommand": true,', '\t"showOutput": "always",', '\t"suppressTaskName": true,', '\t"tasks": [', '\t\t{', '\t\t\t"taskName": "install",', '\t\t\t"args": ["install"]', '\t\t},', '\t\t{', '\t\t\t"taskName": "update",', '\t\t\t"args": ["update"]', '\t\t},', '\t\t{', '\t\t\t"taskName": "test",', '\t\t\t"args": ["run", "test"]', '\t\t}', '\t]', '}' ].join('\n') }; const tscConfig: TaskEntry = { id: 'tsc.config', label: 'TypeScript - tsconfig.json', autoDetect: false, description: nls.localize('tsc.config', 'Compiles a TypeScript project'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "tsc",', '\t"isShellCommand": true,', '\t"args": ["-p", "."],', '\t"showOutput": "silent",', '\t"problemMatcher": "$tsc"', '}' ].join('\n') }; const tscWatch: TaskEntry = { id: 'tsc.watch', label: 'TypeScript - Watch Mode', autoDetect: false, description: nls.localize('tsc.watch', 'Compiles a TypeScript project in watch mode'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "tsc",', '\t"isShellCommand": true,', '\t"args": ["-w", "-p", "."],', '\t"showOutput": "silent",', '\t"isBackground": true,', '\t"problemMatcher": "$tsc-watch"', '}' ].join('\n') }; const dotnetBuild: TaskEntry = { id: 'dotnetCore', label: '.NET Core', sort: 'NET Core', autoDetect: false, description: nls.localize('dotnetCore', 'Executes .NET Core build command'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "dotnet",', '\t"isShellCommand": true,', '\t"args": [],', '\t"tasks": [', '\t\t{', '\t\t\t"taskName": "build",', '\t\t\t"args": [ ],', '\t\t\t"isBuildCommand": true,', '\t\t\t"showOutput": "silent",', '\t\t\t"problemMatcher": "$msCompile"', '\t\t}', '\t]', '}' ].join('\n') }; const msbuild: TaskEntry = { id: 'msbuild', label: 'MSBuild', autoDetect: false, description: nls.localize('msbuild', 'Executes the build target'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "msbuild",', '\t"args": [', '\t\t// Ask msbuild to generate full paths for file names.', '\t\t"/property:GenerateFullPaths=true"', '\t],', '\t"taskSelector": "/t:",', '\t"showOutput": "silent",', '\t"tasks": [', '\t\t{', '\t\t\t"taskName": "build",', '\t\t\t// Show the output window only if unrecognized errors occur.', '\t\t\t"showOutput": "silent",', '\t\t\t// Use the standard MS compiler pattern to detect errors, warnings and infos', '\t\t\t"problemMatcher": "$msCompile"', '\t\t}', '\t]', '}' ].join('\n') }; const command: TaskEntry = { id: 'externalCommand', label: 'Others', autoDetect: false, description: nls.localize('externalCommand', 'Example to run an arbitrary external command'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "echo",', '\t"isShellCommand": true,', '\t"args": ["Hello World"],', '\t"showOutput": "always"', '}' ].join('\n') }; const maven: TaskEntry = { id: 'maven', label: 'maven', sort: 'MVN', autoDetect: false, description: nls.localize('Maven', 'Executes common maven commands'), content: [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558', '\t// for the documentation about the tasks.json format', '\t"version": "0.1.0",', '\t"command": "mvn",', '\t"isShellCommand": true,', '\t"showOutput": "always",', '\t"suppressTaskName": true,', '\t"tasks": [', '\t\t{', '\t\t\t"taskName": "verify",', '\t\t\t"args": ["-B", "verify"],', '\t\t\t"isBuildCommand": true', '\t\t},', '\t\t{', '\t\t\t"taskName": "test",', '\t\t\t"args": ["-B", "test"],', '\t\t\t"isTestCommand": true', '\t\t}', '\t]', '}' ].join('\n') }; */ const rosBuild: TaskEntry = { id: 'ros', label: 'ROS Build', sort: 'ros', autoDetect: false, description: nls.localize('rosBuild', 'ROS building commands'), content: [ '{', '\t"version": "0.1.0",', '\t"command": "bash",', '\t"args": [', '\t\t"-c"', '\t],', '\t"isShellCommand": true,', '\t"showOutput": "always",', '\t"suppressTaskName": true,', '\t"tasks": [', '\t\t{', '\t\t\t"taskName": "Debug",', '\t\t\t"args": [', '\t\t\t\t"catkin_make -C ${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release",', '\t\t\t"args": [', '\t\t\t\t"catkin_make -C ${workspaceRoot}"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Debug (isolated)",', '\t\t\t"args": [', '\t\t\t\t"catkin_make_isolated -C ${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release (isolated)",', '\t\t\t"args": [', '\t\t\t\t"catkin_make_isolated -C ${workspaceRoot}"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Debug (remote)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release (remote)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Debug (remote isolated)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release (remote isolated)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Debug (catkin)",', '\t\t\t"args": [', '\t\t\t\t"catkin build -w ${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release (catkin)",', '\t\t\t"args": [', '\t\t\t\t"catkin build -w ${workspaceRoot}"', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Debug (remote catkin)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Release (remote catkin)",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"problemMatcher": [', '\t\t\t\t{', '\t\t\t\t\t"owner": "cpp",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": {', '\t\t\t\t\t\t"regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",', '\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t"column": 3,', '\t\t\t\t\t\t"severity": 4,', '\t\t\t\t\t\t"message": 5', '\t\t\t\t\t}', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\w.*):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+).*at\\\\s+(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 2,', '\t\t\t\t\t\t\t"line": 3,', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"absolute"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^CMake\\\\s+(\\\\w+)",', '\t\t\t\t\t\t\t"severity": 1', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(\\\\/.+):(\\\\d+)",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2', '\t\t\t\t\t\t},', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^(.+)$",', '\t\t\t\t\t\t\t"message": 1', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t},', '\t\t\t\t{', '\t\t\t\t\t"owner": "cmake",', '\t\t\t\t\t"fileLocation": [', '\t\t\t\t\t\t"relative",', '\t\t\t\t\t\t"${workspaceRoot}/src"', '\t\t\t\t\t],', '\t\t\t\t\t"pattern": [', '\t\t\t\t\t\t{', '\t\t\t\t\t\t\t"regexp": "^\\\\s+(\\\\w.*):(\\\\d+)\\\\s+(.+)$",', '\t\t\t\t\t\t\t"file": 1,', '\t\t\t\t\t\t\t"line": 2,', '\t\t\t\t\t\t\t"message": 3', '\t\t\t\t\t\t}', '\t\t\t\t\t]', '\t\t\t\t}', '\t\t\t]', '\t\t},', '\t\t{', '\t\t\t"taskName": "Remote Deploy",', '\t\t\t"args": [', '\t\t\t\t"echo \\"Remote Arguments not configured!\\""', '\t\t\t],', '\t\t\t"isBuildCommand": true', '\t\t}', '\t]', '}' ].join('\n') }; export let templates: TaskEntry[] = [rosBuild].sort((a, b) => { return (a.sort || a.label).localeCompare(b.sort || b.label); }); // templates.push(command);
the_stack
import { NodesApiService, SearchService, setupTestBed } from '@alfresco/adf-core'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TranslateModule } from '@ngx-translate/core'; import { of, throwError } from 'rxjs'; import { PermissionListComponent } from './permission-list.component'; import { NodePermissionService } from '../../services/node-permission.service'; import { fakeEmptyResponse, fakeNodeInheritedOnly, fakeNodeLocalSiteManager, fakeNodeWithOnlyLocally, fakeNodeWithoutPermissions, fakeNodeWithPermissions, fakeReadOnlyNodeInherited, fakeSiteNodeResponse, fakeSiteRoles } from '../../../mock/permission-list.component.mock'; import { ContentTestingModule } from '../../../testing/content.testing.module'; import { MinimalNode } from '@alfresco/js-api'; describe('PermissionListComponent', () => { let fixture: ComponentFixture<PermissionListComponent>; let component: PermissionListComponent; let element: HTMLElement; let nodeService: NodesApiService; let nodePermissionService: NodePermissionService; let searchApiService: SearchService; let getNodeSpy: jasmine.Spy; let searchQuerySpy: jasmine.Spy; const fakeLocalPermission = JSON.parse(JSON.stringify(fakeNodeWithOnlyLocally)); setupTestBed({ imports: [ TranslateModule.forRoot(), ContentTestingModule ] }); beforeEach(() => { fixture = TestBed.createComponent(PermissionListComponent); component = fixture.componentInstance; element = fixture.nativeElement; nodeService = TestBed.inject(NodesApiService); nodePermissionService = TestBed.inject(NodePermissionService); searchApiService = TestBed.inject(SearchService); spyOn(nodePermissionService, 'getGroupMemberByGroupName').and.returnValue(of(fakeSiteRoles)); getNodeSpy = spyOn(nodeService, 'getNode').and.returnValue(of(fakeNodeWithoutPermissions)); searchQuerySpy = spyOn(searchApiService, 'searchByQueryBody').and.returnValue(of(fakeEmptyResponse)); component.nodeId = 'fake-node-id'; fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); }); it('should render default layout', async () => { component.nodeId = 'fake-node-id'; getNodeSpy.and.returnValue(of(fakeNodeWithoutPermissions)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('.adf-permission-container')).not.toBeNull(); expect(element.querySelector('[data-automation-id="adf-locally-set-permission"]')).not.toBeNull(); }); it('should render error template', async () => { component.nodeId = 'fake-node-id'; getNodeSpy.and.returnValue(throwError(null)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('.adf-no-permission__template')).not.toBeNull(); expect(element.querySelector('.adf-no-permission__template p').textContent).toContain('PERMISSION_MANAGER.ERROR.NOT-FOUND'); }); it('should show the node permissions', () => { component.nodeId = 'fake-node-id'; getNodeSpy.and.returnValue(of(fakeNodeWithPermissions)); component.ngOnInit(); fixture.detectChanges(); expect(element.querySelectorAll('[data-automation-id="adf-locally-set-permission"] .adf-datatable-row').length).toBe(2); const showButton = element.querySelector<HTMLButtonElement>('[data-automation-id="permission-info-button"]'); showButton.click(); fixture.detectChanges(); expect(document.querySelectorAll('[data-automation-id="adf-inherited-permission"] .adf-datatable-row').length).toBe(3); }); describe('Inherited Permission', () => { it('should show inherited details', async() => { getNodeSpy.and.returnValue(of(fakeNodeInheritedOnly)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('.adf-inherit-container .mat-checked')).toBeDefined(); expect(element.querySelector('.adf-inherit-container h3').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-PERMISSIONS PERMISSION_MANAGER.LABELS.ON'); expect(element.querySelector('span[title="total"]').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-SUBTITLE'); }); it('should toggle the inherited button', fakeAsync(() => { getNodeSpy.and.returnValue(of(fakeNodeInheritedOnly)); component.ngOnInit(); fixture.detectChanges(); expect(element.querySelector('.adf-inherit-container .mat-checked')).toBeDefined(); expect(element.querySelector('.adf-inherit-container h3').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-PERMISSIONS PERMISSION_MANAGER.LABELS.ON'); expect(element.querySelector('span[title="total"]').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-SUBTITLE'); spyOn(nodeService, 'updateNode').and.returnValue(of(fakeLocalPermission)); const slider = fixture.debugElement.query(By.css('mat-slide-toggle')); slider.triggerEventHandler('change', { source: { checked: false } }); fixture.detectChanges(); expect(element.querySelector('.adf-inherit-container .mat-checked')).toBe(null); expect(element.querySelector('.adf-inherit-container h3').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-PERMISSIONS PERMISSION_MANAGER.LABELS.OFF'); expect(element.querySelector('span[title="total"]').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-SUBTITLE'); })); it('should not toggle inherited button for read only users', async () => { getNodeSpy.and.returnValue(of(fakeReadOnlyNodeInherited)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('.adf-inherit-container .mat-checked')).toBeDefined(); expect(element.querySelector('.adf-inherit-container h3').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-PERMISSIONS PERMISSION_MANAGER.LABELS.ON'); expect(element.querySelector('span[title="total"]').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-SUBTITLE'); spyOn(nodeService, 'updateNode').and.returnValue(of(fakeLocalPermission)); const slider = fixture.debugElement.query(By.css('mat-slide-toggle')); slider.triggerEventHandler('change', { source: { checked: false } }); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('.adf-inherit-container .mat-checked')).toBeDefined(); expect(element.querySelector('.adf-inherit-container h3').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-PERMISSIONS PERMISSION_MANAGER.LABELS.ON'); expect(element.querySelector('span[title="total"]').textContent.trim()) .toBe('PERMISSION_MANAGER.LABELS.INHERITED-SUBTITLE'); expect(document.querySelector('simple-snack-bar').textContent) .toContain('PERMISSION_MANAGER.ERROR.NOT-ALLOWED'); }); }); describe('locally set permission', () => { beforeEach(() => { getNodeSpy.and.returnValue(of(fakeLocalPermission)); }); it('should show locally set permissions', async() => { searchQuerySpy.and.returnValue(of(fakeSiteNodeResponse)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('adf-user-name-column').textContent).toContain('GROUP_EVERYONE'); expect(element.querySelector('#adf-select-role-permission').textContent).toContain('Contributor'); }); it('should see the settable roles if the node is not in any site', async() => { searchQuerySpy.and.returnValue(of(fakeSiteNodeResponse)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('adf-user-name-column').textContent).toContain('GROUP_EVERYONE'); expect(element.querySelector('#adf-select-role-permission').textContent).toContain('Contributor'); const selectBox = fixture.debugElement.query(By.css(('[id="adf-select-role-permission"] .mat-select-trigger'))); selectBox.triggerEventHandler('click', null); fixture.detectChanges(); const options = fixture.debugElement.queryAll(By.css('mat-option')); expect(options).not.toBeNull(); expect(options.length).toBe(4); expect(options[0].nativeElement.innerText).toContain('ADF.ROLES.SITECOLLABORATOR'); expect(options[1].nativeElement.innerText).toContain('ADF.ROLES.SITECONSUMER'); expect(options[2].nativeElement.innerText).toContain('ADF.ROLES.SITECONTRIBUTOR'); expect(options[3].nativeElement.innerText).toContain('ADF.ROLES.SITEMANAGER'); }); it('should show readonly member for site manager to toggle the inherit permission', async() => { getNodeSpy.and.returnValue(of(fakeNodeLocalSiteManager)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('adf-user-name-column').textContent).toContain('GROUP_site_testsite_SiteManager'); expect(element.querySelector('#adf-select-role-permission').textContent).toContain('ADF.ROLES.SITEMANAGER'); const deleteButton = element.querySelector<HTMLButtonElement>('[data-automation-id="adf-delete-permission-button-GROUP_site_testsite_SiteManager"]'); expect(deleteButton.disabled).toBe(true); const otherDeleteButton = element.querySelector<HTMLButtonElement>('[data-automation-id="adf-delete-permission-button-superadminuser"]'); expect(otherDeleteButton.disabled).toBe(false); }); it('should update the role when another value is chosen', async () => { spyOn(nodeService, 'updateNode').and.returnValue(of(new MinimalNode({id: 'fake-uwpdated-node'}))); searchQuerySpy.and.returnValue(of(fakeEmptyResponse)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('adf-user-name-column').textContent).toContain('GROUP_EVERYONE'); expect(element.querySelector('#adf-select-role-permission').textContent).toContain('Contributor'); const selectBox = fixture.debugElement.query(By.css(('[id="adf-select-role-permission"] .mat-select-trigger'))); selectBox.triggerEventHandler('click', null); fixture.detectChanges(); const options = fixture.debugElement.queryAll(By.css('mat-option')); expect(options).not.toBeNull(); expect(options.length).toBe(5); options[3].triggerEventHandler('click', {}); fixture.detectChanges(); expect(nodeService.updateNode).toHaveBeenCalledWith('f472543f-7218-403d-917b-7a5861257244', { permissions: { locallySet: [ { accessStatus: 'ALLOWED', name: 'Editor', authorityId: 'GROUP_EVERYONE' } ] } }); }); it('should delete the person', async () => { spyOn(nodeService, 'updateNode').and.returnValue(of(new MinimalNode({id: 'fake-uwpdated-node'}))); searchQuerySpy.and.returnValue(of(fakeEmptyResponse)); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); expect(element.querySelector('adf-user-name-column').textContent).toContain('GROUP_EVERYONE'); expect(element.querySelector('#adf-select-role-permission').textContent).toContain('Contributor'); const deleteButton = element.querySelector<HTMLButtonElement>('[data-automation-id="adf-delete-permission-button-GROUP_EVERYONE"]'); deleteButton.click(); fixture.detectChanges(); expect(nodeService.updateNode).toHaveBeenCalledWith('f472543f-7218-403d-917b-7a5861257244', { permissions: { locallySet: [ ] } }); }); }); });
the_stack
import React, { useCallback, useEffect, useState } from "react"; import { i18n } from "@webiny/app/i18n"; import { SimpleForm, SimpleFormContent, SimpleFormFooter, SimpleFormHeader } from "@webiny/app-admin/components/SimpleForm"; import { useApolloClient } from "@apollo/react-hooks"; import { Alert } from "@webiny/ui/Alert"; import { CircularProgress } from "@webiny/ui/Progress"; import { Cell, Grid } from "@webiny/ui/Grid"; import { ButtonPrimary } from "@webiny/ui/Button"; import { Typography } from "@webiny/ui/Typography"; import { createCmsApolloClient } from "./5.19.0/createCmsApolloClient"; import { config as appConfig } from "@webiny/app/config"; import { LIST_LOCALES } from "@webiny/app-i18n/admin/views/locales/hooks/graphql"; import { CmsEditorContentModel } from "~/types"; import { Clients, ErrorValue, UpgradeItems } from "./5.19.0/types"; import { UpgradeItemsInfo } from "./5.19.0/UpgradeItemsInfo"; import { fetchModelEntries } from "./5.19.0/fetchModelEntries"; import { createRepublishMutation } from "./5.19.0/createRepublishMutation"; import { createUpgradeMutation } from "./5.19.0/createUpgradeMutation"; import { createListModelsQuery } from "./5.19.0/createListModelsQuery"; const t = i18n.ns("app-headless-cms/admin/installation"); const clients: Record<string, Clients> = {}; const getClient = (locale: string) => { if (!clients[locale]) { throw new Error(`There are no clients for locale "${locale}".`); } return clients[locale]; }; const getManageClient = (locale: string) => { return getClient(locale).manage; }; const getReadClient = (locale: string) => { return getClient(locale).read; }; interface CreateUpgradeItemsParams { locales: { code: string; }[]; } const createUpgradeItems = (params: CreateUpgradeItemsParams): UpgradeItems => { const { locales } = params; const items: UpgradeItems = { loadedModels: false, locales: {} }; const apiUrl = appConfig.getKey("API_URL", process.env.REACT_APP_API_URL); for (const locale of locales) { items.locales[locale.code] = null; clients[locale.code] = { read: createCmsApolloClient({ locale: locale.code, apiUrl, endpoint: "read" }), manage: createCmsApolloClient({ locale: locale.code, apiUrl, endpoint: "manage" }) }; } return items; }; interface UpdateUpgradeItemsParams { previous: UpgradeItems; models: Record<string, CmsEditorContentModel[]>; } const updateUpgradeItems = (params: UpdateUpgradeItemsParams): UpgradeItems => { const { previous, models } = params; const locales: UpgradeItems["locales"] = {}; for (const locale in previous.locales) { locales[locale] = (models[locale] || []).reduce((collection, model) => { collection[model.modelId] = { model, done: false, entries: [], upgrading: false }; return collection; }, {}); } return { loadedModels: true, locales }; }; type JobStatus = "pending" | "upgrading" | "completed"; const Upgrade = ({ onInstalled }) => { const client = useApolloClient(); const [error, setError] = useState<ErrorValue>(null); const [loading, setLoading] = useState(false); const [upgrade, setUpgrade] = useState(false); const [status, setStatus] = useState<JobStatus>("pending"); const [upgradeItems, setUpgradeItems] = useState<UpgradeItems>(null); useEffect(() => { /** * Never do this if we have upgrade items. */ if (upgradeItems || loading === true) { return; } setLoading(true); const fetchLocales = async () => { const response = await client.query({ query: LIST_LOCALES }); if ( !response || !response.data || !response.data.i18n || !response.data.i18n.listI18NLocales ) { console.error("Missing response when fetching locales."); return; } else if (response.data.i18n.listI18NLocales.error) { console.error(response.data.i18n.listI18NLocales.error.message); setError(error); return; } /** * New state for the upgrade items. */ setUpgradeItems(() => { return createUpgradeItems({ locales: response.data.i18n.listI18NLocales.data }); }); /** * And stop the spinner. */ setLoading(false); }; fetchLocales(); }, []); useEffect(() => { if ( !upgradeItems || !upgradeItems.locales || upgradeItems.loadedModels === true || loading === true ) { return; } setLoading(true); const fetchModels = async () => { const models: Record<string, CmsEditorContentModel[]> = {}; /** * Load all models from locales, one by one so we dont nuke API too much. */ const { locales } = upgradeItems; /** * Query does not care about locale so we can create it before the loop. */ const query = createListModelsQuery(); /** * */ for (const locale in locales) { const response = (await getManageClient(locale).query({ query })) as any; const { listContentModels } = response.data || {}; const { data, error } = listContentModels; if (error) { setError(error); return; } else if (!data) { setError({ message: `No data received when loading all models in locale "${locale}".` }); return; } else if (data.length === 0) { continue; } /** * We only need models that have at least one ref field or an object field that MIGHT contain ref fields. */ models[locale] = data.filter(model => { return model.fields.some( field => field.type === "object" || field.type === "ref" ); }); } /** * We add models only once to skip unnecessary state changes. */ setUpgradeItems(previous => { return updateUpgradeItems({ previous, models: models }); }); setLoading(false); }; fetchModels(); }, [upgradeItems, loading]); const startUpgrade = useCallback(() => { if (!upgradeItems || upgradeItems.loadedModels !== true || upgrade === true) { return; } setUpgrade(true); }, [upgradeItems]); useEffect(() => { if ( !upgrade || !upgradeItems || !upgradeItems.locales || upgradeItems.loadedModels === false || status !== "pending" ) { return; } const { locales } = upgradeItems; setStatus("upgrading"); const republish = async () => { for (const locale in locales) { const localeData = locales[locale]; const manageClient = getManageClient(locale); const readClient = getReadClient(locale); for (const modelId in localeData) { const modelData = localeData[modelId]; /** * This should never be true but let's check just in case of some missed loop breaks. */ if (modelData.done || modelData.upgrading) { continue; } const entries = await fetchModelEntries({ model: modelData.model, client: readClient }); setUpgradeItems(previous => { return { ...previous, locales: { ...previous.locales, [locale]: { ...previous.locales[locale], [modelId]: { model: modelData.model, done: false, upgrading: true, entries: entries.map(id => { return { id, done: false }; }) } } } }; }); const mutation = createRepublishMutation(modelData.model); for (const id of entries) { const republishResponse = await manageClient.mutate({ mutation, variables: { revision: id } }); const { error } = republishResponse.data.content; if (error) { setError(error); return; } setUpgradeItems(previous => { return { ...previous, locales: { ...previous.locales, [locale]: { ...previous.locales[locale], [modelId]: { model: previous.locales[locale][modelId].model, entries: previous.locales[locale][modelId].entries.map( info => { return { id: info.id, done: info.done === true || id === info.id }; } ), done: false, upgrading: true } } } }; }); } setUpgradeItems(previous => { return { ...previous, locales: { ...previous.locales, [locale]: { ...previous.locales[locale], [modelId]: { model: modelData.model, entries: [], done: true, upgrading: false } } } }; }); } } const response = await client.mutate({ mutation: createUpgradeMutation(), variables: { version: "5.19.0" } }); const { error } = response.data.cms.upgrade; setStatus("completed"); if (error) { setError(error); return; } onInstalled(); }; republish(); }, [upgrade, upgradeItems, status]); const label = error ? ( <Alert title={t`Something went wrong`} type={"danger"}> {error.message} </Alert> ) : upgrade ? ( t`Upgrading Headless CMS...` ) : ( "Loading Headless CMS information" ); return ( <SimpleForm> {(loading || error) && <CircularProgress label={label} />} <SimpleFormHeader title={"Upgrade Headless CMS"} /> <SimpleFormContent> <Grid> <Cell span={12}> <Typography use={"body1"} tag={"div"}> This upgrade will do the following: <ul> <li>update entries</li> </ul> <UpgradeItemsInfo upgradeItems={upgradeItems} /> </Typography> </Cell> </Grid> </SimpleFormContent> <SimpleFormFooter> <ButtonPrimary disabled={loading || upgrade} onClick={startUpgrade}> Upgrade </ButtonPrimary> </SimpleFormFooter> </SimpleForm> ); }; export default Upgrade;
the_stack
import { Component, OnInit, ViewChild, Input,Output, EventEmitter } from "@angular/core"; import { TranslateService } from "@ngx-translate/core"; import { IdpService } from "../idp-service.service"; import { IdprestapiService } from "../idprestapi.service"; import { Router } from "@angular/router"; import { IdpdataService } from "../idpdata.service"; import { DataTable, DataTableResource } from "angular-2-data-table"; import { ActivatedRoute } from "@angular/router"; import { TabsetComponent } from 'ngx-bootstrap'; import * as _ from 'lodash' import { TreeviewModule, TreeviewConfig, TreeviewItem, TreeviewHelper, DownlineTreeviewItem, TreeviewI18n, TreeviewComponent, TreeviewEventParser, OrderDownlineTreeviewEventParser } from "ngx-treeview"; import { IDPEncryption } from "../idpencryption.service"; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service'; import { Item } from "angular2-multiselect-dropdown"; declare var jQuery: any; @Component({ selector: "app-trigger", templateUrl: "./triggerPipeline.component.html", styleUrls: ["./triggerPipeline.component.css"], providers: [ { provide: TreeviewEventParser, useClass: OrderDownlineTreeviewEventParser } ] }) export class TriggerComponent implements OnInit { @ViewChild(TreeviewComponent) treeviewComponent: TreeviewComponent; @ViewChild("modalforAlert") modalforAlert; @ViewChild("modalforArtifactAlert") modalforArtifactAlert; @ViewChild("modalforSubmitAlert") modalforSubmitAlert; @ViewChild("modalforTrigger") modalforTrigger; @ViewChild("modalforAlertDBDep") modalforAlertDBDep; @ViewChild("modalforReqSCMAlert") modalforReqSCMAlert; @ViewChild('staticTabs') staticTabs: TabsetComponent; // save button both for schedule and workflow (master pipeline) feature @ViewChild("modalforSave") modalforSave; @Input() workflowSequenceIndexI: number; @Input() workflowSequenceIndexJ: number; @Input() workflowSequenceIndexK: number; @Output() onTriggerDetailsSaved = new EventEmitter<boolean>(); isParameterDisabled = false; applicationName:any=""; pipelineName:any=""; data = { "applicationName": "", "pipelineName": "", "userName": "" }; paramData = { "applicationName": "", "pipelineName": "", "userName": "" }; approvalStages = []; SAPEnvList: any = []; crApprover: any = ""; deployEnvList: any; error: any = ""; devEnvList: any = []; userStoryArray: any = []; validateClick: any = ""; valideStory: any = ""; envJson: any = ""; SAPEnv: any = ""; TransReq: any = ""; SapBuild: any; SapDeploy: any; SapTest: any; parameterloading: any = false; msg: any; IDPParamData: any = {}; IDPDataSwitch: any = {}; Env: any; Envbiz: any; SapSystemName: any = ""; hideTransportRequest = false; import: any; ApproveDep: any; environment: any; SapsystemNames: any; transportRequests: any = []; transportRequest: any; unselectedTRs: any = []; selectedTR: any; showData: any; devTrue: any; build: any = {}; allArtifactlist: any; buildSelect: any = "off"; deploySelect: any = "off"; testSelect: any = "off"; reconcileSelect: any = "off"; buildEnv: any = []; deployEnv: any = []; testEnv: any = []; allEnv: any = []; buildTestEnv: any = []; downgradeTransportRequest: any = ""; objectData: any = []; objectTypeList: any = []; objectNameList: any = []; selectedItems: any = []; dropdownSettings: any = {}; dbDeployRollbackTypeList: any = []; hideTransportRequests: any = false; branchList: any; testPlansList: any = []; branchTemp: any; buildIntervalData: any; tagTemp: any; tagList: any; branchOrTag: any; isCollapsed:boolean=true; scmType: any; dropdownListTest: any = []; testSuitList: any = []; dropdownListDeploy: any = []; rmsComponentName:any; rmsArtifacts: any = []; trialArr=[]; deployMultiselectSettings = { singleSelection: false, text: "Select Deploy Steps", enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; testMultiselectSettings = { singleSelection: false, text: "Select Test Steps", enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; virtualServiceMultiselectSettings = { singleSelection: false, text: "Select Virtual Services", enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; ibmRQMTestCaseMultiselectSettings = { singleSelection: false, text: "Select IBM RQM Test Case", enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; dbMultiselectSettings = { singleSelection: false, text: "Select DB operations", enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; isBuild: any = false; isDeploy: any = false; testSuitId: any = []; resetSelect = "off"; deploySteps: any = []; testSteps: any = []; tempDeploySteps: any = []; tempTestSteps: any = []; deployArr: any = []; testArr: any = []; jobParamList: any; operation: any; disableflag: any; showJobParamFlag: any; testStepWithToolList: any = []; notFound: any = []; invalid: any = []; module: any = {}; validWorkItems = false; slavestatus: any; testslavestatus: any; artifactDetails: any; packageContent: any; informatica: any; grantAccess: any = this.IdpdataService.data.grantAccess; isEnableTrack: string; config = TreeviewConfig.create({ hasAllCheckBox: false, hasFilter: false, hasCollapseExpand: false, decoupleChildFromParent: true, maxHeight: 400 }); siebel = { repoList: [], nonRepoList: [] }; pega = { pegaFileList: [] }; ant: any; dotNet: any; bigData: any; fetchedVirtualServicesList: any; tempVirtualServicesList: any; selectedVirtualServicesList: any; virtualServicesArr: any = []; dashboardUrl: String; fetchedIBMRQMTestCaseList: any; tempIBMRQMTestCaseList: any; selectedIBMRQMTestCaseList: any; ibmRQMTestCaseArr: any = []; changeReqestList: any; crListShow: any = []; artifacts: any; requiredSCM: any = false; branchListReqTemp: any = []; branchOrTagValue = ""; rmsEnv:any; alertModalRef: BsModalRef; missingSCMBranchModalRef: BsModalRef; confirmSaveModalRef: BsModalRef; dbDepModalRef: BsModalRef; selectArtifactModalRef: BsModalRef; submitModalRef: BsModalRef; triggerModalRef: BsModalRef; disableSubmitBtn: boolean = false; tempTrArrayDeploy: any = []; tempTrArrayJira: any = []; userstoryDropdownSettings: any = {}; changeDocumentDropdownSettings : any = {} userStoryList: any; selectedUS: any; selectedUSStr: any; selectedUSData: any; selectedCD : any; selectedCDData : any; cdListWithDescription : any =[]; cdListWithStatus : any =[]; changeRequestDetails = { "buildCaCr": [], "buildUtCr": [], "buildCr": [], "changeDocumentMapping": [ { "changeDocument": "", "changeDocumentData": [ { "crNumber": "", "crDescription": "", "cdNumber": "", "cdDescription": "", "cdStatus": "", "cdType": "", "trNumber": "", "trDescription": "", "trStatus": "", "track": "", "trackDescription": "", "subTrack": "", "subTrackDescription": "", } ], "developer":"", "technicalReviewer":"", "functionalReviewer":"", "functionalTester":"", "CC":"", "PFA":"", "DM":"" } ], "crcdRelationList": [ { "changeRequest": "", "changeDocumentList": [] } ], "deployEnvCrList": [ { "environmentName": "", "changeRequestList": [] } ], "deployEnvCdList": [ { "environmentName": "", "changeDocumentList": [] } ], "listOfStatus": [], "crAndDescription" : [], "crsBasedOnStatusOfCD": [ { "statusOfCD": "", "crAndDescriptionList": [] } ], "crsBasedOnTrackSubtrack": [ { "track": "", "trackDescription": "", "subTrack": "", "subTrackDescription": "", "crAndDescriptionList": [], "trackRolesMapping": [] } ] }; charmTriggerData = { "changeRequest" : "", "changeDocument" : [], "sapTrackSelected": "", "sapSubTrackSelected": "" } changeRequestList : any = []; changeRequestListTemp : any = []; changeDocumentList : any = []; changeDocumentListTemp : any = []; sapTrackListTemp : any = []; sapSubTrackListTemp : any = []; hideChangeDocument : boolean = false; hideChangeRequest : boolean = false; hideTrackDetails : boolean = false; isAllowed : boolean = false; showErrorForST : boolean = false; cdDetailsList : any = []; hideLandscape : any = ""; changeDocumentListDescDropdown=[]; rmsApprovedArtifact : any; showPermissionError: any = ""; selectedLandscapeType: string = ""; // [ // { // "crNumber": "", // "crDescription": "", // "cdDescription": "", // "cdStatus": "", // "cdType": "", // "trNumber": "", // "trDescription": "", // "trStatus": "", // "cdNumber": "" // } // ] ngOnInit() { this.getapptype(this.idpdataService.appName); this.triggerDataInitialization(); this.getJobParamDetails(); if(this.IDPParamData.technology==='sapcharm'){ this.getChangeRequest(); } } constructor( public idpdataService: IdpdataService, private idprestapiService: IdprestapiService, private router: Router, private route:ActivatedRoute, public idpService: IdpService, private idpencryption: IDPEncryption, private modalService:BsModalService, private IdprestapiService: IdprestapiService, private IdpdataService: IdpdataService, ) { this.route.queryParams.subscribe(params => { if(params['applicationName'] && params['pipelineName'] ) { this.idpdataService.appName = params['applicationName']; this.idpdataService.pipelineName = params['pipelineName']; } }); this.buildIntervalData = this.idpdataService.buildIntervalData; if (this.idpdataService.buildIntervalData === undefined) { this.idpdataService.buildIntervalData = []; } } populateDBDeployRollBackTypeList() { this.dbDeployRollbackTypeList = [{ 'name': 'byTag', 'value': 'byTag' }, { 'name': 'byChangeSet', 'value': 'byChangeSet' }, { 'name': 'byHours', 'value': 'byHours' }, { 'name': 'byDate', 'value': 'byDate' } ]; } getapptype(appName){ this.IdprestapiService.checkForApplicationType(appName).then(response => { try { if (response) { if (response.json().errorMessage === null && response.json().resource !== "") { if (response.json().resource === "true") { //alert("true") this.idpdataService.isSAPApplication = true; } else { this.idpdataService.isSAPApplication = false; } } else { alert("Failed to verify application Type"); } } } catch (e) { alert("Failed during verifying the application type"); } this.idpdataService.loading = false; }); } changeDBDeployRollbackValues() { this.IDPParamData.deploy.dbDeployRollbackValue = ""; } selectTab(tabId: number) { this.staticTabs.tabs[tabId].active = true; } fetchReleaseBranches(data) { const releaseDetails = this.idpdataService.triggerJobData.releaseBranches; if (releaseDetails.hasOwnProperty(data)) { if (releaseDetails[data].length && releaseDetails[data].length !== 0) { this.branchList = releaseDetails[data]; this.requiredSCM = true; this.branchListReqTemp = this.idpService.copy(this.branchList); } else { this.branchList = this.idpService.copy(this.branchTemp); this.requiredSCM = false; } } // SAP filter to fetch landscape names if (this.idpdataService.isSAPApplication) { this.setLandscapeNames(); } } // Fetch userstory details from Jira as per the release number selected fetchUserStories(releaseNumber) { this.userStoryArray = []; // this.IDPParamData.userStories = []; this.selectedUS = []; this.userStoryList = []; this.selectedUSData = []; const data = { "application_name": this.IDPParamData.applicationName, "pipeline_name": this.IDPParamData.pipelineName, "release": this.IDPDataSwitch.releaseNumber }; try { if (this.idpdataService.checkpollALM) { this.idpdataService.loading = true; this.idprestapiService.getUserStoriesSAP(data).then(response => { if (response) { this.idpdataService.loading = false; if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { if(JSON.parse(response.json().resource).UserStoryInfo !== undefined){ const userStoryArray = JSON.parse(response.json().resource).UserStoryInfo; const temp = []; for (let i = 0; i < userStoryArray.length; i++) { if (userStoryArray[i].Transport) { if (userStoryArray[i].Transport.length !== 0) { temp.push({ "Userstory": userStoryArray[i].Userstory, "Transport": userStoryArray[i].Transport }); } } } this.userStoryArray = temp; } } if (this.userStoryArray.length > 0) { for (let i = 0; i < this.userStoryArray.length; i++) { this.userStoryList.push({"id": i, "itemName": this.userStoryArray[i].Userstory}); } } } }); } } catch (e) { alert("Failed in getting User Stories data"); } } fetchSapSubTracks() { this.sapSubTrackListTemp = []; const trackList = this.changeRequestDetails.crsBasedOnTrackSubtrack; for( let i = 0 ; i< trackList.length ; i++){ let localTrackList = trackList[i].track; if(this.charmTriggerData.sapTrackSelected === localTrackList){ this.sapSubTrackListTemp.push({"val": trackList[i].subTrack, "description": trackList[i].subTrack+ " --> "+ trackList[i].subTrackDescription}); } } } addArtifact() { const temp = this.idpdataService.triggerJobData.artifactList; this.artifacts = []; this.allArtifactlist = []; if (this.IDPDataSwitch.deploySelected === "on" && this.IDPDataSwitch.buildSelected === "on") { const tempLatestArtifact = [{ "artifactName": "", "artifactID": "", "groupId": "", "nexusURL": "", "repoName": "", "version": "", "buildModules": "", "enviromment": "", "userInfo": "", "timestamp": "", "downloadURL": "" }]; tempLatestArtifact[0].artifactName = this.idpdataService.triggerJobData.applicationName + "_" + this.idpdataService.triggerJobData.pipelineName + "_latestArtifact"; tempLatestArtifact[0].groupId = this.idpdataService.triggerJobData.applicationName; tempLatestArtifact[0].artifactID = this.idpdataService.triggerJobData.pipelineName; tempLatestArtifact[0].nexusURL = this.idpdataService.triggerJobData.nexusURL; tempLatestArtifact[0].repoName = this.idpdataService.triggerJobData.repoName; this.artifacts = tempLatestArtifact; this.allArtifactlist = tempLatestArtifact; } } clearWorkItemField() { this.notFound = []; this.invalid = []; this.validWorkItems = false; } validate() { const list = this.IDPParamData.tfsWorkItem.split(","); const mainList = []; let x = true; if (x) { for (let y = 0; y < list.length; y++) { if (y === list.length - 1) { x = false; } console.log(list[y]); const data = list[y]; this.idpdataService.loading = true; this.idprestapiService.getWorkItems(data) .then(response => { if (response) { this.idpdataService.loading = false; const fields = response.json().fields; const msg = response.json().message; if (fields) { const workType = fields["System.WorkItemType"]; const obj = {"workItem": data, "status": workType }; mainList.push(obj); } else if (msg && msg.indexOf("does not exist") !== -1) { const obj = { "workItem": data, "status": "not Found" }; mainList.push(obj); } if (mainList.length === list.length) { console.log(mainList.length); this.checkValidity(mainList); } } this.idpdataService.loading = false; }) .catch(error => { this.idpdataService.loading = false; console.log(error); }); } } } checkValidity(data) { for (let i = 0; i < data.length; i++) { if (data[i].status === "not Found") { this.notFound.push(data[i]); } else if (data[i].status !== "Product Backlog Item" && data[i].status !== "Task") { this.invalid.push(data[i]); } } if (this.invalid.length === 0 && this.notFound.length === 0) { this.validWorkItems = true; } } clearUserStory() { this.validateClick = "false"; this.valideStory = "false"; } validateStories() { this.idpdataService.loading = true; this.idprestapiService.getUserStories(this.IDPParamData.jiraProjectKey).then(response => { if (response) { this.idpdataService.loading = false; this.valideStory = "true"; if (response.json().resource !== null) { const userStories = JSON.parse(response.json().resource).userStoryInfo; const stories = this.IDPParamData.userStoryString.split(","); let count = 0; for (const i of stories) { if (userStories.indexOf(i) === -1) { count += 1; this.validateClick = "false"; } } if (count === 0) { this.validateClick = "true"; } } else { alert("No user stories available for this project"); this.validateClick = "false"; } } else { this.idpdataService.loading = false; alert("Failed to get User Stories for the project"); this.validateClick = "false"; } }); } setArtifact1() { this.IDPDataSwitch.buildSelected = "on"; this.IDPParamData.deploy.artifacts = ""; if (this.IDPParamData.deploy.deployModule !== undefined) { this.IDPParamData.deploy.deployModule = []; } this.addArtifact(); return "on"; } setArtifact2() { this.IDPDataSwitch.deploySelected = "on"; this.IDPParamData.deploy.artifacts = ""; this.addArtifact(); this.checkDBOperation(); if (this.IDPDataSwitch.subModules !== undefined && this.IDPDataSwitch.subModules.length !== undefined) { for (let i = 0; i < this.IDPDataSwitch.subModules.length; i++) { if (this.IDPDataSwitch.subModules[i].defaultModule === "on") { const modName = this.IDPDataSwitch.subModules[i].moduleName; this.IDPParamData.deploy.subModule.push(modName); } } } return "on"; } alertforNoArtifact() { if (this.idpdataService.triggerJobData.artifactList === undefined || this.idpdataService.triggerJobData.artifactList.length === 0 || this.idpdataService.triggerJobData.artifactList === null) { this.triggerAlertArtifact(); } } clearTriggerArtifact() { this.IDPParamData.deploy.artifacts = []; } populateEnv() { if (this.error === "SUCCESS") { if (this.deployEnvList.length === 0) { this.Env = []; this.disableflag = true; this.IDPDataSwitch.deploySelected = "off"; alert("You can not deploy this application now. Please trigger it at planned time."); const currentTime = new Date(); const hours = currentTime.getHours(); const minutes = currentTime.getMinutes(); const timeZoneOffset = hours + ":" + minutes; this.idprestapiService.getAvailableSlot(this.IDPParamData.applicationName, this.IDPDataSwitch.releaseNumber, timeZoneOffset).then(response => { if (response) { if (response.json().resource !== null) { alert(response.json().resource); } else { alert("No slots available for the day"); } } else { alert("Could not suggest next available slot"); } }); if (this.IDPDataSwitch.testSelected === "on") { this.Env = this.IDPDataSwitch.testEnv; } return; } else { const tempEnv = []; for (const i of this.Env) { if (this.deployEnvList.indexOf(i) !== -1) { tempEnv.push(i); } this.Env = tempEnv; } if (this.Env.length === 0) { alert("You can not deploy this application now. Please trigger it at planned time"); const currentTime = new Date(); const hours = currentTime.getHours(); const minutes = currentTime.getMinutes(); const timeZoneOffset = hours + ":" + minutes; this.idprestapiService.getAvailableSlot(this.IDPParamData.applicationName, this.IDPDataSwitch.releaseNumber, timeZoneOffset).then(response => { if (response) { if (response.json().resource !== null) { alert(response.json().resource); } else { alert("No slots available for the day"); } } else { alert("Couild not suggest next available slot"); } }); this.disableflag = true; this.IDPDataSwitch.deploySelected = "off"; } if (this.IDPDataSwitch.testSelected === "on" && this.IDPDataSwitch.deploySelected === "off") { this.Env = this.IDPDataSwitch.testEnv; } return; } } } getEnvNames() { this.idprestapiService.getEnvNames(this.IDPParamData.applicationName, this.IDPDataSwitch.releaseNumber).then(response => { if (response) { if (JSON.parse(response.text()).status !== "Env was not planned") { if (response.status === 200) { this.deployEnvList = JSON.parse(response.json().resource).names; this.error = "SUCCESS"; this.populateEnv(); } else { this.error = "Could not fetch"; } } else { this.error = "Env was not planned"; } } }); } checkDBOperation() { } toggleSelection(module) { const idx = this.IDPParamData.build.module.indexOf(module); if (idx > -1) { this.IDPParamData.build.module.splice(idx, 1); } else { this.IDPParamData.build.module.push(module); } } toggleSelection1(subModule) { const idx = this.IDPParamData.deploy.subModule.indexOf(subModule); if (idx > -1) { this.IDPParamData.deploy.subModule.splice(idx, 1); } else { this.IDPParamData.deploy.subModule.push(subModule); } } toggleSelectionDeploy(module) { const idx = this.IDPParamData.deploy.deployModule.indexOf(module); if (idx > -1) { this.IDPParamData.deploy.deployModule.splice(idx, 1); } else { this.IDPParamData.deploy.deployModule.push(module); } } toggleSelection2() { alert("in toggle2"); if (this.IDPDataSwitch.subModules) { alert("in if"); for (let i = 0; i < this.IDPDataSwitch.subModules.length; i++) { alert(this.IDPDataSwitch.subModules[i].moduleName); if (this.IDPDataSwitch.subModules[i].defaultModule === "on") { this.IDPParamData.deploy.subModule.push(this.IDPDataSwitch.subModules[i].moduleName); } } } } checkEnvToPopulate() { if (this.IDPDataSwitch.testSelected === "on" && this.IDPDataSwitch.deploySelected === "on") { this.Env = this.IDPDataSwitch.deployTestEnv; this.getEnvNames(); this.Envbiz = this.IDPDataSwitch.deploytestbizEnv; } else if (this.IDPDataSwitch.testSelected === "on" && this.IDPDataSwitch.deploySelected === "off") { this.Env = this.IDPDataSwitch.testEnv; } else if (this.IDPDataSwitch.buildSelected === "on" && this.IDPDataSwitch.deploySelected === "on") { const temp = this.IDPDataSwitch.buildDeployEnv; this.Env = []; for (const obj of temp) { if (obj.releaseNumber === this.IDPDataSwitch.releaseNumber) { this.Env = obj.Env; this.getEnvNames(); break; } } } else { this.Env = this.IDPDataSwitch.deployEnv; this.getEnvNames(); this.Envbiz = this.IDPDataSwitch.deploybizEnv; } } checkrm() { if (this.Envbiz !== undefined) { for (let i = 0; i < this.Envbiz.length; i++) { if (this.Envbiz[i].EnvName === this.IDPParamData.envSelected) { if (this.Envbiz[i].bizCheck === "on") { return true; } else { return false; } } } } return false; } checkrmcheck() { this.IDPParamData.removePrevAssem = "off"; this.IDPParamData.rmAssemblies = ""; this.clearArtifact(); if (this.IDPParamData.envSelected !== undefined) { this.fetchSteps(); } } triggerDataInitialization() { this.IdpdataService.isSAPApplication = false; this.paramData.applicationName = this.idpdataService.appName; this.paramData.pipelineName=this.idpdataService.pipelineName; this.idprestapiService.getUserName().then(response=>{ try{ if(response) { const result=response.json().resource; console.log(JSON.parse(result)); this.idpdataService.idpUserName=JSON.parse(result).user_id; console.log(response); this.paramData.userName=this.idpdataService.idpUserName; console.log("data",this.paramData); this.IdprestapiService.triggerJob(this.paramData) .then(response => { if (response) { const result = response.json().resource; if (result !== "{}" && result !== null) { this.IdpdataService.triggerJobData = JSON.parse(result); const temp = JSON.parse(result); const checkInBuild = this.IdpdataService.triggerJobData.hasOwnProperty("build") && this.IdpdataService.triggerJobData.build.approveBuild !== undefined && this.IdpdataService.triggerJobData.build.approveBuild !== null && this.IdpdataService.triggerJobData.build.approveBuild.length !== 0; const checkInDeploy = this.IdpdataService.triggerJobData.hasOwnProperty("deploy") && this.IdpdataService.triggerJobData.deploy.workEnvApprovalList !== undefined && this.IdpdataService.triggerJobData.deploy.workEnvApprovalList !== null && Object.keys(this.IdpdataService.triggerJobData.deploy.workEnvApprovalList).length !== 0 && this.IdpdataService.triggerJobData.deploy.workEnvApprovalList.constructor === Object; if (checkInBuild || checkInDeploy) { this.IdpdataService.checkPausedBuilds = true; if (checkInBuild) { this.isBuild = true; } if (checkInDeploy) { this.isDeploy = true; } } else { this.IdpdataService.checkPausedBuilds = false; } if (this.IdpdataService.triggerJobData.applicationName) { const applicationName = this.IdpdataService.triggerJobData.applicationName; } if (this.IdpdataService.triggerJobData.releaseNumber !== null && this.IdpdataService.triggerJobData.releaseNumber.length !== 0) { if (this.IdpdataService.checkPausedBuilds === true) { if (this.IdpdataService.triggerJobData.roles.indexOf("RELEASE_MANAGER") !== -1 && (this.isBuild === true || this.isDeploy === true)) { const forBuild = this.isBuild && this.IdpdataService.approveBuildFlag; const forDeploy = this.isDeploy && this.IdpdataService.approveDeployFlag; if (forBuild && forDeploy) { this.router.navigate(["/previousConfig/approveBuild"]); } if (forBuild) { if ((this.IdpdataService.approveDeployFlag !== true)) { alert("You do no thave permission to approve build for Deploy Stage"); } this.router.navigate(["/previousConfig/approveBuild"]); } if (forDeploy) { if ((this.IdpdataService.approveBuildFlag !== true)) { alert("You do no thave permission to approve build for Build Stage"); } this.router.navigate(["/previousConfig/approveBuild"]); } } else { alert("A build is waiting approval. Kindly contact your release manager."); } } } else if (this.IdpdataService.triggerJobData.roles.indexOf("RELEASE_MANAGER") !== -1) { alert("No active releases for this pipeline. Please add releases."); this.router.navigate(["/releaseConfig/release"]); } else { alert("No active releases for this pipeline. Please contact the release manager."); } } else { alert("Failed to get the Trigger Job Details"); } this.initialize(); } }); } } catch (e) { alert("Failed to get trigger details"); console.log(e); } }) } initialize() { if (!this.idpdataService.isSAPApplication) { this.dbDeployRollbackTypeList = [{ 'name': 'byTag', 'value': 'byTag' }, { 'name': 'byChangeSet', 'value': 'byChangeSet' }, { 'name': 'byHours', 'value': 'byHours' }, { 'name': 'byDate', 'value': 'byDate' } ]; this.IDPParamData = { "applicationName": "", "artifactorySelected": "off", "technology": this.idpdataService.triggerJobData.technology, "subApplicationName": "", "ibmRQMTestSuiteId": "", "schedule": false, "dashBoardLink": this.idpdataService.IDPDashboardURL, "pairNames": [], "jobParam": [], "jiraProjectKey": "", "build": { "branchSelected": "", "module": [], "checkmarxTag": this.idpdataService.triggerJobData.build.checkmarxTag , "checkmarxIncremental" : "", "runCheckmarxInput": "", }, "deploy": { "deployArtifact": {}, "artifactID": "", "nexusId": "", "version": "", "artifacts": {}, "deployStep": [], "dbDeployRollbackType": "", "deployModule": [], "subModule": [] }, "env": [], "charmRequests": [], "envSelected": "", "approvalSelected": "", "pipelineName": "", "releaseNumber": "", "jobBuildId": "", "userTeam":"", "slaveName": "", "testSlaveName": "", "branchOrTag": "", "testPlanId": "", "testSuitId": "", "mtmStepName": "", "rebase": { "sourceEnvSelected": "", "transportObjectType": "", "transportObject": "", "targetEnvSelected": "", "bugFixTR": "" }, "repoDeployStatus": "", "nonRepoDeployStatus": "", "testSelected": "off", "testStep": [], "userName": this.idpdataService.idpUserName, "gitTag": "", "scanTag": this.idpdataService.triggerJobData.build.scanTag , "buildartifactNumber": "", }; this.IDPDataSwitch = { "test": false, "build": false, "deploy": false, "nexusURL": "", "repoName": "", "releaseManager": true, "buildSelected": "off", "deploySelected": "off", "testSelected": "off", "reconcileSelected": "off", "sifImport": "off", "srfCompile": "off", "srfCompileType": "", "repoDeployStatus": "", "nonRepoDeployStatus": "", "slaves": [], "appSlaves": [], "modules": [], "subModules": [], "artifacts": [], "buildBranch": [], "jobParm": [], "buildenv": [], "testEnv": [], "buildDeployEnv": [], "deployEnv": [], "gitTagEnable": "", "checkmarxTag": "", "sshAndDependent": "", "relaseList": [], "releaseNumberList": [], "releaseNumber": "" }; try { if (this.idpdataService.triggerJobData) { if (this.idpdataService.triggerJobData.hasOwnProperty("build")) { this.IDPDataSwitch.build = true; this.IDPDataSwitch.modules = this.idpdataService.triggerJobData.build.hasOwnProperty("modules") ? this.idpdataService.triggerJobData.build.modules : []; this.IDPDataSwitch.subModules = this.idpdataService.triggerJobData.build.hasOwnProperty("subModules") ? this.idpdataService.triggerJobData.build.subModules : []; for (let i = 0; i < this.IDPDataSwitch.modules.length; i++) { if (this.IDPDataSwitch.modules[i].defaultModule === "on") { const modName = this.IDPDataSwitch.modules[i].moduleName; this.IDPParamData.build.module.push(modName); } } this.IDPDataSwitch.buildBranch = this.idpdataService.triggerJobData.build.hasOwnProperty("gitBranches") ? this.idpdataService.triggerJobData.build.gitBranches : []; this.IDPDataSwitch.gitTagEnable = this.idpdataService.triggerJobData.build.hasOwnProperty("gitTag") ? this.idpdataService.triggerJobData.build.gitTag : []; this.IDPDataSwitch.checkmarxTag = this.idpdataService.triggerJobData.build.hasOwnProperty("checkmarxTag") ? this.idpdataService.triggerJobData.build.checkmarxTag : "off"; this.IDPDataSwitch.sshAndDependent = this.idpdataService.triggerJobData.hasOwnProperty("sshAndDependent") ? this.idpdataService.triggerJobData.sshAndDependent : []; this.IDPDataSwitch.relaseList = this.idpdataService.triggerJobData.hasOwnProperty("relaseList") ? this.idpdataService.triggerJobData.relaseList : []; this.IDPDataSwitch.releaseNumberList = this.idpdataService.triggerJobData.hasOwnProperty("releaseNumber") ? this.idpdataService.triggerJobData.releaseNumber : []; } this.branchList = this.idpdataService.triggerJobData.hasOwnProperty("branchList") ? this.idpdataService.triggerJobData.branchList : []; this.tagList = this.idpdataService.triggerJobData.hasOwnProperty("tagList") ? this.idpdataService.triggerJobData.tagList : []; this.branchTemp = this.idpService.copy(this.branchList); this.tagTemp = this.idpService.copy(this.tagList); this.scmType = this.idpdataService.triggerJobData.hasOwnProperty("scmType") ? this.idpdataService.triggerJobData.scmType : ""; if (this.idpdataService.triggerJobData.hasOwnProperty("test")) { this.IDPDataSwitch.test = true; this.IDPDataSwitch.testEnv = this.idpdataService.triggerJobData.test.hasOwnProperty("testEnv") ? this.idpdataService.triggerJobData.test.testEnv : []; } if (this.idpdataService.triggerJobData.hasOwnProperty("rmsComponentName")){ this.rmsComponentName = this.idpdataService.triggerJobData.rmsComponentName; }else{ this.rmsComponentName = ""; } if (this.idpdataService.triggerJobData.hasOwnProperty("deploy")) { this.IDPDataSwitch.deploy = true; this.IDPDataSwitch.buildDeployEnv = this.idpdataService.triggerJobData.hasOwnProperty("buildDeployEnv") ? this.idpdataService.triggerJobData.buildDeployEnv : []; this.IDPDataSwitch.deployEnv = this.idpdataService.triggerJobData.deploy.hasOwnProperty("deployEnv") ? this.idpdataService.triggerJobData.deploy.deployEnv : []; this.IDPDataSwitch.deploybizEnv = this.idpdataService.triggerJobData.deploy.hasOwnProperty("bizobj") ? this.idpdataService.triggerJobData.deploy.bizobj : []; this.IDPParamData.env = this.IDPDataSwitch.deployEnv; this.rmsEnv = this.idpdataService.triggerJobData.deploy.hasOwnProperty("deployEnvRms") ? this.idpdataService.triggerJobData.deploy.deployEnvRms : []; } if (this.idpdataService.triggerJobData.hasOwnProperty("deployTestEnv")) { this.IDPDataSwitch.deploy = true; this.IDPDataSwitch.test = true; this.IDPDataSwitch.deployTestEnv = this.idpdataService.triggerJobData.deployTestEnv.hasOwnProperty("Env") ? this.idpdataService.triggerJobData.deployTestEnv.Env : []; this.IDPDataSwitch.deploytestbizEnv = this.idpdataService.triggerJobData.deployTestEnv.hasOwnProperty("envObj") ? this.idpdataService.triggerJobData.deployTestEnv.envObj : []; } else { this.IDPDataSwitch.deployTestEnv = []; } } this.IDPDataSwitch.slaves = this.idpdataService.triggerJobData.hasOwnProperty("slaves") ? this.idpdataService.triggerJobData.slaves : []; this.IDPDataSwitch.appSlaves = this.idpdataService.triggerJobData.hasOwnProperty("appSlaves") ? this.idpdataService.triggerJobData.appSlaves : []; this.IDPParamData.applicationName = this.idpdataService.triggerJobData.hasOwnProperty("applicationName") ? this.idpdataService.triggerJobData.applicationName : ""; this.IDPParamData.jiraProjectKey = this.idpdataService.triggerJobData.hasOwnProperty("jiraProjectKey") ? this.idpdataService.triggerJobData.jiraProjectKey : ""; this.IDPParamData.pipelineName = this.idpdataService.triggerJobData.hasOwnProperty("pipelineName") ? this.idpdataService.triggerJobData.pipelineName : ""; this.IDPDataSwitch.releaseNumberList = this.idpdataService.triggerJobData.hasOwnProperty("releaseNumber") ? this.idpdataService.triggerJobData.releaseNumber : ""; this.IDPParamData.jobBuildId = this.idpdataService.triggerJobData.hasOwnProperty("jobBuildId") ? this.idpdataService.triggerJobData.jobBuildId : ""; this.IDPDataSwitch.nexusURL = this.idpdataService.triggerJobData.hasOwnProperty("nexusURL") ? this.idpdataService.triggerJobData.nexusURL : ""; this.IDPDataSwitch.repoName = this.idpdataService.triggerJobData.hasOwnProperty("repoName") ? this.idpdataService.triggerJobData.repoName : ""; this.IDPDataSwitch.jobBuildId = this.IDPParamData.jobBuildId; this.IDPParamData.subApplicationName = this.idpdataService.triggerJobData.hasOwnProperty("subApplicationName") ? this.idpdataService.triggerJobData.subApplicationName : ""; if (this.IDPDataSwitch.repoName !== "na") { this.IDPParamData.artifactorySelected = "on"; } if (this.IDPParamData.releaseNumber !== null && this.IDPParamData.releaseNumber !== "" && this.IDPParamData.releaseNumber !== undefined) { this.IDPDataSwitch.releaseNumber = this.IDPParamData.releaseNumber; } else { this.IDPDataSwitch.releaseNumber = ""; } } catch (e) { console.log(e); alert("Error in Trigger job details"); this.router.navigate(["/previousConfig"]); } } else { this.userstoryDropdownSettings = { singleSelection: false, text: "Select User story(s)", selectAllText: "Select All", unSelectAllText: "UnSelect All", enableSearchFilter: true, classes: "myclass custom-class" }; this.changeDocumentDropdownSettings = { singleSelection: false, text: "Select change document(s)", selectAllText: "Select All", unSelectAllText: "UnSelect All", enableSearchFilter: true, classes: "myclass custom-class" }; this.dropdownSettings = { singleSelection: false, text: "Select Transport Requests", selectAllText: "Select All", unSelectAllText: "UnSelect All", enableSearchFilter: true, classes: "myclass custom-class" }; this.IDPParamData = { "applicationName": this.paramData.applicationName, "pipelineName": "pipName", "releaseNumber": "", "ibmRQMTestSuiteId": "", "userName": this.idpdataService.idpUserName, "landscapesDetails": [], "subApplicationName": "", "userTeam": "", "slaveName": "", "testSlaveName": "", "castSlaveName": "", "reconcileSlaveName": "", "envSelected": "", "approvalSelected": "", "systemName": "", "SapsystemNames": "", "instance": "", "client": "", "charmRequests": [], "sapUserName": "", "branchOrTag": "", "password": "", "technology": this.idpdataService.triggerJobData.technology, "language": "", "transportRequest": [], "copyTR": false, "userStories": [], "userStoryMapping": [], "jobParam": [], "testPlanId": "", "testSuitId": "", "mtmStepName": "", "rebase": { "sourceEnvSelected": "", "transportObjectType": "", "transportObject": "", "targetEnvSelected": "", "bugFixTR": "" }, "resetSelected":"", "build": { "branchSelected": "", "codeAnalysis": "", "unitTest": "", "cast": "", "currentDate": "", "oldVersion": "", "newVersion": "", "module": [ ] }, "deploy": { "version": "", "artifactID": "", "nexusId": "", "deploymentType": "", "deployOperationSelected": "", "deployStep": [], "subModule": [] }, "testSelected": "", "testStep": [] }; this.IDPDataSwitch = { "test": false, "build": false, "deploy": false, "releaseManager": true, "buildSelected": "off", "deploySelected": "off", "testSelected": "off", "charmConfigType" : "master", "reconcileSelected": "off", "slaves": [], "modules": [], "buildBranch": [], "buildenv": [], "testEnv": [], "deployEnv": [], "releaseNumberList": [], "releaseNumber": "" }; if(this.IDPParamData.technology==='sapcharm') this.getChangeRequest(); try { if (this.idpdataService.triggerJobData) { if (this.idpdataService.triggerJobData.hasOwnProperty("build")) { this.IDPDataSwitch.build = true; if (this.idpdataService.triggerJobData.build.hasOwnProperty("buildEnv")) { if (this.idpdataService.triggerJobData.build.buildEnv.length !== 0) { this.buildEnv = this.idpdataService.triggerJobData.build.buildEnv; } else { this.buildEnv = []; } } if (this.idpdataService.triggerJobData.build.hasOwnProperty("codeAnalysis")) { if (this.idpdataService.triggerJobData.build.codeAnalysis) { this.build.codeAnalysis = this.idpdataService.triggerJobData.build.codeAnalysis; } } if (this.idpdataService.triggerJobData.build.hasOwnProperty("cast")) { if (this.idpdataService.triggerJobData.build.cast) { this.build.cast = this.idpdataService.triggerJobData.build.cast; } } if (this.idpdataService.triggerJobData.build.hasOwnProperty("unitTesting")) { if (this.idpdataService.triggerJobData.build.unitTesting) { this.build.unitTest = this.idpdataService.triggerJobData.build.unitTesting; } } } if (this.idpdataService.triggerJobData.hasOwnProperty("test")) { if (this.idpdataService.triggerJobData.test === "on") { this.IDPDataSwitch.test = true; } else { this.IDPDataSwitch.test = false; } if (this.idpdataService.triggerJobData.test.hasOwnProperty("testEnv")) { if (this.idpdataService.triggerJobData.test.testEnv.length !== 0) { this.testEnv = this.idpdataService.triggerJobData.test.testEnv; } else { this.testEnv = []; } } } if (this.idpdataService.triggerJobData.hasOwnProperty("systemNames")) { if (this.idpdataService.triggerJobData.systemNames) { this.SapsystemNames = this.idpdataService.triggerJobData.systemNames; } } if (this.idpdataService.triggerJobData.hasOwnProperty("deploy")) { this.IDPDataSwitch.deploy = true; this.IDPDataSwitch.deployEnv = this.idpdataService.triggerJobData.deploy.hasOwnProperty("deployEnv") ? this.idpdataService.triggerJobData.deploy.deployEnv : []; if (this.idpdataService.triggerJobData.deploy.hasOwnProperty("deployEnv")) { if (this.idpdataService.triggerJobData.deploy.deployEnv.length !== 0) { this.deployEnv = this.idpdataService.triggerJobData.deploy.deployEnv; } else { this.deployEnv = []; } } } this.IDPDataSwitch.slaves = this.idpdataService.triggerJobData.hasOwnProperty("slaves") ? this.idpdataService.triggerJobData.slaves : []; this.IDPParamData.applicationName = this.idpdataService.triggerJobData.hasOwnProperty("applicationName") ? this.idpdataService.triggerJobData.applicationName : ""; this.IDPParamData.pipelineName = this.idpdataService.triggerJobData.hasOwnProperty("pipelineName") ? this.idpdataService.triggerJobData.pipelineName : ""; this.IDPDataSwitch.releaseNumberList = this.idpdataService.triggerJobData.hasOwnProperty("releaseNumber") ? this.idpdataService.triggerJobData.releaseNumber : ""; this.IDPParamData.jobBuildId = this.idpdataService.triggerJobData.hasOwnProperty("jobBuildId") ? this.idpdataService.triggerJobData.jobBuildId : ""; this.IDPDataSwitch.jobBuildId = this.IDPParamData.jobBuildId; this.branchList = this.idpdataService.triggerJobData.hasOwnProperty("branchList") ? this.idpdataService.triggerJobData.branchList : []; this.tagList = this.idpdataService.triggerJobData.hasOwnProperty("tagList") ? this.idpdataService.triggerJobData.tagList : []; this.branchTemp = this.idpService.copy(this.branchList); this.tagTemp = this.idpService.copy(this.tagList); this.scmType = this.idpdataService.triggerJobData.hasOwnProperty("scmType") ? this.idpdataService.triggerJobData.scmType : ""; if (this.IDPParamData.releaseNumber !== null && this.IDPParamData.releaseNumber !== "" && this.IDPParamData.releaseNumber !== undefined) { this.IDPDataSwitch.releaseNumber = this.IDPParamData.releaseNumber; } else { this.IDPDataSwitch.releaseNumber = ""; } } { this.idprestapiService.getApplicationInfo(this.IDPParamData.applicationName).then(response => { if (response) { const app = JSON.parse(response.json().resource); this.isEnableTrack = app.enableSapTrack; if (this.idpdataService.isSAPApplication) { this.IDPParamData.landscapesDetails = app.environmentOwnerDetails; const details = this.IDPParamData.landscapesDetails; for (let i = 0; i < details.length; i++) { if ("DEV" === details[i].landscapeType || "HOTFIX" === details[i].landscapeType) { this.devEnvList.push(details[i].environmentName); } } } } }); } this.environment = this.idpdataService.SAPEnvList; this.intersectionValues(); this.removeDuplicates(); } catch (e) { console.log(e); alert("Failed , Trigger job data is not proper"); } } } toggleSelectionSiebel(module) { var idx = this.IDPParamData.build.module.indexOf(module); if (idx > -1) { this.IDPParamData.build.module.splice(idx, 1); if (module == 'Full_Compile') { this.IDPDataSwitch.srfcompile = 'off'; } if (module == 'SIFSelected') { this.IDPDataSwitch.sifImport = 'off'; } } else { this.IDPParamData.build.module.push(module); if (module == 'Full_Compile') { this.IDPDataSwitch.srfcompile = 'on'; } if (module == 'SIFSelected') { this.IDPDataSwitch.sifImport = 'on'; } } console.log(this.IDPParamData.build.module) } closeBuild() { this.IDPParamData.build.module = []; this.IDPParamData.build.checkmarxIncremental = "off"; this.IDPParamData.build.runCheckmarxInput = ""; this.IDPDataSwitch.buildSelected = "off"; this.IDPParamData.slaveName = ""; this.slavestatus=""; if (this.IDPParamData.deploy.artifacts === "") { this.IDPDataSwitch.deploySelected = "off"; } this.IDPParamData.deploy.artifacts = ""; this.addArtifact(); return "off"; } closeDeploy() { this.IDPDataSwitch.deploySelected = "off"; this.IDPParamData.deploy.artifacts = ""; if(this.IDPDataSwitch.buildSelected === "off"){ this.IDPParamData.slaveName=""; this.slavestatus=""; } this.tempDeploySteps = []; this.deployArr = []; this.IDPParamData.deploy.deployStep = []; this.IDPParamData.deploy.subModule = []; this.operation = []; this.addArtifact(); this.closeDBDeploy(); return "off"; } closeTest() { this.IDPDataSwitch.testSelected = "off"; this.tempTestSteps = []; this.testArr = []; this.IDPParamData.testStep = []; this.fetchedIBMRQMTestCaseList = []; this.fetchedVirtualServicesList = []; return "off"; } closeDBDeploy() { this.IDPParamData.deployDB = "off"; this.IDPParamData.restoreDB = "off"; this.IDPParamData.deploy.subApplication = ""; this.IDPParamData.dbOperations = []; } checkEnv() { if (this.IDPDataSwitch.deploySelected !== "on" && this.IDPDataSwitch.testSelected !== "on") { this.IDPParamData.envSelected = ""; } } //siebel repoDeployTrue() { this.IDPParamData.repoDeployStatus = 'true'; return "on"; } repoDeployFalse() { this.IDPParamData.repoDeployStatus = 'false'; return "off"; } nonRepoDeployTrue() { this.IDPParamData.nonRepoDeployStatus = 'true'; this.IDPParamData.technology = 'siebel'; return "on"; } nonRepoDeployFalse() { this.IDPParamData.nonRepoDeployStatus = 'false'; this.IDPParamData.technology = 'siebel'; return "off"; } deployOptionAlert() { alert("Please select atleast one deploy option"); } siebelBuildOption() { this.IDPParamData.build.module[0] = [] if (this.IDPDataSwitch.sifImport == 'on') { this.IDPParamData.build.module[0] += ';SIFSelected;'; if (this.IDPDataSwitch.srfCompile == 'on') this.IDPParamData.build.module[0] += 'SRFSelected;'; if (this.IDPDataSwitch.srfCompileType == 'fullCompile') this.IDPParamData.build.module[0] += 'Full_Compile;'; if (this.IDPDataSwitch.srfCompileType == 'incCompile') this.IDPParamData.build.module[0] += 'Incremental_Compile;'; } else { if (this.IDPDataSwitch.srfCompile == 'on') this.IDPParamData.build.module[0] += ';SRFSelected;'; if (this.IDPDataSwitch.srfCompileType == 'fullCompile') this.IDPParamData.build.module[0] += 'Full_Compile;'; if (this.IDPDataSwitch.srfCompileType == 'incCompile') this.IDPParamData.build.module[0] += 'Incremental_Compile;'; } this.IDPParamData.technology = 'siebel'; return true; } triggerAlert() { this.alertModalRef = this.modalService.show(this.modalforAlert); } triggerAlertDBDep() { this.dbDepModalRef = this.modalService.show(this.modalforAlertDBDep); } triggerAlertArtifact() { this.selectArtifactModalRef = this.modalService.show(this.modalforArtifactAlert); } triggerSubmitArtifactAlert() { this.submitModalRef = this.modalService.show(this.modalforSubmitAlert); } getLandscapeType() { if (this.IDPDataSwitch.deploySelected === "on") { this.hideTransportRequest = false; this.selectedItems = []; this.selectedTR = []; const details = this.IDPParamData.landscapesDetails; this.devTrue = false; this.IDPParamData.deploy.deployOperationSelected = ""; let landscapeType = ""; for (let i = 0; i < details.length; i++) { if (this.IDPParamData.envSelected === details[i].environmentName) { landscapeType = details[i].landscapeType; break; } } if (landscapeType === "DEV") { this.devTrue = true; } else { this.getTransportRequest(); } } else { this.getTransportRequest(); } } // Fetch transport request for SAP getTransportRequest() { this.transportRequests = []; this.selectedItems = []; this.selectedTR = []; this.showData = false; this.IDPParamData.copyTR = false; let data; if(this.buildSelect==='on' && this.deploySelect==='on'){// BD, BDT fetch tr from dev even when QA or prod selected data = { "application_name": this.IDPParamData.applicationName, "landscapeName": this.buildEnv, "deployOperation": this.IDPParamData.deploy.deployOperationSelected }; }else{ data = { "application_name": this.IDPParamData.applicationName, "landscapeName": this.IDPParamData.envSelected, "deployOperation": this.IDPParamData.deploy.deployOperationSelected }; } console.log(data) this.idpdataService.loading = true; this.hideTransportRequests = false; try { if (data.application_name !== "" && data.landscapeName !== "") { this.idpdataService.loading = true; this.idprestapiService.getTransportRequest(data).then(response => { this.idpdataService.loading = false; if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { const tData = JSON.parse(response.json().resource); const transportData = tData.transportRequests; this.showData = tData.show; this.unselectedTRs = transportData; this.selectedTR = []; if (transportData.length !== 0) { this.IDPParamData.transportRequest = []; this.transportRequests = []; let c = 1; let transportList = null; if (this.IDPDataSwitch.deploySelected === "on" && this.IDPParamData.deploy.deployOperationSelected !== "release" && !this.idpdataService.checkpollALM) { transportList = null; // Filtering transport based on release number if (this.IDPDataSwitch.releaseNumber !== "" && this.idpdataService.triggerJobData.releaseTransportInfo.length !== 0) { for (const relTransportInfo of this.idpdataService.triggerJobData.releaseTransportInfo) { if (relTransportInfo.releaseNumber === this.IDPDataSwitch.releaseNumber) { transportList = relTransportInfo.transportList; break; } } } if (transportList != null && transportList.length > 0) { for (const i of transportData) { if (transportList.includes(i.transportReqName)) { this.transportRequests.push({ "id": c, "itemName": i.transportReqName }); c = c + 1; } } } } else { for (const i of transportData) { this.transportRequests.push({ "id": c, "itemName": i.transportReqName }); c = c + 1; } } if (this.idpdataService.checkpollALM) { this.tempTrArrayDeploy = []; const tempTrList = []; for (const i of this.transportRequests) { tempTrList.push(i.itemName); } this.transportRequests = []; this.tempTrArrayDeploy = Array.from(new Set(tempTrList)); let c = 1; if (this.tempTrArrayDeploy !== null && this.tempTrArrayDeploy.length > 0) { for (let i = 0; i < this.tempTrArrayDeploy.length; i++) { if (this.tempTrArrayJira.includes(this.tempTrArrayDeploy[i])) { this.transportRequests.push({ "id": c, "itemName": this.tempTrArrayDeploy[i] }); c = c + 1; } } } } } else { alert("No Transport Request available for SAP System : " + data.landscapeName); } } else { alert("Failed to get Transport Request for SAP System : " + data.landscapeName); } } else { alert("Failed to get Transport Request for SAP System : " + data.landscapeName); } this.idpdataService.loading = false; }); } else { this.hideTransportRequest = false; } } catch (e) { alert("Failed in getting Transport Request"); } } clearLandscapeAndUserStory() { if (this.IDPDataSwitch.buildSelected === "on" && this.IDPParamData.build.cast !== "on" && this.IDPParamData.build.codeAnalysis !== "on" && this.IDPParamData.build.unitTest !== "on") { this.IDPParamData.envSelected = ""; this.selectedUS = []; this.hideTransportRequest = true; this.selectedItems = []; } } // Checks conditions to show Landscape dropdown checkCheckBoxesOn() { if (this.IDPDataSwitch.buildSelected === "on" && (this.IDPParamData.build.cast === "on" || this.IDPParamData.build.codeAnalysis === "on" || this.IDPParamData.build.unitTest === "on")) { return true; } else if (this.IDPDataSwitch.buildSelected !== "on" && (this.IDPDataSwitch.deploySelected === "on" || this.IDPDataSwitch.testSelected === "on")) { return true; } else { return false; } } setReconcileSelected(selected) { if (selected) { this.IDPDataSwitch.reconcileSelected = "on"; this.reconcileSelect = "on"; this.setbuildLandScapeNames(false); this.setdeployLandScapeNames(false); this.settestLandScapeNames(false); } else { this.IDPDataSwitch.reconcileSelected = "off"; this.reconcileSelect = "off"; this.IDPParamData.reconcileSlaveName = ""; this.reconcilationChange(); } } setbuildLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.buildSelected = "on"; this.buildSelect = "on"; this.setReconcileSelected(false); } else { this.IDPDataSwitch.buildSelected = "off"; this.buildSelect = "off"; this.IDPParamData.slaveName = ""; this.IDPParamData.build.codeAnalysis = "off"; this.IDPParamData.build.cast = "off"; this.IDPParamData.build.unitTest = "off"; if (this.idpdataService.checkpollALM) { this.selectedUS = []; this.hideTransportRequest = false; } } this.setLandscapeNames(); } setCharmResetLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.resetSelected = "on"; this.resetSelect = "on"; } else { this.IDPDataSwitch.resetSelected = "off"; this.resetSelect = "off"; this.IDPParamData.slaveName = ""; this.IDPParamData.build.codeAnalysis = "off"; this.IDPParamData.build.unitTest = "off"; } this.setCharmLandscapeNames(); } setCharmbuildLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.buildSelected = "on"; this.buildSelect = "on"; } else { this.IDPDataSwitch.buildSelected = "off"; this.buildSelect = "off"; this.IDPParamData.slaveName = ""; this.IDPParamData.build.codeAnalysis = "off"; this.IDPParamData.build.unitTest = "off"; } this.setCharmLandscapeNames(); } setCharmDeployLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.deploySelected = "on"; this.deploySelect = "on"; } else { this.IDPDataSwitch.deploySelected = "off"; this.deploySelect = "off"; this.IDPParamData.slaveName = ""; this.IDPParamData.deploy.deployOperationSelected = ""; } this.IDPParamData.build.codeAnalysis = "off"; this.IDPParamData.build.unitTest = "off"; if (this.idpdataService.checkpollALM) { this.selectedUS = []; } this.setCharmLandscapeNames(); } setCharmTestLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.testSelected = "on"; this.testSelect = "on"; } else { this.IDPDataSwitch.testSelected = "off"; this.testSelect = "off"; this.closeTest(); } this.setCharmLandscapeNames(); } setdeployLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.deploySelected = "on"; this.deploySelect = "on"; this.setReconcileSelected(false); } else { this.IDPDataSwitch.deploySelected = "off"; this.deploySelect = "off"; this.IDPParamData.slaveName = ""; this.IDPParamData.deploy.deployOperationSelected = ""; } if (this.idpdataService.checkpollALM) { this.selectedUS = []; } this.setLandscapeNames(); } settestLandScapeNames(selected) { if (selected) { this.IDPDataSwitch.testSelected = "on"; this.testSelect = "on"; this.setReconcileSelected(false); } else { this.IDPDataSwitch.testSelected = "off"; this.testSelect = "off"; this.closeTest(); } this.setLandscapeNames(); } getChangeRequest(){ try { this.idpdataService.loading = true; this.idprestapiService.getChangeRequestDetails(this.IDPParamData.applicationName , this.IDPDataSwitch.charmConfigType).then(response => { if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { const tData = JSON.parse(response.json().resource); this.changeRequestDetails = tData; if (this.IDPDataSwitch.charmConfigType === 'master') { this.approvalStages = ["Successfully Tested", "Authorized for Production", "Imported into Production", "Confirmed", "Completed"]; } else if (this.IDPDataSwitch.charmConfigType === 'workflow') { this.approvalStages = ["Successfully Tested", "Ready for Production Import", "PFA Approved", "DM Approved", "Imported into Production", "Confirmed", "Completed"]; } } else { alert("Failed to get Change Request for SAP System : " ); } } else { alert("Failed to get Change Request for SAP System : " ); } this.idpdataService.loading = false; }); } catch (e) { alert("Failed in getting Change Request"); } } fetchChangeRequest(){ this.changeRequestListTemp = []; this.changeRequestList = []; this.showPermissionError = ""; this.hideChangeRequest = false; if(this.IDPDataSwitch.buildSelected === 'on'){ if(this.IDPParamData.build.codeAnalysis === 'on' && this.IDPParamData.build.unitTest === 'on'){ this.changeRequestList = this.changeRequestDetails.buildCr; } else if(this.IDPParamData.build.codeAnalysis === 'on'){ this.changeRequestList = this.changeRequestDetails.buildCaCr; } else if(this.IDPParamData.build.unitTest === 'on'){ this.changeRequestList = this.changeRequestDetails.buildUtCr; } } if(this.IDPDataSwitch.deploySelected === 'on'){ let envCrList = this.changeRequestDetails.deployEnvCrList; for( let i = 0 ; i< envCrList.length ; i++){ if(this.IDPParamData.envSelected === envCrList[i].environmentName){ let localChangeRequestList = envCrList[i].changeRequestList; for(let i=0 ;i < localChangeRequestList.length ; i++){ if( !(this.changeRequestList.includes(localChangeRequestList[i]))){ this.changeRequestList.push(localChangeRequestList[i]); } } break; } } } if(this.IDPDataSwitch.testSelected === 'on'){ let crStatusList= this.changeRequestDetails.crsBasedOnStatusOfCD.filter (x => (x.statusOfCD === 'Unit Testing Completed')); for( let i = 0 ; i< crStatusList.length ; i++){ let localChangeRequestList = crStatusList[i].crAndDescriptionList; for(let i=0 ;i < localChangeRequestList.length ; i++){ if( !(this.changeRequestList.includes(localChangeRequestList[i]))){ this.changeRequestList.push(localChangeRequestList[i]); } } break; } } if(this.isEnableTrack === 'on') { this.changeRequestListTemp = []; let changeRequestArr = []; let approvalStageArr = []; if(this.charmTriggerData.sapTrackSelected!==undefined && this.charmTriggerData.sapTrackSelected!==null && this.charmTriggerData.sapSubTrackSelected !==undefined && this.charmTriggerData.sapSubTrackSelected!=null) { let trackCrList = this.changeRequestDetails.crsBasedOnTrackSubtrack; if (this.IDPParamData.approvalSelected) { for(let k = 0; k < this.changeRequestDetails.crsBasedOnStatusOfCD.length; k++){ let currentStatus = this.changeRequestDetails.crsBasedOnStatusOfCD[k]; if( (currentStatus.statusOfCD === this.IDPParamData.approvalSelected ) ) { approvalStageArr.push(currentStatus.crAndDescriptionList); } } } for( let i = 0 ; i< trackCrList.length ; i++){ if(this.charmTriggerData.sapSubTrackSelected === trackCrList[i].subTrack){ let localChangeRequestList = trackCrList[i].crAndDescriptionList; for(let i=0 ;i < localChangeRequestList.length ; i++){ if( !(this.changeRequestList.includes(localChangeRequestList[i]))){ changeRequestArr.push(localChangeRequestList[i]); } } break; } } for(let j = 0; j < changeRequestArr.length; j++){ if(this.IDPParamData.approvalSelected){ if(approvalStageArr.length > 0) { let cr = approvalStageArr[0].filter (x => (changeRequestArr[j].crNumber === x.crNumber)); if(cr !== null && cr.length > 0) { this.showPermissionError = ""; this.changeRequestListTemp.push({"val": changeRequestArr[j].crNumber, "description": changeRequestArr[j].crNumber+ " --> "+ changeRequestArr[j].crDescription,"role": changeRequestArr[j].crApprover}); } else if(cr==null || cr.length == 0) { if(this.changeRequestListTemp.length === 0) { this.showPermissionError = "No data available for this request." } } } else { this.showPermissionError = "No data available for this request." } } else { this.changeRequestListTemp.push({"val": changeRequestArr[j].crNumber, "description": changeRequestArr[j].crNumber+ " --> "+ changeRequestArr[j].crDescription,"role": changeRequestArr[j].crApprover}); } } } } else { this.changeRequestListTemp = []; for(let k = 0; k < this.changeRequestList.length; k++){ let cr= this.changeRequestDetails.crAndDescription.filter (x => (this.changeRequestList[k] === x.crNumber)); if(cr==null || cr.length==0) { this.changeRequestListTemp.push({"val": this.changeRequestList[k], "description": this.changeRequestList[k]}); } else { if(cr[0].crDescription) { this.changeRequestListTemp.push({"val": this.changeRequestList[k], "description": this.changeRequestList[k]+ " --> "+ cr[0].crDescription}); } else { this.changeRequestListTemp.push({"val": this.changeRequestList[k], "description": this.changeRequestList[k]}); } } } } } updateCRRole() { let crRole,currentCR; for(let k = 0; k < this.changeRequestDetails.crsBasedOnTrackSubtrack.length; k++){ currentCR = this.changeRequestDetails.crsBasedOnTrackSubtrack[k]; let cr= currentCR.crAndDescriptionList.filter (x => (this.charmTriggerData.changeRequest === x.crNumber)); if(cr !==null && cr.length !==0) { crRole = cr[0].crApprover; } } this.crApprover = crRole; } checkIfTrackEnabled() { if(this.isEnableTrack === 'on') { let currentLandscape = this.IDPParamData.landscapesDetails.filter (x => (this.IDPParamData.envSelected === x.environmentName)); this.selectedLandscapeType = currentLandscape[0].landscapeType; this.IDPParamData.approvalSelected = ''; this.clearCrData(); this.fetchSteps(); } else { this.clearCrData(); this.fetchChangeRequest(); this.fetchSteps(); } } trackEnabledForUT() { this.isEnableTrack === 'on' ? this.clearCrData() : this.clearCrData();this.fetchChangeRequest(); } filterTrack(itemList) { let mySet: Set<string> = new Set<string>(); let result = [] ; if(itemList !== undefined) { for(let i=0;i<itemList.length; i++){ if(!mySet.has(itemList[i].track)){ result.push(itemList[i]) } mySet.add(itemList[i].track) } } return result; } fetchChangeDocument(){ this.changeDocumentListDescDropdown = []; this.hideChangeDocument=false; let changeRequest : String = this.charmTriggerData.changeRequest; this.changeDocumentList=[]; this.selectedCDData = []; this.selectedCD = []; this.transportRequests = []; this.cdDetailsList = []; this.changeDocumentListTemp = []; this.cdListWithStatus = []; //Prepare CD list with description for(let cd of this.changeRequestDetails.changeDocumentMapping){ this.cdListWithDescription.push({"cdNum":cd.changeDocument,"cdDescription":cd.changeDocumentData[0].cdDescription}); } for(let cd of this.changeRequestDetails.changeDocumentMapping){ this.cdListWithStatus.push({"cdNum":cd.changeDocument,"cdStatus":cd.changeDocumentData[0].cdStatus,"cdDescription":cd.changeDocumentData[0].cdDescription}); } for(let i=0 ;i<this.changeRequestDetails.crcdRelationList.length ; i++){ let cdmap = this.changeRequestDetails.crcdRelationList[i]; if(this.IDPDataSwitch.testSelected === 'on') { for(let k = 0; k < this.cdListWithStatus.length; k++){ if( (changeRequest === cdmap.changeRequest) && cdmap.changeDocumentList.includes(this.cdListWithStatus[k].cdNum) && (this.cdListWithStatus[k].cdStatus === 'Ready for QA') ) { this.changeDocumentListDescDropdown.push({"id": this.cdListWithStatus[k].cdNum, "itemName": this.cdListWithStatus[k].cdNum + " --> "+this.cdListWithStatus[k].cdDescription}); } } } if(changeRequest === cdmap.changeRequest){ for(let j=0; j<cdmap.changeDocumentList.length ; j++){ //Don't add all the CD's; first filter based on status if(this.IDPDataSwitch.deploySelected === 'on'){ for(let cdList of this.changeRequestDetails.deployEnvCdList){ if(cdList.environmentName === this.IDPParamData.envSelected){ for(let cd of cdList.changeDocumentList){ if(cdmap.changeDocumentList.includes(cd)){ if(!this.changeDocumentListTemp.includes(cd)){ this.changeDocumentListTemp.push(cd); } } } } } } if(this.IDPDataSwitch.buildSelected === 'on'){ //B if(this.IDPParamData.build.unitTest==='on' && this.IDPParamData.build.codeAnalysis==='on'){ //UT & CA let status = this.idpdataService.buildCAUT.split(","); let currentCDstatus = this.cdListWithStatus.filter(obj => { //console.log(obj.cdNum); //console.log(cdmap.changeDocumentList[j]); return obj.cdNum === cdmap.changeDocumentList[j] }); console.log(currentCDstatus); console.log(status.includes(currentCDstatus[0].cdStatus)); if(status.includes(currentCDstatus[0].cdStatus)){ if(!this.changeDocumentListTemp.includes(cdmap.changeDocumentList[j])) this.changeDocumentListTemp.push(cdmap.changeDocumentList[j]); //this.changeDocumentList.push({"id": j, "itemName": cdmap.changeDocumentList[j]}); } console.log(status); }else if(this.IDPParamData.build.unitTest==='on'){ //only UT let status = this.idpdataService.buildUT.split(","); let currentCDstatus = this.cdListWithStatus.filter(obj => { return obj.cdNum === cdmap.changeDocumentList[j] }); if(status.includes(currentCDstatus[0].cdStatus)){ if(!this.changeDocumentListTemp.includes(cdmap.changeDocumentList[j])) this.changeDocumentListTemp.push(cdmap.changeDocumentList[j]); } console.log(status); }else if(this.IDPParamData.build.codeAnalysis==='on'){ //only CA let status = this.idpdataService.buildCA.split(","); let currentCDstatus = this.cdListWithStatus.filter(obj => { return obj.cdNum === cdmap.changeDocumentList[j] }); if(status.includes(currentCDstatus[0].cdStatus)){ if(!this.changeDocumentListTemp.includes(cdmap.changeDocumentList[j])) this.changeDocumentListTemp.push(cdmap.changeDocumentList[j]); } console.log(status); } } //this.changeDocumentList.push({"id": j, "itemName": cdmap.changeDocumentList[j]}); if(this.IDPDataSwitch.testSelected !== 'on') { for(let k = 0; k < this.cdListWithDescription.length; k++){ if(cdmap.changeDocumentList[j] === this.cdListWithDescription[k].cdNum){ this.changeDocumentListDescDropdown.push({"id": this.cdListWithDescription[k].cdNum, "itemName": this.cdListWithDescription[k].cdNum+" --> "+this.cdListWithDescription[k].cdDescription}); } } } // break; } } } for(let k = 0; k < this.changeDocumentListTemp.length; k++) { this.changeDocumentList.push({"id": k, "itemName": this.changeDocumentListTemp[k]}); } } setLandscapeNames() { this.idpdataService.SAPEnvList = []; this.IDPParamData.envSelected = ""; this.devTrue = false; this.showData = false; this.transportRequest = ""; this.hideTransportRequests = false; this.hideTransportRequest = false; if (this.IDPParamData.envSelected === "") { this.hideTransportRequest = false; } /* if (this.reconcileSelect === "on") { this.idpdataService.SAPEnvList = this.allEnv; } else if (this.deploySelect === "on" && this.buildSelect === "on") {// B || B+D this.idpdataService.SAPEnvList = this.deployEnv; } else if (this.deploySelect === "on" && this.buildSelect !== "on" && this.testSelect !== "on") {// D this.idpdataService.SAPEnvList = this.allEnv; } else if (this.testSelect === "on" || (this.deploySelect === "on" && this.testSelect === "on")) {// T || D+T this.idpdataService.SAPEnvList = this.testEnv; } else if (this.buildSelect === "on" && this.testSelect === "on") {// B +T //this.idpdataService.SAPEnvList = this.buildTestEnv; this.idpdataService.SAPEnvList = this.buildEnv; } else if (this.buildSelect === "on" && this.testSelect === "on" && this.deploySelect === "on") { // B +T+D this.idpdataService.SAPEnvList = this.buildTestEnv; } else { this.hideTransportRequests = false; this.hideTransportRequest = false; } */ this.hideLandscape = false; if (this.reconcileSelect === "on") { this.idpdataService.SAPEnvList = this.allEnv; } else if (this.testSelect === "on") {// BDT || DT || T || BT this.idpdataService.SAPEnvList = this.testEnv; if(this.deploySelect !== "on" && this.buildSelect === "on"){ //BT this.hideLandscape = true; console.log(this.buildEnv); // if(!this.idpdataService.checkpollALM){ this.hideTransportRequest=true; this.IDPParamData.envSelected = this.buildEnv; //} // this.getTransportRequest(); } } else if (this.deploySelect === "on" ) {// D, BD this.idpdataService.SAPEnvList = this.deployEnv; } else if (this.buildSelect === "on" ) {// B //alert("in build") console.log(this.buildEnv); this.IDPParamData.envSelected = this.buildEnv; this.hideLandscape = true; //this.getTransportRequest(); if(this.idpdataService.checkpollALM){ } } } showTransportReq(){ this.hideTransportRequest = false; } setCharmLandscapeNames() { this.idpdataService.SAPEnvList = []; this.IDPParamData.envSelected = ""; this.devTrue = false; this.showData = false; this.transportRequest = ""; if (this.IDPParamData.envSelected === "") { this.hideTransportRequest = false; } if (this.buildSelect === "on" || (this.deploySelect === "on" && this.buildSelect === "on")) {// B || B+D this.idpdataService.SAPEnvList = this.buildEnv; } else if (this.deploySelect === "on" && this.buildSelect !== "on" && this.testSelect !== "on") {// D this.idpdataService.SAPEnvList = this.allEnv; this.hideTransportRequest = false; } else if (this.testSelect === "on" || (this.deploySelect === "on" && this.testSelect === "on")) {// T || D+T this.idpdataService.SAPEnvList = this.testEnv; this.hideTransportRequest = false; if (this.deploySelect !== "on") { this.hideTransportRequests = true; } else { this.hideTransportRequests = false; } } else if (this.buildSelect === "on" && this.testSelect === "on") {// B +T this.idpdataService.SAPEnvList = this.buildTestEnv; } else if (this.buildSelect === "on" && this.testSelect === "on" && this.deploySelect === "on") { // B +T+D this.idpdataService.SAPEnvList = this.buildTestEnv; } else if(this.resetSelect === "on"){ //R this.idpdataService.SAPEnvList = this.buildEnv; this.hideTransportRequest = false; }else if (this.testSelect === "on" && this.buildSelect === "off" && this.deploySelect === "off") { this.hideTransportRequests = true; } else { this.hideTransportRequests = false; this.hideTransportRequest = false; } } reconcilationChange() { this.IDPParamData.rebase.sourceEnvSelected = ""; this.IDPParamData.rebase.transportObjectType = ""; this.IDPParamData.rebase.transportObject = ""; this.IDPParamData.rebase.targetEnvSelected = ""; this.IDPParamData.rebase.bugFixTR = ""; } getObjects() { this.IDPParamData.rebase.transportObjectType = ""; this.IDPParamData.rebase.transportObject = ""; this.IDPParamData.rebase.targetEnvSelected = ""; this.IDPParamData.rebase.bugFixTR = ""; this.idpdataService.loading = true; this.idprestapiService.getTRObjects(this.IDPParamData.applicationName, this.IDPParamData.rebase.sourceEnvSelected).then(response => { if (response) { this.idpdataService.loading = false; if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { this.objectData = JSON.parse(response.json().resource); if (this.objectData.length !== 0) { const tempObjList = []; for (let i = 0 ; i < this.objectData.length ; i++) { tempObjList.push(this.objectData[i].objectType); } this.objectTypeList = Array.from(new Set(tempObjList)); } } } }); } getObjectNames() { this.IDPParamData.rebase.transportObject = ""; this.IDPParamData.rebase.targetEnvSelected = ""; this.IDPParamData.rebase.bugFixTR = ""; const tempObjectName = []; for (let i = 0; i < this.objectData.length; i++) { if (this.objectData[i].objectType === this.IDPParamData.rebase.transportObjectType) { tempObjectName.push(this.objectData[i].objectName); } } this.objectNameList = Array.from(new Set(tempObjectName)); } getTRforObject() { this.IDPParamData.rebase.targetEnvSelected = ""; this.IDPParamData.rebase.bugFixTR = ""; for (let i = 0 ; i < this.objectData.length ; i++) { if (this.objectData[i].objectType === this.IDPParamData.rebase.transportObjectType && this.objectData[i].objectName === this.IDPParamData.rebase.transportObject) { this.IDPParamData.rebase.bugFixTR = this.objectData[i].transportRequest; } } } intersectionValues() { const finalData = this.buildEnv.filter(x => this.testEnv.indexOf(x) > -1); if (finalData !== undefined) { this.buildTestEnv = finalData; } else { this.buildTestEnv = []; } } removeDuplicates() { const temp = this.deployEnv.concat(this.buildEnv.concat(this.testEnv)); const len = temp.length; const obj = {}; for (let i = 0; i < len; i++) { obj[temp[i]] = 0; } for (const i in obj) { if (obj.hasOwnProperty(i)) { this.allEnv.push(i); } } } getTransportRequestForUserStories(operation, userStory) { this.idpdataService.loading = true; const temp1 = []; let temp2 = ""; const temp = this.userStoryArray; let count; if (operation === "onDeselectAll") { this.selectedItems = []; this.transportRequests = []; } else if (operation === "onSelectAll") { this.selectedItems = []; this.transportRequests = []; for (let j = 0; j < temp.length; j++) { for (let i = 0; i < temp[j].Transport.length; i++) { temp1.push(temp[j].Transport[i]); } } } else if (operation === "onSelect") { this.selectedItems = []; for (let j = 0; j < temp.length; j++) { if (userStory === temp[j].Userstory) { for (let i = 0; i < temp[j].Transport.length; i++) { temp1.push(temp[j].Transport[i]); } } } } else if (operation === "onDeselect") { this.selectedItems = []; let index; for (let j = 0; j < temp.length; j++) { if (userStory === temp[j].Userstory) { temp2 = temp[j].Transport[0]; count = temp[j].Transport.length; break; } } for (let i = 0; i < this.transportRequests.length; i++) { if (temp2 === this.transportRequests[i].itemName) { index = i; break; } } this.transportRequests.splice(index, count); } this.hideTransportRequest = false; if(this.deploySelect==='on'){ this.IDPParamData.envSelected = ""; this.devTrue = false; this.showData = false; this.IDPParamData.deploy.deployOperationSelected = ""; } this.transportRequests = []; this.selectedTR = []; if (temp1.length > 0) { for (const element of temp1) { this.tempTrArrayJira.push(element); } } else { if (temp2.length > 0) { let index; for (let i = 0; i < this.tempTrArrayJira.length; i++) { if (temp2 === this.tempTrArrayJira[i].itemName) { index = i; break; } } this.tempTrArrayJira.splice(index, count); } else { this.tempTrArrayJira = []; } } this.idpdataService.loading = true; if(this.buildSelect==='on' && this.deploySelect!=='on'){ this.getTransportRequest(); } } onItemSelect(item: any) { for (let j = 0; j < this.unselectedTRs.length; j++) { if (item.itemName === this.unselectedTRs[j].transportReqName) { this.selectedTR.push(this.unselectedTRs[j]); break; } } } OnItemDeSelect(item: any) { let index; for (let j = 0; j < this.unselectedTRs.length; j++) { if (item.itemName === this.selectedTR[j].transportReqName) { index = j; break; } } this.selectedTR.splice(index, 1); } onSelectAll(items: any) { this.selectedTR = this.unselectedTRs; } onDeSelectAll(items: any) { this.selectedTR = []; } trigger() { this.showPermissionError = ""; if (this.requiredSCM === true && (this.IDPParamData.branchOrTagValue === undefined || this.IDPParamData.branchOrTagValue === "")) { this.missingSCMBranchModalRef = this.modalService.show(this.modalforReqSCMAlert); } else if (((this.IDPDataSwitch.buildSelected === "off" || this.IDPDataSwitch.buildSelected === null || this.IDPDataSwitch.buildSelected === undefined) && (this.IDPDataSwitch.testSelected === "off" || this.IDPDataSwitch.testSelected === null || this.IDPDataSwitch.testSelected === undefined) && (this.IDPDataSwitch.deploySelected === "off" || this.IDPDataSwitch.deploySelected === null || this.IDPDataSwitch.deploySelected === undefined) && (this.IDPDataSwitch.resetSelected === "off" || this.IDPDataSwitch.resetSelected === null || this.IDPDataSwitch.resetSelected === undefined))) { this.idpdataService.loading = false; this.triggerAlert(); } else { if(this.IDPParamData.technology==='sapcharm'){ this.checkPermissions(); this.validateApprovalStage(); } if(!this.showPermissionError) { if (this.IDPParamData.build.runCheckmarxInput === ''){ this.IDPParamData.build.checkmarxIncremental = "NA"; } if (this.idpdataService.schedulePage === true || this.idpdataService.createWorkflowSequenceflag) { this.confirmSaveModalRef = this.modalService.show(this.modalforSave); } else { this.triggerModalRef = this.modalService.show(this.modalforTrigger); } } } } saveData(modalRef) { modalRef.hide(); this.onTriggerDetailsSaved.emit(true); this.idpdataService.loading = true; this.IDPParamData.releaseNumber = this.IDPDataSwitch.releaseNumber; if (this.IDPDataSwitch.repoName === "na") { this.IDPParamData.deploy.deployArtifact = {}; } else { if (this.IDPParamData.deploy !== null) { this.IDPParamData.deploy.deployArtifact = this.IDPParamData.deploy.artifacts; } } console.log(this.IDPParamData.deploy.deployArtifact); if (this.idpdataService.isSAPApplication) { if (this.idpdataService.checkpollALM) { if (this.IDPParamData.userStories === undefined) { this.IDPParamData.useStories = []; } for (const i of this.selectedUS) { this.IDPParamData.userStories.push(i.itemName); } } for (const i of this.selectedItems) { this.IDPParamData.transportRequest.push(i.itemName); } if (this.idpdataService.checkpollALM) { const userStoryMapsTRs = new Map<String, any>(); for (const data of this.userStoryArray) { if (this.IDPParamData.userStories.indexOf(data.Userstory) !== -1) { const tempTRs = []; for (const tr of data.transportRequest) { if (this.IDPParamData.transportRequest.includes(tr)) { tempTRs.push(tr); } } if (tempTRs.length > 0) { userStoryMapsTRs.set(data.Userstory, tempTRs); } } } this.IDPParamData.userStoryMapping = userStoryMapsTRs; } } if (((this.IDPDataSwitch.buildSelected === "off" || this.IDPDataSwitch.buildSelected === null || this.IDPDataSwitch.buildSelected === undefined) && (this.IDPDataSwitch.testSelected === "off" || this.IDPDataSwitch.testSelected === null || this.IDPDataSwitch.testSelected === undefined) && (this.IDPDataSwitch.deploySelected === "off" || this.IDPDataSwitch.deploySelected === null || this.IDPDataSwitch.deploySelected === undefined)) || (this.IDPParamData.deploy.update !== "on" && this.IDPParamData.deploy.rollback !== "on" && this.IDPParamData.deploy.misc !== "on" && this.idpdataService.triggerJobData.technology === "dbDeployDelphix")) { this.idpdataService.loading = false; if (this.IDPParamData.deploy.update !== "on" && this.IDPParamData.deploy.rollback !== "on" && this.IDPParamData.deploy.misc !== "on" && this.idpdataService.triggerJobData.technology === "dbDeployDelphix") { this.triggerAlertDBDep(); } else { this.triggerAlert(); } // this.parameterloading = false; } else { if (this.tempDeploySteps.length !== 0 && this.tempDeploySteps.length !== undefined) { for (let i = 0; i < this.deployArr.length; i++) { const step = this.deployArr[i]; if (this.deployArr[i] !== null) { this.IDPParamData.deploy.deployStep.push(step); console.log(this.IDPParamData.deploy.deployStep); } } } if (this.tempTestSteps.length !== 0 && this.tempTestSteps.length !== undefined) { for (let i = 0; i < this.testArr.length; i++) { const step = this.testArr[i]; if (this.testArr[i] !== null) { this.IDPParamData.testStep.push(step); console.log(this.IDPParamData.testStep); } } } const requestData = this.IDPParamData; console.log(requestData); if (this.idpdataService.isSAPApplication) { if (this.IDPDataSwitch.buildSelected === "on" && this.idpdataService.checkpollALM) { if (this.buildEnv[0]) { requestData.envSelected = this.buildEnv[0]; console.log(this.buildEnv[0]); } } } if (this.IDPDataSwitch.buildSelected === "off" || this.IDPDataSwitch.buildSelected === null || this.IDPDataSwitch.buildSelected === undefined) { requestData.build = null; } if (this.IDPDataSwitch.deploySelected !== "on" || this.IDPDataSwitch.deploySelected === null || this.IDPDataSwitch.deploySelected === undefined) { requestData.deploy = null; } if (this.IDPDataSwitch.resetSelected !== "on" || this.IDPDataSwitch.resetSelected === null || this.IDPDataSwitch.resetSelected === undefined) { requestData.resetStatus = null; requestData.resetSelected="off"; }else{ requestData.resetSelected="on"; } if (this.IDPDataSwitch.testSelected === "off" || this.IDPDataSwitch.testSelected === null || this.IDPDataSwitch.testSelected === undefined) { if (this.idpdataService.isSAPApplication) { // requestData.testSelected = 'off'; } else { requestData.testSelected = "off"; // requestData.test = null; } } else if (this.IDPDataSwitch.testSelected === "on") { requestData.testSelected = "on"; } if (this.IDPDataSwitch.resetSelected === "on") { requestData.resetSelected = "on"; } else { requestData.resetSelected = "off"; } if (this.IDPDataSwitch.reconcileSelected === undefined || this.IDPDataSwitch.reconcileSelected === null || this.IDPDataSwitch.reconcileSelected === "off") { requestData.rebase = null; console.log("rebase: " + requestData.rebase); } if (this.IDPDataSwitch.deploySelected === "off" && this.IDPDataSwitch.testSelected === "off" && (!this.idpdataService.isSAPApplication)) { requestData.envSelected = ""; } requestData.jobParam = []; console.log(requestData); // console.log(JSON.stringify(requestData)); this.idpdataService.buildIntervalData[this.idpdataService.index].details = requestData; this.idpdataService.statusCheck[this.idpdataService.index] = "off"; console.log(this.idpdataService.buildIntervalData); this.idpdataService.loading = false; } console.log(this.idpdataService.triggerJobData); this.initialize(); } triggerData(modalRef) { modalRef.hide(); this.idpdataService.loading = true; const requestData = this.getRequestData(); if (requestData === undefined) { } else { this.idprestapiService.triggerJobs(requestData) .then(response => { try { if (response) { const err = response.json().errorMessage; if (err === null && response.json().resource.toLowerCase() === "success") { this.idpdataService.loading = false; this.msg = "success"; this.disableSubmitBtn = true; setTimeout(() => { this.router.navigate(["/previousConfig/stageviewTrigger"]); }, 7000); this.redirectTo(); } else { this.disableSubmitBtn = false; this.idpdataService.loading = false; this.msg = "error"; setTimeout(() => { this.router.navigate(["/previousConfig"]); }, 7000); } } } catch (e) { console.log(e); alert("Failed while triggering "); } }); } } getRequestData() { let buildUncheck = false; let deployUncheck = false; let testUncheck = false; let reconcileUncheck = false; let resetUncheck = false; this.IDPParamData.releaseNumber = this.IDPDataSwitch.releaseNumber; this.IDPParamData.resetSelected = (this.IDPDataSwitch.resetSelected === 'on') ? 'on' : 'off'; let requestData; if (this.IDPDataSwitch.repoName === "na") { this.IDPParamData.deploy.deployArtifact = {}; } else { this.IDPParamData.deploy.deployArtifact = this.IDPParamData.deploy.artifacts; } if (this.idpdataService.isSAPApplication) { if (this.idpdataService.checkpollALM) { if (this.IDPParamData.userStories === undefined) { this.IDPParamData.userStories = []; } else{ for (const i of this.selectedUS) { this.IDPParamData.userStories.push(i.itemName); } } } for (const i of this.selectedItems) { this.IDPParamData.transportRequest.push(i.itemName); } if (this.idpdataService.checkpollALM) { for (const data of this.userStoryArray) { const userStoryMapsTRs = { userstory : "", transportRequests : [] }; if (this.IDPParamData.userStories.indexOf(data.Userstory) !== -1) { const tempTRs = []; for (const tr of data.Transport) { if (this.IDPParamData.transportRequest.includes(tr)) { tempTRs.push(tr); } } if (tempTRs.length > 0) { userStoryMapsTRs.userstory = data.Userstory; userStoryMapsTRs.transportRequests = tempTRs; this.IDPParamData.userStoryMapping.push(userStoryMapsTRs); } } } } if(this.IDPParamData.technology==='sapcharm'){ this.IDPParamData.transportRequest = this.transportRequests; /* let onlyCDNosList = []; for (let cd of this.selectedCDData ){ onlyCDNosList.push(cd.split(",")[0]); } this.IDPParamData.changeDocumentList = onlyCDNosList;*/ this.IDPParamData.changeDocumentList = this.selectedCDData; this.IDPParamData.charmConfigType = this.IDPDataSwitch.charmConfigType; this.IDPParamData.changeDocumentDetialsList = this.changeRequestDetails.changeDocumentMapping; } } if (this.IDPDataSwitch.buildSelected === "off" || this.IDPDataSwitch.buildSelected === null || this.IDPDataSwitch.buildSelected === undefined) { buildUncheck = true; } if (this.IDPDataSwitch.testSelected === "off" || this.IDPDataSwitch.testSelected === null || this.IDPDataSwitch.testSelected === undefined) { testUncheck = true; } if (this.IDPDataSwitch.deploySelected === "off" || this.IDPDataSwitch.deploySelected === null || this.IDPDataSwitch.deploySelected === undefined) { deployUncheck = true; } if (this.IDPDataSwitch.reconcileSelected === "off" || this.IDPDataSwitch.reconcileSelected === null || this.IDPDataSwitch.reconcileSelected === undefined) { reconcileUncheck = true; } if (this.IDPDataSwitch.resetSelected === "off" || this.IDPDataSwitch.resetSelected === null || this.IDPDataSwitch.resetSelected === undefined) { resetUncheck = true; } if ((!this.idpdataService.isSAPApplication && buildUncheck && testUncheck && deployUncheck) || (this.idpdataService.isSAPApplication && buildUncheck && testUncheck && deployUncheck && reconcileUncheck && resetUncheck) || (this.idpdataService.triggerJobData.technology === "dbDeployDelphix" && this.IDPParamData.deployDB === "on" && this.IDPParamData.dbOperations !== undefined && this.IDPParamData.dbOperations.length === 0)) { this.idpdataService.loading = false; if (this.idpdataService.triggerJobData.technology === "dbDeployDelphix" && this.IDPParamData.deployDB === "on" && this.IDPParamData.dbOperations !== undefined && this.IDPParamData.dbOperations.length === 0) { this.triggerAlertDBDep(); } else { this.triggerAlert(); } } else { if (this.tempDeploySteps.length !== 0 && this.tempDeploySteps.length !== undefined) { for (let i = 0; i < this.deployArr.length; i++) { const step = this.deployArr[i]; if (this.deployArr[i] !== null) { console.log(this.deployArr[i]); this.IDPParamData.deploy.deployStep.push(step); } } } if (this.tempTestSteps.length !== 0 && this.tempTestSteps.length !== undefined) { for (let i = 0; i < this.testArr.length; i++) { const step = this.testArr[i]; if (this.testArr[i] !== null) { this.IDPParamData.testStep.push(step); } } } if (this.IDPParamData.dbOperations !== undefined && this.IDPParamData.dbOperations.length !== 0) { const list = this.idpService.copy(this.IDPParamData.dbOperations); this.IDPParamData.dbOperations = ""; for (let i = 0; i < list.length; i++) { this.IDPParamData.dbOperations += list[i] + ";"; } } else if (this.IDPParamData.dbOperations !== undefined) { this.IDPParamData.dbOperations = ""; } if (this.virtualServicesArr !== undefined && this.virtualServicesArr.length > 0) { this.IDPParamData.virtualServicesList = this.virtualServicesArr; } requestData = this.IDPParamData; if (this.idpdataService.isSAPApplication) { if (this.IDPDataSwitch.buildSelected === "on" && this.IDPDataSwitch.deploySelected !== "on" && ( this.idpdataService.checkpollALM || this.IDPParamData.technology==='sapcharm')) { if (this.buildEnv[0]) { requestData.envSelected = this.buildEnv[0]; } } } if (this.IDPDataSwitch.buildSelected === "off" || this.IDPDataSwitch.buildSelected === null || this.IDPDataSwitch.buildSelected === undefined) { requestData.build = null; } if (this.IDPDataSwitch.deploySelected !== "on" || this.IDPDataSwitch.deploySelected === null || this.IDPDataSwitch.deploySelected === undefined) { requestData.deploy = null; } if (this.IDPDataSwitch.resetSelected !== "on" || this.IDPDataSwitch.resetSelected === null || this.IDPDataSwitch.resetSelected === undefined) { requestData.resetStatus = null; } if (this.IDPDataSwitch.testSelected === "off" || this.IDPDataSwitch.testSelected === null || this.IDPDataSwitch.testSelected === undefined) { if (!this.idpdataService.isSAPApplication) { requestData.testSelected = "off"; } } else if (this.IDPDataSwitch.testSelected === "on") { requestData.testSelected = "on"; } if (this.IDPDataSwitch.reconcileSelected === undefined || this.IDPDataSwitch.reconcileSelected === null || this.IDPDataSwitch.reconcileSelected === "off") { requestData.rebase = null; } if (this.IDPDataSwitch.deploySelected === "off" && this.IDPDataSwitch.testSelected === "off" && (!this.idpdataService.isSAPApplication)) { requestData.envSelected = ""; } let ids = ""; for (let x = 0; x < this.testSuitId.length; x++) { ids += this.testSuitId[x]; if (x !== this.testSuitId.length - 1) { ids += ","; } } requestData.testSuitId = ids; if(this.IDPParamData.build !== undefined && this.IDPParamData.build !== null && this.IDPParamData.build.checkmarxIncremental!==undefined){ requestData.build.checkmarxIncremental= this.IDPParamData.build.checkmarxIncremental; } if(this.IDPParamData.build !== undefined && this.IDPParamData.build !== null && this.IDPParamData.build.checkmarxTag!==undefined && this.IDPParamData.build.checkmarxTag === 'on' && this.IDPParamData.build.checkmarxIncremental === ''){ requestData.build.checkmarxIncremental= "off"; } if(this.IDPParamData.build !== undefined && this.IDPParamData.build !== null && this.IDPParamData.build.runCheckmarxInput === ''){ requestData.build.runCheckmarxInput= "off"; } if(this.idpdataService.triggerJobData.build!=null && this.idpdataService.triggerJobData.build.checkMarxDetails!==undefined && this.idpdataService.triggerJobData.build.checkMarxDetails!=null){ requestData.build.checkMarxDetails= this.idpdataService.triggerJobData.build.checkMarxDetails; } } return requestData; } checkPermissions(){ this.showPermissionError = ""; if(this.idpdataService.idpUserName.toLowerCase() === this.crApprover.toLowerCase()) { // checking CR Approver permissions if (this.IDPDataSwitch.charmConfigType === 'master') { if (this.IDPParamData.envSelected === "DEV") { this.showPermissionError = "CR Approver cannot be developer."; } } else if( (this.IDPParamData.build.unitTest === "on") || (this.IDPParamData.build.codeAnalysis === "on")) { this.showPermissionError = "CR Approver cannot be developer."; } else if(this.IDPParamData.envSelected === "PROD") { this.showPermissionError = "CR Approver cannot be CC."; } } if(this.showPermissionError == "") { // checking CD related permissions for(let k = 0; k < this.changeRequestDetails.changeDocumentMapping.length; k++){ let currentCD = this.changeRequestDetails.changeDocumentMapping[k]; if( this.selectedCDData.indexOf(currentCD.changeDocument)!== -1) { if (this.idpdataService.idpUserName.toLowerCase() === currentCD.developer.toLowerCase()) { if( (this.IDPParamData.envSelected === "QA") || (this.IDPParamData.envSelected === "PROD")) { this.showPermissionError = "Developer/Technical Reviewer cannot be Functional Reviewer."; } } else if (this.idpdataService.idpUserName.toLowerCase() === currentCD.functionalReviewer.toLowerCase()) { if( (this.IDPParamData.build.unitTest === "on") || (this.IDPParamData.build.codeAnalysis === "on")) { this.showPermissionError = "Functional Reviewer cannot be Developer/Technical Reviewer."; } } else if (this.idpdataService.idpUserName.toLowerCase() === currentCD.technicalReviewer.toLowerCase()) { if( (this.IDPParamData.envSelected === "QA") || (this.IDPParamData.envSelected === "PROD")) { this.showPermissionError = "Technical Reviewer cannot be Functional Reviewer/CC."; } else if (this.IDPParamData.envSelected && this.IDPDataSwitch.testSelected === 'on') { this.showPermissionError = "Technical Reviewer cannot be Functional Tester."; } } else if (this.idpdataService.idpUserName.toLowerCase() === currentCD.CC.toLowerCase()) { if( (this.IDPParamData.build.unitTest === "on") || (this.IDPParamData.build.codeAnalysis === "on")) { this.showPermissionError = "CC cannot be Developer/Technical Reviewer."; } } else if ( (this.IDPParamData.approvalSelected === 'Successfully Tested') || (this.IDPParamData.approvalSelected === 'DM Approved') ) { let trackSelected = this.changeRequestDetails.crsBasedOnTrackSubtrack.filter(x=> (this.charmTriggerData.sapTrackSelected === x.track)); if (trackSelected[0].trackRolesMapping.includes("CC")){ if (this.idpdataService.idpUserName.toLowerCase() === currentCD.developer.toLowerCase()) { this.showPermissionError = "CC cannot be Developer/Technical Reviewer."; } } } } } } } validateApprovalStage() { this.isAllowed = false; if (!this.showPermissionError) { let currentApproverStage = this.IDPParamData.approvalSelected; let trackSelected = this.changeRequestDetails.crsBasedOnTrackSubtrack.filter(x=> (this.charmTriggerData.sapTrackSelected === x.track)); switch(currentApproverStage) { case 'Successfully Tested' : { if (trackSelected[0].trackRolesMapping.includes("CC")){ this.isAllowed = true; } else { this.showPermissionError = "You are not authorized for this request."; } break; } case 'Authorized for Production' : { if (trackSelected[0].trackRolesMapping.includes("DM")){ this.isAllowed = true; } else { this.showPermissionError = "You are not authorized for this request."; } break; } case 'Ready for Production Import' : { if (trackSelected[0].trackRolesMapping.includes("PF")){ this.isAllowed = true; } else { this.showPermissionError = "You are not authorized for this request."; } break; } case 'PFA Approved' : { if (trackSelected[0].trackRolesMapping.includes("DM")){ this.isAllowed = true; } else { this.showPermissionError = "You are not authorized for this request."; } break; } case 'DM Approved' : { if (trackSelected[0].trackRolesMapping.includes("CC")){ this.isAllowed = true; } else { this.showPermissionError = "You are not authorized for this request."; } break; } } } } saveWorkflowData(modalRef) { modalRef.hide(); this.onTriggerDetailsSaved.emit(true); this.idpdataService.loading = true; const requestData = this.getRequestData(); if (requestData === undefined) { console.log("Request data undefined: " + requestData); } else { console.log(requestData); console.log(JSON.stringify(requestData)); if (this.workflowSequenceIndexI !== undefined) { console.log("workflowSequenceIndex: " + this.workflowSequenceIndexI); this.idpdataService.workflowData.workflowSequence[this.workflowSequenceIndexI]. applicationDetails[this.workflowSequenceIndexJ].pipelineDetails[this.workflowSequenceIndexK] = requestData; this.idpdataService.workflowData.workflowSequenceTemp[this.workflowSequenceIndexI].IDPDataSwitch = this.IDPDataSwitch; } else { console.log("Unable to update as workflowSequenceIndex is: " + this.workflowSequenceIndexI); } } this.idpdataService.loading = false; } redirectTo() { } getSlaveStatus(slave) { this.idprestapiService.getSlaveStatus(slave).then(response => { if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { if (response.json().resource !== null) { this.slavestatus = response.json().resource; } else { this.slavestatus = "Not Found"; } } } else{ this.slavestatus=""; } }); } getTestSlaveStatus(slave) { this.idprestapiService.getSlaveStatus(slave).then(response => { if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { if (response.json().resource !== null) { this.testslavestatus = response.json().resource; } else { this.testslavestatus = "Not Found"; } } } else{ this.testslavestatus=""; } }); } optionalGetArtifactsRm(){ if(this.rmsEnv === undefined || (this.rmsEnv.indexOf(this.IDPParamData.envSelected) === -1)){ this.getArtifactsRm(); } } getArtifactsRm() { if (this.IDPDataSwitch.repoName !== "na") { if (this.IDPDataSwitch.deploySelected === "on" && (this.IDPDataSwitch.buildSelected !== "on" || this.IDPParamData.technology === "dbDeployDelphix")) { if (this.IDPParamData.envSelected !== "") { const data = { "applicationName": this.IDPParamData.applicationName, "artifactList": this.idpdataService.triggerJobData.artifactList, "environmentName": this.IDPParamData.envSelected, "pipelineName": this.IDPParamData.pipelineName, "releaseNumber": this.IDPDataSwitch.releaseNumber }; this.idprestapiService.getArtifactsRm(data).then(response => { if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { this.artifacts = JSON.parse(response.json().resource).artifactList; this.allArtifactlist = JSON.parse(response.json().resource).artifactList; const tempLatestArtifact = [{ "artifactName": "", "artifactID": "", "groupId": "", "nexusURL": "", "repoName": "", "version": "", "buildModules": "", "enviromment": "", "userInfo": "", "timestamp": "", "downloadURL": "" }]; this.filterArtifacts(); if(this.rmsEnv.indexOf(this.IDPParamData.envSelected) !== -1){ this.filterArtifactsRms(); } const artifactSize=this.artifacts.length; tempLatestArtifact[0].artifactName = this.idpdataService.triggerJobData.applicationName + "_" + this.idpdataService.triggerJobData.pipelineName + "_latestArtifact"; //alert("version" + this.artifacts[artifactSize-1].version); tempLatestArtifact[0].groupId = this.idpdataService.triggerJobData.applicationName; tempLatestArtifact[0].artifactID = this.idpdataService.triggerJobData.pipelineName; tempLatestArtifact[0].nexusURL = this.idpdataService.triggerJobData.nexusURL; tempLatestArtifact[0].repoName = this.idpdataService.triggerJobData.repoName; tempLatestArtifact[0].downloadURL="http://"+tempLatestArtifact[0].nexusURL + "/repository/" + tempLatestArtifact[0].repoName+"/"+this.IDPParamData.applicationName+"/"+this.IDPParamData.pipelineName+"/"+this.artifacts[artifactSize-1].version+"/"+this.IDPParamData.pipelineName+"-"+this.artifacts[artifactSize-1].version+".zip"; if(this.rmsEnv.indexOf(this.IDPParamData.envSelected) === -1) this.artifacts.push(tempLatestArtifact[0]); } } this.idpdataService.loading = false; }); } } } } filterArtifactsRms() { this.rmsArtifacts = []; for (let i = 0; i < this.artifacts.length; i++) { if (_.includes(this.artifacts[i].artifactName, this.rmsApprovedArtifact) !== false) { this.rmsArtifacts.push(this.artifacts[i]); } } if (this.rmsArtifacts.length === 0) { alert("Please select both build and deploy as no approved artifacts are present"); } this.artifacts = this.rmsArtifacts; } filterArtifacts() { this.artifacts = []; for (let i = 0; i < this.allArtifactlist.length; i++) { if (_.includes(this.allArtifactlist[i].version, this.IDPDataSwitch.releaseNumber) !== false) { this.artifacts.push(this.allArtifactlist[i]); } } if (this.artifacts.length === 0) { alert("Please select both build and deploy"); } } /*calling rest service for getting jobparam details*/ getJobParamDetails() { this.idprestapiService.getJobParamList() .then(response => { if (response) { const resp = response.json().resource; let parsed; try { if (response.json().resource !== "{}" && response.json().resource !== null) { parsed = response.json().resource; this.idpdataService.triggerJobData.jobParamList = JSON.parse(parsed); this.jobParamList = this.idpdataService.triggerJobData.jobParamList; this.IDPParamData.jobParam = this.jobParamList; let checkStatic = 0; for (let x = 0; x < this.jobParamList.length; x++) { if (this.jobParamList[x].jobParamSatic === true) { checkStatic++; } } if (checkStatic === this.jobParamList.length) { this.showJobParamFlag = "off"; } else { this.showJobParamFlag = "on"; } } else { console.log("Failed to get JobparamDetails Details"); } } catch (e) { //alert("Failed to get JobparamDetails Details"); console.log(e); } } }); } setValue(val) { this.IDPParamData.branchOrTagValue = val; this.branchList = this.idpService.copy(this.branchTemp); this.tagList = this.idpService.copy(this.tagTemp); this.fetchReleaseBranches(this.IDPDataSwitch.releaseNumber); } setBranchTag(data) { this.branchOrTag = data; this.IDPParamData.branchOrTag = data; this.IDPParamData.branchOrTagValue = ""; this.branchList = this.idpService.copy(this.branchTemp); this.tagList = this.idpService.copy(this.tagTemp); this.fetchReleaseBranches(this.IDPDataSwitch.releaseNumber); } setBranchOrTag() { this.IDPParamData.branchOrTag = "branch"; this.IDPParamData.branchOrTagValue = ""; this.branchList = this.idpService.copy(this.branchTemp); this.tagList = this.idpService.copy(this.tagTemp); this.fetchReleaseBranches(this.IDPDataSwitch.releaseNumber); } searchValue() { const list = []; if (this.branchOrTag === "branch") { this.tagList = this.idpService.copy(this.tagTemp); if (this.IDPParamData.branchOrTagValue !== "") { let branchFrom = this.idpService.copy(this.branchTemp); if (this.requiredSCM) { branchFrom = this.idpService.copy(this.branchListReqTemp); } for (let x = 0; x < branchFrom.length; x++) { if (branchFrom[x].indexOf(this.IDPParamData.branchOrTagValue) !== -1) { list.push(branchFrom[x]); } } this.branchList = this.idpService.copy(list); } else { this.branchList = this.idpService.copy(this.branchTemp); this.fetchReleaseBranches(this.IDPDataSwitch.releaseNumber); } } else if (this.branchOrTag === "tag") { this.branchList = this.idpService.copy(this.branchTemp); this.fetchReleaseBranches(this.IDPDataSwitch.releaseNumber); if (this.IDPParamData.branchOrTagValue !== "") { for (let x = 0; x < this.tagTemp.length; x++) { if (this.tagTemp[x].indexOf(this.IDPParamData.branchOrTagValue) !== -1) { list.push(this.tagTemp[x]); } } this.tagList = this.idpService.copy(list); } else { this.tagList = this.idpService.copy(this.tagTemp); } } } fetchSteps() { this.dropdownListDeploy = []; this.dropdownListTest = []; this.testStepWithToolList = []; this.tempTestSteps = []; this.testArr = []; const data = { "application_name": this.IDPParamData.applicationName, "pipeline_name": this.IDPParamData.pipelineName, "env_name": this.IDPParamData.envSelected }; let resp; this.idprestapiService.fetchTriggerSteps(data) .then(response => { try { if (response) { const err = response.json().errorMessage; if (err === null && response.json().status.toLowerCase() === "success") { resp = JSON.parse(response.json().resource); if (resp.deploySteps !== undefined) { for (let i = 0; i < resp.deploySteps.length; i++) { const step = { "id": i, "itemName": resp.deploySteps[i] }; this.dropdownListDeploy.push(step); console.log(this.dropdownListDeploy); this.deployArr[i] = null; } } if (resp.testSteps !== undefined) { for (let j = 0; j < resp.testSteps.length; j++) { const step = { "id": j, "itemName": resp.testSteps[j].stepName }; this.testStepWithToolList.push(resp.testSteps[j]); this.dropdownListTest.push(step); this.testArr[j] = null; } } } } } catch (e) { console.log(e); } }); } getTestPlan() { let flagTestPlan = false; for (let j = 0; j < this.testArr.length; j++) { for (let i = 0; i < this.testStepWithToolList.length; i++) { if (this.testArr[j] === this.testStepWithToolList[i].stepName) { if (this.testStepWithToolList[i].toolName === "mtm") { flagTestPlan = true; this.IDPParamData.mtmStepName = this.testStepWithToolList[i].stepName; break; } } } } if (flagTestPlan) { this.idpdataService.loading = true; this.idprestapiService.getTestPlanList(this.IDPParamData.applicationName, this.IDPParamData.pipelineName) .then(response => { if (response) { this.idpdataService.loading = false; const respResource = JSON.parse(response.json().resource); this.testPlansList = respResource; } }); } } getTestSuits(planId) { this.idpdataService.loading = true; this.testSuitList = []; this.testSuitId = []; this.idprestapiService.getTestSuitList(planId, this.IDPParamData.applicationName, this.IDPParamData.pipelineName) .then(response => { if (response) { this.idpdataService.loading = false; const respResource = JSON.parse(response.json().resource); const testSuitList = respResource; this.addTestSuitesChildren(testSuitList); } }); } getEnvPair() { this.envJson = { "applicationName": this.IDPParamData.applicationName, "pipelineName": this.IDPParamData.pipelineName, "envName": this.IDPParamData.envSelected }; this.idprestapiService.getEnvironmentPairs(this.envJson).then(response => { if (response) { if (response.json().resource !== null) { this.IDPParamData.pairNames = JSON.parse(response.json().resource).names; } } }); } addTestSuitesChildren(array) { const tempJson = {}; for (let i = 0; i < array.length; i++) { const suiteObj = array[i]; suiteObj.children = []; tempJson[suiteObj.testSuitId] = suiteObj; let parentKey; if (suiteObj.testSuitParent === "na") { parentKey = "root"; } else { parentKey = suiteObj.testSuitParent; } if (parentKey !== "root" && parentKey !== "na") { const parentKeyJson = JSON.parse(suiteObj.testSuitParent); parentKey = parentKeyJson.id; } if (!tempJson[parentKey]) { tempJson[parentKey] = { children: [] }; } tempJson[parentKey].children.push(suiteObj); } let finalList; finalList = JSON.parse(JSON.stringify(tempJson["root"].children).split("\"testSuitName\":").join("\"text\":")); finalList = JSON.parse(JSON.stringify(finalList).split("\"testSuitId\":").join("\"value\":")); finalList = JSON.parse(JSON.stringify(finalList).replace("\"testSuitParent\":\"na\",", "")); const result = this.createTreeView({ "text": "na", "value": "na", "children": finalList }); this.testSuitList = result.children; } onSelectedChange(downlineItems: DownlineTreeviewItem[]) { } addItem(item) { if (item.srcElement.checked) { if (this.testSuitId.indexOf(item.srcElement.name) === -1) { this.testSuitId.push(item.srcElement.name); } return true; } else { if (this.testSuitId.indexOf(item.srcElement.name) !== -1) { this.testSuitId.splice(this.testSuitId.indexOf(item.srcElement.name), 1); } return false; } } checkChecked(checked) { if (checked) { return true; } else { return false; } } createTreeView(data) { if (data.children.length === 0) { const x = { "value": data.value, "text": data.text, "children": [], "checked": false, "collapsed": true }; return new TreeviewItem(x, true); } else { const d = { "text": data.text, "value": data.value, "children": data.children, "checked": false, "collapsed": true }; for (let i = 0; i < data.children.length; i++) { data.children[i] = this.createTreeView(data.children[i]); d.children[i] = data.children[i]; } return new TreeviewItem(d, true); } } // <----- Deploy Steps Multi-select Dropdown functions----> onItemSelectDepSteps(item: any) { this.deployArr.push(item.itemName); } trOnItemSelect(item: any) { this.trialArr[item.id] = item.itemName; } trOnItemSelectDe(item: any) { const i = this.trialArr.indexOf(item.itemName); if (i !== -1) { this.trialArr[i] = null; } } onItemDeSelectDepSteps(item: any) { const i = this.deployArr.indexOf(item.itemName); if (i !== -1) { this.deployArr[i] = null; } } onSelectAllDepSteps(items: any) { for (const item of items) { this.deployArr[item.id] = item.itemName; } } onDeSelectAllDepSteps(items: any) { this.deployArr = []; } // <----- Test Steps Multi-select Dropdown functions----> onItemSelectTestSteps(item: any) { this.testArr.push(item.itemName); } onItemDeSelectTestSteps(item: any) { const i = this.testArr.indexOf(item.itemName); if (i !== -1) { this.testArr[i] = null; } for (let k = 0; k < this.testStepWithToolList.length; k++) { if (item.itemName === this.testStepWithToolList[k].stepName) { if (this.testStepWithToolList[k].toolName === "mtm") { this.IDPParamData.mtmStepName = ""; this.testPlansList = []; this.testSuitList = []; this.testSuitId = []; this.IDPParamData.testPlanId = ""; break; } } } } onSelectAllTestSteps(items: any) { for (const item of items) { this.testArr[item.id] = item.itemName; } } onDeSelectAllTestSteps(items: any) { this.testArr = []; this.IDPParamData.mtmStepName = ""; this.testPlansList = []; this.testSuitList = []; this.testSuitId = []; this.IDPParamData.testPlanId = ""; } updateSelectedOperation(event) { if (event.target.checked) { if (this.IDPParamData.dbOperations.indexOf(event.target.name) < 0) { this.IDPParamData.dbOperations.push(event.target.name); } } else { if (this.IDPParamData.dbOperations.indexOf(event.target.name) > -1) { this.IDPParamData.dbOperations.splice(this.IDPParamData.dbOperations.indexOf(event.target.name), 1); } } } unCheckCast() { this.IDPParamData.build.cast = "off"; this.IDPParamData.castSlaveName = ""; this.IDPParamData.build.oldVersion = ""; this.IDPParamData.build.newVersion = ""; } scheduleJobOn() { const data = { "applicationName": this.IDPParamData.applicationName, "pipelineName": this.IDPParamData.pipelineName, "userName": this.idpdataService.idpUserName }; this.idpdataService.loading = true; this.idprestapiService.getPipelineDetails(data) .then(response => { console.log(new Date().toUTCString(), "Pipeline details retrieved"); try { const responseData = this.idpencryption.decryptAES(response.json().resource); let resp = JSON.parse(responseData); resp = this.idpencryption.doubleEncryptPassword(resp.pipelineJson); this.idpdataService.buildIntervalData = resp.basicInfo.customTriggerInterval.interval; } catch (e) { console.log("Failed to get the Build Interval Schedule Details"); console.log(e); } }); this.idpdataService.loading = false; return "on"; } scheduleJobOff() { this.idpdataService.schedulePage = 0; return "off"; } addJob() { this.idpdataService.buildIntervalData.push({ "type": "", "minute": "", "time": "", "details": {} }); } getArtifactLatestDetails(artifacts) { console.log(artifacts.artifactName); const dashboardURL: String = this.idpdataService.IDPDashboardURL; console.log("dashboard url: " + dashboardURL) const hostName: String = dashboardURL.split(":")[1].substr(2); this.dashboardUrl = "https://" + hostName + ":3000/dashboard/db/artifact-view?orgId=1&var-Application=" + this.IDPParamData.applicationName; this.dashboardUrl = this.dashboardUrl + "&var-Pipeline=" + this.IDPParamData.pipelineName; this.dashboardUrl = this.dashboardUrl + "&var-ReleaseNo=" + this.IDPDataSwitch.releaseNumber; this.dashboardUrl = this.dashboardUrl + "&var-ArtifactId=" + artifacts.artifactName; this.idprestapiService.getArtifactLatestDetails(artifacts.artifactName).then(response => { if (response) { if (response.json().resource !== null && response.json().resource !== "[]" && response.json().resource !== "{}") { this.artifactDetails = JSON.parse(response.json().resource).artifactDetails; this.packageContent = JSON.parse(response.json().resource).packageContent; for (const artifactvalue of this.artifactDetails) { } if (this.packageContent !== undefined && this.packageContent.ant !== undefined && this.packageContent.ant.moduleName !== undefined) { this.ant = this.packageContent.ant.moduleName; } if (this.packageContent !== undefined && this.packageContent.dotNet !== undefined && this.packageContent.dotNet.moduleName !== undefined) { this.dotNet = this.packageContent.dotNet.moduleName; } if (this.packageContent !== undefined && this.packageContent.bigData !== undefined && this.packageContent.bigData.moduleName !== undefined) { this.bigData = this.packageContent.bigData.moduleName; } if(this.packageContent !== undefined && this.packageContent.pega !== undefined){ this.pega = this.packageContent.pega; } if(this.packageContent !== undefined && this.packageContent.siebel !== undefined){ this.siebel = this.packageContent.siebel; console.log(" Siebel DataContent " +this.siebel); } } } }); } clearArtifact() { this.artifactDetails = []; this.informatica = []; this.dotNet = []; this.bigData = []; this.ant = []; this.siebel.repoList = []; this.siebel.nonRepoList = []; this.pega.pegaFileList = []; } isLatestArtifact() { return (this.IDPParamData.deploy.artifacts.artifactName as String).endsWith("_latestArtifact"); } onItemSelectUserStory(item: any) { for (let j = 0; j < this.userStoryArray.length; j++) { if (item.itemName === this.userStoryArray[j].Userstory) { this.selectedUSData.push(this.userStoryArray[j]); break; } } console.log(this.selectedUSData); this.getTransportRequestForUserStories("onSelect", item.itemName); } OnItemDeSelectUserStory(item: any) { let index; for (let j = 0; j < this.selectedUSData.length; j++) { if (item.itemName === this.selectedUSData[j].Userstory) { index = j; break; } } this.selectedUSData.splice(index, 1); this.getTransportRequestForUserStories("onDeselect", item.itemName); } onSelectAllUserStory(items: any) { this.selectedUSData = this.userStoryArray; this.getTransportRequestForUserStories("onSelectAll", ""); } onDeSelectAllUserStory(items: any) { this.selectedUSData = []; this.getTransportRequestForUserStories("onDeselectAll", ""); } rmsToken(){ if (this.IDPDataSwitch.repoName !== "na") { if (this.IDPDataSwitch.deploySelected === "on" && (this.IDPDataSwitch.buildSelected !== "on" || this.IDPParamData.technology === "dbDeployDelphix")) { if (this.IDPParamData.envSelected !== "") { if(this.rmsEnv.indexOf(this.IDPParamData.envSelected) !== -1){ if(this.rmsComponentName===""){ alert("No Rms Component Name present. Please edit the pipeline."); } this.idprestapiService.getRmsToken(this.rmsComponentName) .then(response => { try { alert("Successfully retrieved RMS token!!"); console.log(response.json().resource); const str = response.json().resource; this.rmsApprovedArtifact=str.substr(1).slice(0, -1); //alert("after token call") this.getArtifactsRm(); } catch (e) { console.log("Failed to get Rms token"); console.log(e); } }); } } } } } OnItemSelectChangeDocument(item: any) { this.selectedCDData.push(item.itemName.split(" -->")[0]); this.getCharmTransportData(); } OnItemDeSelectChangeDocument(item: any) { let index; for (let j = 0; j < this.selectedCDData.length; j++) { if (item.itemName.split(" -->")[0] === this.selectedCDData[j]) { index = j; break; } } this.selectedCDData.splice(index, 1); this.getCharmTransportData(); } onSelectAllChangeDocument(items: any) { for(let cd of this.changeDocumentList) { this.selectedCDData.push(cd.itemName); console.log(this.selectedCDData); } this.getCharmTransportData(); } onDeSelectAllChangeDocument(items: any) { this.selectedCDData = []; console.log(this.selectedCDData); this.getCharmTransportData(); } getCharmTransportData(){ let cdDetails = this.changeRequestDetails.changeDocumentMapping; this.transportRequests = []; this.cdDetailsList = []; for(let i=0 ; i < cdDetails.length; i++){ for(let j=0 ; j< this.selectedCDData.length ; j++){ console.log( " selected Cd data :" + this.selectedCDData[j]); // console.log(" change Document : " + cdDetails[i].changeDocument); if(this.selectedCDData[j] === cdDetails[i].changeDocument){ console.log("true inside func"); let cdDataList = cdDetails[i].changeDocumentData; for(let k=0 ; k < cdDataList.length ; k++){ // console.log(cdDetails[i].changeDocumentData[k].trNumber); this.cdDetailsList.push(cdDetails[i].changeDocumentData[k]); if(cdDetails[i].changeDocumentData[k].trStatus!=="Released"){ this.transportRequests.push(cdDetails[i].changeDocumentData[k].trNumber); } } } } } } trackDisplayedName(trackInfo) { if (trackInfo.track) { return trackInfo.track + "-->" + trackInfo.trackDescription ; } } clearCrData(){ // this.hideChangeDocument=true; // this.hideChangeRequest=true; this.changeRequestList = []; this.changeRequestListTemp = []; this.changeDocumentList = []; this.sapSubTrackListTemp = []; this.IDPParamData.resetSlave = ""; this.showPermissionError = ""; // this.IDPParamData.resetStatus.fromState = ""; this.selectedCDData = []; this.selectedCD = []; this.charmTriggerData.changeRequest = ""; this.charmTriggerData.sapTrackSelected = ""; this.charmTriggerData.sapSubTrackSelected = ""; this.transportRequests = []; this.cdDetailsList = []; this.showErrorForST = false; // this.IDPParamData.approvalSelected = ""; // this.IDPParamData.slaveName = ""; // this.slavestatus = ""; } clearCrCd(){ this.changeRequestList = []; this.changeRequestListTemp = []; this.changeDocumentList = []; this.changeDocumentListTemp = []; this.changeDocumentListDescDropdown = []; this.selectedCDData = []; this.selectedCD = []; this.charmTriggerData.changeRequest = ""; this.transportRequests = []; this.cdDetailsList = []; this.showPermissionError = ""; this.showErrorForST = false; } validateForST() { if ( (this.IDPParamData.approvalSelected === 'Successfully Tested') && this.selectedLandscapeType === 'PROD' ){ this.showErrorForST = true; } } clearCharmConfigType(){ this.clearCrCd(); this.IDPDataSwitch.buildSelected="off"; this.IDPDataSwitch.deploySelected="off"; this.IDPDataSwitch.testSelected="off"; this.showPermissionError = ""; this.IDPParamData.slaveName = ""; this.slavestatus = ""; this.IDPParamData.approvalSelected = ""; this.selectedLandscapeType = ""; if(this.IDPParamData.technology==='sapcharm') this.getChangeRequest(); } updateIncrementalScan() { if ((this.IDPParamData.build.runCheckmarxInput==="on")){ if(this.IDPParamData.build.checkmarxIncremental === "on") { this.IDPParamData.build.checkmarxIncremental = "on"; } else { this.IDPParamData.build.checkmarxIncremental = "off"; } } else { this.IDPParamData.build.checkmarxIncremental = "NA"; } } }
the_stack
import React, { useMemo, useRef, useCallback, useState, useEffect } from 'react'; import { UUIFunctionComponent, UUIFunctionComponentProps } from '../../core'; import { useEvent } from 'react-use'; import { clamp, clone, inRange, isArray } from 'lodash-es'; import { KeyCode } from '../../utils/keyboardHelper'; import { createComponentPropTypes, PropTypes } from '../../utils/createPropTypes'; export interface SliderRemark { value: number; label: React.ReactNode; } export interface SliderFeatureProps { /** * The value to display in the input field. */ value: [number, number] | number; /** * Event handler invoked when input value is changed. */ onChange: (value: [number, number] | number) => void; /** * The minimum value of the input. */ min: number; /** * The maximum value of the input. */ max: number; /** * The step sets the stepping interval when clicking up and down spinner buttons. */ step: number; /** * Tick mark, the value is in the closed interval [min, max]. * @default [] */ remarks?: SliderRemark[]; /** * Whether the control is non-interactive. * @default false */ disabled?: boolean; /** * Whether to render the Slider vertically. Defaults to rendering horizontal. * @default false */ vertical?: boolean; onFocus?: React.FocusEventHandler<HTMLDivElement>; onBlur?: React.FocusEventHandler<HTMLDivElement>; } export const SliderRemarkPropTypes = createComponentPropTypes<SliderRemark>({ value: PropTypes.number.isRequired, label: PropTypes.node.isRequired, }) export const SliderPropTypes = createComponentPropTypes<SliderFeatureProps>({ value: PropTypes.oneOfType([ PropTypes.number, PropTypes.arrayOf(PropTypes.number), ]), onChange: PropTypes.func, min: PropTypes.number.isRequired, max: PropTypes.number.isRequired, step: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, remarks: PropTypes.arrayOf(PropTypes.shape(SliderRemarkPropTypes)), disabled: PropTypes.bool, vertical: PropTypes.bool, onFocus: PropTypes.func, onBlur: PropTypes.func, }) export const Slider = UUIFunctionComponent({ name: 'Slider', nodes: { Root: 'div', Container: 'div', ActiveLine: 'div', InactiveLine: 'div', Thumb: 'div', Remark: 'div', RemarkLabel: 'div', }, propTypes: SliderPropTypes, }, (props: SliderFeatureProps, { nodes, NodeDataProps }) => { const { Root, Container, ActiveLine, InactiveLine, Thumb, Remark, RemarkLabel } = nodes const finalProps = { remarks: props.remarks || [], } /** * Due to Slider supports the selection of a value or a range of values, * a unified interface is needed to handle what type of data the component should return. */ const finalValue = useMemo(() => { return [ typeof props.value === 'number' ? props.min : props.value[0], typeof props.value === 'number' ? props.value : props.value[1], ] as const }, [props.min, props.value]) const onFinalChange = useCallback((value: [number, number]) => { const newValue: [number, number] = [Number(value[0].toFixed(8)), Number(value[1].toFixed(8))] if (typeof props.value === 'number') { props.onChange.call(undefined, newValue[1]) } else { props.onChange.call(undefined, newValue) } }, [props.value, props.onChange]) /** * Handle thumbs position */ const [thumbDragging, setThumbDragging] = useState<0 | 1 | null>(null) const [finalPosition, setFinalPosition] = useState<[number, number]>([ (finalValue[0]-props.min) / (props.max-props.min), (finalValue[1]-props.min) / (props.max-props.min), ]) useEffect(() => { setFinalPosition([ (finalValue[0]-props.min) / (props.max-props.min), (finalValue[1]-props.min) / (props.max-props.min), ]) }, [finalValue, props.min, props.max]) const containerRef = useRef<any>() const getPositionFromEvent = (event: MouseEvent | TouchEvent) => { if (!containerRef.current) return null const containerRect = containerRef.current.getBoundingClientRect() const leadingPosition = props.vertical ? containerRect.bottom : containerRect.left const trailingPosition = props.vertical ? containerRect.top : containerRect.right const currentPosition = (() => { switch (event.type) { case 'mousedown': case 'mousemove': case 'click': return props.vertical ? (event as MouseEvent).clientY : (event as MouseEvent).clientX case 'touchstart': case 'touchmove': return props.vertical ? (event as TouchEvent).touches[0].clientY :(event as TouchEvent).touches[0].clientX default: return null } })(); if (!currentPosition) return null let newPosition = (currentPosition - leadingPosition) / (trailingPosition - leadingPosition) newPosition = clamp(newPosition, 0.00, 1.00) return newPosition } const onEventPositionChange = (position: number, thumbIndex: 0 | 1) => { const newValue = Math.round((props.max-props.min) / props.step * position) * props.step + props.min setFinalPosition((value) => { value[thumbIndex] = position return value }) if (newValue !== props.value) { const newFinalValue: [number, number] = [finalValue[0], finalValue[1]] newFinalValue[thumbIndex] = newValue onFinalChange(newFinalValue) } } const onMouseDownOrTouchStart = (event: React.MouseEvent<HTMLDivElement, MouseEvent> | React.TouchEvent<HTMLDivElement>) => { if (props.disabled) return; const newPosition = getPositionFromEvent(event as any) if (!newPosition) return; const targetIndex = isArray(props.value) ? (Math.abs(finalPosition[0] - newPosition) < Math.abs(finalPosition[1] - newPosition) ? 0 : 1) : 1; !props.disabled && setThumbDragging(targetIndex) onEventPositionChange(newPosition, targetIndex) } const onMouseUpOrTouchEnd = () => { !props.disabled && setThumbDragging(null) } const onMouseOrTouchMove = (event: MouseEvent | TouchEvent) => { if (props.disabled) return; if (thumbDragging === null) return; const newPosition = getPositionFromEvent(event) if (newPosition === null) return; onEventPositionChange(newPosition, thumbDragging) } useEvent('mousemove', onMouseOrTouchMove as any, window, { capture: !props.disabled && !!thumbDragging }) useEvent('touchmove', onMouseOrTouchMove as any, window, { capture: !props.disabled && !!thumbDragging }) useEvent('mouseup', onMouseUpOrTouchEnd as any, window, { capture: !props.disabled && !!thumbDragging }) useEvent('touchend', onMouseUpOrTouchEnd as any, window, { capture: !props.disabled && !!thumbDragging }) /** * Calculate the position and size of thumbs, remarks and lines. */ const styles = useMemo(() => { const sortPosition = clone(finalPosition).sort() switch (props.vertical) { case false: case undefined: return { LeadingInactiveLine: { width: toPercentage(sortPosition[0]), display: typeof props.value === 'number' ? 'none' : undefined, }, ActiveLine: { width: toPercentage(sortPosition[1] - sortPosition[0]), }, TrailingInactiveLine: { width: toPercentage(1 - sortPosition[1]), }, LeadingThumb: { left: toPercentage(finalPosition[0]), display: typeof props.value === 'number' ? 'none' : undefined, transform: 'translateX(-50%)', }, TrailingThumb: { left: toPercentage(finalPosition[1]), transform: 'translateX(-50%)', }, Remark: finalProps.remarks.map((remark) => { const position = (remark.value - props.min) / (props.max - props.min) return { left: toPercentage(position), transform: 'translateX(-50%)', } }) } case true: return { TrailingInactiveLine: { height: toPercentage(sortPosition[0]), display: typeof props.value === 'number' ? 'none' : undefined, }, ActiveLine: { height: toPercentage(sortPosition[1] - sortPosition[0]), }, LeadingInactiveLine: { height: toPercentage(1 - sortPosition[1]), }, LeadingThumb: { bottom: toPercentage(finalPosition[0]), display: typeof props.value === 'number' ? 'none' : undefined, transform: 'translateY(50%)', }, TrailingThumb: { bottom: toPercentage(finalPosition[1]), transform: 'translateY(50%)', }, Remark: finalProps.remarks.map((remark) => { const position = (remark.value - props.min) / (props.max - props.min) return { bottom: toPercentage(position), transform: 'translateY(50%)', } }) } } }, [finalPosition, props.value, props.max, props.min, props.vertical, finalProps.remarks]) const [focusThumbIndex, setFocusThumbIndex] = useState<number | null>(null) return ( <Root {...NodeDataProps({ 'disabled': !!props.disabled, 'vertical': !!props.vertical, })} onMouseDown={onMouseDownOrTouchStart} onTouchStart={onMouseDownOrTouchStart} onKeyDown={(event) => { switch (event.keyCode) { case KeyCode.ArrowLeft: case KeyCode.ArrowDown: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = clamp(newValue[focusThumbIndex] - props.step, props.min, props.max); onFinalChange(newValue) } break } case KeyCode.ArrowRight: case KeyCode.ArrowUp: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = clamp(newValue[focusThumbIndex] + props.step, props.min, props.max); onFinalChange(newValue) } break } case KeyCode.PageDown: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = clamp(newValue[focusThumbIndex] - props.step * 10, props.min, props.max); onFinalChange(newValue) } break } case KeyCode.PageUp: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = clamp(newValue[focusThumbIndex] + props.step * 10, props.min, props.max); onFinalChange(newValue) } break } case KeyCode.Home: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = props.max; onFinalChange(newValue) } break } case KeyCode.End: { if (focusThumbIndex !== null) { const newValue = Array.from(finalValue) as [number, number]; newValue[focusThumbIndex] = props.min; onFinalChange(newValue) } break } default: // do nothing } }} onFocus={props.onFocus} onBlur={props.onBlur} > <Container ref={containerRef}> <InactiveLine style={{ ...styles.LeadingInactiveLine }} /> <ActiveLine style={{ ...styles.ActiveLine }} /> <InactiveLine style={{ ...styles.TrailingInactiveLine }} /> {finalProps.remarks.map((remark, index) => { const isActive = inRange(remark.value, finalValue[0], finalValue[1]) return ( <Remark key={index} {...NodeDataProps({ 'active': !!isActive, })} style={{ ...styles.Remark[index] }} > <RemarkLabel>{remark.label}</RemarkLabel> </Remark> ) })} <Thumb role="slider" aria-orientation={props.vertical ? "vertical" : "horizontal"} aria-valuemin={props.min} aria-valuemax={props.max} aria-valuenow={finalValue[0]} aria-valuetext={`${finalValue[0]}`} tabIndex={props.disabled ? -1 : 0} style={{ ...styles.LeadingThumb }} onFocus={() => { setFocusThumbIndex(0) }} onBlur={() => { setFocusThumbIndex(null)}} /> <Thumb role="slider" aria-orientation={props.vertical ? "vertical" : "horizontal"} aria-valuemin={props.min} aria-valuemax={props.max} aria-valuenow={finalValue[1]} aria-valuetext={`${finalValue[1]}`} tabIndex={props.disabled ? -1 : 0} style={{ ...styles.TrailingThumb }} onFocus={() => { setFocusThumbIndex(1) }} onBlur={() => { setFocusThumbIndex(null)}} /> </Container> </Root> ) }) export type SliderProps = UUIFunctionComponentProps<typeof Slider> const toPercentage = (n: number) => `${(n * 100).toFixed(4)}%`
the_stack
import {sortBy, zeroPad, getOrInsert, lastOf} from '../lib/utils' import {ProfileGroup, CallTreeProfileBuilder, FrameInfo, Profile} from '../lib/profile' import {TimeFormatter} from '../lib/value-formatters' // This file concerns import from the "Trace Event Format", authored by Google // and used for Google's own chrome://trace. // // The file format is extremely general, and we only support the parts of it // that logically map onto speedscope's visualization capabilities. // Specifically, we only support the "B", "E", and "X" event types. Everything // else is ignored. We do, however, support import of profiles that are // multi-process/multi-threaded. Each process is split into a separate profile. // // Note that Chrome Developer Tools uses this format as well, but all the // relevant data used in those profiles is stored in events with the name // "CpuProfile", "Profile", or "ProfileChunk". If we detect those, we prioritize // importing the profile as a Chrome Developer Tools profile. Otherwise, // we try to import it as a "Trace Event Format" file. // // Spec: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview interface TraceEvent { // The process ID for the process that output this event. pid: number // The thread ID for the thread that output this event. tid: number // The event type. This is a single character which changes depending on the type of event being output. The valid values are listed in the table below. We will discuss each phase type below. ph: string // The tracing clock timestamp of the event. The timestamps are provided at microsecond granularity. ts: number // The thread clock timestamp of the event. The timestamps are provided at microsecond granularity. tts?: number // The name of the event, as displayed in Trace Viewer name?: string // The event categories. This is a comma separated list of categories for the event. The categories can be used to hide events in the Trace Viewer UI. cat?: string // Any arguments provided for the event. Some of the event types have required argument fields, otherwise, you can put any information you wish in here. The arguments are displayed in Trace Viewer when you view an event in the analysis section. args: any // A fixed color name to associate with the event. If provided, cname must be one of the names listed in trace-viewer's base color scheme's reserved color names list cname?: string } interface BTraceEvent extends TraceEvent { ph: 'B' } interface ETraceEvent extends TraceEvent { ph: 'E' } interface XTraceEvent extends TraceEvent { ph: 'X' dur?: number tdur?: number } // The trace format supports a number of event types that we ignore. type ImportableTraceEvent = BTraceEvent | ETraceEvent | XTraceEvent function pidTidKey(pid: number, tid: number): string { // We zero-pad the PID and TID to make sorting them by pid/tid pair later easier. return `${zeroPad('' + pid, 10)}:${zeroPad('' + tid, 10)}` } function partitionByPidTid(events: ImportableTraceEvent[]): Map<string, ImportableTraceEvent[]> { const map = new Map<string, ImportableTraceEvent[]>() for (let ev of events) { const list = getOrInsert(map, pidTidKey(ev.pid, ev.tid), () => []) list.push(ev) } return map } function selectQueueToTakeFromNext( bEventQueue: BTraceEvent[], eEventQueue: ETraceEvent[], ): 'B' | 'E' { if (bEventQueue.length === 0 && eEventQueue.length === 0) { throw new Error('This method should not be given both queues empty') } if (eEventQueue.length === 0) return 'B' if (bEventQueue.length === 0) return 'E' const bFront = bEventQueue[0] const eFront = eEventQueue[0] const bts = bFront.ts const ets = eFront.ts if (bts < ets) return 'B' if (ets < bts) return 'E' // If we got here, the 'B' event queue and the 'E' event queue have events at // the front with equal timestamps. // If the front of the 'E' queue matches the front of the 'B' queue by name, // then it means we have a zero duration event. Process the 'B' queue first // to ensure it opens before we try to close it. // // Otherwise, process the 'E' queue first. return bFront.name === eFront.name ? 'B' : 'E' } function convertToEventQueues(events: ImportableTraceEvent[]): [BTraceEvent[], ETraceEvent[]] { const beginEvents: BTraceEvent[] = [] const endEvents: ETraceEvent[] = [] // Rebase all of the timestamps on the lowest timestamp if (events.length > 0) { let firstTs = Number.MAX_SAFE_INTEGER for (let ev of events) { firstTs = Math.min(firstTs, ev.ts) } for (let ev of events) { ev.ts -= firstTs } } // Next, combine B, E, and X events into two timestamp ordered queues. const xEvents: XTraceEvent[] = [] for (let ev of events) { switch (ev.ph) { case 'B': { beginEvents.push(ev) break } case 'E': { endEvents.push(ev) break } case 'X': { xEvents.push(ev) break } default: { const _exhaustiveCheck: never = ev return _exhaustiveCheck } } } function dur(x: XTraceEvent): number { return x.dur ?? x.tdur ?? 0 } xEvents.sort((a, b) => { if (a.ts < b.ts) return -1 if (a.ts > b.ts) return 1 // Super weird special case: if we have two 'X' events with the same 'ts' // but different 'dur' the only valid interpretation is to put the one with // the longer 'dur' first, because you can't nest longer things in shorter // things. const aDur = dur(a) const bDur = dur(b) if (aDur > bDur) return -1 if (aDur < bDur) return 1 // Otherwise, retain the original order by relying upon a stable sort here. return 0 }) for (let x of xEvents) { const xDur = dur(x) beginEvents.push({...x, ph: 'B'} as BTraceEvent) endEvents.push({...x, ph: 'E', ts: x.ts + xDur} as ETraceEvent) } function compareTimestamps(a: TraceEvent, b: TraceEvent) { if (a.ts < b.ts) return -1 if (a.ts > b.ts) return 1 // Important: if the timestamps are the same, return zero. We're going to // rely upon a stable sort here. return 0 } beginEvents.sort(compareTimestamps) endEvents.sort(compareTimestamps) return [beginEvents, endEvents] } function filterIgnoredEventTypes(events: TraceEvent[]): ImportableTraceEvent[] { const ret: ImportableTraceEvent[] = [] for (let ev of events) { switch (ev.ph) { case 'B': case 'E': case 'X': ret.push(ev as ImportableTraceEvent) } } return ret } function getProcessNamesByPid(events: TraceEvent[]): Map<number, string> { const processNamesByPid = new Map<number, string>() for (let ev of events) { if (ev.ph === 'M' && ev.name === 'process_name' && ev.args && ev.args.name) { processNamesByPid.set(ev.pid, ev.args.name) } } return processNamesByPid } function getThreadNamesByPidTid(events: TraceEvent[]): Map<string, string> { const threadNameByPidTid = new Map<string, string>() for (let ev of events) { if (ev.ph === 'M' && ev.name === 'thread_name' && ev.args && ev.args.name) { threadNameByPidTid.set(pidTidKey(ev.pid, ev.tid), ev.args.name) } } return threadNameByPidTid } function keyForEvent(event: TraceEvent): string { let name = `${event.name || '(unnamed)'}` if (event.args) { name += ` ${JSON.stringify(event.args)}` } return name } function frameInfoForEvent(event: TraceEvent): FrameInfo { const key = keyForEvent(event) return { name: key, key: key, } } function eventListToProfileGroup(events: TraceEvent[]): ProfileGroup { const importableEvents = filterIgnoredEventTypes(events) const partitioned = partitionByPidTid(importableEvents) const processNamesByPid = getProcessNamesByPid(events) const threadNamesByPidTid = getThreadNamesByPidTid(events) const profilePairs: [string, Profile][] = [] partitioned.forEach(eventsForThread => { if (eventsForThread.length === 0) return const {pid, tid} = eventsForThread[0] const profile = new CallTreeProfileBuilder() profile.setValueFormatter(new TimeFormatter('microseconds')) const processName = processNamesByPid.get(pid) const threadName = threadNamesByPidTid.get(pidTidKey(pid, tid)) if (processName != null && threadName != null) { profile.setName(`${processName} (pid ${pid}), ${threadName} (tid ${tid})`) } else if (processName != null) { profile.setName(`${processName} (pid ${pid}, tid ${tid})`) } else if (threadName != null) { profile.setName(`${threadName} (pid ${pid}, tid ${tid})`) } else { profile.setName(`pid ${pid}, tid ${tid}`) } // The trace event format is hard to deal with because it specifically // allows events to be recorded out of order, *but* event ordering is still // important for events with the same timestamp. Because of this, rather // than thinking about the entire event stream as a single queue of events, // we're going to first construct two time-ordered lists of events: // // 1. ts ordered queue of 'B' events // 2. ts ordered queue of 'E' events // // We deal with 'X' events by converting them to one entry in the 'B' event // queue and one entry in the 'E' event queue. // // The high level goal is to deal with 'B' events in 'ts' order, breaking // ties by the order the events occurred in the file, and deal with 'E' // events in 'ts' order, breaking ties in whatever order causes the 'E' // events to match whatever is on the top of the stack. const [bEventQueue, eEventQueue] = convertToEventQueues(eventsForThread) const frameStack: BTraceEvent[] = [] const enterFrame = (b: BTraceEvent) => { frameStack.push(b) profile.enterFrame(frameInfoForEvent(b), b.ts) } const tryToLeaveFrame = (e: ETraceEvent) => { const b = lastOf(frameStack) if (b == null) { console.warn( `Tried to end frame "${ frameInfoForEvent(e).key }", but the stack was empty. Doing nothing instead.`, ) return } const eFrameInfo = frameInfoForEvent(e) const bFrameInfo = frameInfoForEvent(b) if (e.name !== b.name) { console.warn( `ts=${e.ts}: Tried to end "${eFrameInfo.key}" when "${bFrameInfo.key}" was on the top of the stack. Doing nothing instead.`, ) return } if (eFrameInfo.key !== bFrameInfo.key) { console.warn( `ts=${e.ts}: Tried to end "${eFrameInfo.key}" when "${bFrameInfo.key}" was on the top of the stack. Ending ${bFrameInfo.key} instead.`, ) } frameStack.pop() profile.leaveFrame(bFrameInfo, e.ts) } while (bEventQueue.length > 0 || eEventQueue.length > 0) { const queueName = selectQueueToTakeFromNext(bEventQueue, eEventQueue) switch (queueName) { case 'B': { enterFrame(bEventQueue.shift()!) break } case 'E': { // Before we take the first event in the 'E' queue, let's first see if // there are any e events that exactly match the top of the stack. // We'll prioritize first by key, then by name if we can't find a key // match. const stackTop = lastOf(frameStack) if (stackTop != null) { const bFrameInfo = frameInfoForEvent(stackTop) let swapped: boolean = false for (let i = 1; i < eEventQueue.length; i++) { const eEvent = eEventQueue[i] if (eEvent.ts > eEventQueue[0].ts) { // Only consider 'E' events with the same ts as the front of the queue. break } const eFrameInfo = frameInfoForEvent(eEvent) if (bFrameInfo.key === eFrameInfo.key) { // We have a match! Process this one first. const temp = eEventQueue[0] eEventQueue[0] = eEventQueue[i] eEventQueue[i] = temp swapped = true break } } if (!swapped) { // There was no key match, let's see if we can find a name match for (let i = 1; i < eEventQueue.length; i++) { const eEvent = eEventQueue[i] if (eEvent.ts > eEventQueue[0].ts) { // Only consider 'E' events with the same ts as the front of the queue. break } if (eEvent.name === stackTop.name) { // We have a match! Process this one first. const temp = eEventQueue[0] eEventQueue[0] = eEventQueue[i] eEventQueue[i] = temp swapped = true break } } } // If swapped is still false at this point, it means we're about to // pop a stack frame that doesn't even match by name. Bummer. } const e = eEventQueue.shift()! tryToLeaveFrame(e) break } default: const _exhaustiveCheck: never = queueName return _exhaustiveCheck } } for (let i = frameStack.length - 1; i >= 0; i--) { const frame = frameInfoForEvent(frameStack[i]) console.warn(`Frame "${frame.key}" was still open at end of profile. Closing automatically.`) profile.leaveFrame(frame, profile.getTotalWeight()) } profilePairs.push([pidTidKey(pid, tid), profile.build()]) }) // For now, we just sort processes by pid & tid. // TODO: The standard specifies that metadata events with the name // "process_sort_index" and "thread_sort_index" can be used to influence the // order, but for simplicity we'll ignore that until someone complains :) sortBy(profilePairs, p => p[0]) return { name: '', indexToView: 0, profiles: profilePairs.map(p => p[1]), } } function isTraceEventList(maybeEventList: any): maybeEventList is TraceEvent[] { if (!Array.isArray(maybeEventList)) return false if (maybeEventList.length === 0) return false // Both ph and ts should be provided for every event. In theory, many other // fields are mandatory, but without these fields, we won't usefully be able // to import the data, so we'll rely upon these. for (let el of maybeEventList) { if (!('ph' in el)) { return false } switch (el.ph) { case 'B': case 'E': case 'X': // All B, E, and X events must have a timestamp specified, otherwise we // won't be able to import correctly. if (!('ts' in el)) { return false } case 'M': // It's explicitly okay for "M" (metadata) events not to specify a "ts" // field, since usually there is no logical timestamp for them to have break } } return true } function isTraceEventObject( maybeTraceEventObject: any, ): maybeTraceEventObject is {traceEvents: TraceEvent[]} { if (!('traceEvents' in maybeTraceEventObject)) return false return isTraceEventList(maybeTraceEventObject['traceEvents']) } export function isTraceEventFormatted( rawProfile: any, ): rawProfile is {traceEvents: TraceEvent[]} | TraceEvent[] { // We're only going to support the JSON formatted profiles for now. // The spec also discusses support for data embedded in ftrace supported data: https://lwn.net/Articles/365835/. return isTraceEventObject(rawProfile) || isTraceEventList(rawProfile) } export function importTraceEvents( rawProfile: {traceEvents: TraceEvent[]} | TraceEvent[], ): ProfileGroup { if (isTraceEventObject(rawProfile)) { return eventListToProfileGroup(rawProfile.traceEvents) } else if (isTraceEventList(rawProfile)) { return eventListToProfileGroup(rawProfile) } else { const _exhaustiveCheck: never = rawProfile return _exhaustiveCheck } }
the_stack
import * as Result from './result'; type Result<T, E> = import('./result').Result<T, E>; import { curry1, isVoid } from './-private/utils'; /** Discriminant for the `Just` and `Nothing` variants. You can use the discriminant via the `variant` property of `Maybe` instances if you need to match explicitly on it. */ export const Variant = { Just: 'Just', Nothing: 'Nothing', } as const; export type Variant = keyof typeof Variant; interface JustJSON<T> { variant: 'Just'; value: T; } interface NothingJSON { variant: 'Nothing'; } type MaybeJSON<T> = JustJSON<T> | NothingJSON; type Repr<T> = [tag: 'Just', value: T] | [tag: 'Nothing']; /** A single instance of the `Nothing` object, to minimize memory usage. No matter how many `Maybe`s are floating around, there will always be exactly and only one `Nothing`. @private */ // SAFETY: `any` is required here because the whole point is that we're going to // use this *everywhere* there is a `Nothing`, so that there is effectively no // overhead of having a `Nothing` in your system: there is only ever once // instance of it. let NOTHING: Nothing<any>; // Defines the *implementation*, but not the *types*. See the exports below. class _Maybe<T> { private repr: Repr<T>; constructor(value?: T | null | undefined) { if (isVoid(value)) { // SAFETY: there is only a single `Nothing` in the system, because the // only difference between `Nothing<string>` and `Nothing<number>` is at // the type-checking level. this.repr = [Variant.Nothing]; if (!NOTHING) { NOTHING = (this as Maybe<any>) as Nothing<any>; } return (NOTHING as Maybe<any>) as this; } else { this.repr = [Variant.Just, value]; } } /** Create a `Maybe` from any value. To specify that the result should be interpreted as a specific type, you may invoke `Maybe.of` with an explicit type parameter: ```ts const foo = Maybe.of<string>(null); ``` This is usually only important in two cases: 1. If you are intentionally constructing a `Nothing` from a known `null` or undefined value *which is untyped*. 2. If you are specifying that the type is more general than the value passed (since TypeScript can define types as literals). @typeparam T The type of the item contained in the `Maybe`. @param value The value to wrap in a `Maybe`. If it is `undefined` or `null`, the result will be `Nothing`; otherwise it will be the type of the value passed. */ static of<T>(value: T | null | undefined): Maybe<T> { return new _Maybe(value) as Maybe<T>; } /** Create an instance of `Maybe.Just`. `null` and `undefined` are allowed by the type signature so that the function may `throw` on those rather than constructing a type like `Maybe<undefined>`. @typeparam T The type of the item contained in the `Maybe`. @param value The value to wrap in a `Maybe.Just`. @returns An instance of `Maybe.Just<T>`. @throws If you pass `null` or `undefined`. */ static just<T>(value?: T | null): Maybe<T> { if (isVoid(value)) { throw new Error(`attempted to call "just" with ${value}`); } return new Maybe<T>(value); } /** Create an instance of `Maybe.Nothing`. If you want to create an instance with a specific type, e.g. for use in a function which expects a `Maybe<T>` where the `<T>` is known but you have no value to give it, you can use a type parameter: ```ts const notString = Maybe.nothing<string>(); ``` @typeparam T The type of the item contained in the `Maybe`. @returns An instance of `Maybe.Nothing<T>`. */ static nothing<T>(_?: null): Maybe<T> { return new _Maybe() as Maybe<T>; } /** Distinguish between the `Just` and `Nothing` [variants](../enums/_maybe_.variant). */ get variant(): Variant { return this.repr[0]; } /** The wrapped value. */ get value(): T | never { if (this.repr[0] === Variant.Nothing) { throw new Error('Cannot get the value of `Nothing`'); } return this.repr[1]; } /** Is the `Maybe` a `Just`? */ get isJust(): boolean { return this.repr[0] === Variant.Just; } /** Is the `Maybe` a `Nothing`? */ get isNothing(): boolean { return this.repr[0] === Variant.Nothing; } /** Method variant for [`Maybe.map`](../modules/_maybe_.html#map) */ map<U>(this: Maybe<T>, mapFn: (t: T) => U): Maybe<U> { return map(mapFn, this); } /** Method variant for [`Maybe.mapOr`](../modules/_maybe_.html#mapor) */ mapOr<U>(this: Maybe<T>, orU: U, mapFn: (t: T) => U): U { return mapOr(orU, mapFn, this); } /** Method variant for [`Maybe.mapOrElse`](../modules/_maybe_.html#maporelse) */ mapOrElse<U>(this: Maybe<T>, orElseFn: () => U, mapFn: (t: T) => U): U { return mapOrElse(orElseFn, mapFn, this); } /** Method variant for [`Maybe.match`](../modules/_maybe_.html#match) */ match<U>(this: Maybe<T>, matcher: Matcher<T, U>): U { return match(matcher, this); } /** Method variant for [`Maybe.or`](../modules/_maybe_.html#or) */ or(this: Maybe<T>, mOr: Maybe<T>): Maybe<T> { return or(mOr, this); } /** Method variant for [`Maybe.orElse`](../modules/_maybe_.html#orelse) */ orElse(this: Maybe<T>, orElseFn: () => Maybe<T>): Maybe<T> { return orElse(orElseFn, this); } /** Method variant for [`Maybe.and`](../modules/_maybe_.html#and) */ and<U>(this: Maybe<T>, mAnd: Maybe<U>): Maybe<U> { return and(mAnd, this); } /** Method variant for [`Maybe.andThen`](../modules/_maybe_.html#andthen) */ andThen<U>(this: Maybe<T>, andThenFn: (t: T) => Maybe<U>): Maybe<U> { return andThen(andThenFn, this); } unwrapOr<U>(this: Maybe<T>, defaultValue: U): T | U { return unwrapOr(defaultValue, this); } /** Method variant for [`Maybe.unwrapOrElse`](../modules/_maybe_.html#unwraporelse) */ unwrapOrElse<U>(this: Maybe<T>, elseFn: () => U): T | U { return unwrapOrElse(elseFn, this); } /** Method variant for [`Maybe.toOkOrErr`](../modules/_maybe_.html#tookorerr) */ toOkOrErr<E>(this: Maybe<T>, error: E): Result<T, E> { return toOkOrErr(error, this); } /** Method variant for [`Maybe.toOkOrElseErr`](../modules/_maybe_.html#tookorelseerr) */ toOkOrElseErr<E>(this: Maybe<T>, elseFn: () => E): Result<T, E> { return toOkOrElseErr(elseFn, this); } /** Method variant for [`Maybe.toString`](../modules/_maybe_.html#tostring) */ toString(this: Maybe<T>): string { return toString(this); } /** Method variant for [`Maybe.toJSON`](../modules/_maybe_.html#toJSON) */ toJSON(this: Maybe<T>): MaybeJSON<unknown> { return toJSON(this); } /** Method variant for [`Maybe.equals`](../modules/_maybe_.html#equals) */ equals(this: Maybe<T>, comparison: Maybe<T>): boolean { return equals(comparison, this); } /** Method variant for [`Maybe.ap`](../modules/_maybe_.html#ap) */ ap<A, B>(this: Maybe<(val: A) => B>, val: Maybe<A>): Maybe<B> { return ap(this, val); } /** Method variant for [`Maybe.get`](../modules/_maybe_.html#prop) If you have a `Maybe` of an object type, you can do `thatMaybe.get('a key')` to look up the next layer down in the object. ```ts type DeepOptionalType = { something?: { with?: { deeperKeys?: string; } } }; const fullySet: DeepType = { something: { with: { deeperKeys: 'like this' } } }; const deepJust = Maybe.of(fullySet) .get('something') .get('with') .get('deeperKeys'); console.log(deepJust); // Just('like this'); const partiallyUnset: DeepType = { something: { } }; const deepEmpty = Maybe.of(partiallyUnset) .get('something') .get('with') .get('deeperKeys'); console.log(deepEmpty); // Nothing ``` */ get<K extends keyof T>(this: Maybe<T>, key: K): Maybe<NonNullable<T[K]>> { return get(key, this); } } /** A `Just` instance is the *present* variant instance of the [`Maybe`](../modules/_maybe_.html#maybe) type, representing the presence of a value which may be absent. For a full discussion, see [the module docs](../modules/_maybe_.html). @typeparam T The type wrapped in this `Just` variant of `Maybe`. */ export interface Just<T> extends _Maybe<T> { /** `Just` is always [`Variant.Just`](../enums/_maybe_.variant#just). */ variant: 'Just'; value: T; isJust: true; isNothing: false; } /** A `Nothing` instance is the *absent* variant instance of the [`Maybe`](../modules/_maybe_.html#maybe) type, representing the presence of a value which may be absent. For a full discussion, see [the module docs](../modules/_maybe_.html). @typeparam T The type which would be wrapped in a `Just` variant of `Maybe`. */ export interface Nothing<T> extends _Maybe<T> { /** `Nothing` is always [`Variant.Nothing`](../enums/_maybe_.variant#nothing). */ readonly variant: 'Nothing'; value: never; isJust: false; isNothing: true; } /** Create an instance of `Maybe.Just`. `null` and `undefined` are allowed by the type signature so that the function may `throw` on those rather than constructing a type like `Maybe<undefined>`. @typeparam T The type of the item contained in the `Maybe`. @param value The value to wrap in a `Maybe.Just`. @returns An instance of `Maybe.Just<T>`. @throws If you pass `null` or `undefined`. */ export const just = _Maybe.just; /** Create an instance of `Maybe.Nothing`. If you want to create an instance with a specific type, e.g. for use in a function which expects a `Maybe<T>` where the `<T>` is known but you have no value to give it, you can use a type parameter: ```ts const notString = Maybe.nothing<string>(); ``` @typeparam T The type of the item contained in the `Maybe`. @returns An instance of `Maybe.Nothing<T>`. */ export const nothing = _Maybe.nothing; /** Create a `Maybe` from any value. To specify that the result should be interpreted as a specific type, you may invoke `Maybe.of` with an explicit type parameter: ```ts const foo = Maybe.of<string>(null); ``` This is usually only important in two cases: 1. If you are intentionally constructing a `Nothing` from a known `null` or undefined value *which is untyped*. 2. If you are specifying that the type is more general than the value passed (since TypeScript can define types as literals). @typeparam T The type of the item contained in the `Maybe`. @param value The value to wrap in a `Maybe`. If it is `undefined` or `null`, the result will be `Nothing`; otherwise it will be the type of the value passed. */ export function of<T>(value?: T | null): Maybe<T> { return Maybe.of(value); } /** Alias for [`of`](#of), convenient for a standalone import: ```ts import { maybe } from 'true-myth/maybe'; interface Dict<T> { [key: string]: T | null | undefined; } interface StrictDict<T> { [key: string]: Maybe<T>; } function wrapNullables<T>(dict: Dict<T>): StrictDict<T> { return Object.keys(dict).reduce((strictDict, key) => { strictDict[key] = maybe(dict[key]); return strictDict; }, {} as StrictDict<T>); } ``` */ export const maybe = of; /** Alias for [`of`](#of), primarily for compatibility with Folktale. */ export const fromNullable = of; /** Map over a `Maybe` instance: apply the function to the wrapped value if the instance is `Just`, and return `Nothing` if the instance is `Nothing`. `Maybe.map` works a lot like `Array.prototype.map`: `Maybe` and `Array` are both *containers* for other things. If you have no items in an array of numbers named `foo` and call `foo.map(x => x + 1)`, you'll still just have an array with nothing in it. But if you have any items in the array (`[2, 3]`), and you call `foo.map(x => x + 1)` on it, you'll get a new array with each of those items inside the array "container" transformed (`[3, 4]`). That's exactly what's happening with `Maybe.map`. If the container is *empty* – the `Nothing` variant – you just get back an empty container. If the container has something in it – the `Just` variant – you get back a container with the item inside transformed. (So... why not just use an array? The biggest reason is that an array can be any length. With a `Maybe`, we're capturing the idea of "something or nothing" rather than "0 to n" items. And this lets us implement a whole set of *other* interfaces, like those in this module.) #### Examples ```ts const length = (s: string) => s.length; const justAString = Maybe.just('string'); const justTheStringLength = map(length, justAString); console.log(justTheStringLength.toString()); // Just(6) const notAString = Maybe.nothing<string>(); const notAStringLength = map(length, notAString); console.log(notAStringLength.toString()); // "Nothing" ``` @typeparam T The type of the wrapped value. @typeparam U The type of the wrapped value of the returned `Maybe`. @param mapFn The function to apply the value to if `Maybe` is `Just`. @param maybe The `Maybe` instance to map over. @returns A new `Maybe` with the result of applying `mapFn` to the value in a `Just`, or `Nothing` if `maybe` is `Nothing`. */ export function map<T, U>(mapFn: (t: T) => U): (maybe: Maybe<T>) => Maybe<U>; export function map<T, U>(mapFn: (t: T) => U, maybe: Maybe<T>): Maybe<U>; export function map<T, U>( mapFn: (t: T) => U, maybe?: Maybe<T> ): Maybe<U> | ((maybe: Maybe<T>) => Maybe<U>) { const op = (m: Maybe<T>) => (m.isJust ? just(mapFn(m.value)) : nothing<U>()); return curry1(op, maybe); } /** Map over a `Maybe` instance and get out the value if `maybe` is a `Just`, or return a default value if `maybe` is a `Nothing`. #### Examples ```ts const length = (s: string) => s.length; const justAString = Maybe.just('string'); const theStringLength = mapOr(0, length, justAString); console.log(theStringLength); // 6 const notAString = Maybe.nothing<string>(); const notAStringLength = mapOr(0, length, notAString) console.log(notAStringLength); // 0 ``` @typeparam T The type of the wrapped value. @typeparam U The type of the wrapped value of the returned `Maybe`. @param orU The default value to use if `maybe` is `Nothing` @param mapFn The function to apply the value to if `Maybe` is `Just` @param maybe The `Maybe` instance to map over. */ export function mapOr<T, U>(orU: U, mapFn: (t: T) => U, maybe: Maybe<T>): U; export function mapOr<T, U>(orU: U, mapFn: (t: T) => U): (maybe: Maybe<T>) => U; export function mapOr<T, U>(orU: U): (mapFn: (t: T) => U) => (maybe: Maybe<T>) => U; export function mapOr<T, U>( orU: U, mapFn?: (t: T) => U, maybe?: Maybe<T> ): U | ((maybe: Maybe<T>) => U) | ((mapFn: (t: T) => U) => (maybe: Maybe<T>) => U) { function fullOp(fn: (t: T) => U, m: Maybe<T>) { return m.isJust ? fn(m.value) : orU; } function partialOp(fn: (t: T) => U): (maybe: Maybe<T>) => U; function partialOp(fn: (t: T) => U, curriedMaybe: Maybe<T>): U; function partialOp(fn: (t: T) => U, curriedMaybe?: Maybe<T>): U | ((maybe: Maybe<T>) => U) { return curriedMaybe !== undefined ? fullOp(fn, curriedMaybe) : (extraCurriedMaybe: Maybe<T>) => fullOp(fn, extraCurriedMaybe); } return mapFn === undefined ? partialOp : maybe === undefined ? partialOp(mapFn) : partialOp(mapFn, maybe); } /** Map over a `Maybe` instance and get out the value if `maybe` is a `Just`, or use a function to construct a default value if `maybe` is `Nothing`. #### Examples ```ts const length = (s: string) => s.length; const getDefault = () => 0; const justAString = Maybe.just('string'); const theStringLength = mapOrElse(getDefault, length, justAString); console.log(theStringLength); // 6 const notAString = Maybe.nothing<string>(); const notAStringLength = mapOrElse(getDefault, length, notAString) console.log(notAStringLength); // 0 ``` @typeparam T The type of the wrapped value. @typeparam U The type of the wrapped value of the returned `Maybe`. @param orElseFn The function to apply if `maybe` is `Nothing`. @param mapFn The function to apply to the wrapped value if `maybe` is `Just` @param maybe The `Maybe` instance to map over. */ export function mapOrElse<T, U>(orElseFn: () => U, mapFn: (t: T) => U, maybe: Maybe<T>): U; export function mapOrElse<T, U>(orElseFn: () => U, mapFn: (t: T) => U): (maybe: Maybe<T>) => U; export function mapOrElse<T, U>(orElseFn: () => U): (mapFn: (t: T) => U) => (maybe: Maybe<T>) => U; export function mapOrElse<T, U>( orElseFn: () => U, mapFn?: (t: T) => U, maybe?: Maybe<T> ): U | ((maybe: Maybe<T>) => U) | ((mapFn: (t: T) => U) => (maybe: Maybe<T>) => U) { function fullOp(fn: (t: T) => U, m: Maybe<T>) { return m.isJust ? fn(m.value) : orElseFn(); } function partialOp(fn: (t: T) => U): (maybe: Maybe<T>) => U; function partialOp(fn: (t: T) => U, curriedMaybe: Maybe<T>): U; function partialOp(fn: (t: T) => U, curriedMaybe?: Maybe<T>): U | ((maybe: Maybe<T>) => U) { return curriedMaybe !== undefined ? fullOp(fn, curriedMaybe) : (extraCurriedMaybe: Maybe<T>) => fullOp(fn, extraCurriedMaybe); } if (mapFn === undefined) { return partialOp; } else if (maybe === undefined) { return partialOp(mapFn); } else { return partialOp(mapFn, maybe); } } /** You can think of this like a short-circuiting logical "and" operation on a `Maybe` type. If `maybe` is `Just`, then the result is the `andMaybe`. If `maybe` is `Nothing`, the result is `Nothing`. This is useful when you have another `Maybe` value you want to provide if and *only if* you have a `Just` – that is, when you need to make sure that if you `Nothing`, whatever else you're handing a `Maybe` to *also* gets a `Nothing`. Notice that, unlike in [`map`](#map) or its variants, the original `maybe` is not involved in constructing the new `Maybe`. #### Examples ```ts import Maybe from 'true-myth/maybe'; const justA = Maybe.just('A'); const justB = Maybe.just('B'); const nothing: Maybe<number> = nothing(); console.log(Maybe.and(justB, justA).toString()); // Just(B) console.log(Maybe.and(justB, nothing).toString()); // Nothing console.log(Maybe.and(nothing, justA).toString()); // Nothing console.log(Maybe.and(nothing, nothing).toString()); // Nothing ``` @typeparam T The type of the initial wrapped value. @typeparam U The type of the wrapped value of the returned `Maybe`. @param andMaybe The `Maybe` instance to return if `maybe` is `Just` @param maybe The `Maybe` instance to check. @return `Nothing` if the original `maybe` is `Nothing`, or `andMaybe` if the original `maybe` is `Just`. */ export function and<T, U>(andMaybe: Maybe<U>, maybe: Maybe<T>): Maybe<U>; export function and<T, U>(andMaybe: Maybe<U>): (maybe: Maybe<T>) => Maybe<U>; export function and<T, U>( andMaybe: Maybe<U>, maybe?: Maybe<T> ): Maybe<U> | ((maybe: Maybe<T>) => Maybe<U>) { const op = (m: Maybe<T>) => (m.isJust ? andMaybe : nothing<U>()); return curry1(op, maybe); } /** Apply a function to the wrapped value if `Just` and return a new `Just` containing the resulting value; or return `Nothing` if `Nothing`. This differs from `map` in that `thenFn` returns another `Maybe`. You can use `andThen` to combine two functions which *both* create a `Maybe` from an unwrapped type. You may find the `.then` method on an ES6 `Promise` helpful for b: if you have a `Promise`, you can pass its `then` method a callback which returns another `Promise`, and the result will not be a *nested* promise, but a single `Promise`. The difference is that `Promise#then` unwraps *all* layers to only ever return a single `Promise` value, whereas `Maybe.andThen` will not unwrap nested `Maybe`s. This is also commonly known as (and therefore aliased as) [`flatMap`][flatMap] or [`chain`][chain]. It is sometimes also known as `bind`, but *not* aliased as such because [`bind` already means something in JavaScript][bind]. [flatMap]: #flatmap [chain]: #chain [bind]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind #### Example (This is a somewhat contrived example, but it serves to show the way the function behaves.) ```ts import Maybe from 'true-myth/maybe'; // string -> Maybe<number> const toMaybeLength = (s: string): Maybe<number> => Maybe.of(s.length); // Maybe<string> const aMaybeString = Maybe.of('Hello, there!'); // Maybe<number> const resultingLength = Maybe.andThen(toMaybeLength, aMaybeString); console.log(Maybe.toString(resultingLength)); // 13 ``` Note that the result is not `(Just(13))`, but `13`! @typeparam T The type of the wrapped value. @typeparam U The type of the wrapped value in the resulting `Maybe`. @param thenFn The function to apply to the wrapped `T` if `maybe` is `Just`. @param maybe The `Maybe` to evaluate and possibly apply a function to the contents of. @returns The result of the `thenFn` (a new `Maybe`) if `maybe` is a `Just`, otherwise `Nothing` if `maybe` is a `Nothing`. */ export function andThen<T, U>(thenFn: (t: T) => Maybe<U>, maybe: Maybe<T>): Maybe<U>; export function andThen<T, U>(thenFn: (t: T) => Maybe<U>): (maybe: Maybe<T>) => Maybe<U>; export function andThen<T, U>( thenFn: (t: T) => Maybe<U>, maybe?: Maybe<T> ): Maybe<U> | ((maybe: Maybe<T>) => Maybe<U>) { const op = (m: Maybe<T>) => (m.isJust ? thenFn(m.value) : nothing<U>()); return maybe !== undefined ? op(maybe) : op; } /** Provide a fallback for a given `Maybe`. Behaves like a logical `or`: if the `maybe` value is a `Just`, returns that `maybe`; otherwise, returns the `defaultMaybe` value. This is useful when you want to make sure that something which takes a `Maybe` always ends up getting a `Just` variant, by supplying a default value for the case that you currently have a nothing. ```ts import Maybe from 'true-utils/maybe'; const justA = Maybe.just("a"); const justB = Maybe.just("b"); const aNothing: Maybe<string> = nothing(); console.log(Maybe.or(justB, justA).toString()); // Just(A) console.log(Maybe.or(aNothing, justA).toString()); // Just(A) console.log(Maybe.or(justB, aNothing).toString()); // Just(B) console.log(Maybe.or(aNothing, aNothing).toString()); // Nothing ``` @typeparam T The type of the wrapped value. @param defaultMaybe The `Maybe` to use if `maybe` is a `Nothing`. @param maybe The `Maybe` instance to evaluate. @returns `maybe` if it is a `Just`, otherwise `defaultMaybe`. */ export function or<T>(defaultMaybe: Maybe<T>, maybe: Maybe<T>): Maybe<T>; export function or<T>(defaultMaybe: Maybe<T>): (maybe: Maybe<T>) => Maybe<T>; export function or<T>( defaultMaybe: Maybe<T>, maybe?: Maybe<T> ): Maybe<T> | ((maybe: Maybe<T>) => Maybe<T>) { const op = (m: Maybe<T>) => (m.isJust ? m : defaultMaybe); return maybe !== undefined ? op(maybe) : op; } /** Like `or`, but using a function to construct the alternative `Maybe`. Sometimes you need to perform an operation using other data in the environment to construct the fallback value. In these situations, you can pass a function (which may be a closure) as the `elseFn` to generate the fallback `Maybe<T>`. Useful for transforming empty scenarios based on values in context. @typeparam T The type of the wrapped value. @param elseFn The function to apply if `maybe` is `Nothing` @param maybe The `maybe` to use if it is `Just`. @returns The `maybe` if it is `Just`, or the `Maybe` returned by `elseFn` if the `maybe` is `Nothing`. */ export function orElse<T>(elseFn: () => Maybe<T>, maybe: Maybe<T>): Maybe<T>; export function orElse<T>(elseFn: () => Maybe<T>): (maybe: Maybe<T>) => Maybe<T>; export function orElse<T>( elseFn: () => Maybe<T>, maybe?: Maybe<T> ): Maybe<T> | ((maybe: Maybe<T>) => Maybe<T>) { const op = (m: Maybe<T>) => (m.isJust ? m : elseFn()); return curry1(op, maybe); } /** Safely get the value out of a `Maybe`. Returns the content of a `Just` or `defaultValue` if `Nothing`. This is the recommended way to get a value out of a `Maybe` most of the time. ```ts import Maybe from 'true-myth/maybe'; const notAString = Maybe.nothing<string>(); const isAString = Maybe.just('look ma! some characters!'); console.log(Maybe.unwrapOr('<empty>', notAString)); // "<empty>" console.log(Maybe.unwrapOr('<empty>', isAString)); // "look ma! some characters!" ``` @typeparam T The type of the wrapped value. @param defaultValue The value to return if `maybe` is a `Nothing`. @param maybe The `Maybe` instance to unwrap if it is a `Just`. @returns The content of `maybe` if it is a `Just`, otherwise `defaultValue`. */ export function unwrapOr<T, U>(defaultValue: U, maybe: Maybe<T>): T | U; export function unwrapOr<T, U>(defaultValue: U): (maybe: Maybe<T>) => T | U; export function unwrapOr<T, U>(defaultValue: U, maybe?: Maybe<T>) { const op = (m: Maybe<T>) => (m.isJust ? m.value : defaultValue); return curry1(op, maybe); } /** Alias for [`unwrapOr`](#unwrapor) */ export const getOr = unwrapOr; /** Safely get the value out of a [`Maybe`](#maybe) by returning the wrapped value if it is `Just`, or by applying `orElseFn` if it is `Nothing`. This is useful when you need to *generate* a value (e.g. by using current values in the environment – whether preloaded or by local closure) instead of having a single default value available (as in [`unwrapOr`](#unwrapor)). ```ts import Maybe from 'true-myth/maybe'; // You can imagine that someOtherValue might be dynamic. const someOtherValue = 99; const handleNothing = () => someOtherValue; const aJust = Maybe.just(42); console.log(Maybe.unwrapOrElse(handleNothing, aJust)); // 42 const aNothing = nothing<number>(); console.log(Maybe.unwrapOrElse(handleNothing, aNothing)); // 99 ``` @typeparam T The wrapped value. @param orElseFn A function used to generate a valid value if `maybe` is a `Nothing`. @param maybe The `Maybe` instance to unwrap if it is a `Just` @returns Either the content of `maybe` or the value returned from `orElseFn`. */ export function unwrapOrElse<T, U>(orElseFn: () => U, maybe: Maybe<T>): T | U; export function unwrapOrElse<T, U>(orElseFn: () => U): (maybe: Maybe<T>) => T | U; export function unwrapOrElse<T, U>( orElseFn: () => U, maybe?: Maybe<T> ): (T | U) | ((maybe: Maybe<T>) => T | U) { const op = (m: Maybe<T>) => (m.isJust ? m.value : orElseFn()); return curry1(op, maybe); } /** Alias for [`unwrapOrElse`](#unwraporelse) */ export const getOrElse = unwrapOrElse; /** Transform the [`Maybe`](#maybe) into a [`Result`](../modules/_result_.html#result), using the wrapped value as the `Ok` value if `Just`; otherwise using the supplied `error` value for `Err`. @typeparam T The wrapped value. @typeparam E The error type to in the `Result`. @param error The error value to use if the `Maybe` is `Nothing`. @param maybe The `Maybe` instance to convert. @returns A `Result` containing the value wrapped in `maybe` in an `Ok`, or `error` in an `Err`. */ export function toOkOrErr<T, E>(error: E, maybe: Maybe<T>): Result<T, E>; export function toOkOrErr<T, E>(error: E): (maybe: Maybe<T>) => Result<T, E>; export function toOkOrErr<T, E>( error: E, maybe?: Maybe<T> ): Result<T, E> | ((maybe: Maybe<T>) => Result<T, E>) { const op = (m: Maybe<T>) => (m.isJust ? Result.ok<T, E>(m.value) : Result.err<T, E>(error)); return maybe !== undefined ? op(maybe) : op; } /** Transform the [`Maybe`](#maybe) into a [`Result`](../modules/_result_.html#result), using the wrapped value as the `Ok` value if `Just`; otherwise using `elseFn` to generate `Err`. @typeparam T The wrapped value. @typeparam E The error type to in the `Result`. @param elseFn The function which generates an error of type `E`. @param maybe The `Maybe` instance to convert. @returns A `Result` containing the value wrapped in `maybe` in an `Ok`, or the value generated by `elseFn` in an `Err`. */ export function toOkOrElseErr<T, E>(elseFn: () => E, maybe: Maybe<T>): Result<T, E>; export function toOkOrElseErr<T, E>(elseFn: () => E): (maybe: Maybe<T>) => Result<T, E>; export function toOkOrElseErr<T, E>( elseFn: () => E, maybe?: Maybe<T> ): Result<T, E> | ((maybe: Maybe<T>) => Result<T, E>) { const op = (m: Maybe<T>) => (m.isJust ? Result.ok<T, E>(m.value) : Result.err<T, E>(elseFn())); return curry1(op, maybe); } /** Construct a `Maybe<T>` from a `Result<T, E>`. If the `Result` is an `Ok`, wrap its value in `Just`. If the `Result` is an `Err`, throw away the wrapped `E` and transform to a `Nothing`. @typeparam T The type of the value wrapped in a `Result.Ok` and in the `Just` of the resulting `Maybe`. @param result The `Result` to construct a `Maybe` from. @returns `Just` if `result` was `Ok` or `Nothing` if it was `Err`. */ export function fromResult<T>(result: Result<T, unknown>): Maybe<T> { return result.isOk ? just(result.value) : nothing<T>(); } /** Create a `String` representation of a `Maybe` instance. A `Just` instance will be printed as `Just(<representation of the value>)`, where the representation of the value is simply the value's own `toString` representation. For example: | call | output | |----------------------------------------|-------------------------| | `toString(Maybe.of(42))` | `Just(42)` | | `toString(Maybe.of([1, 2, 3]))` | `Just(1,2,3)` | | `toString(Maybe.of({ an: 'object' }))` | `Just([object Object])` | | `toString(Maybe.nothing())` | `Nothing` | @typeparam T The type of the wrapped value; its own `.toString` will be used to print the interior contents of the `Just` variant. @param maybe The value to convert to a string. @returns The string representation of the `Maybe`. */ export function toString<T extends { toString(): string }>(maybe: Maybe<T>): string { const body = maybe.isJust ? `(${maybe.value.toString()})` : ''; return `${maybe.variant}${body}`; } /** * Create an `Object` representation of a `Maybe` instance. * * Useful for serialization. `JSON.stringify()` uses it. * * @param maybe The value to convert to JSON * @returns The JSON representation of the `Maybe` */ export function toJSON<T>(maybe: Maybe<T>): MaybeJSON<unknown> { return maybe.isJust ? { variant: maybe.variant, value: isInstance(maybe.value) ? maybe.value.toJSON() : maybe.value, } : { variant: maybe.variant }; } /** A lightweight object defining how to handle each variant of a Maybe. */ export type Matcher<T, A> = { Just: (value: T) => A; Nothing: () => A; }; /** Performs the same basic functionality as `getOrElse`, but instead of simply unwrapping the value if it is `Just` and applying a value to generate the same default type if it is `Nothing`, lets you supply functions which may transform the wrapped type if it is `Just` or get a default value for `Nothing`. This is kind of like a poor man's version of pattern matching, which JavaScript currently lacks. Instead of code like this: ```ts import Maybe from 'true-myth/maybe'; const logValue = (mightBeANumber: Maybe<number>) => { const valueToLog = Maybe.mightBeANumber.isJust ? Maybe.unsafelyUnwrap(mightBeANumber).toString() : 'Nothing to log.'; console.log(valueToLog); }; ``` ...we can write code like this: ```ts import Maybe from 'true-myth/maybe'; const logValue = (mightBeANumber: Maybe<number>) => { const value = Maybe.match( { Just: n => n.toString(), Nothing: () => 'Nothing to log.', }, mightBeANumber ); console.log(value); }; ``` This is slightly longer to write, but clearer: the more complex the resulting expression, the hairer it is to understand the ternary. Thus, this is especially convenient for times when there is a complex result, e.g. when rendering part of a React component inline in JSX/TSX. @param matcher A lightweight object defining what to do in the case of each variant. @param maybe The `maybe` instance to check. */ export function match<T, A>(matcher: Matcher<T, A>, maybe: Maybe<T>): A; export function match<T, A>(matcher: Matcher<T, A>): (m: Maybe<T>) => A; export function match<T, A>(matcher: Matcher<T, A>, maybe?: Maybe<T>): A | ((m: Maybe<T>) => A) { const op = (curriedMaybe: Maybe<T>) => mapOrElse(matcher.Nothing, matcher.Just, curriedMaybe); return curry1(op, maybe); } /** Allows quick triple-equal equality check between the values inside two `maybe`s without having to unwrap them first. ```ts const a = Maybe.of(3); const b = Maybe.of(3); const c = Maybe.of(null); const d = Maybe.nothing(); Maybe.equals(a, b); // true Maybe.equals(a, c); // false Maybe.equals(c, d); // true ``` @param mb A `maybe` to compare to. @param ma A `maybe` instance to check. */ export function equals<T>(mb: Maybe<T>, ma: Maybe<T>): boolean; export function equals<T>(mb: Maybe<T>): (ma: Maybe<T>) => boolean; export function equals<T>(mb: Maybe<T>, ma?: Maybe<T>): boolean | ((a: Maybe<T>) => boolean) { const op = (maybeA: Maybe<T>) => maybeA.match({ Just: (aVal) => mb.isJust && mb.value === aVal, Nothing: () => mb.isNothing, }); return curry1(op, ma); } /** Allows you to *apply* (thus `ap`) a value to a function without having to take either out of the context of their `Maybe`s. This does mean that the transforming function is itself within a `Maybe`, which can be hard to grok at first but lets you do some very elegant things. For example, `ap` allows you to this: ```ts import { just, nothing } from 'true-myth/maybe'; const one = just(1); const five = just(5); const none = nothing(); const add = (a: number) => (b: number) => a + b; const maybeAdd = just(add); maybeAdd.ap(one).ap(five); // Just(6) maybeAdd.ap(one).ap(none); // Nothing maybeAdd.ap(none).ap(five) // Nothing ``` Without `Maybe.ap`, you'd need to do something like a nested `Maybe.match`: ```ts import { just, nothing } from 'true-myth/maybe'; const one = just(1); const five = just(5); const none = nothing(); one.match({ Just: n => five.match({ Just: o => just(n + o), Nothing: () => nothing(), }), Nothing: () => nothing(), }); // Just(6) one.match({ Just: n => none.match({ Just: o => just(n + o), Nothing: () => nothing(), }), Nothing: () => nothing(), }); // Nothing none.match({ Just: n => five.match({ Just: o => just(n + o), Nothing: () => nothing(), }), Nothing: () => nothing(), }); // Nothing ``` And this kind of thing comes up quite often once you're using `Maybe` to handle optionality throughout your application. For another example, imagine you need to compare the equality of two ImmutableJS data structures, where a `===` comparison won't work. With `ap`, that's as simple as this: ```ts import Maybe from 'true-myth/maybe'; import Immutable from 'immutable'; import { curry } from 'lodash' const is = curry(Immutable.is); const x = Maybe.of(Immutable.Set.of(1, 2, 3)); const y = Maybe.of(Immutable.Set.of(2, 3, 4)); Maybe.of(is).ap(x).ap(y); // Just(false) ``` Without `ap`, we're back to that gnarly nested `match`: ```ts * import Maybe, { just, nothing } from 'true-myth/maybe'; import Immutable from 'immutable'; import { curry } from 'lodash' const is = curry(Immutable.is); const x = Maybe.of(Immutable.Set.of(1, 2, 3)); const y = Maybe.of(Immutable.Set.of(2, 3, 4)); x.match({ Just: iX => y.match({ Just: iY => Maybe.just(Immutable.is(iX, iY)), Nothing: () => Maybe.nothing(), }) Nothing: () => Maybe.nothing(), }); // Just(false) ``` In summary: anywhere you have two `Maybe` instances and need to perform an operation that uses both of them, `ap` is your friend. Two things to note, both regarding *currying*: 1. All functions passed to `ap` must be curried. That is, they must be of the form (for add) `(a: number) => (b: number) => a + b`, *not* the more usual `(a: number, b: number) => a + b` you see in JavaScript more generally. For convenience, you may want to look at Lodash's `_.curry` or Ramda's `R.curry`, which allow you to create curried versions of functions whenever you want: ``` import Maybe from 'true-myth/maybe'; import { curry } from 'lodash'; const normalAdd = (a: number, b: number) => a + b; const curriedAdd = curry(normalAdd); // (a: number) => (b: number) => a + b; Maybe.of(curriedAdd).ap(Maybe.of(1)).ap(Maybe.of(5)); // Just(6) ``` 2. You will need to call `ap` as many times as there are arguments to the function you're dealing with. So in the case of `add`, which has the "arity" (function argument count) of 2 (`a` and `b`), you'll need to call `ap` twice: once for `a`, and once for `b`. To see why, let's look at what the result in each phase is: ```ts const add = (a: number) => (b: number) => a + b; const maybeAdd = Maybe.of(add); // Just((a: number) => (b: number) => a + b) const maybeAdd1 = maybeAdd.ap(Maybe.of(1)); // Just((b: number) => 1 + b) const final = maybeAdd1.ap(Maybe.of(3)); // Just(4) ``` So for `toString`, which just takes a single argument, you would only need to call `ap` once. ```ts const toStr = (v: { toString(): string }) => v.toString(); Maybe.of(toStr).ap(12); // Just("12") ``` One other scenario which doesn't come up *quite* as often but is conceivable is where you have something that may or may not actually construct a function for handling a specific `Maybe` scenario. In that case, you can wrap the possibly-present in `ap` and then wrap the values to apply to the function to in `Maybe` themselves. **Aside:** `ap` is not named `apply` because of the overlap with JavaScript's existing [`apply`] function – and although strictly speaking, there isn't any direct overlap (`Maybe.apply` and `Function.prototype.apply` don't intersect at all) it's useful to have a different name to avoid implying that they're the same. [`apply`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply @param maybeFn maybe a function from T to U @param maybe maybe a T to apply to `fn` */ export function ap<T, U>(maybeFn: Maybe<(t: T) => U>, maybe: Maybe<T>): Maybe<U>; export function ap<T, U>(maybeFn: Maybe<(t: T) => U>): (maybe: Maybe<T>) => Maybe<U>; export function ap<T, U>( maybeFn: Maybe<(t: T) => U>, maybe?: Maybe<T> ): Maybe<U> | ((val: Maybe<T>) => Maybe<U>) { const op = (m: Maybe<T>) => m.andThen((val) => maybeFn.map((fn) => fn(val))); return curry1(op, maybe); } /** Determine whether an item is an instance of `Just` or `Nothing`. @param item The item to check. */ export function isInstance<T>(item: unknown): item is Maybe<T> { return item instanceof Maybe; } /** Transposes a `Maybe` of a `Result` into a `Result` of a `Maybe`. | Input | Output | | -------------- | ------------- | | `Just(Ok(T))` | `Ok(Just(T))` | | `Just(Err(E))` | `Err(E)` | | `Nothing` | `Ok(Nothing)` | @param maybe a `Maybe<Result<T, E>>` to transform to a `Result<Maybe<T>, E>>`. */ export function transpose<T, E>(maybe: Maybe<Result<T, E>>): Result<Maybe<T>, E> { return maybe.match({ Just: Result.match({ Ok: (v) => Result.ok<Maybe<T>, E>(just(v)), Err: (e) => Result.err<Maybe<T>, E>(e), }), Nothing: () => Result.ok<Maybe<T>, E>(nothing()), }); } /** Safely extract a key from an object, returning `Just` if the key has a value on the object and `Nothing` if it does not. The check is type-safe: you won't even be able to compile if you try to look up a property that TypeScript *knows* doesn't exist on the object. ```ts type Person = { name?: string }; const me: Person = { name: 'Chris' }; console.log(Maybe.property('name', me)); // Just('Chris') const nobody: Person = {}; console.log(Maybe.property('name', nobody)); // Nothing ``` However, it also works correctly with dictionary types: ```ts type Dict<T> = { [key: string]: T }; const score: Dict<number> = { player1: 0, player2: 1 }; console.log(Maybe.property('player1', score)); // Just(0) console.log(Maybe.property('player2', score)); // Just(1) console.log(Maybe.property('player3', score)); // Nothing ``` The order of keys is so that it can be partially applied: ```ts type Person = { name?: string }; const lookupName = Maybe.property('name'); const me: Person = { name: 'Chris' }; console.log(lookupName(me)); // Just('Chris') const nobody: Person = {}; console.log(lookupName(nobody)); // Nothing ``` @param key The key to pull out of the object. @param obj The object to look up the key from. */ export function property<T, K extends keyof T>(key: K, obj: T): Maybe<NonNullable<T[K]>>; export function property<T, K extends keyof T>(key: K): (obj: T) => Maybe<NonNullable<T[K]>>; export function property<T, K extends keyof T>( key: K, obj?: T ): Maybe<NonNullable<T[K]>> | ((obj: T) => Maybe<NonNullable<T[K]>>) { const op = (a: T) => maybe(a[key]) as Maybe<NonNullable<T[K]>>; return curry1(op, obj); } /** Safely extract a key from a Maybe of an object, returning `Just` if the key has a value on the object and `Nothing` if it does not. (Like `Maybe.property` but operating on a `Maybe<T>` rather than directly on a `T`.) The check is type-safe: you won't even be able to compile if you try to look up a property that TypeScript *knows* doesn't exist on the object. ```ts type Person = { name?: string }; const me: Maybe<Person> = Maybe.just({ name: 'Chris' }); console.log(Maybe.get('name', me)); // Just('Chris') const nobody = Maybe.nothing<Person>(); console.log(Maybe.get('name', nobody)); // Nothing ``` However, it also works correctly with dictionary types: ```ts type Dict<T> = { [key: string]: T }; const score: Maybe<Dict<number>> = Maybe.just({ player1: 0, player2: 1 }); console.log(Maybe.get('player1', score)); // Just(0) console.log(Maybe.get('player2', score)); // Just(1) console.log(Maybe.get('player3', score)); // Nothing ``` The order of keys is so that it can be partially applied: ```ts type Person = { name?: string }; const lookupName = Maybe.get('name'); const me: Person = { name: 'Chris' }; console.log(lookupName(me)); // Just('Chris') const nobody: Person = {}; console.log(lookupName(nobody)); // Nothing ``` @param key The key to pull out of the object. @param obj The object to look up the key from. */ export function get<T, K extends keyof T>(key: K, maybeObj: Maybe<T>): Maybe<NonNullable<T[K]>>; export function get<T, K extends keyof T>(key: K): (maybeObj: Maybe<T>) => Maybe<NonNullable<T[K]>>; export function get<T, K extends keyof T>( key: K, maybeObj?: Maybe<T> ): Maybe<NonNullable<T[K]>> | ((maybeObj: Maybe<T>) => Maybe<NonNullable<T[K]>>) { return curry1(andThen(property<T, K>(key)), maybeObj); } /** Transform a function from a normal JS function which may return `null` or `undefined` to a function which returns a `Maybe` instead. For example, dealing with the `Document#querySelector` DOM API involves a *lot* of things which can be `null`: ```ts const foo = document.querySelector('#foo'); let width: number; if (foo !== null) { width = foo.getBoundingClientRect().width; } else { width = 0; } const getStyle = (el: HTMLElement, rule: string) => el.style[rule]; const bar = document.querySelector('.bar'); let color: string; if (bar != null) { let possibleColor = getStyle(bar, 'color'); if (possibleColor !== null) { color = possibleColor; } else { color = 'black'; } } ``` (Imagine in this example that there were more than two options: the simplifying workarounds you commonly use to make this terser in JS, like the ternary operator or the short-circuiting `||` operator, eventually become very confusing with more complicated flows.) We can work around this with `Maybe`, always wrapping each layer in `Maybe.of` invocations, and this is *somewhat* better: ```ts const aWidth = Maybe.of(document.querySelector('#foo')) .map(el => el.getBoundingClientRect().width) .unwrapOr(0); const aColor = Maybe.of(document.querySelector('.bar')) .andThen(el => Maybe.of(getStyle(el, 'color')) .unwrapOr('black'); ``` With `wrapReturn`, though, you can create a transformed version of a function *once* and then be able to use it freely throughout your codebase, *always* getting back a `Maybe`: ```ts const querySelector = Maybe.wrapReturn(document.querySelector.bind(document)); const safelyGetStyle = Maybe.wrapReturn(getStyle); const aWidth = querySelector('#foo') .map(el => el.getBoundingClientRect().width) .unwrapOr(0); const aColor = querySelector('.bar') .andThen(el => safelyGetStyle(el, 'color')) .unwrapOr('black'); ``` @param fn The function to transform; the resulting function will have the exact same signature except for its return type. */ // SAFETY: assignability requires the use of `any` here instead of `unknown`, // which would otherwise be preferable. export function wrapReturn<F extends (...args: any[]) => any>( fn: F ): (...args: Parameters<F>) => Maybe<NonNullable<ReturnType<F>>> { return (...args: Parameters<F>) => of(fn(...args)) as Maybe<NonNullable<ReturnType<F>>>; } // The public interface for the Maybe class *as a value*: a constructor and the // single associated static property. interface M { new <T>(value?: T | null | undefined): Maybe<T>; of: typeof _Maybe.of; just: typeof _Maybe.just; nothing: typeof _Maybe.nothing; } /** A value which may (`Just<T>`) or may not (`Nothing`) be present. */ export type Maybe<T> = Just<T> | Nothing<T>; export const Maybe = _Maybe as M; export default Maybe;
the_stack
import { XmlAttribute, XmlDocument, XmlElement } from "xmlcreate"; import { IOptions, Options } from "./options"; import { isArray, isMap, isNull, isObject, isSet, isUndefined, stringify, } from "./utils"; export { IOptions, IDeclarationOptions, IDtdOptions, IFormatOptions, ITypeHandlers, IWrapHandlers, } from "./options"; /** * Indicates that an object of a particular type should be suppressed from the * XML output. * * See the `typeHandlers` property in {@link IOptions} for more details. */ export class Absent { private static _instance = new Absent(); private constructor() {} /** * Returns the sole instance of Absent. */ public static get instance(): Absent { return Absent._instance; } } /** * Gets the type handler associated with a value. */ function getHandler( value: unknown, options: Options, ): ((value: unknown) => unknown) | undefined { const type = Object.prototype.toString.call(value); let handler: ((value: unknown) => unknown) | undefined; if (Object.prototype.hasOwnProperty.call(options.typeHandlers, "*")) { handler = options.typeHandlers["*"]; } if (Object.prototype.hasOwnProperty.call(options.typeHandlers, type)) { handler = options.typeHandlers[type]; } return handler; } /** * Parses a string into XML and adds it to the parent element or attribute. */ function parseString( str: string, parentElement: XmlAttribute<unknown> | XmlElement<unknown>, options: Options, ): void { const requiresCdata = (s: string) => { return ( (options.cdataInvalidChars && (s.indexOf("<") !== -1 || s.indexOf("&") !== -1)) || options.cdataKeys.indexOf(parentElement.name) !== -1 || options.cdataKeys.indexOf("*") !== -1 ); }; if (parentElement instanceof XmlElement) { if (requiresCdata(str)) { const cdataStrs = str.split("]]>"); for (let i = 0; i < cdataStrs.length; i++) { if (requiresCdata(cdataStrs[i])) { parentElement.cdata({ charData: cdataStrs[i], replaceInvalidCharsInCharData: options.replaceInvalidChars, }); } else { parentElement.charData({ charData: cdataStrs[i], replaceInvalidCharsInCharData: options.replaceInvalidChars, }); } if (i < cdataStrs.length - 1) { parentElement.charData({ charData: "]]>", replaceInvalidCharsInCharData: options.replaceInvalidChars, }); } } } else { parentElement.charData({ charData: str, replaceInvalidCharsInCharData: options.replaceInvalidChars, }); } } else { parentElement.text({ charData: str, replaceInvalidCharsInCharData: options.replaceInvalidChars, }); } } /** * Parses an attribute into XML and adds it to the parent element. */ function parseAttribute( name: string, value: string, parentElement: XmlElement<unknown>, options: Options, ): void { const attribute = parentElement.attribute({ name, replaceInvalidCharsInName: options.replaceInvalidChars, }); parseString(stringify(value), attribute, options); } /** * Parses an object or Map entry into XML and adds it to the parent element. */ function parseObjectOrMapEntry( key: string, value: unknown, parentElement: XmlElement<unknown>, options: Options, ): void { // Alias key if (key === options.aliasString) { parentElement.name = stringify(value); return; } // Attributes key if (key.indexOf(options.attributeString) === 0 && isObject(value)) { for (const subkey of Object.keys(value)) { parseAttribute( subkey, stringify(value[subkey]), parentElement, options, ); } return; } // Value key if (key.indexOf(options.valueString) === 0) { parseValue(key, stringify(value), parentElement, options); return; } // Standard handling (create new element for entry) let element = parentElement; if (!isArray(value) && !isSet(value)) { // If handler for value returns absent, then do not add element const handler = getHandler(value, options); if (!isUndefined(handler)) { if (handler(value) === Absent.instance) { return; } } element = parentElement.element({ name: key, replaceInvalidCharsInName: options.replaceInvalidChars, useSelfClosingTagIfEmpty: options.useSelfClosingTagIfEmpty, }); } parseValue(key, value, element, options); } /** * Parses an Object or Map into XML and adds it to the parent element. */ function parseObjectOrMap( objectOrMap: Record<string, unknown> | Map<unknown, unknown>, parentElement: XmlElement<unknown>, options: Options, ): void { if (isMap(objectOrMap)) { objectOrMap.forEach((value: unknown, key: unknown) => { parseObjectOrMapEntry( stringify(key), value, parentElement, options, ); }); } else { for (const key of Object.keys(objectOrMap)) { parseObjectOrMapEntry( key, objectOrMap[key], parentElement, options, ); } } } /** * Parses an array or Set into XML and adds it to the parent element. */ function parseArrayOrSet( key: string, arrayOrSet: unknown[] | Set<unknown>, parentElement: XmlElement<unknown>, options: Options, ): void { let arrayNameFunc: | ((key: string, value: unknown) => string | null) | undefined; if (Object.prototype.hasOwnProperty.call(options.wrapHandlers, "*")) { arrayNameFunc = options.wrapHandlers["*"]; } if (Object.prototype.hasOwnProperty.call(options.wrapHandlers, key)) { arrayNameFunc = options.wrapHandlers[key]; } let arrayKey = key; let arrayElement = parentElement; if (!isUndefined(arrayNameFunc)) { const arrayNameFuncKey = arrayNameFunc(arrayKey, arrayOrSet); if (!isNull(arrayNameFuncKey)) { arrayKey = arrayNameFuncKey; arrayElement = parentElement.element({ name: key, replaceInvalidCharsInName: options.replaceInvalidChars, useSelfClosingTagIfEmpty: options.useSelfClosingTagIfEmpty, }); } } arrayOrSet.forEach((item: unknown) => { let element = arrayElement; if (!isArray(item) && !isSet(item)) { // If handler for value returns absent, then do not add element const handler = getHandler(item, options); if (!isUndefined(handler)) { if (handler(item) === Absent.instance) { return; } } element = arrayElement.element({ name: arrayKey, replaceInvalidCharsInName: options.replaceInvalidChars, useSelfClosingTagIfEmpty: options.useSelfClosingTagIfEmpty, }); } parseValue(arrayKey, item, element, options); }); } /** * Parses an arbitrary JavaScript value into XML and adds it to the parent * element. */ function parseValue( key: string, value: unknown, parentElement: XmlElement<unknown>, options: Options, ): void { // If a handler for a particular type is user-defined, use that handler // instead of the defaults const handler = getHandler(value, options); if (!isUndefined(handler)) { value = handler(value); } if (isObject(value) || isMap(value)) { parseObjectOrMap(value, parentElement, options); return; } if (isArray(value) || isSet(value)) { parseArrayOrSet(key, value, parentElement, options); return; } parseString(stringify(value), parentElement, options); } /** * Converts the specified object to XML and adds the XML representation to the * specified XmlElement object using the specified options. * * This function does not add a root element. In addition, it does not add an * XML declaration or DTD, and the associated options in {@link IOptions} are * ignored. If desired, these must be added manually. */ export function parseToExistingElement( element: XmlElement<unknown>, object: unknown, options?: IOptions, ): void { const opts: Options = new Options(options); parseValue(element.name, object, element, opts); } /** * Returns a XML string representation of the specified object using the * specified options. * * `root` is the name of the root XML element. When the object is converted * to XML, it will be a child of this root element. */ export function parse( root: string, object: unknown, options?: IOptions, ): string { const opts = new Options(options); const document = new XmlDocument({ validation: opts.validation, }); if (opts.declaration.include) { document.decl(opts.declaration); } if (opts.dtd.include) { document.dtd({ // Validated in options.ts // eslint-disable-next-line @typescript-eslint/no-non-null-assertion name: opts.dtd.name!, pubId: opts.dtd.pubId, sysId: opts.dtd.sysId, }); } const rootElement = document.element({ name: root, replaceInvalidCharsInName: opts.replaceInvalidChars, useSelfClosingTagIfEmpty: opts.useSelfClosingTagIfEmpty, }); parseToExistingElement(rootElement, object, options); return document.toString(opts.format); }
the_stack
namespace $ { $mol_test({ // https://github.com/nin-jin/slides/tree/master/reactivity#component-states 'Cached channel' ($) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static value( next = 1 ) { return next + 1 } } $mol_assert_equal( App.value(), 2 ) App.value( 2 ) $mol_assert_equal( App.value(), 3 ) }, 'Read Pushed' ($) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static value( next = 0 ) { return next } } $mol_assert_equal( App.value( 1 ), 1 ) $mol_assert_equal( App.value(), 1 ) }, 'Mem overrides mem' ($) { class Base extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static value( next = 1 ) { return next + 1 } } class Middle extends Base { @ $mol_wire_mem(0) static value( next?: number ) { return super.value( next ) + 1 } } class App extends Middle { @ $mol_wire_mem(0) static value( next?: number ) { return super.value( next ) * 3 } } $mol_assert_equal( App.value(), 9 ) $mol_assert_equal( App.value( 5 ), 21 ) $mol_assert_equal( App.value(), 21 ) }, // https://github.com/nin-jin/slides/tree/master/reactivity#wish-consistency 'Auto recalculation of cached values'( $ ) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static xxx( next? : number ) { return next || 1 } @ $mol_wire_mem(0) static yyy() { return this.xxx() + 1 } @ $mol_wire_mem(0) static zzz() { return this.yyy() + 1 } } $mol_assert_equal( App.yyy(), 2 ) $mol_assert_equal( App.zzz(), 3 ) App.xxx( 5 ) $mol_assert_equal( App.zzz(), 7 ) }, // https://github.com/nin-jin/slides/tree/master/reactivity#wish-reasonability 'Skip recalculation when actually no dependency changes'( $ ) { const log = [] as string[] class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static xxx( next? : number ) { log.push( 'xxx' ) return next || 1 } @ $mol_wire_mem(0) static yyy() { log.push( 'yyy' ) return [ Math.sign( this.xxx() ) ] } @ $mol_wire_mem(0) static zzz() { log.push( 'zzz' ) return this.yyy()[0] + 1 } } App.zzz() $mol_assert_like( log, [ 'zzz', 'yyy', 'xxx' ] ) App.xxx( 5 ) $mol_assert_like( log, [ 'zzz', 'yyy', 'xxx', 'xxx' ] ) App.zzz() $mol_assert_like( log, [ 'zzz', 'yyy', 'xxx', 'xxx', 'yyy' ] ) }, // https://github.com/nin-jin/slides/tree/master/reactivity#flow-auto 'Flow: Auto'( $ ) { class App extends $mol_object2 { static get $() { return $ } @ $mol_wire_mem(0) static first( next = 1 ) { return next } @ $mol_wire_mem(0) static second( next = 2 ) { return next } @ $mol_wire_mem(0) static condition( next = true ) { return next } static counter = 0 @ $mol_wire_mem(0) static result() { const res = this.condition() ? this.first() : this.second() return res + this.counter ++ } } $mol_assert_equal( App.result() , 1 ) $mol_assert_equal( App.counter , 1 ) App.condition( false ) $mol_assert_equal( App.result() , 3 ) $mol_assert_equal( App.counter , 2 ) App.first( 10 ) $mol_assert_equal( App.result() , 3 ) $mol_assert_equal( App.counter , 2 ) } , // https://github.com/nin-jin/slides/tree/master/reactivity#dupes-equality 'Dupes: Equality'( $ ) { let counter = 0 class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static foo( next? : { numbs: number[] } ) { return next ?? { numbs: [ 1 ] } } @ $mol_wire_mem(0) static bar() { return { ... this.foo(), count: ++ counter } } } $mol_assert_like( App.bar(), { numbs: [ 1 ], count: 1 } ) App.foo({ numbs: [ 1 ] }) $mol_assert_like( App.bar(), { numbs: [ 1 ], count: 1 } ) App.foo({ numbs: [ 2 ] }) $mol_assert_like( App.bar(), { numbs: [ 2 ], count: 2 } ) }, // https://github.com/nin-jin/slides/tree/master/reactivity#cycle-fail 'Cycle: Fail'( $ ) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static foo() : number { return this.bar() + 1 } @ $mol_wire_mem(0) static bar() : number { return this.foo() + 1 } @ $mol_wire_method static test() { $mol_assert_fail( ()=> App.foo(), 'Circular subscription' ) } } App.test() } , // https://github.com/nin-jin/slides/tree/master/reactivity#wish-stability // 'Update deps on push'( $ ) { // class App extends $mol_object2 { // static $ = $ // @ $mol_wire_mem(0) // static left( next = false ) { // return next // } // @ $mol_wire_mem(0) // static right( next = false ) { // return next // } // @ $mol_wire_mem(0) // static res( next?: boolean ) { // return this.left( next ) && this.right() // } // } // $mol_assert_equal( App.res(), false ) // $mol_assert_equal( App.res( true ), false ) // $mol_assert_equal( App.right( true ), true ) // $mol_assert_equal( App.res(), true ) // } , // https://github.com/nin-jin/slides/tree/master/reactivity#wish-stability 'Different order of pull and push'( $ ) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static store( next = 0 ) { return next } @ $mol_wire_mem(0) static fast( next?: number ) { return this.store( next ) } @ $mol_wire_mem(0) static slow( next?: number ) { if( next !== undefined ) this.slow() // enforce pull before push return this.store( next ) } } App.fast() $mol_assert_equal( App.slow( 666 ), 666 ) $mol_assert_equal( App.fast(), App.slow(), 666 ) App.store( 777 ) $mol_assert_equal( App.fast(), App.slow(), 777 ) } , // https://github.com/nin-jin/slides/tree/master/reactivity#wish-stability 'Actions inside invariant'( $ ) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static count( next = 0 ) { return next } @ $mol_wire_mem(0) static count2() { return this.count() } @ $mol_wire_mem(0) static res() { const count = this.count2() if( !count ) this.count( count + 1 ) return count + 1 } } $mol_assert_like( App.res(), 1 ) App.count( 5 ) $mol_assert_like( App.res(), 6 ) } , async 'Toggle with async'( $ ) { class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static checked( next = false ) { $$.$mol_wait_timeout(0) return next } @ $mol_wire_method static toggle() { const prev = this.checked() $mol_assert_unique( this.checked( !prev ), prev ) // $mol_assert_equal( this.checked() , prev ) } @ $mol_wire_mem(0) static res() { return this.checked() } @ $mol_wire_method static test() { $mol_assert_equal( App.res(), false ) App.toggle() $mol_assert_equal( App.res(), true ) } } await $mol_wire_async( App ).test() } , // // https://github.com/nin-jin/slides/tree/master/reactivity#wish-stability // 'Stable order of multiple root'( $ ) { // class App extends $mol_object2 { // static $ = $ // static counter = 0 // @ $mol_wire_mem(0) // static left_trigger( next = 0 ) { // return next // } // @ $mol_wire_mem(0) // static left_root() { // this.left_trigger() // return ++ this.counter // } // @ $mol_wire_mem(0) // static right_trigger( next = 0 ) { // return next // } // @ $mol_wire_mem(0) // static right_root() { // this.right_trigger() // return ++ this.counter // } // } // $mol_assert_equal( App.left_root(), 1 ) // $mol_assert_equal( App.right_root(), 2 ) // App.right_trigger( 1 ) // App.left_trigger( 1 ) // $mol_wire_fiber.sync() // $mol_assert_equal( App.right_root(), 4 ) // $mol_assert_equal( App.left_root(), 3 ) // } , // https://github.com/nin-jin/slides/tree/master/reactivity#error-store 'Restore after error'( $ ) { class App extends $mol_object2 { static get $() { return $ } @ $mol_wire_mem(0) static condition( next = false ) { return next } @ $mol_wire_mem(0) static broken() { if( this.condition() ) { $mol_fail( new Error( 'test error' ) ) } return 1 } @ $mol_wire_mem(0) static result() { return this.broken() } } $mol_assert_equal( App.result() , 1 ) App.condition( true ) $mol_assert_fail( ()=> App.result() ) App.condition( false ) $mol_assert_equal( App.result() , 1 ) } , async 'Wait for data'($) { class App extends $mol_object2 { static $ = $ static async source() { return 'Jin' } @ $mol_wire_mem(0) static middle() { return $mol_wire_sync( this ).source() } @ $mol_wire_mem(0) static target() { return this.middle() } @ $mol_wire_method static test() { $mol_assert_equal( App.target() , 'Jin' ) } } await $mol_wire_async( App ).test() }, 'Auto destroy on long alone'( $ ) { let destroyed = false class App extends $mol_object2 { static $ = $ @ $mol_wire_mem(0) static showing( next = true ) { return next } @ $mol_wire_mem(0) static details() { return { destructor() { destroyed = true } } } @ $mol_wire_mem(0) static render() { return this.showing() ? this.details() : null } } const details = App.render() $mol_assert_ok( details ) App.showing( false ) $mol_assert_not( App.render() ) App.showing( true ) $mol_assert_equal( App.render() , details ) $mol_wire_fiber.sync() $mol_assert_not( destroyed ) App.showing( false ) $mol_wire_fiber.sync() $mol_assert_ok( destroyed ) App.showing( true ) $mol_assert_unique( App.render() , details ) }, // https://github.com/nin-jin/slides/tree/master/reactivity#wish-stability async 'Hold pubs while wait async task'($) { class App extends $mol_object2 { static $ = $ static counter = 0 @ $mol_wire_mem(0) static resets( next?: null ): number { return ( $mol_wire_probe( ()=> this.resets() ) ?? -1 ) + 1 } static async wait() { } @ $mol_wire_mem(0) static value() { return ++ this.counter } @ $mol_wire_mem(0) static result() { if( this.resets() ) $mol_wire_sync( this ).wait() return this.value() } @ $mol_wire_method static test() { } } $mol_assert_equal( App.result() , 1 ) App.resets( null ) $mol_wire_fiber.sync() $mol_assert_equal( await $mol_wire_async( App ).result() , 1 ) }, 'Memoize by single simple key' ($) { class Team extends $mol_object2 { static $ = $ @ $mol_wire_mem(1) static user_name( user: string , next?: string ) { return next ?? user } @ $mol_wire_mem(1) static user_names() { return [ this.user_name( 'jin' ), this.user_name( 'john' ), ] } @ $mol_wire_method static test() { } } $mol_assert_like( Team.user_names(), [ 'jin', 'john' ] ) Team.user_name( 'jin', 'JIN' ) $mol_assert_like( Team.user_names(), [ 'JIN', 'john' ] ) } , 'Memoize by single complex key' ($) { class Map extends $mol_object2 { static $ = $ @ $mol_wire_mem(1) static tile( pos: [ number, number ] ) { return new String( `/tile=${pos}` ) } @ $mol_wire_method static test() { $mol_assert_like( this.tile([0,1]), new String( '/tile=0,1' ) ) $mol_assert_equal( this.tile([0,1]), this.tile([0,1]) ) } } Map.test() } , 'Memoize by multiple keys' ($) { class Map extends $mol_object2 { static $ = $ @ $mol_wire_mem(2) static tile( x: number, y: number ) { return new String( `/tile=${x},${y}` ) } @ $mol_wire_method static test() { $mol_assert_like( this.tile(0,1), new String( '/tile=0,1' ) ) $mol_assert_equal( this.tile(0,1), this.tile(0,1) ) } } Map.test() } , 'Owned value has js-path name' () { class App extends $mol_object2 { @ $mol_wire_mem(0) static title() { return new $mol_object2 } @ $mol_wire_mem(1) static like( friend: number ) { return new $mol_object2 } @ $mol_wire_mem(2) static relation( friend: number, props: [ number ] ) { return new $mol_object2 } } $mol_assert_equal( `${ App.title() }` , 'App.title()' ) $mol_assert_equal( `${ App.like(123) }` , 'App.like(123)' ) $mol_assert_equal( `${ App.relation(123,[456]) }` , 'App.relation(123,[456])' ) } , 'Deep deps' ($) { class Fib extends $mol_object2 { static $ = $ static sums = 0 @ $mol_wire_mem(1) static value( index: number , next?: number ): number { if( next ) return next if( index < 2 ) return 1 ++ this.sums return this.value( index - 1 ) + this.value( index - 2 ) } } $mol_assert_equal( Fib.value( 4 ), 5 ) $mol_assert_equal( Fib.sums, 3 ) Fib.value( 1, 2 ) $mol_assert_equal( Fib.value( 4 ), 8 ) $mol_assert_equal( Fib.sums, 6 ) } , 'Unsubscribe from temp pubs on complete' ($) { class Random extends $mol_object2 { static $ = $ @ $mol_wire_method static seed() { return Math.random() } @ $mol_wire_mem(0) static resets( next?: null ) { return Math.random() } @ $mol_wire_mem(0) static value() { this.resets() return this.seed() } } const first = Random.value() Random.resets( null ) $mol_assert_unique( Random.value(), first ) } , }) }
the_stack
import * as English from "./english.js"; import * as Formats from "./formats.js"; import { hasFormatToParts, padStart } from "./util.js"; function stringifyTokens(splits, tokenToString) { let s = ""; for (const token of splits) { if (token.literal) { s += token.val; } else { s += tokenToString(token.val); } } return s; } const macroTokenToFormatOpts = { D: Formats.DATE_SHORT, DD: Formats.DATE_MED, DDD: Formats.DATE_FULL, DDDD: Formats.DATE_HUGE, t: Formats.TIME_SIMPLE, tt: Formats.TIME_WITH_SECONDS, ttt: Formats.TIME_WITH_SHORT_OFFSET, tttt: Formats.TIME_WITH_LONG_OFFSET, T: Formats.TIME_24_SIMPLE, TT: Formats.TIME_24_WITH_SECONDS, TTT: Formats.TIME_24_WITH_SHORT_OFFSET, TTTT: Formats.TIME_24_WITH_LONG_OFFSET, f: Formats.DATETIME_SHORT, ff: Formats.DATETIME_MED, fff: Formats.DATETIME_FULL, ffff: Formats.DATETIME_HUGE, F: Formats.DATETIME_SHORT_WITH_SECONDS, FF: Formats.DATETIME_MED_WITH_SECONDS, FFF: Formats.DATETIME_FULL_WITH_SECONDS, FFFF: Formats.DATETIME_HUGE_WITH_SECONDS }; /** * @private */ export default class Formatter { static create(locale, opts = {}) { return new Formatter(locale, opts); } static parseFormat(fmt) { let current = null, currentFull = "", bracketed = false; const splits = []; for (let i = 0; i < fmt.length; i++) { const c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } current = null; currentFull = ""; bracketed = !bracketed; } else if (bracketed) { currentFull += c; } else if (c === current) { currentFull += c; } else { if (currentFull.length > 0) { splits.push({ literal: false, val: currentFull }); } currentFull = c; current = c; } } if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } return splits; } static macroTokenToFormatOpts(token) { return macroTokenToFormatOpts[token]; } constructor(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } const df = this.systemLoc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); } formatDateTime(dt, opts = {}) { const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); } formatDateTimeParts(dt, opts = {}) { const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.formatToParts(); } resolvedOptions(dt, opts = {}) { const df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.resolvedOptions(); } num(n, p = 0) { // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } const opts = Object.assign({}, this.opts); if (p > 0) { opts.padTo = p; } return this.loc.numberFormatter(opts).format(n); } formatDateTimeFromString(dt, fmt) { const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory" && hasFormatToParts(), string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset = opts => { if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { return "Z"; } return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; }, meridiem = () => knownEnglish ? English.meridiemForDateTime(dt) : string({ hour: "numeric", hour12: true }, "dayperiod"), month = (length, standalone) => knownEnglish ? English.monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? English.weekdayForDateTime(dt, length) : string( standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday" ), maybeMacro = token => { const formatOpts = Formatter.macroTokenToFormatOpts(token); if (formatOpts) { return this.formatWithSystemDefault(dt, formatOpts); } else { return token; } }, era = length => knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = token => { // Where possible: http://cldr.unicode.org/translation/date-time#TOC-Stand-Alone-vs.-Format-Styles switch (token) { // ms case "S": return this.num(dt.millisecond); case "u": // falls through case "SSS": return this.num(dt.millisecond, 3); // seconds case "s": return this.num(dt.second); case "ss": return this.num(dt.second, 2); // minutes case "m": return this.num(dt.minute); case "mm": return this.num(dt.minute, 2); // hours case "h": return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); case "hh": return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); case "H": return this.num(dt.hour); case "HH": return this.num(dt.hour, 2); // offset case "Z": // like +6 return formatOffset({ format: "narrow", allowZ: this.opts.allowZ }); case "ZZ": // like +06:00 return formatOffset({ format: "short", allowZ: this.opts.allowZ }); case "ZZZ": // like +0600 return formatOffset({ format: "techie", allowZ: this.opts.allowZ }); case "ZZZZ": // like EST return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); case "ZZZZZ": // like Eastern Standard Time return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); // zone case "z": // like America/New_York return dt.zoneName; // meridiems case "a": return meridiem(); // dates case "d": return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); case "dd": return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); // weekdays - standalone case "c": // like 1 return this.num(dt.weekday); case "ccc": // like 'Tues' return weekday("short", true); case "cccc": // like 'Tuesday' return weekday("long", true); case "ccccc": // like 'T' return weekday("narrow", true); // weekdays - format case "E": // like 1 return this.num(dt.weekday); case "EEE": // like 'Tues' return weekday("short", false); case "EEEE": // like 'Tuesday' return weekday("long", false); case "EEEEE": // like 'T' return weekday("narrow", false); // months - standalone case "L": // like 1 return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); case "LL": // like 01, doesn't seem to work return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2); case "LLL": // like Jan return month("short", true); case "LLLL": // like January return month("long", true); case "LLLLL": // like J return month("narrow", true); // months - format case "M": // like 1 return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month); case "MM": // like 01 return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2); case "MMM": // like Jan return month("short", false); case "MMMM": // like January return month("long", false); case "MMMMM": // like J return month("narrow", false); // years case "y": // like 2014 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); case "yy": // like 14 return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); case "yyyy": // like 0012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4); case "yyyyyy": // like 000012 return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6); // eras case "G": // like AD return era("short"); case "GG": // like Anno Domini return era("long"); case "GGGGG": return era("narrow"); case "kk": return this.num(dt.weekYear.toString().slice(-2), 2); case "kkkk": return this.num(dt.weekYear, 4); case "W": return this.num(dt.weekNumber); case "WW": return this.num(dt.weekNumber, 2); case "o": return this.num(dt.ordinal); case "ooo": return this.num(dt.ordinal, 3); case "q": // like 1 return this.num(dt.quarter); case "qq": // like 01 return this.num(dt.quarter, 2); case "X": return this.num(Math.floor(dt.ts / 1000)); case "x": return this.num(dt.ts); default: return maybeMacro(token); } }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); } formatDurationFromString(dur, fmt) { const tokenToField = token => { switch (token[0]) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": return "hour"; case "d": return "day"; case "M": return "month"; case "y": return "year"; default: return null; } }, tokenToString = lildur => token => { const mapped = tokenToField(token); if (mapped) { return this.num(lildur.get(mapped), token.length); } else { return token; } }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce( (found, { literal, val }) => (literal ? found : found.concat(val)), [] ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t)); return stringifyTokens(tokens, tokenToString(collapsed)); } }
the_stack
import {createContext, useContext, useMemo, useState} from 'react' import {Badge, Divider, H4, ListInnerContainer, Select, Tabs, Text} from '@/omui' import {Dot, SearchInput, TopContent} from '@/components/lib' import {Alert} from '@/components/Alert' import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import {faAngleDoubleRight, faCaretUp} from '@fortawesome/free-solid-svg-icons' import dayjs from 'dayjs' import {Accordion} from '@/components/Accordion' import {Base} from '@/components/Layouts' import {AcceptDeny} from '@/components/AcceptDenyButtons' import {TableItem, useOMUITable} from '@/components/Table' import {useBudgetRequests, useRequests} from '@/lib/data' import {RequestStatusBadge} from '@/components/RequestStatusBadge' const RequestsContext = createContext({budgets: [], requests: [], highlighted: null, selected: []}) function PendingUpgrade() { const {budgets} = useContext(RequestsContext) const pending = budgets?.filter(b => b?.req?.status === 'pending') if (pending?.length === 0) return <EmptyUpgradeRequests /> return <RequestsAccordion budgets={pending} /> } function RequestsAccordion({budgets}) { const buildUserInfo = info => [ { text: 'Role', value: ( <Badge variant="primary" type="subtle"> {info.user.role} </Badge> ) }, { text: 'Email', value: ( <a href={`mailto:${info.user.email}`}> <Text size="sm" underline> {info.user.email} </Text> </a> ) }, {text: 'Company/Institution', value: info.user.company}, {text: 'Website/Profile', value: info.user.website} ] return ( <> <div className="col-span-3 mt-10"> <SearchInput /> </div> <div className="col-span-full mt-6"> <Accordion> {budgets?.map(item => { const update = useRequests().update(item.req.id).mutate return ( <Accordion.Item> <div className="flex justify-between w-full items-center"> <div className="items-center flex space-x-2"> <Text>{item.user?.name}</Text> <Badge variant="gray" type="subtle"> {item.user.current_budget} </Badge> <Text>+</Text> <Badge variant="primary" type="subtle"> {item.req.requested_budget} ε </Badge> </div> <div className="flex space-x-2 items-center"> <Text size="sm">{dayjs(item.req.date).fromNow()}</Text> <ListInnerContainer> <Dot /> </ListInnerContainer> <AcceptDeny onAccept={() => update({status: 'accepted'})} onDeny={() => update({status: 'denied'})} />{' '} </div> </div> <div className="flex space-x-6 w-full"> {/* upgrade-card */} <div className="w-1/2 flex-shrink-0 bg-gray-50 border border-gray-100 px-6 py-4 items-center" style={{ background: 'linear-gradient(90deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.5) 100%), #F1F0F4' }}> <div className="flex space-x-6 items-start"> <div className="flex-shrink-0"> <div className="flex items-center space-x-2 text-error-500"> <Text size="xl">{item.user.current_budget.toFixed(2)}</Text> <Text size="lg">ε</Text> </div> <Text size="sm">Current Balance</Text> </div> <div className="self-stretch"> <Divider orientation="vertical" color="light" /> </div> <div className="flex-shrink-0"> <div className="flex items-center space-x-2"> <Text size="xl">{item.user.current_budget.toFixed(2)}</Text> <Text size="lg">ε</Text> </div> <Text size="sm">Current Balance</Text> </div> </div> <Divider color="light" className="mt-8" /> <div className="flex space-x-4 items-start mt-4"> <div className="flex-shrink-0"> <div className="flex space-x-2"> <div className="flex items-center"> <Text size="xl">{item.user.current_budget.toFixed(2)}</Text> <Text size="lg">ε</Text> </div> <div className="flex items-center space-x-1"> <Text className="text-primary-600" bold> + </Text> <Badge variant="primary" type="subtle"> {item.req.requested_budget - item.user.current_budget} ε </Badge> </div> </div> <Text size="sm">Current Balance</Text> </div> <div className="text-gray-400 w-10 h-10"> <FontAwesomeIcon icon={faAngleDoubleRight} className="flex-shrink-0" /> </div> <div className="flex-shrink-0"> <div className="flex space-x-2"> <div flex="flex items-center justify-between"> <Text size="xl">{item.req.requested_budget.toFixed(2)}</Text> <Text size="lg">ε</Text> </div> <div flex="flex items-center justify-between"> <Badge variant="primary" type="subtle"> {item.req.requested_budget - item.user.current_budget} <FontAwesomeIcon icon={faCaretUp} className="pl-1" /> </Badge> </div> </div> <Text size="sm">Requested Budget</Text> </div> </div> </div> <div className="flex justify-between space-x-2 truncate"> {/* request details card */} <div className="w-full border border-gray-100 p-6 space-y-4"> {() => { const info = buildUserInfo(item) return ( <div key={info.property} className="space-x-2 truncate"> <Text bold size="sm"> {info.text}: </Text> {typeof info.value === 'string' && ( <Text size="sm" className="truncate"> {info.value} </Text> )} {typeof info.value === 'object' && info.value} </div> ) }} <div className="flex flex-col flex-wrap w-full whitespace-normal"> <Text bold size="sm"> Reason: </Text> <Text size="sm">{item.req.reason}</Text> </div> {/* <div> */} {/* <Link href="/"> */} {/* <a> */} {/* <Text as="p" underline size="xs" className="text-primary-600"> */} {/* View User Profile */} {/* </Text> */} {/* </a> */} {/* </Link> */} {/* </div> */} </div> </div> </div> </Accordion.Item> ) })} </Accordion> </div> </> ) } function HistoryUpgrade() { const {budgets} = useContext(RequestsContext) const history = budgets?.filter(req => req.req.status !== 'pending') return ( <div className="col-span-full mt-8"> {history?.length === 0 && <EmptyUpgradeRequests />} {history?.length > 0 && <UpgradeRequestsHistoryTable />} </div> ) } function UpgradeRequestsHistoryTable() { const {budgets} = useContext(RequestsContext) const tableData = useMemo(() => budgets?.filter(req => req.req.status !== 'pending') ?? [], [budgets]) const tableColumns = useMemo( () => [ { Header: 'ID#', accessor: 'req.id', Cell: ({cell: {value}}) => ( <Badge size="sm" variant="gray" type="subtle" truncate> {value} </Badge> ) }, { Header: 'Name', accessor: 'user.name', Cell: ({cell: {value}}) => <Text size="sm">{value}</Text> }, { Header: 'Status', accessor: 'req.status', Cell: ({cell: {value}}) => <RequestStatusBadge status={value} /> }, // { // Header: ( // <Text size="sm" className="space-x-1"> // <FontAwesomeIcon icon={faCalendar} /> <span>Updated on</span> // </Text> // ), // accessor: 'req.updated_on', // Cell: ({cell: {value}}) => ( // <Text size="sm" uppercase> // {formatDate(value)} // </Text> // ) // }, // { // Header: ( // <Text size="sm" className="space-x-1"> // <FontAwesomeIcon icon={faUser} /> <span>Updated by</span> // </Text> // ), // accessor: 'req.updated_by', // Cell: ({cell: {value}}) => ( // <Text size="sm" uppercase> // {value} // </Text> // ) // }, { Header: 'Requested', accessor: 'req.requested_budget', Cell: ({cell: {value, row}}) => ( <TableItem center> <Badge variant={row.original.status === 'accepted' ? 'success' : 'danger'} type="subtle"> {value} ε </Badge> </TableItem> ) }, { Header: 'New budget', accessor: '', Cell: ({cell: {value, row}}) => ( <TableItem className="h-full flex"> <div className="flex items-center border-r pr-3"> <Badge variant="gray" type="subtle"> {row.original.req.status === 'denied' ? row.original.user.current_budget : row.original.req.requested_budget}{' '} ε </Badge> </div> <div className="flex items-center ml-3"> <Text size="sm" className={row.original.req.status === 'denied' ? 'text-error-600' : 'text-success-600'}> {row.original.req.status === 'denied' ? '--' : `+${row.original.req.requested_budget - row.original.user.current_budget}`} </Text> </div> </TableItem> ) } ], [] ) const table = useOMUITable({ data: tableData, columns: tableColumns, selectable: true, sortable: true }) // const selected = table.instance.selectedFlatRows return ( <> {/* <div className="flex col-span-full mt-10"> */} {/* <SearchInput /> */} {/* <Dot /> */} {/* <Select placeholder="Filter by Status" /> */} {/* </div> */} <section className="col-span-full space-y-6"> {table.Component} {/* TODO: support pagination */} <Text as="p" size="sm"> {tableData.length} / {tableData.length} results </Text> </section> </> ) } function EmptyUpgradeRequests() { return ( <div className="col-span-full space-y-2 w-full text-center mt-20"> <H4>Congratulations</H4> <Text className="text-gray-400">You’ve cleared all upgrade requests in your queue!</Text> </div> ) } export default function UpgradeRequests() { const {data: budgetReq} = useBudgetRequests().all() const [currentTab, setCurrentTab] = useState(() => 1) const tabsList = [ {id: 1, title: 'Pending'}, {id: 2, title: 'History'} ] const requests = [] return ( <Base> <RequestsContext.Provider value={{budgets: budgetReq, requests, highlighted: null, selected: []}}> <TopContent heading="Upgrade Requests" /> <div className="col-span-10"> <Alert.Info alertStyle="topAccent" description={ <Text className="text-gray-800"> Upgrade requests are requests made by Data Scientists on your node to get a larger amount of privacy budget allocated to them. You can think of privacy budget as credits you give to a user to perform computations from. These credits of{' '} <Text mono className="text-gray-600"> Epsilon(ɛ) </Text>{' '} indicate the amount of visibility a user has into any one entity of your data. </Text> } /> </div> <div className="col-span-full mt-10"> <Tabs tabsList={tabsList} onChange={setCurrentTab} align="auto" active={currentTab} /> </div> {currentTab === 1 && <PendingUpgrade />} {currentTab === 2 && <HistoryUpgrade />} </RequestsContext.Provider> </Base> ) }
the_stack
import * as errors from './errors'; import { BATCH_REGEX, BINDING_REGEX, END_OF_INPUT, HELP_COMMAND_INDEX, HELP_REGEX, NODE_ERRORED, NODE_INITIAL, NODE_SUCCESS, OPTION_REGEX, START_OF_INPUT, DEBUG, } from './constants'; declare const console: any; // ------------------------------------------------------------------------ export function debug(str: string) { if (DEBUG) { console.log(str); } } // ------------------------------------------------------------------------ export type StateMachine = { nodes: Array<Node>; }; export type RunState = { candidateUsage: string | null; requiredOptions: Array<Array<string>>; errorMessage: string | null; ignoreOptions: boolean; options: Array<{name: string, value: any}>; path: Array<string>; positionals: Array<{value: string, extra: boolean | typeof NoLimits}>; remainder: string | null; selectedIndex: number | null; }; const basicHelpState: RunState = { candidateUsage: null, requiredOptions: [], errorMessage: null, ignoreOptions: false, path: [], positionals: [], options: [], remainder: null, selectedIndex: HELP_COMMAND_INDEX, }; export function makeStateMachine(): StateMachine { return { nodes: [makeNode(), makeNode(), makeNode()], }; } export function makeAnyOfMachine(inputs: Array<StateMachine>) { const output = makeStateMachine(); const heads = []; let offset = output.nodes.length; for (const input of inputs) { heads.push(offset); for (let t = 0; t < input.nodes.length; ++t) if (!isTerminalNode(t)) output.nodes.push(cloneNode(input.nodes[t], offset)); offset += input.nodes.length - 2; } for (const head of heads) registerShortcut(output, NODE_INITIAL, head); return output; } export function injectNode(machine: StateMachine, node: Node) { machine.nodes.push(node); return machine.nodes.length - 1; } export function simplifyMachine(input: StateMachine) { const visited = new Set(); const process = (node: number) => { if (visited.has(node)) return; visited.add(node); const nodeDef = input.nodes[node]; for (const transitions of Object.values(nodeDef.statics)) for (const {to} of transitions) process(to); for (const [,{to}] of nodeDef.dynamics) process(to); for (const {to} of nodeDef.shortcuts) process(to); const shortcuts = new Set(nodeDef.shortcuts.map(({to}) => to)); while (nodeDef.shortcuts.length > 0) { const {to} = nodeDef.shortcuts.shift()!; const toDef = input.nodes[to]; for (const [segment, transitions] of Object.entries(toDef.statics)) { const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) ? nodeDef.statics[segment] = [] : nodeDef.statics[segment]; for (const transition of transitions) { if (!store.some(({to}) => transition.to === to)) { store.push(transition); } } } for (const [test, transition] of toDef.dynamics) if (!nodeDef.dynamics.some(([otherTest, {to}]) => test === otherTest && transition.to === to)) nodeDef.dynamics.push([test, transition]); for (const transition of toDef.shortcuts) { if (!shortcuts.has(transition.to)) { nodeDef.shortcuts.push(transition); shortcuts.add(transition.to); } } } }; process(NODE_INITIAL); } export function debugMachine(machine: StateMachine, {prefix = ``}: {prefix?: string} = {}) { // Don't iterate unless it's needed if (DEBUG) { debug(`${prefix}Nodes are:`); for (let t = 0; t < machine.nodes.length; ++t) { debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`); } } } export function runMachineInternal(machine: StateMachine, input: Array<string>, partial: boolean = false) { debug(`Running a vm on ${JSON.stringify(input)}`); let branches: Array<{node: number, state: RunState}> = [{node: NODE_INITIAL, state: { candidateUsage: null, requiredOptions: [], errorMessage: null, ignoreOptions: false, options: [], path: [], positionals: [], remainder: null, selectedIndex: null, }}]; debugMachine(machine, {prefix: ` `}); const tokens = [START_OF_INPUT, ...input]; for (let t = 0; t < tokens.length; ++t) { const segment = tokens[t]; debug(` Processing ${JSON.stringify(segment)}`); const nextBranches: Array<{node: number, state: RunState}> = []; for (const {node, state} of branches) { debug(` Current node is ${node}`); const nodeDef = machine.nodes[node]; if (node === NODE_ERRORED) { nextBranches.push({node, state}); continue; } console.assert( nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`, ); const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment); if (!partial || t < tokens.length - 1 || hasExactMatch) { if (hasExactMatch) { const transitions = nodeDef.statics[segment]; for (const {to, reducer} of transitions) { nextBranches.push({node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state}); debug(` Static transition to ${to} found`); } } else { debug(` No static transition found`); } } else { let hasMatches = false; for (const candidate of Object.keys(nodeDef.statics)) { if (!candidate.startsWith(segment)) continue; if (segment === candidate) { for (const {to, reducer} of nodeDef.statics[candidate]) { nextBranches.push({node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state}); debug(` Static transition to ${to} found`); } } else { for (const {to} of nodeDef.statics[candidate]) { nextBranches.push({node: to, state: {...state, remainder: candidate.slice(segment.length)}}); debug(` Static transition to ${to} found (partial match)`); } } hasMatches = true; } if (!hasMatches) { debug(` No partial static transition found`); } } if (segment !== END_OF_INPUT) { for (const [test, {to, reducer}] of nodeDef.dynamics) { if (execute(tests, test, state, segment)) { nextBranches.push({node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state}); debug(` Dynamic transition to ${to} found (via ${test})`); } } } } if (nextBranches.length === 0 && segment === END_OF_INPUT && input.length === 1) { return [{ node: NODE_INITIAL, state: basicHelpState, }]; } if (nextBranches.length === 0) { throw new errors.UnknownSyntaxError(input, branches.filter(({node}) => { return node !== NODE_ERRORED; }).map(({state}) => { return {usage: state.candidateUsage!, reason: null}; })); } if (nextBranches.every(({node}) => node === NODE_ERRORED)) { throw new errors.UnknownSyntaxError(input, nextBranches.map(({state}) => { return {usage: state.candidateUsage!, reason: state.errorMessage}; })); } branches = trimSmallerBranches(nextBranches); } if (branches.length > 0) { debug(` Results:`); for (const branch of branches) { debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`); } } else { debug(` No results`); } return branches; } function checkIfNodeIsFinished(node: Node, state: RunState) { if (state.selectedIndex !== null) return true; if (Object.prototype.hasOwnProperty.call(node.statics, END_OF_INPUT)) for (const {to} of node.statics[END_OF_INPUT]) if (to === NODE_SUCCESS) return true; return false; } function suggestMachine(machine: StateMachine, input: Array<string>, partial: boolean) { // If we're accepting partial matches, then exact matches need to be // prefixed with an extra space. const prefix = partial && input.length > 0 ? [``] : []; const branches = runMachineInternal(machine, input, partial); const suggestions: Array<Array<string>> = []; const suggestionsJson = new Set<string>(); const traverseSuggestion = (suggestion: Array<string>, node: number, skipFirst: boolean = true) => { let nextNodes = [node]; while (nextNodes.length > 0) { const currentNodes = nextNodes; nextNodes = []; for (const node of currentNodes) { const nodeDef = machine.nodes[node]; const keys = Object.keys(nodeDef.statics); // The fact that `key` is unused is likely a bug, but no one has investigated it yet. // TODO: Investigate it. // eslint-disable-next-line @typescript-eslint/no-unused-vars for (const key of Object.keys(nodeDef.statics)) { const segment = keys[0]; for (const {to, reducer} of nodeDef.statics[segment]) { if (reducer !== `pushPath`) continue; if (!skipFirst) suggestion.push(segment); nextNodes.push(to); } } } skipFirst = false; } const json = JSON.stringify(suggestion); if (suggestionsJson.has(json)) return; suggestions.push(suggestion); suggestionsJson.add(json); }; for (const {node, state} of branches) { if (state.remainder !== null) { traverseSuggestion([state.remainder], node); continue; } const nodeDef = machine.nodes[node]; const isFinished = checkIfNodeIsFinished(nodeDef, state); for (const [candidate, transitions] of Object.entries(nodeDef.statics)) if ((isFinished && candidate !== END_OF_INPUT) || (!candidate.startsWith(`-`) && transitions.some(({reducer}) => reducer === `pushPath`))) traverseSuggestion([...prefix, candidate], node); if (!isFinished) continue; for (const [test, {to}] of nodeDef.dynamics) { if (to === NODE_ERRORED) continue; const tokens = suggest(test, state); if (tokens === null) continue; for (const token of tokens) { traverseSuggestion([...prefix, token], node); } } } return [...suggestions].sort(); } function runMachine(machine: StateMachine, input: Array<string>) { const branches = runMachineInternal(machine, [...input, END_OF_INPUT]); return selectBestState(input, branches.map(({state}) => { return state; })); } export function trimSmallerBranches(branches: Array<{node: number, state: RunState}>) { let maxPathSize = 0; for (const {state} of branches) if (state.path.length > maxPathSize) maxPathSize = state.path.length; return branches.filter(({state}) => { return state.path.length === maxPathSize; }); } export function selectBestState(input: Array<string>, states: Array<RunState>) { const terminalStates = states.filter(state => { return state.selectedIndex !== null; }); if (terminalStates.length === 0) throw new Error(); const requiredOptionsSetStates = terminalStates.filter(state => state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name) ) ) ); if (requiredOptionsSetStates.length === 0) { throw new errors.UnknownSyntaxError(input, terminalStates.map(state => ({ usage: state.candidateUsage!, reason: null, }))); } let maxPathSize = 0; for (const state of requiredOptionsSetStates) if (state.path.length > maxPathSize) maxPathSize = state.path.length; const bestPathBranches = requiredOptionsSetStates.filter(state => { return state.path.length === maxPathSize; }); const getPositionalCount = (state: RunState) => state.positionals.filter(({extra}) => { return !extra; }).length + state.options.length; const statesWithPositionalCount = bestPathBranches.map(state => { return {state, positionalCount: getPositionalCount(state)}; }); let maxPositionalCount = 0; for (const {positionalCount} of statesWithPositionalCount) if (positionalCount > maxPositionalCount) maxPositionalCount = positionalCount; const bestPositionalStates = statesWithPositionalCount.filter(({positionalCount}) => { return positionalCount === maxPositionalCount; }).map(({state}) => { return state; }); const fixedStates = aggregateHelpStates(bestPositionalStates); if (fixedStates.length > 1) throw new errors.AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage!)); return fixedStates[0]; } export function aggregateHelpStates(states: Array<RunState>) { const notHelps: Array<RunState> = []; const helps: Array<RunState> = []; for (const state of states) { if (state.selectedIndex === HELP_COMMAND_INDEX) { helps.push(state); } else { notHelps.push(state); } } if (helps.length > 0) { notHelps.push({ ...basicHelpState, path: findCommonPrefix(...helps.map(state => state.path)), options: helps.reduce((options, state) => options.concat(state.options), [] as RunState['options']), }); } return notHelps; } function findCommonPrefix(...paths: Array<Array<string>>): Array<string>; function findCommonPrefix(firstPath: Array<string>, secondPath: Array<string>|undefined, ...rest: Array<Array<string>>): Array<string> { if (secondPath === undefined) return Array.from(firstPath); return findCommonPrefix( firstPath.filter((segment, i) => segment === secondPath[i]), ...rest ); } // ------------------------------------------------------------------------ type Transition = { to: number; reducer?: Callback<keyof typeof reducers, typeof reducers>; }; type Node = { dynamics: Array<[Callback<keyof typeof tests, typeof tests>, Transition]>; shortcuts: Array<Transition>; statics: {[segment: string]: Array<Transition>}; }; export function makeNode(): Node { return { dynamics: [], shortcuts: [], statics: {}, }; } export function isTerminalNode(node: number) { return node === NODE_SUCCESS || node === NODE_ERRORED; } export function cloneTransition(input: Transition, offset: number = 0) { return { to: !isTerminalNode(input.to) ? input.to > 2 ? input.to + offset - 2 : input.to + offset : input.to, reducer: input.reducer, }; } export function cloneNode(input: Node, offset: number = 0) { const output = makeNode(); for (const [test, transition] of input.dynamics) output.dynamics.push([test, cloneTransition(transition, offset)]); for (const transition of input.shortcuts) output.shortcuts.push(cloneTransition(transition, offset)); for (const [segment, transitions] of Object.entries(input.statics)) output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset)); return output; } export function registerDynamic<T extends keyof typeof tests, R extends keyof typeof reducers>(machine: StateMachine, from: number, test: Callback<T, typeof tests>, to: number, reducer?: Callback<R, typeof reducers>) { machine.nodes[from].dynamics.push([ test as Callback<keyof typeof tests, typeof tests>, {to, reducer: reducer as Callback<keyof typeof reducers, typeof reducers>}, ]); } export function registerShortcut<R extends keyof typeof reducers>(machine: StateMachine, from: number, to: number, reducer?: Callback<R, typeof reducers>) { machine.nodes[from].shortcuts.push( {to, reducer: reducer as Callback<keyof typeof reducers, typeof reducers>} ); } export function registerStatic<R extends keyof typeof reducers>(machine: StateMachine, from: number, test: string, to: number, reducer?: Callback<R, typeof reducers>) { const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) ? machine.nodes[from].statics[test] = [] : machine.nodes[from].statics[test]; store.push({to, reducer: reducer as Callback<keyof typeof reducers, typeof reducers>}); } // ------------------------------------------------------------------------ type UndefinedKeys<T> = {[P in keyof T]-?: undefined extends T[P] ? P : never}[keyof T]; type UndefinedTupleKeys<T extends Array<unknown>> = UndefinedKeys<Omit<T, keyof []>>; type TupleKeys<T> = Exclude<keyof T, keyof []>; export type CallbackFn<P extends Array<any>, R> = (state: RunState, segment: string, ...args: P) => R; export type CallbackFnParameters<T extends CallbackFn<any, any>> = T extends ((state: RunState, segment: string, ...args: infer P) => any) ? P : never; export type CallbackStore<T extends string, R> = Record<T, CallbackFn<any, R>>; export type Callback<T extends string, S extends CallbackStore<T, any>> = [TupleKeys<CallbackFnParameters<S[T]>>] extends [UndefinedTupleKeys<CallbackFnParameters<S[T]>>] ? (T | [T, ...CallbackFnParameters<S[T]>]) : [T, ...CallbackFnParameters<S[T]>]; export function execute<T extends string, R, S extends CallbackStore<T, R>>(store: S, callback: Callback<T, S>, state: RunState, segment: string) { // TypeScript's control flow can't properly narrow // generic conditionals for some mysterious reason if (Array.isArray(callback)) { const [name, ...args] = callback as [T, ...CallbackFnParameters<S[T]>]; return store[name](state, segment, ...args); } else { return store[callback as T](state, segment); } } export function suggest(callback: Callback<keyof typeof tests, typeof tests>, state: RunState): Array<string> | null { const fn = Array.isArray(callback) ? tests[callback[0]] : tests[callback]; // @ts-ignore if (typeof fn.suggest === `undefined`) return null; const args = Array.isArray(callback) ? callback.slice(1) : []; // @ts-ignore return fn.suggest(state, ...args); } export const tests = { always: () => { return true; }, isOptionLike: (state: RunState, segment: string) => { return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`)); }, isNotOptionLike: (state: RunState, segment: string) => { return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`); }, isOption: (state: RunState, segment: string, name: string, hidden?: boolean) => { return !state.ignoreOptions && segment === name; }, isBatchOption: (state: RunState, segment: string, names: Array<string>) => { return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.includes(`-${name}`)); }, isBoundOption: (state: RunState, segment: string, names: Array<string>, options: Array<OptDefinition>) => { const optionParsing = segment.match(BINDING_REGEX); return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.includes(optionParsing[1]) // Disallow bound options with no arguments (i.e. booleans) && options.filter(opt => opt.names.includes(optionParsing[1])).every(opt => opt.allowBinding); }, isNegatedOption: (state: RunState, segment: string, name: string) => { return !state.ignoreOptions && segment === `--no-${name.slice(2)}`; }, isHelp: (state: RunState, segment: string) => { return !state.ignoreOptions && HELP_REGEX.test(segment); }, isUnsupportedOption: (state: RunState, segment: string, names: Array<string>) => { return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.includes(segment); }, isInvalidOption: (state: RunState, segment: string) => { return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment); }, }; // @ts-ignore tests.isOption.suggest = (state: RunState, name: string, hidden: boolean = true) => { return !hidden ? [name] : null; }; export const reducers = { setCandidateState: (state: RunState, segment: string, candidateState: Partial<RunState>) => { return {...state, ...candidateState}; }, setSelectedIndex: (state: RunState, segment: string, index: number) => { return {...state, selectedIndex: index}; }, pushBatch: (state: RunState, segment: string) => { return {...state, options: state.options.concat([...segment.slice(1)].map(name => ({name: `-${name}`, value: true})))}; }, pushBound: (state: RunState, segment: string) => { const [, name, value] = segment.match(BINDING_REGEX)!; return {...state, options: state.options.concat({name, value})}; }, pushPath: (state: RunState, segment: string) => { return {...state, path: state.path.concat(segment)}; }, pushPositional: (state: RunState, segment: string) => { return {...state, positionals: state.positionals.concat({value: segment, extra: false})}; }, pushExtra: (state: RunState, segment: string) => { return {...state, positionals: state.positionals.concat({value: segment, extra: true})}; }, pushExtraNoLimits: (state: RunState, segment: string) => { return {...state, positionals: state.positionals.concat({value: segment, extra: NoLimits})}; }, pushTrue: (state: RunState, segment: string, name: string = segment) => { return {...state, options: state.options.concat({name: segment, value: true})}; }, pushFalse: (state: RunState, segment: string, name: string = segment) => { return {...state, options: state.options.concat({name, value: false})}; }, pushUndefined: (state: RunState, segment: string) => { return {...state, options: state.options.concat({name: segment, value: undefined})}; }, pushStringValue: (state: RunState, segment: string) => { const copy = {...state, options: [...state.options]}; const lastOption = state.options[state.options.length - 1]; lastOption.value = (lastOption.value ?? []).concat([segment]); return copy; }, setStringValue: (state: RunState, segment: string) => { const copy = {...state, options: [...state.options]}; const lastOption = state.options[state.options.length - 1]; lastOption.value = segment; return copy; }, inhibateOptions: (state: RunState) => { return {...state, ignoreOptions: true}; }, useHelp: (state: RunState, segment: string, command: number) => { const [, /* name */, index] = segment.match(HELP_REGEX)!; if (typeof index !== `undefined`) { return {...state, options: [{name: `-c`, value: String(command)}, {name: `-i`, value: index}]}; } else { return {...state, options: [{name: `-c`, value: String(command)}]}; } }, setError: (state: RunState, segment: string, errorMessage: string) => { if (segment === END_OF_INPUT) { return {...state, errorMessage: `${errorMessage}.`}; } else { return {...state, errorMessage: `${errorMessage} ("${segment}").`}; } }, setOptionArityError: (state: RunState, segment: string) => { const lastOption = state.options[state.options.length - 1]; return {...state, errorMessage: `Not enough arguments to option ${lastOption.name}.`}; }, }; // ------------------------------------------------------------------------ export const NoLimits = Symbol(); export type ArityDefinition = { leading: Array<string>; extra: Array<string> | typeof NoLimits; trailing: Array<string>; proxy: boolean; }; export type OptDefinition = { names: Array<string>; description?: string; arity: number; hidden: boolean; required: boolean; allowBinding: boolean; }; export class CommandBuilder<Context> { public readonly cliIndex: number; public readonly cliOpts: Readonly<CliOptions>; public readonly allOptionNames: Array<string> = []; public readonly arity: ArityDefinition = {leading: [], trailing: [], extra: [], proxy: false}; public readonly options: Array<OptDefinition> = []; public readonly paths: Array<Array<string>> = []; private context?: Context; constructor(cliIndex: number, cliOpts: CliOptions) { this.cliIndex = cliIndex; this.cliOpts = cliOpts; } addPath(path: Array<string>) { this.paths.push(path); } setArity({leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy}: Partial<ArityDefinition>) { Object.assign(this.arity, {leading, trailing, extra, proxy}); } addPositional({name = `arg`, required = true}: {name?: string, required?: boolean} = {}) { if (!required && this.arity.extra === NoLimits) throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`); if (!required && this.arity.trailing.length > 0) throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`); if (!required && this.arity.extra !== NoLimits) { this.arity.extra.push(name); } else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) { this.arity.leading.push(name); } else { this.arity.trailing.push(name); } } addRest({name = `arg`, required = 0}: {name?: string, required?: number} = {}) { if (this.arity.extra === NoLimits) throw new Error(`Infinite lists cannot be declared multiple times in the same command`); if (this.arity.trailing.length > 0) throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`); for (let t = 0; t < required; ++t) this.addPositional({name}); this.arity.extra = NoLimits; } addProxy({required = 0}: {name?: string, required?: number} = {}) { this.addRest({required}); this.arity.proxy = true; } addOption({names, description, arity = 0, hidden = false, required = false, allowBinding = true}: Partial<OptDefinition> & {names: Array<string>}) { if (!allowBinding && arity > 1) throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`); if (!Number.isInteger(arity)) throw new Error(`The arity must be an integer, got ${arity}`); if (arity < 0) throw new Error(`The arity must be positive, got ${arity}`); this.allOptionNames.push(...names); this.options.push({names, description, arity, hidden, required, allowBinding}); } setContext(context: Context) { this.context = context; } usage({detailed = true, inlineOptions = true}: {detailed?: boolean; inlineOptions?: boolean} = {}) { const segments = [this.cliOpts.binaryName]; const detailedOptionList: Array<{ definition: string; description: string; required: boolean; }> = []; if (this.paths.length > 0) segments.push(...this.paths[0]); if (detailed) { for (const {names, arity, hidden, description, required} of this.options) { if (hidden) continue; const args = []; for (let t = 0; t < arity; ++t) args.push(` #${t}`); const definition = `${names.join(`,`)}${args.join(``)}`; if (!inlineOptions && description) { detailedOptionList.push({definition, description, required}); } else { segments.push(required ? `<${definition}>` : `[${definition}]`); } } segments.push(...this.arity.leading.map(name => `<${name}>`)); if (this.arity.extra === NoLimits) segments.push(`...`); else segments.push(...this.arity.extra.map(name => `[${name}]`)); segments.push(...this.arity.trailing.map(name => `<${name}>`)); } const usage = segments.join(` `); return {usage, options: detailedOptionList}; } compile() { if (typeof this.context === `undefined`) throw new Error(`Assertion failed: No context attached`); const machine = makeStateMachine(); let firstNode = NODE_INITIAL; const candidateUsage = this.usage().usage; const requiredOptions = this.options .filter(opt => opt.required) .map(opt => opt.names); firstNode = injectNode(machine, makeNode()); registerStatic(machine, NODE_INITIAL, START_OF_INPUT, firstNode, [`setCandidateState`, {candidateUsage, requiredOptions}]); const positionalArgument = this.arity.proxy ? `always` : `isNotOptionLike`; const paths = this.paths.length > 0 ? this.paths : [[]]; for (const path of paths) { let lastPathNode = firstNode; // We allow options to be specified before the path. Note that we // only do this when there is a path, otherwise there would be // some redundancy with the options attached later. if (path.length > 0) { const optionPathNode = injectNode(machine, makeNode()); registerShortcut(machine, lastPathNode, optionPathNode); this.registerOptions(machine, optionPathNode); lastPathNode = optionPathNode; } for (let t = 0; t < path.length; ++t) { const nextPathNode = injectNode(machine, makeNode()); registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`); lastPathNode = nextPathNode; } if (this.arity.leading.length > 0 || !this.arity.proxy) { const helpNode = injectNode(machine, makeNode()); registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]); registerStatic(machine, helpNode, END_OF_INPUT, NODE_SUCCESS, [`setSelectedIndex`, HELP_COMMAND_INDEX]); this.registerOptions(machine, lastPathNode); } if (this.arity.leading.length > 0) registerStatic(machine, lastPathNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); let lastLeadingNode = lastPathNode; for (let t = 0; t < this.arity.leading.length; ++t) { const nextLeadingNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextLeadingNode); if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) registerStatic(machine, nextLeadingNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`); lastLeadingNode = nextLeadingNode; } let lastExtraNode = lastLeadingNode; if (this.arity.extra === NoLimits || this.arity.extra.length > 0) { const extraShortcutNode = injectNode(machine, makeNode()); registerShortcut(machine, lastLeadingNode, extraShortcutNode); if (this.arity.extra === NoLimits) { const extraNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, extraNode); registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`); registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`); registerShortcut(machine, extraNode, extraShortcutNode); } else { for (let t = 0; t < this.arity.extra.length; ++t) { const nextExtraNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextExtraNode); registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`); registerShortcut(machine, nextExtraNode, extraShortcutNode); lastExtraNode = nextExtraNode; } } lastExtraNode = extraShortcutNode; } if (this.arity.trailing.length > 0) registerStatic(machine, lastExtraNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); let lastTrailingNode = lastExtraNode; for (let t = 0; t < this.arity.trailing.length; ++t) { const nextTrailingNode = injectNode(machine, makeNode()); if (!this.arity.proxy) this.registerOptions(machine, nextTrailingNode); if (t + 1 < this.arity.trailing.length) registerStatic(machine, nextTrailingNode, END_OF_INPUT, NODE_ERRORED, [`setError`, `Not enough positional arguments`]); registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`); lastTrailingNode = nextTrailingNode; } registerDynamic(machine, lastTrailingNode, positionalArgument, NODE_ERRORED, [`setError`, `Extraneous positional argument`]); registerStatic(machine, lastTrailingNode, END_OF_INPUT, NODE_SUCCESS, [`setSelectedIndex`, this.cliIndex]); } return { machine, context: this.context, }; } private registerOptions(machine: StateMachine, node: number) { registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`); registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, `pushBatch`); registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`); registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NODE_ERRORED, [`setError`, `Unsupported option name`]); registerDynamic(machine, node, [`isInvalidOption`], NODE_ERRORED, [`setError`, `Invalid option name`]); for (const option of this.options) { const longestName = option.names.reduce((longestName, name) => { return name.length > longestName.length ? name : longestName; }, ``); if (option.arity === 0) { for (const name of option.names) { registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], node, `pushTrue`); if (name.startsWith(`--`) && !name.startsWith(`--no-`)) { registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, name]); } } } else { // We inject a new node at the end of the state machine let lastNode = injectNode(machine, makeNode()); // We register transitions from the starting node to this new node for (const name of option.names) registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], lastNode, `pushUndefined`); // For each argument, we inject a new node at the end and we // register a transition from the current node to this new node for (let t = 0; t < option.arity; ++t) { const nextNode = injectNode(machine, makeNode()); // We can provide better errors when another option or END_OF_INPUT is encountered registerStatic(machine, lastNode, END_OF_INPUT, NODE_ERRORED, `setOptionArityError`); registerDynamic(machine, lastNode, `isOptionLike`, NODE_ERRORED, `setOptionArityError`); // If the option has a single argument, no need to store it in an array const action: keyof typeof reducers = option.arity === 1 ? `setStringValue` : `pushStringValue`; registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action); lastNode = nextNode; } // In the end, we register a shortcut from // the last node back to the starting node registerShortcut(machine, lastNode, node); } } } } export type CliOptions = { binaryName: string; }; export type CliBuilderCallback<Context> = (command: CommandBuilder<Context>) => CommandBuilder<Context> | void; export class CliBuilder<Context> { private readonly opts: CliOptions; private readonly builders: Array<CommandBuilder<Context>> = []; static build<Context>(cbs: Array<CliBuilderCallback<Context>>, opts: Partial<CliOptions> = {}) { return new CliBuilder<Context>(opts).commands(cbs).compile(); } constructor({binaryName = `...`}: Partial<CliOptions> = {}) { this.opts = {binaryName}; } getBuilderByIndex(n: number) { if (!(n >= 0 && n < this.builders.length)) throw new Error(`Assertion failed: Out-of-bound command index (${n})`); return this.builders[n]; } commands(cbs: Array<CliBuilderCallback<Context>>) { for (const cb of cbs) cb(this.command()); return this; } command() { const builder = new CommandBuilder<Context>(this.builders.length, this.opts); this.builders.push(builder); return builder; } compile() { const machines = []; const contexts = []; for (const builder of this.builders) { const {machine, context} = builder.compile(); machines.push(machine); contexts.push(context); } const machine = makeAnyOfMachine(machines); simplifyMachine(machine); return { machine, contexts, process: (input: Array<string>) => { return runMachine(machine, input); }, suggest: (input: Array<string>, partial: boolean) => { return suggestMachine(machine, input, partial); }, }; } }
the_stack
import * as i18n from "i18next"; import * as immutability from "immutability-helper"; import * as React from "react"; import ContentEditable = require("react-contenteditable"); import { PermissionKind, Web } from "sp-pnp-js"; import IDiscussion from "../../../models/IDiscussion"; import { DiscussionPermissionLevel, IDiscussionReply } from "../../../models/IDiscussionReply"; import SocialModule from "../../../modules/SocialModule"; import DiscussionReply from "../DiscussionReply/DiscussionReply"; import IDiscussionBoardProps from "./IDiscussionBoardProps"; import IDiscussionBoardState from "./IDiscussionBoardState"; // Needed to get it work at runtime const update = immutability as any; class DiscussionBoard extends React.Component<IDiscussionBoardProps, IDiscussionBoardState> { private socialModule: SocialModule; private associatedPageId: number; private parentId: number; private dicussionBoardListRelativeUrl: string; public constructor(props: IDiscussionBoardProps) { super(props); this.state = { areCommentsLoading: true, discussion: null, inputPlaceHolderValue: i18n.t("comments_new_placeholder"), inputValue: "", isAdding: false, userPermissions: [], }; this.dicussionBoardListRelativeUrl = `${_spPageContextInfo.webServerRelativeUrl}/Lists/${props.listRootFolderUrl}`; // You can parametrized the list URL if you want this.socialModule = new SocialModule(this.dicussionBoardListRelativeUrl); // Handlers this.addNewComment = this.addNewComment.bind(this); this.deleteReply = this.deleteReply.bind(this); this.updateReply = this.updateReply.bind(this); this.toggleLikeReply = this.toggleLikeReply.bind(this); this.onValueChange = this.onValueChange.bind(this); this.onFocus = this.onFocus.bind(this); this.onBlur = this.onBlur.bind(this); } public render() { let renderPageComments = null; let renderNewReply = null; let renderIsAdding = null; let renderCommentsAreLoading = null; let renderCommentsCount = null; let discussion = this.state.discussion; if (this.state.isAdding) { renderIsAdding = <div className="reply--loading"><i className="fa fa-spinner fa-spin"/></div>; } if (this.state.areCommentsLoading) { renderCommentsAreLoading = <div className="loading"><i className="fa fa-spinner fa-spin"/><span>{ i18n.t("comments_loading")}</span></div>; } // If the current user can add list item to the list, it means he can comment if (this.state.userPermissions.indexOf(DiscussionPermissionLevel.Add) !== -1) { renderNewReply = <div className="reply main"> <ContentEditable html={ this.state.inputValue } disabled={ false } onChange={ this.onValueChange } data-placeholder={ this.state.inputPlaceHolderValue } className="input" role="textbox" onFocus={ this.onFocus } onBlur={ this.onBlur } /> { renderIsAdding } <button type="button" className="btn" onClick={ () => { let parentId = null; if (this.state.discussion) { parentId = this.state.discussion.Id; } this.addNewComment(parentId, this.state.inputValue); }}>{ i18n.t("comments_post") }</button> </div>; } // Get the number of comments const commentsCount = !discussion ? 0 : discussion.Replies.length; renderCommentsCount = !this.state.areCommentsLoading ? <div className="count">{`${commentsCount} ${i18n.t("comments_commentsLabel")}`}</div> : null; // Render comments as tree if (discussion) { const discussionTree = this.setDiscussionFeedAsTree(discussion.Replies, discussion.Id); discussion = update(discussion, { Replies: {$set: discussionTree }}); if (discussion.Replies.length > 0) { renderPageComments = discussion.Replies.map((reply, index) => { return <DiscussionReply key={ reply.Id } id={ reply.Id.toString() } addNewReply= { this.addNewComment } deleteReply={ this.deleteReply } updateReply={ this.updateReply } toggleLikeReply={ this.toggleLikeReply } reply={ reply } isLikeEnabled={ this.state.discussion.AreLikesEnabled } replyLevel={ 0 } />; }); } } else { renderPageComments = <div> { renderCommentsAreLoading } </div>; } return <div id="page-comments"> { renderCommentsCount } { renderNewReply } { renderPageComments } </div>; } /** * Event handlers */ public onValueChange(e: any) { this.setState({ inputValue: e.target.value }); } public onFocus() { if (!this.state.inputValue || this.state.inputValue.localeCompare("</br>") === 0) { this.setState({ inputPlaceHolderValue: "", inputValue: "<show-placeholder>", // This is just to re-render the <ContentEditable/> component by faking a new value }); } } public onBlur() { if (!$(`<div>${this.state.inputValue}</div>`).text()) { this.setState({ inputPlaceHolderValue: i18n.t("comments_new_placeholder"), inputValue: "", }); } } /** * React component lifecycle */ public async componentDidMount() { this.associatedPageId = _spPageContextInfo.pageItemId; // Load JSOM dependencies before playing with the discussion board await this.socialModule.init(); // Retrieve the discussion for this page const discussion = await this.getPageDiscussion(this.associatedPageId); // Get current user permissions const userListPermissions = await this.socialModule.getCurrentUserPermissionsOnList(this.dicussionBoardListRelativeUrl); this.setState({ areCommentsLoading: false, discussion, inputValue: "", userPermissions: userListPermissions, }); } /** * Adde a new comment and create the discussion if doesn't exist * @param parentId the reply parent item id * @param replyBody the reply body text */ public async addNewComment(parentId: number, replyBody: string) { if (!replyBody) { alert(i18n.t("comments_empty")); } else { let currentDiscussion = this.state.discussion; // First comment will create a new discussion and a reply if (!parentId) { this.setState({ isAdding: true, }); const newDiscussion = await this.createNewDiscussion($("#title").text(), window.location.href); currentDiscussion = update(currentDiscussion, { $set: newDiscussion}); // Set the new parent Id parentId = newDiscussion.Id; } else { if (parentId === currentDiscussion.Id) { this.setState({ isAdding: true, }); } } // Create reply to the discussion and and it to the state // Set the content as HTML (default field type) const reply = await this.createNewDiscussionReply(parentId, `<div>${replyBody}</div>`); currentDiscussion = update(currentDiscussion, { Replies: { $push: [reply]} }); // Update the discussion this.setState({ discussion: currentDiscussion, inputPlaceHolderValue: i18n.t("comments_new_placeholder"), inputValue: "", isAdding: false, }); } } /** * Deletes a reply * @param reply the reply object to delete */ public async deleteReply(reply: IDiscussionReply): Promise<void> { const hasBeenDeleted: boolean = false; let deletedIds: number[] = []; if (reply.Children.length > 0) { // Delete the root reply await this.socialModule.deleteReply(reply.Id); // Delete children replies deletedIds = await this.socialModule.deleteRepliesHierachy(reply, deletedIds); } else { await this.socialModule.deleteReply(reply.Id); } // Update the state const updatedReplies = this.state.discussion.Replies.filter((currentReply) => { let shouldReturn = true; if (currentReply.Id === reply.Id) { shouldReturn = false; } else { if (deletedIds.indexOf(currentReply.Id) !== -1) { shouldReturn = false; } } return shouldReturn; }); // Update state this.setState({ discussion: update(this.state.discussion, { Replies: { $set: updatedReplies }}), }); } /** * Updates a reply * @param reply the reply object to update */ public async updateReply(replyToUpdate: IDiscussionReply) { if (!$(replyToUpdate.Body).text()) { alert(i18n.t("comments_empty")); } else { await this.socialModule.updateReply(replyToUpdate.Id, replyToUpdate.Body); const updatedReplies = this.state.discussion.Replies.map((currentReply) => { const updatedReply = currentReply; if (currentReply.Id === replyToUpdate.Id) { updatedReply.Body = replyToUpdate.Body; updatedReply.Edited = new Date(); } return updatedReply; }); // Update state this.setState({ discussion: update(this.state.discussion, { Replies: { $set: updatedReplies }}), }); } } private async createNewDiscussion(title: string, body: string): Promise<IDiscussion> { return this.socialModule.createNewDiscussion(this.associatedPageId, title, body); } private async toggleLikeReply(reply: IDiscussionReply, isLiked: boolean): Promise<void> { const updatdeLikesCount = await this.socialModule.toggleLike(reply.Id, reply.ParentListId, isLiked); const updatedReplies = this.state.discussion.Replies.map((currentReply) => { const updatedReply = currentReply; const userId = _spPageContextInfo.userId.toString(); if (currentReply.Id === reply.Id) { updatedReply.LikesCount = updatdeLikesCount; updatedReply.LikedBy = isLiked ? update(updatedReply.LikedBy, {$push: [_spPageContextInfo.userId.toString()]}) : update(updatedReply.LikedBy, {$splice: [[updatedReply.LikedBy.indexOf(userId), 1]]}) ; } return updatedReply; }); // Update state this.setState({ discussion: update(this.state.discussion, { Replies: { $set: updatedReplies }}), }); } private async getPageDiscussion(associatedPageId: number): Promise<IDiscussion> { return this.socialModule.getDiscussionById(associatedPageId); } private async createNewDiscussionReply(parentId: number, replyBody: string): Promise<IDiscussionReply> { return this.socialModule.createNewDiscussionReply(parentId, replyBody); } private setDiscussionFeedAsTree(list: any[], rootParentID: number, idAttr?, parentAttr?, childrenAttr?): any[] { if (!idAttr) { idAttr = "Id"; } if (!parentAttr) { parentAttr = "ParentItemID"; } if (!childrenAttr) { childrenAttr = "Children"; } const treeList = []; const lookup = {}; list.forEach((obj) => { lookup[obj[idAttr]] = obj; obj[childrenAttr] = []; }); list.forEach((obj) => { if (obj[parentAttr] !== rootParentID) { if (lookup[obj[parentAttr]]) { lookup[obj[parentAttr]][childrenAttr].push(obj); } } else { treeList.push(obj); } }); return treeList; } } export default DiscussionBoard;
the_stack
import { beginAdd, botHashGenerated, open as openEditorDocument, openBotViaFilePathAction, newNotification, BotAction, BotActionType, SharedConstants, } from '@bfemulator/app-shared'; import { BotConfigWithPath, ConversationService } from '@bfemulator/sdk-shared'; import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'; import { CommandServiceImpl, CommandServiceInstance } from '@bfemulator/sdk-shared'; import { ActiveBotHelper } from '../../ui/helpers/activeBotHelper'; import { generateHash } from '../helpers/botHelpers'; import { botSagas, BotSagas } from './botSagas'; import { SharedSagas } from './sharedSagas'; jest.mock('../store', () => ({ get store() { return {}; }, })); jest.mock('electron', () => ({ ipcMain: new Proxy( {}, { get(): any { return () => ({}); }, has() { return true; }, } ), ipcRenderer: new Proxy( {}, { get(): any { return () => ({}); }, has() { return true; }, } ), })); (global as any).fetch = (function() { const fetch = (url, opts) => { return { ok: true, json: async () => ({ id: "Hi! I'm in ur json" }), text: async () => '{}', }; }; (fetch as any).Headers = class {}; (fetch as any).Response = class {}; return fetch; })(); const mockSharedConstants = SharedConstants; let mockRemoteCommandsCalled = []; let mockLocalCommandsCalled = []; describe('The botSagas', () => { let commandService: CommandServiceImpl; beforeAll(() => { const decorator = CommandServiceInstance(); const descriptor = decorator({ descriptor: {} }, 'none') as any; commandService = descriptor.descriptor.get(); commandService.call = async (commandName: string, ...args: any[]) => { mockLocalCommandsCalled.push({ commandName, args: args }); switch (commandName) { case mockSharedConstants.Commands.Bot.OpenBrowse: return Promise.resolve(true); default: return Promise.resolve(true) as any; } }; commandService.remoteCall = async (commandName: string, ...args: any[]) => { mockRemoteCommandsCalled.push({ commandName, args: args }); return Promise.resolve(true) as any; }; }); beforeEach(() => { mockRemoteCommandsCalled = []; mockLocalCommandsCalled = []; ConversationService.startConversation = jest.fn().mockResolvedValue(true); }); it('should initialize the root saga', () => { const gen = botSagas(); expect(gen.next().value).toEqual(takeEvery(BotActionType.browse, BotSagas.browseForBot)); expect(gen.next().value).toEqual(takeEvery(BotActionType.openViaUrl, BotSagas.openBotViaUrl)); expect(gen.next().value).toEqual(takeEvery(BotActionType.openViaFilePath, BotSagas.openBotViaFilePath)); expect(gen.next().value).toEqual(takeEvery(BotActionType.setActive, BotSagas.generateHashForActiveBot)); expect(gen.next().value).toEqual( takeLatest( [BotActionType.setActive, BotActionType.load, BotActionType.close], SharedSagas.refreshConversationMenu ) ); expect(gen.next().done).toBe(true); }); it('should generate a hash for an active bot', () => { const botConfigPath: BotConfigWithPath = { name: 'botName', description: 'a bot description here', padlock: null, services: [], path: '/some/Path/something', version: '0.1', }; const setActiveBotAction: BotAction<any> = { type: BotActionType.setActive, payload: { bot: botConfigPath, }, }; const gen = BotSagas.generateHashForActiveBot(setActiveBotAction); const generatedHash = gen.next().value; expect(generatedHash).toEqual(call(generateHash, botConfigPath)); const putGeneratedHash = gen.next(generatedHash).value; expect(putGeneratedHash).toEqual(put(botHashGenerated(generatedHash))); expect(gen.next().done).toBe(true); }); it('should open native open file dialog to browse for .bot file', () => { const gen = BotSagas.browseForBot(); expect(gen.next().value).toEqual(call([ActiveBotHelper, ActiveBotHelper.confirmAndOpenBotFromFile])); expect(gen.next().done).toBe(true); }); it('should open a bot from a file path', () => { const gen = BotSagas.openBotViaFilePath(openBotViaFilePathAction('/some/path.bot')); jest.spyOn(ActiveBotHelper, 'confirmAndOpenBotFromFile').mockResolvedValue(true); expect(gen.next().value).toEqual( call([ActiveBotHelper, ActiveBotHelper.confirmAndOpenBotFromFile], '/some/path.bot') ); }); it('should send a notification when opening a bot from a file path fails', () => { const gen = BotSagas.openBotViaFilePath(openBotViaFilePathAction('/some/path.bot')); const callOpenBot = gen.next().value; expect(callOpenBot).toEqual(call([ActiveBotHelper, ActiveBotHelper.confirmAndOpenBotFromFile], '/some/path.bot')); const putNotification = gen.throw(new Error('oh noes!')); const errorNotification = beginAdd( newNotification('An Error occurred opening the bot at /some/path.bot: Error: oh noes!') ); (errorNotification as any).payload.notification.timestamp = jasmine.any(Number); (errorNotification as any).payload.notification.id = jasmine.any(String); expect(putNotification.value).toEqual(put(errorNotification)); }); it('should open a bot via url with the custom user ID', () => { const mockAction: any = { payload: { endpoint: 'http://localhost:3978/api/messages', channelService: 'public', mode: 'livechat', appId: 'someAppId', appPassword: 'someAppPw', }, }; const gen = BotSagas.openBotViaUrl(mockAction); gen.next(); gen.next('userId'); // select custom user GUID // select server url expect(gen.next('http://localhost:52673').value).toEqual( call([ConversationService, ConversationService.startConversation], 'http://localhost:52673', { botUrl: mockAction.payload.endpoint, channelServiceType: mockAction.payload.channelService, members: [{ id: 'userId', name: 'User', role: 'user' }], mode: mockAction.payload.mode, msaAppId: mockAction.payload.appId, msaPassword: mockAction.payload.appPassword, }) ); const mockStartConvoResponse = { json: async () => undefined, ok: true, }; // startConversation gen.next(mockStartConvoResponse); gen.next({ conversationId: 'someConvoId', endpointId: 'someEndpointId', members: [], }); //res.json() let next = gen.next(); // bootstrapChat() const putOpenValue = next.value; expect(putOpenValue).toEqual( put( openEditorDocument({ contentType: SharedConstants.ContentTypes.CONTENT_TYPE_LIVE_CHAT, documentId: 'someConvoId', isGlobal: false, }) ) ); gen.next(); // put open() gen.next({ ok: true }); // sendInitialLogReport() next = gen.next({ ok: true }); // sendInitialActivity() const callValue = next.value; expect(callValue).toEqual( call( [commandService, commandService.remoteCall], SharedConstants.Commands.Settings.SaveBotUrl, 'http://localhost:3978/api/messages' ) ); expect(gen.next().done).toBe(true); }); it('should open a bot via url with a newly generated user GUID', () => { const mockAction: any = { payload: { endpoint: 'http://localhost:3978/api/messages', channelService: 'public', mode: 'livechat', appId: 'someAppId', appPassword: 'someAppPw', }, }; const gen = BotSagas.openBotViaUrl(mockAction); gen.next(); gen.next(''); // select custom user GUID (force generation of new GUID) // select server url const startConversationCall = gen.next('http://localhost:52673').value; const startConversationPayload = startConversationCall.CALL.args[1]; expect(startConversationPayload.members[0].id.length).toBeGreaterThan(0); const mockStartConvoResponse = { json: async () => undefined, ok: true, }; // startConversation gen.next(mockStartConvoResponse); gen.next({ conversationId: 'someConvoId', endpointId: 'someEndpointId', members: [], }); //res.json() let next = gen.next(); // bootstrapChat() const putOpenValue = next.value; expect(putOpenValue).toEqual( put( openEditorDocument({ contentType: SharedConstants.ContentTypes.CONTENT_TYPE_LIVE_CHAT, documentId: 'someConvoId', isGlobal: false, }) ) ); gen.next(); // put open() gen.next({ ok: true }); // sendInitialLogReport() next = gen.next({ ok: true }); // sendInitialActivity() const callValue = next.value; expect(callValue).toEqual( call( [commandService, commandService.remoteCall], SharedConstants.Commands.Settings.SaveBotUrl, 'http://localhost:3978/api/messages' ) ); expect(gen.next().done).toBe(true); }); it('should throw if starting the conversation fails', () => { const mockAction: any = { payload: { endpoint: 'http://localhost:3978/api/messages', channelService: 'public', mode: 'livechat', appId: 'someAppId', appPassword: 'someAppPw', }, }; const gen = BotSagas.openBotViaUrl(mockAction); gen.next(); gen.next('userId'); // select custom user GUID gen.next('http://localhost:52673'); // select server url const mockStartConvoResponse = { json: async () => undefined, ok: false, status: 500, statusText: 'INTERNAL SERVER ERROR', text: async () => undefined, }; gen.next(mockStartConvoResponse); // startConversation try { gen.next('Cannot read property "id" of undefined.'); expect(true).toBe(false); // ensure catch is hit } catch (e) { expect(e).toEqual({ description: '500 INTERNAL SERVER ERROR', message: 'Error occurred while starting a new conversation', innerMessage: 'Cannot read property "id" of undefined.', status: 500, }); } }); it('should throw if sending the initial log report fails', () => { const mockAction: any = { payload: { endpoint: 'http://localhost:3978/api/messages', channelService: 'public', mode: 'livechat', appId: 'someAppId', appPassword: 'someAppPw', }, }; const gen = BotSagas.openBotViaUrl(mockAction); gen.next(); gen.next('userId'); // select custom user GUID gen.next('http://localhost:52673'); // select server url const mockStartConvoResponse = { json: async () => undefined, ok: true, }; gen.next(mockStartConvoResponse); // startConversation gen.next({ conversationId: 'someConvoId', endpointId: 'someEndpointId', members: [], }); //res.json() const next = gen.next(); // bootstrapChat() const putOpenValue = next.value; expect(putOpenValue).toEqual( put( openEditorDocument({ contentType: SharedConstants.ContentTypes.CONTENT_TYPE_LIVE_CHAT, documentId: 'someConvoId', isGlobal: false, }) ) ); gen.next(); // put open() gen.next({ ok: false, status: 500, statusText: 'INTERNAL SERVER ERROR', text: async () => undefined, }); // sendInitialLogReport() try { gen.next('Could not read property "id" of undefined.'); expect(true).toBe(false); // ensure catch is hit } catch (e) { expect(e).toEqual({ description: '500 INTERNAL SERVER ERROR', message: 'Error occurred while sending the initial log report', innerMessage: 'Could not read property "id" of undefined.', status: 500, }); } }); it('should throw if sending the initial activity fails', () => { const mockAction: any = { payload: { endpoint: 'http://localhost:3978/api/messages', channelService: 'public', mode: 'livechat', appId: 'someAppId', appPassword: 'someAppPw', }, }; const gen = BotSagas.openBotViaUrl(mockAction); gen.next(); gen.next('userId'); // select custom user GUID gen.next('http://localhost:52673'); // select server url const mockStartConvoResponse = { json: async () => undefined, ok: true, }; gen.next(mockStartConvoResponse); // startConversation gen.next({ conversationId: 'someConvoId', endpointId: 'someEndpointId', members: [], }); //res.json() const next = gen.next(); // bootstrapChat() const putOpenValue = next.value; expect(putOpenValue).toEqual( put( openEditorDocument({ contentType: SharedConstants.ContentTypes.CONTENT_TYPE_LIVE_CHAT, documentId: 'someConvoId', isGlobal: false, }) ) ); gen.next(); // put open() gen.next({ ok: true }); // sendInitialLogReport() gen.next({ ok: false, status: 500, statusText: 'INTERNAL SERVER ERROR', text: async () => undefined, }); // sendInitialActivity() try { gen.next('Could not read property "id" of undefined.'); expect(true).toBe(false); // ensure catch is hit } catch (e) { expect(e).toEqual({ description: '500 INTERNAL SERVER ERROR', message: 'Error occurred while sending the initial activity', innerMessage: 'Could not read property "id" of undefined.', status: 500, }); } }); });
the_stack
import { Transform, TransformOptions } from 'stream'; import * as make from 'stream-json'; import * as Assembler from 'stream-json/Assembler'; import * as Disassembler from 'stream-json/Disassembler'; import * as Emitter from 'stream-json/Emitter'; import * as Parser from 'stream-json/Parser'; import * as Stringer from 'stream-json/Stringer'; import * as JsonlParser from 'stream-json/jsonl/Parser'; import * as JsonlStringer from 'stream-json/jsonl/Stringer'; import * as FilterBase from 'stream-json/filters/FilterBase'; import * as Pick from 'stream-json/filters/Pick'; import * as Replace from 'stream-json/filters/Replace'; import * as Ignore from 'stream-json/filters/Ignore'; import * as Filter from 'stream-json/filters/Filter'; import * as StreamArray from 'stream-json/streamers/StreamArray'; import * as StreamObject from 'stream-json/streamers/StreamObject'; import * as StreamValues from 'stream-json/streamers/StreamValues'; import * as Batch from 'stream-json/utils/Batch'; import * as Verifier from 'stream-json/utils/Verifier'; import * as emit from 'stream-json/utils/emit'; import * as withParser from 'stream-json/utils/withParser'; import * as Utf8Stream from 'stream-json/utils/Utf8Stream'; const used = (array: any[]) => array.forEach(value => console.log(!!value)); { // creating parser with the main module const p1 = make(); const p2 = new make.Parser(); const p3 = make.parser(); const p4 = make({}); const p5 = new make.Parser({}); const p6 = make.parser({}); const p7: make.Parser = make(); const p8: make.Parser = new make.Parser(); const p9: make.Parser = make.parser(); used([p1, p2, p3, p4, p5, p6, p7, p8, p9]); } { // Assembler tests const parser: Parser = new Parser({ streamValues: false }); const asm: Assembler = Assembler.connectTo(parser); asm.consume({ name: 'startObject' }); asm.dropToLevel(0); parser.on('keyValue', (value: string) => console.log(value, asm.key, asm.stack.length, asm.done, asm.depth, asm.path), ); asm.on('done', (asm: Assembler) => console.log(JSON.stringify(asm.current))); const asm2: Assembler = new Assembler(); const asm3: Assembler = new Assembler({reviver: (key, value) => value}); used([asm2, asm3]); } { // Emitter tests const parser: Parser = new Parser(); const e1: Emitter = new Emitter(); const e2: Emitter = Emitter.make({}); const e3: Emitter = Emitter.emitter(); const e4: Emitter.make.Constructor = Emitter.make({}); const e5: Emitter.emitter.Constructor = Emitter.emitter({}); parser.pipe(e1); parser.pipe(e2); parser.pipe(e3); parser.pipe(e4); parser.pipe(e5); e1.on('startArray', () => console.log('array')); } { // Parser tests const p1: Parser = new Parser({ packValues: false }); const p2: Parser = Parser.make({ jsonStreaming: true }); const p3: Parser = Parser.parser({ streamValues: false }); const p4: Parser.make.Constructor = Parser.make({ packValues: false, packKeys: true }); const p5: Parser.parser.Constructor = Parser.parser({ packValues: false, packKeys: true, streamKeys: false }); used([p1, p2, p3, p4, p5]); } { // Disassembler tests const d1: Disassembler = new Disassembler({ packValues: false }); const d2: Disassembler = Disassembler.make({ jsonStreaming: true, replacer: (acc, next) => `${acc}${next}`, }); const d3: Disassembler = Disassembler.disassembler({ streamValues: false, replacer: ['foo', 'bar'], }); const d4: Disassembler.make.Constructor = Disassembler.make(); const d5: Disassembler.disassembler.Constructor = Disassembler.disassembler(); used([d1, d2, d3, d4, d5]); } { // Stringer tests const s1: Stringer = new Stringer(); const s2: Stringer = Stringer.make({ useValues: true }); const s3: Stringer = Stringer.stringer({ useKeyValues: true }); const s4: Stringer.make.Constructor = Stringer.make(); const s5: Stringer.stringer.Constructor = Stringer.stringer(); const s6: Stringer = Stringer.stringer({ makeArray: true }); used([s1, s2, s3, s4, s5, s6]); } { // Pick tests const parser: Parser = new Parser(); const f1: Pick = new Pick({ filter: 'data' }); const f2: Pick = Pick.make({ filter: 'data' }); const f3: Pick = Pick.pick({ filter: 'data' }); const f4: Pick.make.Constructor = Pick.make({ filter: 'data' }); const f5: Pick.pick.Constructor = Pick.pick({ filter: 'data' }); used([f1, f2, f3, f4, f5]); parser .pipe(new Pick({ filter: 'data' })) .pipe(Pick.make({ filter: /\bvalues\b/i })) .pipe(Pick.pick({ filter: (stack: FilterBase.Stack, token: FilterBase.Token) => token.name === 'startArray' })); Pick.withParser({ filter: 'data' }); } { // Replace tests const parser: Parser = new Parser(); const f1: Replace = new Replace({ filter: 'data' }); const f2: Replace = Replace.make({ filter: 'data' }); const f3: Replace = Replace.replace({ filter: 'data' }); const f4: Replace.make.Constructor = Replace.make({ filter: 'data' }); const f5: Replace.replace.Constructor = Replace.replace({ filter: 'data' }); used([f1, f2, f3, f4, f5]); parser .pipe(new Replace({ filter: 'total', replacement: [{ name: 'trueValue' }] })) .pipe( new Replace({ filter: 'sum', replacement: [ { name: 'startNumber' }, { name: 'numberChunk', value: '0' }, { name: 'endNumber' }, { name: 'numberValue', value: '0' }, ], }), ) .pipe(Replace.make({ filter: /\b_\w*\b/i, allowEmptyReplacement: true })) .pipe( Replace.replace({ filter: (stack: FilterBase.Stack, token: FilterBase.Token) => stack.length > 2, replacement: (stack: FilterBase.Stack, token: FilterBase.Token) => [ { name: token.name === 'startArray' ? 'trueValue' : 'falseValue' }, ], }), ); Replace.withParser({ filter: '_meta' }); } { // Ignore tests const parser: Parser = new Parser({ streamValues: false }); const f1: Ignore = new Ignore({ filter: 'data' }); const f2: Ignore = Ignore.make({ filter: 'data' }); const f3: Ignore = Ignore.ignore({ filter: 'data' }); const f4: Ignore.make.Constructor = Ignore.make({ filter: 'data' }); const f5: Ignore.ignore.Constructor = Ignore.ignore({ filter: 'data' }); used([f1, f2, f3, f4, f5]); parser .pipe(new Ignore({ filter: 'total' })) .pipe(Ignore.make({ filter: /\b_\w*\b/i })) .pipe(Ignore.ignore({ filter: (stack: FilterBase.Stack, token: FilterBase.Token) => stack.length > 2 })); Ignore.withParser({ filter: '_meta' }); } { // Filter tests const parser: Parser = new Parser({ streamValues: false }); const f1: Filter = new Filter({ filter: 'data' }); const f2: Filter = Filter.make({ filter: 'data' }); const f3: Filter = Filter.filter({ filter: 'data' }); const f4: Filter.make.Constructor = Filter.make({ filter: 'data' }); const f5: Filter.filter.Constructor = Filter.filter({ filter: 'data' }); used([f1, f2, f3, f4, f5]); parser .pipe(new Filter({ filter: 'total' })) .pipe(Filter.make({ filter: /\b_\w*\b/i })) .pipe(Filter.filter({ filter: (stack: FilterBase.Stack, token: FilterBase.Token) => stack.length > 2 })); Filter.withParser({ filter: '_meta' }); } { // StreamArray tests const parser: Parser = new Parser(); const s1: StreamArray = new StreamArray(); const s2: StreamArray = StreamArray.make(); const s3: StreamArray = StreamArray.streamArray(); const s4: StreamArray.make.Constructor = StreamArray.make(); const s5: StreamArray.streamArray.Constructor = StreamArray.streamArray(); used([s1, s2, s3, s4, s5]); parser.pipe( new StreamArray({ includeUndecided: true, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe( StreamArray.make({ includeUndecided: false, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe(StreamArray.streamArray()); StreamArray.withParser(); } { // StreamObject tests const parser: Parser = new Parser(); const s1: StreamObject = new StreamObject(); const s2: StreamObject = StreamObject.make(); const s3: StreamObject = StreamObject.streamObject(); const s4: StreamObject.make.Constructor = StreamObject.make(); const s5: StreamObject.streamObject.Constructor = StreamObject.streamObject(); used([s1, s2, s3, s4, s5]); parser.pipe( new StreamObject({ includeUndecided: true, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe( StreamObject.make({ includeUndecided: false, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe(StreamObject.streamObject()); StreamObject.withParser(); } { // StreamValues tests const parser: Parser = new Parser(); const s1: StreamValues = new StreamValues(); const s2: StreamValues = StreamValues.make(); const s3: StreamValues = StreamValues.streamValues(); const s4: StreamValues.make.Constructor = StreamValues.make(); const s5: StreamValues.streamValues.Constructor = StreamValues.streamValues(); used([s1, s2, s3, s4, s5]); parser.pipe( new StreamValues({ includeUndecided: true, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe( StreamValues.make({ includeUndecided: false, objectFilter: (asm: Assembler) => { if (asm.current) { if (asm.current.action === 'accept') return true; if (asm.current.action === 'reject') return false; } }, }), ); parser.pipe(StreamValues.streamValues()); StreamValues.withParser(); } { // Batch tests const b1: Batch = new Batch(); const b2: Batch = Batch.make({ batchSize: 1000 }); const b3: Batch = Batch.batch({ batchSize: 100 }); const b4: Batch.make.Constructor = Batch.make(); const b5: Batch.batch.Constructor = Batch.batch(); used([b1, b2, b3, b4, b5]); } { // Verifier tests const v1: Verifier = new Verifier(); const v2: Verifier = Verifier.make({ jsonStreaming: true }); const v3: Verifier = Verifier.verifier({ jsonStreaming: false }); const v4: Verifier.make.Constructor = Verifier.make(); const v5: Verifier.verifier.Constructor = Verifier.verifier(); used([v1, v2, v3, v4, v5]); } { // emit() tests const parser: Parser = emit(new Parser()); parser.on('keyValue', () => console.log('key')); } { // withParser() tests withParser(Pick.make, { filter: 'data' }); withParser(Pick.pick, { filter: 'data', packValues: false }); withParser(StreamArray.streamArray, { objectFilter: (asm: Assembler) => asm.current }); withParser(StreamArray.make, { objectFilter: (asm: Assembler) => asm.current, packValues: false }); withParser((options?: TransformOptions) => new Transform(options), { streamValues: false }); } { // Utf8Stream tests const u1: Utf8Stream = new Utf8Stream(); used([u1]); } { // JsonlParser tests const p1: JsonlParser = new JsonlParser(); const p2: JsonlParser = JsonlParser.make({reviver: (key, value) => value}); const p3: JsonlParser = JsonlParser.parser(); const p4: JsonlParser.make.Constructor = JsonlParser.make(); const p5: JsonlParser.parser.Constructor = JsonlParser.parser(); used([p1, p2, p3, p4, p5]); } { // JsonlStringer tests const p1: JsonlStringer = new JsonlStringer(); const p2: JsonlStringer = JsonlStringer.make({replacer: (key, value) => value}); const p3: JsonlStringer = JsonlStringer.stringer(); const p4: JsonlStringer.make.Constructor = JsonlStringer.make(); const p5: JsonlStringer.stringer.Constructor = JsonlStringer.stringer(); used([p1, p2, p3, p4, p5]); }
the_stack
/// <reference types="phantomjs" /> export function create(options?: CasperOptions): Casper; export function selectXPath(expression: string): object; export class Casper { constructor(options: CasperOptions); test: Tester; options: CasperOptions; // Properties __utils__: ClientUtils; // Methods back(): Casper; base64encode(url: string, method?: string, data?: any): string; bypass(nb: number): Casper; click(selector: string, X?: number | string, Y?: number | string): boolean; clickLabel(label: string, tag?: string): boolean; capture(targetFilePath: string, clipRect?: ClipRect, imgOptions?: ImgOptions): Casper; captureBase64(format: string, area?: string | ClipRect | CasperSelector): string; captureSelector(targetFile: string, selector: string, imgOptions?: ImgOptions): Casper; clear(): Casper; clearCache(): Casper; clearMemoryCache(): Casper; debugHTML(selector?: string, outer?: boolean): Casper; debugPage(): Casper; die(message: string, status?: number): Casper; download(url: string, target: string, method?: string, data?: any): Casper; each<T>(array: T[], fn: (this: Casper, item: T, index: number) => void): Casper; eachThen(array: any[], then?: FunctionThen): Casper; echo(message: string, style?: string): Casper; evaluate<T>(fn: (...args: any[]) => T, ...args: any[]): T; evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; exit(status?: number): Casper; exists(selector: string): boolean; fetchText(selector: string): string; forward(): Casper; log(message: string, level?: string, space?: string): Casper; fill(selector: string, values: any, submit?: boolean): void; fillSelectors(selector: string, values: any, submit?: boolean): void; fillXPath(selector: string, values: any, submit?: boolean): void; getCurrentUrl(): string; getElementAttribute(selector: string, attribute: string): string; getElementsAttribute(selector: string, attribute: string): string; getElementBounds(selector: string, page?: boolean): ElementBounds | null; getElementsBounds(selector: string): ElementBounds[]; getElementInfo(selector: string): ElementInfo; getElementsInfo(selector: string): ElementInfo; getFormValues(selector: string): any; getGlobal(name: string): any; getHTML(selector?: string, outer?: boolean): string; getPageContent(): string; getTitle(): string; mouseEvent(type: string, selector: string, X?: number|string, Y?: number|string): boolean; newPage(): any; open(location: string, settings: OpenSettings): Casper; reload(then?: FunctionThen): Casper; repeat(times: number, then: FunctionThen): Casper; resourceExists(test: string | Function | RegExp): boolean; run(onComplete?: Function, time?: number): Casper; scrollTo(x: number, y: number): Casper; scrollToBottom(): Casper; sendKeys(selector: string, keys: string, options?: KeyOptions): Casper; setHttpAuth(username: string, password: string): Casper; setMaxListeners(maxListeners: number): Casper; start(url?: string, then?: FunctionThen): Casper; status(asString?: false): number; status(asString: true): string; switchToFrame(frameInfo: string | number): Casper; switchToMainFrame(): Casper; switchToParentFrame(): Casper; then(fn: (this: Casper) => void): Casper; thenBypass(nb: number): Casper; thenBypassIf(condition: any, nb: number): Casper; thenBypassUnless(condition: any, nb: number): Casper; thenClick(selector: string, then?: FunctionThen): Casper; thenEvaluate(fn: () => any, ...args: any[]): Casper; thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; thenOpenAndEvaluate(location: string, then?: FunctionThen, ...args: any[]): Casper; toString(): string; unwait(): Casper; // 2017-10-19 Doc said returning String but code return Casper object. userAgent(agent: string): Casper; viewport(width: number, height: number, then?: FunctionThen): Casper; visible(selector: string): boolean; wait(timeout: number, then?: FunctionThen): Casper; waitFor(testFx: Function, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number, details?: any): Casper; waitForAlert(then: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForExec(command: string | null, parameter: string[], then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForPopup(urlPattern: RegExp | string | number | FindByUrlNameTitle, then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; waitForResource(testFx: RegExp | string | ((resource: {url: string}) => boolean), then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; waitForUrl(url: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitWhileSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForSelectorTextChange(selectors: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForText(pattern: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitUntilVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitWhileVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; warn(message: string): Casper; withFrame(frameInfo: string | number, then: FunctionThen): Casper; withPopup(popupInfo: RegExp | string | number | FindByUrlNameTitle, step: FunctionThen): Casper; withSelectorScope(selector: string, then: FunctionThen): Casper; zoom(factor: number): Casper; // do not exists anymore // removeAllFilters(filter: string): Casper; // do not exists anymore // setFilter(filter: string, cb: Function): boolean; } export type FunctionThen = (this: Casper, response: HttpResponse) => void; export type FunctionOnTimeout = (this: Casper, timeout: number, details: any) => void; // not visible in doc // interface QtRuntimeObject {id?: any; url?: string;} // see modules/pagestack.js in casperjs export interface ImgOptions { // format to set the image format manually, avoiding relying on the filename format?: string | undefined; // quality to set the image quality, from 1 to 100 quality?: number | undefined; } export interface FindByUrlNameTitle { url?: string | undefined; title?: string | undefined; windowName?: string | undefined; } export interface Header { name: string; value: string; } export interface CasperSelector { type?: 'xpath' | 'css' | undefined; path: string; } export interface KeyOptions { reset?: boolean | undefined; keepFocus?: boolean | undefined; modifiers?: string | undefined; // combinaison of 'ctrl+alt+shift+meta+keypad' } export interface HttpResponse { contentType: string; headers: Header[]; id: number; redirectURL: string | null; stage: string; status: number; statusText: string; time: string; url: string; data: any; } export interface OpenSettings { method: string; data: any; headers: any; } export interface ElementBounds { top: number; left: number; width: number; height: number; } export interface ElementInfo { nodeName: string; attributes: any; tag: string; html: string; text: string; x: number; y: number; width: number; height: number; visible: boolean; } export interface CasperOptions { clientScripts?: any[] | undefined; exitOnError?: boolean | undefined; httpStatusHandlers?: any; logLevel?: string | undefined; onAlert?: Function | undefined; onDie?: Function | undefined; onError?: Function | undefined; onLoadError?: Function | undefined; onPageInitialized?: Function | undefined; onResourceReceived?: Function | undefined; onResourceRequested?: Function | undefined; onStepComplete?: Function | undefined; onStepTimeout?: Function | undefined; onTimeout?: Function | undefined; onWaitTimeout?: Function | undefined; page?: WebPage | undefined; pageSettings?: any; remoteScripts?: any[] | undefined; safeLogs?: boolean | undefined; silentErrors?: boolean | undefined; stepTimeout?: number | undefined; timeout?: number | undefined; verbose?: boolean | undefined; viewportSize?: any; retryTimeout?: number | undefined; waitTimeout?: number | undefined; } export interface ClientUtils { echo(message: string): void; encode(contents: string): void; exists(selector: string): void; findAll(selector: string): void; findOne(selector: string): void; getBase64(url: string, method?: string, data?: any): void; getBinary(url: string, method?: string, data?: any): void; getDocumentHeight(): void; getElementBounds(selector: string): void; getElementsBounds(selector: string): void; getElementByXPath(expression: string, scope?: HTMLElement): void; getElementsByXPath(expression: string, scope?: HTMLElement): void; getFieldValue(inputName: string): void; getFormValues(selector: string): void; mouseEvent(type: string, selector: string): void; removeElementsByXPath(expression: string): void; sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; visible(selector: string): void; } export interface Colorizer { colorize(text: string, styleName: string): void; format(text: string, style: any): void; } export interface Tester { assert(condition: boolean, message?: string): any; assertDoesntExist(selector: string, message?: string): any; assertElementCount(selctor: string, expected: number, message?: string): any; assertEquals(testValue: any, expected: any, message?: string): any; assertEval(fn: Function, message: string, args: any): any; assertEvalEquals(fn: Function, expected: any, message?: string, args?: any): any; assertExists(selector: string, message?: string): any; assertFalsy(subject: any, message?: string): any; assertField(inputName: string, expected: string, message?: string): any; assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; assertFieldCSS(cssSelector: string, expected: string, message?: string): any; assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; assertHttpStatus(status: number, message?: string): any; assertMatch(subject: any, pattern: RegExp, message?: string): any; assertNot(subject: any, message?: string): any; assertNotEquals(testValue: any, expected: any, message?: string): any; assertNotVisible(selector: string, message?: string): any; assertRaises(fn: Function, args: any[], message?: string): any; assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; assertSelectorExists(selector: string, message?: string): any; assertSelectorHasText(selector: string, text: string, message?: string): any; assertResourceExists(testFx: Function, message?: string): any; assertTextExists(expected: string, message?: string): any; assertTextDoesntExist(unexpected: string, message: string): any; assertTitle(expected: string, message?: string): any; assertTitleMatch(pattern: RegExp, message?: string): any; assertTruthy(subject: any, message?: string): any; assertType(input: any, type: string, message?: string): any; assertInstanceOf(input: any, ctor: Function, message?: string): any; assertUrlMatch(pattern: RegExp | string, message?: string): any; assertVisible(selector: string, message?: string): any; /* since 1.1 */ begin(description: string, planned: number, suite: Function): any; begin(description: string, suite: Function): any; begin(description: string, planned: number, config: object): any; begin(description: string, config: object): any; colorize(message: string, style: string): any; comment(message: string): any; done(expected?: number): any; error(message: string): any; fail(message: string): any; formatMessage(message: string, style: string): any; getFailures(): Cases; getPasses(): Cases; info(message: string): any; pass(message: string): any; renderResults(exit: boolean, status: number, save: string): any; setup(fn: Function): any; skip(nb: number, message: string): any; tearDown(fn: Function): any; } export interface Cases { length: number; cases: Case[]; } export interface Case { success: boolean; type: string; standard: string; file: string; values: CaseValues; } export interface CaseValues { subject: boolean; expected: boolean; } export interface Utils { betterTypeOf(input: any): any; dump(value: any): any; fileExt(file: string): any; fillBlanks(text: string, pad: number): any; format(f: string, ...args: any[]): any; getPropertyPath(obj: any, path: string): any; inherits(ctor: any, superCtor: any): any; isArray(value: any): any; isCasperObject(value: any): any; isClipRect(value: any): any; isFalsy(subject: any): any; isFunction(value: any): any; isJsFile(file: string): any; isNull(value: any): any; isNumber(value: any): any; isObject(value: any): any; isRegExp(value: any): any; isString(value: any): any; isTruthy(subject: any): any; isType(what: any, type: string): any; isUndefined(value: any): any; isWebPage(what: any): any; mergeObjects(origin: any, add: any): any; node(name: string, attributes: any): any; serialize(value: any): any; unique(array: any[]): any; }
the_stack
import React from "react"; import { Button, FormGroup, InputGroup, ProgressBar, Intent, Position, Drawer, Popover, Menu, MenuItem, Spinner, Classes, Tabs, Tab, TabId, Icon, IconName, Alert, Alignment, Tag, Navbar, NavbarGroup, IconSize, PopoverInteractionKind, Tooltip, } from "@blueprintjs/core"; import { APIGetRegisteredModels, APIRegisterModel, APIUnloadModel, APILoadModel, APIDeleteRegisteredModel, APIGetModelTags, APIGetLoadedModel, } from "@portal/api/annotation"; import { TagColours } from "@portal/constants/annotation"; import isElectron from "is-electron"; import { CreateGenericToast } from "@portal/utils/ui/toasts"; import classes from "./model.module.css"; export type RegisteredModel = { name: string; hash: string; description: string; directory: string; }; export type FormData = { type: string; name: string; description: string; directory: string; modelKey: string; projectSecret: string; modelURL: string; modelType: "tensorflow" | "darknet" | ""; }; interface ModelProps { project: string; useDarkTheme: boolean; isConnected: boolean; callbacks: { HandleModelChange: (model: RegisteredModel | undefined) => void; }; } interface ModelState { /** Dict of registered model to be obtained from server (key: hashkey) */ registeredModelList: { [key: string]: RegisteredModel } | any; /** This referes to the current loaded model */ currentModel: RegisteredModel | undefined; /** This referes to the model chosen to be viewed or loaded */ chosenModel: RegisteredModel | undefined; /** Contains data from the model registration form */ formData: FormData; /** Tab id */ drawerTabId: TabId; /** Tab id */ registrationTabId: TabId; /** General icon format (used in the registration form to show outcome) */ generalIcon: { name: IconName; intent: Intent } | undefined; /** Model Tag map */ projectTags: { [tag: string]: number } | any; /** Waits for the run time seperately from the heartbeat (so that model list is updated when server loads) */ waitForRuntime: boolean; /** The following are self explanatory boolean states */ isConfirmLoad: boolean; isConfirmDelete: boolean; isConfirmUnload: boolean; isUnloadModelAPI: boolean; isLoadModelAPI: boolean; isAPIcalled: boolean; isGetTagAPI: boolean; isOpenDrawer: boolean; isOpenRegistraionForm: boolean; } export default class Model extends React.Component<ModelProps, ModelState> { constructor(props: ModelProps) { super(props); this.state = { registeredModelList: {}, currentModel: undefined, chosenModel: undefined, waitForRuntime: true, isConfirmLoad: false, isConfirmUnload: false, isConfirmDelete: false, isAPIcalled: false, isUnloadModelAPI: false, isLoadModelAPI: false, isGetTagAPI: false, isOpenDrawer: false, isOpenRegistraionForm: false, generalIcon: undefined, projectTags: {}, formData: { type: "local", modelType: "tensorflow", name: "", description: "", directory: "", modelKey: "", projectSecret: "", modelURL: "", }, drawerTabId: "details", registrationTabId: "local", }; this.createMenuItems = this.createMenuItems.bind(this); this.handleRegisterModel = this.handleRegisterModel.bind(this); this.handleElectronFileDialog = this.handleElectronFileDialog.bind(this); this.handleUnloadAndLoadModel = this.handleUnloadAndLoadModel.bind(this); this.handleDeleteModel = this.handleDeleteModel.bind(this); this.formatLongStringName = this.formatLongStringName.bind(this); // this.handleElectronChangeDirListener = this.handleElectronChangeDirListener.bind(this); } async componentDidMount(): Promise<void> { if (isElectron()) { const { ipcRenderer } = window.require("electron"); ipcRenderer.on( "select-model-reply", this.handleElectronChangeDirListener ); } while (this.state.waitForRuntime) { // eslint-disable-next-line no-await-in-loop await APIGetRegisteredModels() .then(async result => { if (result.status === 200) { this.setState({ registeredModelList: this.generateRegisteredModelList( result.data ), }); if (this.state.registeredModelList !== {}) { // eslint-disable-next-line no-await-in-loop await this.handleGetLoadedModel(); } this.setState({ waitForRuntime: false }); } }) .catch(() => { /** Do Nothing */ }); // eslint-disable-next-line no-await-in-loop await new Promise(res => setTimeout(res, 25000)); } } componentWillUnmount(): void { if (isElectron()) { const { ipcRenderer } = window.require("electron"); ipcRenderer.removeListener( "select-model-reply", this.handleElectronChangeDirListener ); } } /** -------- Methods related to API calls -------- */ /** Calls the Model Registration API with info recorded in formData */ private handleRegisterModel = async () => { this.setState({ isAPIcalled: true }); if ( this.state.formData.type === "hub" && (this.state.formData.modelKey === "" || this.state.formData.projectSecret === "" || this.state.formData.name === "") ) { CreateGenericToast( "Please fill in the name, model key and project secret of the model you want to load from hub.", Intent.WARNING, 3000 ); } else if ( this.state.formData.type === "local" && (this.state.formData.name === "" || this.state.formData.directory === "") ) { CreateGenericToast( "Please fill in the name and path of the model.", Intent.WARNING, 3000 ); } else if ( this.state.formData.type === "endpoint" && (this.state.formData.modelURL === "" || this.state.formData.projectSecret === "" || this.state.formData.name === "") ) { CreateGenericToast( "Please fill in the name, URL and project secret of the model you want to load from endpoint.", Intent.WARNING, 3000 ); } else { await APIRegisterModel( this.state.formData.type, this.state.formData.modelType, this.state.formData.name, this.state.formData.description, this.state.formData.directory, this.state.formData.modelKey, this.state.formData.projectSecret, this.state.formData.modelURL ) .then(result => { if (result.status === 200) { this.setState({ registeredModelList: this.generateRegisteredModelList( result.data ), generalIcon: { name: "tick", intent: Intent.SUCCESS }, }); } }) .catch(error => { this.setState({ generalIcon: { name: "cross", intent: Intent.DANGER }, }); let message = "Failed to register model."; if (error.response) { if (error.response.data.error_code === 3001) { if (this.state.formData.modelType === "tensorflow") message = "Are you sure this is a TensorFlow Model?"; else if (this.state.formData.modelType === "darknet") message = "Are you sure this is a Darknet Model?"; } else { message = `${error.response.data.message}`; } } CreateGenericToast(message, Intent.DANGER, 3000); }); } this.setState({ isAPIcalled: false }); }; /** Calls the get all loaded models API * Note: Even though the api returns a list, there should only be one loaded model * This is ensured in handleUnloadAndLoadModel() * */ private handleGetLoadedModel = async () => { this.setState({ isLoadModelAPI: true }); await APIGetLoadedModel().then(result => { if (result.status === 200) { this.setState(prevState => { const model = prevState.registeredModelList[result.data[0]]; this.props.callbacks.HandleModelChange(model); return { currentModel: model }; }); } }); this.setState({ isLoadModelAPI: false }); }; /** Calls the get all registered models API */ private handleRefreshModelList = async () => { this.setState({ isAPIcalled: true }); await APIGetRegisteredModels() .then(result => { if (result.status === 200) { this.setState({ registeredModelList: this.generateRegisteredModelList(result.data), }); } }) .catch(error => { let message = "Failed to refresh model list."; if (error.response) { message = `${error.response.data.message}`; } CreateGenericToast(message, Intent.DANGER, 3000); }); this.setState({ isAPIcalled: false }); }; /** Calls the unloaded models API * The model it unloads is the currentModel */ private handleUnloadModel = async () => { this.setState({ isUnloadModelAPI: true }); if (this.state.currentModel !== undefined) { await APIUnloadModel(this.state.currentModel.hash) .then(result => { if (result.status === 200) { this.setState({ currentModel: undefined, }); this.props.callbacks.HandleModelChange(undefined); } }) .catch(error => { let message = "Failed to unload current model."; if (error.response) { message = `${error.response.data.message}`; } CreateGenericToast(message, Intent.DANGER, 3000); }); } this.setState({ isUnloadModelAPI: false, isConfirmUnload: false, isOpenDrawer: false, }); }; /** Unloads the currentModel and loads the chosenModel * Calls handleUnloadModel() to unload * Calls the load model API * */ private handleUnloadAndLoadModel = async () => { this.setState({ isLoadModelAPI: true }); if (this.state.chosenModel === undefined) { CreateGenericToast( "There is no model chosen to be loaded", Intent.WARNING, 3000 ); this.setState({ isLoadModelAPI: false, isConfirmLoad: false }); return; } await this.handleUnloadModel(); const key = this.state.chosenModel?.hash; await APILoadModel(key) .then(result => { if (result.status === 200) { const model = this.state.registeredModelList[key]; if (model) { this.setState({ currentModel: model, }); this.props.callbacks.HandleModelChange(model); } else { CreateGenericToast( "Loaded model not found in list of registered model", Intent.DANGER, 3000 ); } } }) .catch(error => { let message = "Cannot load model."; if (error.response) { message = `${error.response.data.message}`; } CreateGenericToast(message, Intent.DANGER, 3000); }); this.setState({ isLoadModelAPI: false, isConfirmLoad: false }); }; /** Deletes a registered model aka chosenModel * If the chosenModel is the currentModel loaded, it will unload it before deletion * Calls handleUnloadModel() to unload * Calls the delete model API * Calls get all registered model api to update the registeredModelList * */ private handleDeleteModel = async () => { this.setState({ isAPIcalled: true, isConfirmDelete: true }); if (this.state.chosenModel !== undefined) { if (this.state.currentModel?.hash === this.state.chosenModel.hash) { this.handleUnloadModel; } await APIDeleteRegisteredModel(this.state.chosenModel.hash) .then(result => { if (result.status === 200) { this.handleRefreshModelList(); } }) .catch(error => { let message = "Failed to delete model."; if (error.response) { message = `${error.response.data.message}`; } CreateGenericToast(message, Intent.DANGER, 3000); }); await APIGetRegisteredModels() .then(async result => { if (result.status === 200) { this.setState({ registeredModelList: this.generateRegisteredModelList( result.data ), }); if (this.state.registeredModelList !== {}) { // eslint-disable-next-line no-await-in-loop await this.handleGetLoadedModel(); } } }) .catch(() => { /** Do Nothing */ }); } this.setState({ isOpenDrawer: false, isAPIcalled: false, isConfirmDelete: false, currentModel: undefined, chosenModel: undefined, }); }; /** Calls the get all model tags for the chosenModel to update the projectTags */ private handleGetModelTags = async () => { this.setState({ isGetTagAPI: true }); if (this.state.chosenModel !== undefined) { await APIGetModelTags(this.state.chosenModel.hash) .then(result => { if (result.status === 200) { this.setState({ projectTags: result.data }); } }) .catch(error => { let message = "Failed to get model tags."; if (error.response) { message = `${error.response.data.message}`; } CreateGenericToast(message, Intent.DANGER, 3000); }); } this.setState({ isGetTagAPI: false }); }; /** ------- Methods related to Registered Model List ------- */ /** Updates the formData. Called when there is a change in the registration form */ private handleChangeForm = (event: any) => { // eslint-disable-next-line react/no-access-state-in-setstate, prefer-const let form: any = this.state.formData; form[event.target.name] = event.target.value; this.setState({ formData: form }); }; /** Sets up a call for electron to browse the file dialog directory */ private handleElectronFileDialog = () => { if (isElectron()) { const { ipcRenderer } = window.require("electron"); ipcRenderer.send("select-model"); } else { CreateGenericToast( "This feature is not alvailable in web browser.", Intent.WARNING, 3000 ); } }; /** Listener for electron to updates the formData.directory when ipcrender sends a reply */ private handleElectronChangeDirListener = (event: any, args: string[]) => { this.setState(prevState => { // eslint-disable-next-line prefer-const let form: any = prevState.formData; // eslint-disable-next-line prefer-destructuring form.directory = args[0]; return { formData: form }; }); }; /** Generate the registered model list * @params data : data from the api call * @return dict : registered model list in a dictionary format */ private generateRegisteredModelList = (data: any) => { const modelArr: string[] = Object.keys(data); // eslint-disable-next-line prefer-const let dict: any = {}; modelArr.forEach(key => { dict[key] = { name: data[key].name, description: data[key].description, hash: key, directory: data[key].directory, }; }); return dict; }; /** Render Tab Input Settings based on registrationTabId. * @param registrationTabId : the tab id of the tab to be rendered * @return jsx : the tab input settings */ private renderTabSettings = ( registrationTabId: TabId, browseButton: JSX.Element, browseHint: JSX.Element ) => { switch (registrationTabId) { case "local": return ( <FormGroup label="Folder Path" labelFor="label-input"> <InputGroup id="directory" name="directory" value={this.state.formData.directory} placeholder={"Enter model folder path..."} onChange={this.handleChangeForm} rightElement={isElectron() ? browseButton : browseHint} /> </FormGroup> ); case "hub": return ( <> <FormGroup label="Model Key" labelFor="label-input"> <InputGroup id="modelKey" name="modelKey" value={this.state.formData.modelKey} placeholder="Enter model key from hub..." onChange={this.handleChangeForm} /> </FormGroup> <FormGroup label="Project Secret" labelFor="label-input"> <InputGroup id="projectSecret" name="projectSecret" value={this.state.formData.projectSecret} placeholder="Enter project secret from hub..." onChange={this.handleChangeForm} />{" "} </FormGroup> </> ); case "endpoint": return ( <> <FormGroup label="Endpoint URL" labelFor="label-input"> <InputGroup id="modelURL" name="modelURL" value={this.state.formData.modelURL} placeholder="Enter the URL from endpoint..." onChange={this.handleChangeForm} /> </FormGroup> <FormGroup label="Project Secret" labelFor="label-input"> <InputGroup id="projectSecret" name="projectSecret" value={this.state.formData.projectSecret} placeholder="Enter project secret from endpoint..." onChange={this.handleChangeForm} />{" "} </FormGroup> </> ); default: return null; } }; /** Create MenuItems from the registereModelList * @return {Array<MenuItem>} An array of registered models in the format of MenuItems */ private createMenuItems = () => { const modelArr: string[] = Object.keys(this.state.registeredModelList); return modelArr.map(key => { const model = this.state.registeredModelList[key]; const icon = ( <span className={"bp3-menu-item-label"}> <Icon icon="dot" intent={ model.hash === this.state.currentModel?.hash ? Intent.SUCCESS : Intent.DANGER } /> </span> ); const rightButtons = ( <div> <Button icon="cog" intent={Intent.NONE} minimal onClick={event => { this.handleOpenDrawer(model); event.stopPropagation(); }} /> </div> ); return ( <MenuItem shouldDismissPopover={false} className={classes.MenuItems} icon={icon} text={this.formatLongStringName(model.name, 35)} id={model.hash} key={model.hash} labelElement={rightButtons} disabled={this.state.isAPIcalled} onClick={() => { if (!this.state.isOpenDrawer) this.setState({ chosenModel: model, isConfirmLoad: true }); }} /> ); }); }; /** ------- Methods related to Drawer ------- */ /** Opens the Drawer of the registered Model clicked. Updates the isOpenDrawe and chosenModel */ private handleOpenDrawer = async (model: RegisteredModel) => { await this.setState({ isOpenDrawer: true, chosenModel: model }); this.handleGetModelTags(); }; /** Close the Drawer of the chosenModel. Updates the isOpenDrawe and chosenModel */ private handleCloseDrawer = () => { this.setState({ isOpenDrawer: false, chosenModel: undefined }); }; /** Handles the change in drawer tab */ private handleDrawerTabChange = (tabId: TabId) => this.setState({ drawerTabId: tabId }); /** Handles the change in registration tab. Resets the formData to default */ private handleRegistrationTabChange = (tabId: TabId) => { this.setState({ formData: { type: tabId.toString(), modelType: "tensorflow", name: "", description: "", directory: "", modelKey: "", projectSecret: "", modelURL: "", }, registrationTabId: tabId, }); }; /** Obtain the tagcolours */ private handleGetTagHashColour = (tagid: number): string => { return TagColours[tagid % TagColours.length]; }; /** ------- Miscellaneous methods ------- */ /** Reduce the length of a string and apend with "..." */ private formatLongStringName = (str: string, length: number) => { if (str.length > length) { return `${str.substring(0, length - 1)}..`; } return str; }; public render(): JSX.Element { const browseButton = ( <Button text="Browse" icon="folder-new" intent="success" loading={false} onClick={() => { this.handleElectronFileDialog(); }} /> ); const browseHint = ( <Tooltip content={ // eslint-disable-next-line react/jsx-wrap-multilines <> <p> Type the path of the folder that contains the model and label_map.pbtxt </p> <b>Example</b> <p> <pre>/user/example/folder</pre> </p> </> } position={Position.TOP} > <Icon icon="help" className={classes.HintIcon} /> </Tooltip> ); const menuOfModels = ( <Menu className={classes.PopOverMenu}> {Object.keys(this.state.registeredModelList).length === 0 ? ( <div className={classes.NonIdealPopOver}> <div className="bp3-non-ideal-state"> <div className="bp3-non-ideal-state-visual"> <Icon icon="folder-open" iconSize={IconSize.LARGE} /> </div> <h5 className="bp3-heading bp3-text-muted"> Press the + sign to add new models </h5> </div> </div> ) : ( this.createMenuItems() )} </Menu> ); const modelTypes = { tensorflow: "TensorFlow 2.0", darknet: "DarkNet (YOLO v3, YOLO v4)", }; const registerModelForm = ( <div className={classes.RegistrationForm}> {this.state.registrationTabId === "local" ? ( <> <FormGroup label="Model Type" labelFor="label-input"> <Popover minimal content={ // eslint-disable-next-line react/jsx-wrap-multilines <Menu> <Menu.Item shouldDismissPopover={false} text={modelTypes.tensorflow} onClick={() => { const event = { target: { name: "modelType", value: "tensorflow" }, }; this.handleChangeForm(event); }} /> <Menu.Item shouldDismissPopover={false} text={modelTypes.darknet} onClick={() => { const event = { target: { name: "modelType", value: "darknet" }, }; this.handleChangeForm(event); }} /> </Menu> } placement="bottom-start" > <Button text={ this.state.formData.modelType !== "" ? modelTypes[this.state.formData.modelType] : "None selected" } rightIcon="double-caret-vertical" /> </Popover> </FormGroup> </> ) : null} <FormGroup label="Name" labelFor="label-input"> <InputGroup id="name" name="name" value={this.state.formData.name} placeholder="Enter name of the model..." onChange={this.handleChangeForm} /> </FormGroup> {this.renderTabSettings( this.state.registrationTabId, browseButton, browseHint )} <Button type="submit" text="Register" disabled={this.state.isAPIcalled} onClick={this.handleRegisterModel} /> <div className={classes.Right}> {this.state.isAPIcalled ? ( <Spinner size={14} /> ) : this.state.generalIcon !== undefined ? ( <Icon icon={this.state.generalIcon?.name} intent={this.state.generalIcon?.intent} iconSize={14} /> ) : null} </div> </div> ); const detailsPanel = ( <div className={classes.Panel}> <div className={["bp3-elevation-2", classes.Section].join(" ")}> <h6 className="bp3-heading"> {/* <Icon icon="folder-open" /> */} Directory </h6> <p className="bp3-running-text"> {this.state.chosenModel?.directory} </p> </div> <div className={["bp3-elevation-2", classes.Section].join(" ")}> <h6 className="bp3-heading"> {/* <Icon icon="tag" /> */} Tag Map </h6> <div className={classes.TagsList}> <FormGroup> {this.state.isGetTagAPI ? ( <Spinner className={classes.Spin} /> ) : ( Object.keys(this.state.projectTags).map(tagname => { return ( <Tag key={this.state.projectTags[tagname]} interactive={true} className={classes.TagLabel} > <Icon icon={"symbol-circle"} color={this.handleGetTagHashColour( this.state.projectTags[tagname] )} />{" "} {tagname} </Tag> ); }) )} </FormGroup> </div> </div> </div> ); const drawer = ( <Drawer className={this.props.useDarkTheme ? "bp3-dark" : "bp3-light"} size="360px" onClose={this.handleCloseDrawer} canEscapeKeyClose={true} canOutsideClickClose={true} isOpen={this.state.isOpenDrawer} position={Position.RIGHT} usePortal={true} > <div className="bp3-drawer-header"> <Icon className="bp3-icon" icon="dot" iconSize={14} intent={ this.state.chosenModel?.hash === this.state.currentModel?.hash ? Intent.SUCCESS : Intent.DANGER } /> <h4 className="bp3-heading">{this.state.chosenModel?.name}</h4> <Button className="bp3-dialog-close-button" minimal icon="arrow-right" onClick={this.handleCloseDrawer} /> </div> <Navbar className={classes.DrawerNavbar}> <NavbarGroup align={Alignment.LEFT} className={classes.DrawerNavbar}> <Tabs id="DrawerTabs" large={true} onChange={this.handleDrawerTabChange} selectedTabId={this.state.drawerTabId} renderActiveTabPanelOnly={true} > <Tab id="details" title="Details" /> <Tabs.Expander /> </Tabs> </NavbarGroup> </Navbar> <div className={Classes.DRAWER_BODY}> <div> {this.state.drawerTabId === "details" ? detailsPanel : null} </div> </div> <div className={[ Classes.DIALOG_FOOTER_ACTIONS, Classes.DRAWER_FOOTER, ].join(" ")} > <Button type="button" text="Unload" disabled={ this.state.chosenModel?.hash !== this.state.currentModel?.hash || this.state.isUnloadModelAPI } onClick={() => { this.setState({ isConfirmUnload: true }); }} /> <Popover interactionKind={PopoverInteractionKind.HOVER} content={<div className={classes.Section}>Delete</div>} > <Button type="button" intent={Intent.DANGER} disabled={this.state.isAPIcalled} icon="trash" onClick={() => { this.setState({ isConfirmDelete: true }); }} /> </Popover> </div> </Drawer> ); return ( <> <div style={{ maxWidth: "140px", minWidth: "140px" }}> {this.state.isLoadModelAPI ? ( <ProgressBar /> ) : ( <Popover className={classes.PopOver} content={menuOfModels} placement="bottom" isOpen={this.state.isOpenDrawer ? false : undefined} disabled={this.state.waitForRuntime && !this.props.isConnected} > <Tooltip content="Select a Model to Load" disabled={ Object.keys(this.state.registeredModelList).length === 0 || !!this.state.currentModel } isOpen={ !this.state.isOpenRegistraionForm && !this.state.isOpenDrawer && !this.state.currentModel && Object.keys(this.state.registeredModelList).length > 0 ? true : undefined } > <Button disabled={ this.state.waitForRuntime && !this.props.isConnected } className={ this.state.waitForRuntime && !this.props.isConnected ? "bp3-skeleton" : "" } style={{ minWidth: "140px", alignContent: "left" }} alignText={Alignment.LEFT} minimal rightIcon="caret-down" text={ this.state.currentModel !== undefined ? this.formatLongStringName( this.state.currentModel.name, 15 ) : "Load Model.." } /> </Tooltip> </Popover> )} </div> <Popover content={ // eslint-disable-next-line react/jsx-wrap-multilines <> <Navbar className={classes.DrawerNavbar}> <NavbarGroup align={Alignment.LEFT} className={classes.DrawerNavbar} > <Tabs id="RegisterationTabs" large={false} onChange={this.handleRegistrationTabChange} selectedTabId={this.state.registrationTabId} renderActiveTabPanelOnly={true} > <Tab id="local" title="Local" /> <Tab id="hub" title="Datature Hub" /> <Tab id="endpoint" title="Datature API (Coming Soon)" disabled={true} /> <Tabs.Expander /> </Tabs> </NavbarGroup>{" "} </Navbar> <div className={Classes.DRAWER_BODY}>{registerModelForm}</div> </> } placement="left-end" onOpening={() => this.setState({ isOpenRegistraionForm: true })} onClosed={() => { this.setState({ generalIcon: undefined, formData: { type: "local", modelType: "tensorflow", name: "", description: "", directory: "", modelKey: "", projectSecret: "", modelURL: "", }, registrationTabId: "local", isOpenRegistraionForm: false, }); }} > <Tooltip disabled={Object.keys(this.state.registeredModelList).length > 0} content="Add a Model Here" isOpen={Object.keys(this.state.registeredModelList).length === 0} > <Button minimal icon="plus" /> </Tooltip> </Popover> {drawer} <Alert isOpen={this.state.isConfirmLoad} intent={Intent.WARNING} icon="warning-sign" loading={this.state.isLoadModelAPI} onCancel={() => this.setState({ isConfirmLoad: false })} onConfirm={this.handleUnloadAndLoadModel} cancelButtonText={"Cancel"} confirmButtonText={"I Understand"} className={this.props.useDarkTheme ? "bp3-dark" : ""} > {this.state.currentModel ? ( <div> We will unload {this.state.currentModel.name} and load{" "} {this.state.chosenModel?.name}. Are you sure you want to continue? </div> ) : ( <div> Confirm that you want to load {this.state.chosenModel?.name}. </div> )} </Alert> <Alert isOpen={this.state.isConfirmUnload} intent={Intent.WARNING} icon="warning-sign" loading={this.state.isUnloadModelAPI} onCancel={() => this.setState({ isConfirmUnload: false })} onConfirm={this.handleUnloadModel} cancelButtonText={"Cancel"} confirmButtonText={"I Understand"} className={this.props.useDarkTheme ? "bp3-dark" : ""} > <div> We will unload {this.state.currentModel?.name}. Are you sure you want to continue? </div> </Alert> <Alert isOpen={this.state.isConfirmDelete} intent={Intent.WARNING} icon="warning-sign" loading={this.state.isAPIcalled} onCancel={() => this.setState({ isConfirmDelete: false })} onConfirm={this.handleDeleteModel} cancelButtonText={"Cancel"} confirmButtonText={"I Understand"} className={this.props.useDarkTheme ? "bp3-dark" : ""} > {this.state.currentModel?.hash === this.state.chosenModel?.hash ? ( <div> This model is loaded. We will unload and delete{" "} {this.state.currentModel?.name}. Are you sure you want to continue? </div> ) : ( <div> Confirm that you want to delete {this.state.chosenModel?.name}. </div> )} </Alert> </> ); } }
the_stack
declare namespace DevExpress.AspNetCore { enum BootstrapSchedulerGroupType { Date = "Date", None = "None", Resource = "Resource", } enum BootstrapSchedulerViewType { Day = "Day", WorkWeek = "WorkWeek", Week = "Week", Month = "Month", Timeline = "Timeline", FullWeek = "FullWeek", Agenda = "Agenda", } enum BootstrapSchedulerAppointmentType { Normal = "Normal", Pattern = "Pattern", Occurrence = "Occurrence", ChangedOccurrence = "ChangedOccurrence", DeletedOccurrence = "DeletedOccurrence", } enum BootstrapSchedulerRecurrenceRange { NoEndDate = "NoEndDate", OccurrenceCount = "OccurrenceCount", EndByDate = "EndByDate", } enum BootstrapSchedulerRecurrenceType { Daily = "Daily", Weekly = "Weekly", Monthly = "Monthly", Yearly = "Yearly", Hourly = "Hourly", } enum WeekDays { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, WeekendDays = 65, WorkDays = 62, EveryDay = 127, } enum WeekOfMonth { None = 0, First = 1, Second = 2, Third = 3, Fourth = 4, Last = 5, } enum BootstrapPopupControlCloseReason { API = "API", CloseButton = "CloseButton", OuterMouseClick = "OuterMouseClick", MouseOut = "MouseOut", Escape = "Escape", } const Utils: { getControls: () => Control[]; getSerializedEditorValuesInContainer: (containerOrId: string | HTMLElement, processInvisibleEditors?: boolean) => any; getEditorValuesInContainer: (containerOrId: string | HTMLElement, processInvisibleEditors?: boolean) => any; }; interface EventArgs { readonly sender: Control; } interface CancelEventArgs extends EventArgs { cancel: boolean; } interface BeginCallbackEventArgs extends EventArgs { readonly command: string; } interface ProcessingModeEventArgs extends EventArgs { processOnServer: boolean; } interface ProcessingModeCancelEventArgs extends ProcessingModeEventArgs { cancel: boolean; } interface GlobalBeginCallbackEventArgs extends BeginCallbackEventArgs { readonly control: Control; } interface EndCallbackEventArgs extends EventArgs { // tslint:disable-line:no-empty-interface } interface GlobalEndCallbackEventArgs extends EndCallbackEventArgs { readonly control: Control; } interface CustomDataCallbackEventArgs extends EventArgs { result: string; } interface CallbackErrorEventArgs extends EventArgs { handled: boolean; message: string; } interface GlobalCallbackErrorEventArgs extends CallbackErrorEventArgs { readonly control: Control; } interface EditValidationEventArgs extends EventArgs { errorText: string; isValid: boolean; value: string; } interface ValidationCompletedEventArgs extends EventArgs { readonly container: any; readonly firstInvalidControl: Control; readonly firstVisibleInvalidControl: Control; readonly invisibleControlsValidated: boolean; isValid: boolean; readonly validationGroup: string; } interface EditClickEventArgs extends EventArgs { readonly htmlElement: any; readonly htmlEvent: any; } interface EditKeyEventArgs extends EventArgs { readonly htmlEvent: any; } class Control { protected readonly instance: any; protected constructor(instance: any); readonly name: string; adjustControl(): void; getHeight(): number; getMainElement(): any; getParentControl(): any; getVisible(): boolean; getWidth(): number; inCallback(): boolean; sendMessageToAssistiveTechnology(message: string): void; setHeight(height: number): void; setVisible(visible: boolean): void; setWidth(width: number): void; on<K extends keyof ControlEventMap>(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; once<K extends keyof ControlEventMap>(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; off<K extends keyof ControlEventMap>(): this; // tslint:disable-line:no-unnecessary-generics off<K extends keyof ControlEventMap>(eventName: K): this; // tslint:disable-line:unified-signatures no-unnecessary-generics off<K extends keyof ControlEventMap>(eventName: K, callback: (this: Control, args?: ControlEventMap[K]) => void): this; // tslint:disable-line:unified-signatures } interface ControlEventMap { "init": EventArgs; } class BootstrapClientEdit extends Control { focus(): void; getCaption(): string; getEnabled(): boolean; getErrorText(): string; getInputElement(): any; getIsValid(): boolean; getReadOnly(): boolean; getValue(): any; setCaption(caption: string): void; setEnabled(value: boolean): void; setErrorText(errorText: string): void; setIsValid(isValid: boolean): void; setReadOnly(readOnly: boolean): void; setValue(value: any): void; validate(): void; on<K extends keyof BootstrapClientEditEventMap>(eventName: K, callback: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; once<K extends keyof BootstrapClientEditEventMap>(eventName: K, callback: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; off<K extends keyof BootstrapClientEditEventMap>(eventName?: K, callback?: (this: BootstrapClientEdit, args?: BootstrapClientEditEventMap[K]) => void): this; } interface BootstrapClientEditEventMap extends ControlEventMap { "gotFocus": EventArgs; "lostFocus": EventArgs; "validation": EditValidationEventArgs; "valueChanged": ProcessingModeEventArgs; } interface AccordionItemEventArgs extends ProcessingModeEventArgs { readonly htmlElement: object; readonly htmlEvent: object; readonly item: BootstrapAccordionItem; } interface AccordionGroupEventArgs extends EventArgs { readonly group: BootstrapAccordionGroup; } interface AccordionGroupCancelEventArgs extends ProcessingModeCancelEventArgs { readonly group: BootstrapAccordionGroup; } interface AccordionGroupClickEventArgs extends AccordionGroupCancelEventArgs { readonly htmlElement: object; readonly htmlEvent: object; } class BootstrapAccordion extends Control { collapseAll(): void; expandAll(): void; getActiveGroup(): BootstrapAccordionGroup | null; getGroup(index: number): BootstrapAccordionGroup | null; getGroupByName(name: string): BootstrapAccordionGroup | null; getGroupCount(): number; getItemByName(name: string): BootstrapAccordionItem | null; getSelectedItem(): BootstrapAccordionItem | null; setActiveGroup(group: BootstrapAccordionGroup): void; setSelectedItem(item: BootstrapAccordionItem): void; on<K extends keyof BootstrapAccordionEventMap>(eventName: K, callback: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; once<K extends keyof BootstrapAccordionEventMap>(eventName: K, callback: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; off<K extends keyof BootstrapAccordionEventMap>(eventName?: K, callback?: (this: BootstrapAccordion, args?: BootstrapAccordionEventMap[K]) => void): this; } interface BootstrapAccordionEventMap extends ControlEventMap { "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "endCallback": EndCallbackEventArgs; "expandedChanged": AccordionGroupEventArgs; "expandedChanging": AccordionGroupCancelEventArgs; "headerClick": AccordionGroupClickEventArgs; "itemClick": AccordionItemEventArgs; } class BootstrapAccordionGroup { protected readonly instance: any; protected constructor(instance: any); readonly index: number; readonly name: string; readonly navBar: BootstrapAccordion | null; getEnabled(): boolean; getExpanded(): boolean; getHeaderBadgeIconCssClass(): string; getHeaderBadgeText(): string; getItem(index: number): BootstrapAccordionItem | null; getItemByName(name: string): BootstrapAccordionItem | null; getItemCount(): number; getText(): string; getVisible(): boolean; setExpanded(value: boolean): void; setHeaderBadgeIconCssClass(cssClass: string): void; setHeaderBadgeText(text: string): void; setText(text: string): void; setVisible(value: boolean): void; } class BootstrapAccordionItem { protected readonly instance: any; protected constructor(instance: any); readonly group: BootstrapAccordionGroup | null; readonly index: number; readonly name: string; readonly navBar: BootstrapAccordion | null; getBadgeIconCssClass(): string; getBadgeText(): string; getEnabled(): boolean; getIconCssClass(): string; getImageUrl(): string; getNavigateUrl(): string; getText(): string; getVisible(): boolean; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setEnabled(value: boolean): void; setIconCssClass(cssClass: string): void; setImageUrl(value: string): void; setNavigateUrl(value: string): void; setText(value: string): void; setVisible(value: boolean): void; } class BootstrapBinaryImage extends BootstrapClientEdit { clear(): void; getUploadedFileName(): string; getValue(): any; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; setSize(width: number, height: number): void; setValue(value: any): void; on<K extends keyof BootstrapBinaryImageEventMap>(eventName: K, callback: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; once<K extends keyof BootstrapBinaryImageEventMap>(eventName: K, callback: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; off<K extends keyof BootstrapBinaryImageEventMap>(eventName?: K, callback?: (this: BootstrapBinaryImage, args?: BootstrapBinaryImageEventMap[K]) => void): this; } interface BootstrapBinaryImageEventMap extends BootstrapClientEditEventMap { "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "click": EditClickEventArgs; "endCallback": EndCallbackEventArgs; } interface ButtonClickEventArgs extends ProcessingModeEventArgs { readonly cancelEventAndBubble: boolean; } class BootstrapButton extends Control { doClick(): void; focus(): void; getBadgeIconCssClass(): string; getBadgeText(): string; getChecked(): boolean; getEnabled(): boolean; getImageUrl(): string; getText(): string; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setChecked(value: boolean): void; setEnabled(value: boolean): void; setImageUrl(value: string): void; setText(value: string): void; on<K extends keyof BootstrapButtonEventMap>(eventName: K, callback: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; once<K extends keyof BootstrapButtonEventMap>(eventName: K, callback: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; off<K extends keyof BootstrapButtonEventMap>(eventName?: K, callback?: (this: BootstrapButton, args?: BootstrapButtonEventMap[K]) => void): this; } interface BootstrapButtonEventMap extends ControlEventMap { "checkedChanged": ProcessingModeEventArgs; "click": ButtonClickEventArgs; "gotFocus": EventArgs; "lostFocus": EventArgs; } interface CalendarCustomDisabledDateEventArgs extends EventArgs { readonly date: Date; isDisabled: boolean; } class BootstrapCalendar extends BootstrapClientEdit { clearSelection(): void; deselectDate(date: Date): void; deselectRange(start: Date, end: Date): void; getEnabled(): boolean; getMaxDate(): Date; getMinDate(): Date; getSelectedDate(): Date; getSelectedDates(): Date[]; getVisibleDate(): Date; isDateSelected(date: Date): boolean; selectDate(date: Date): void; selectRange(start: Date, end: Date): void; setEnabled(enabled: boolean): void; setMaxDate(date: Date): void; setMinDate(date: Date): void; setSelectedDate(date: Date): void; setVisibleDate(date: Date): void; on<K extends keyof BootstrapCalendarEventMap>(eventName: K, callback: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; once<K extends keyof BootstrapCalendarEventMap>(eventName: K, callback: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; off<K extends keyof BootstrapCalendarEventMap>(eventName?: K, callback?: (this: BootstrapCalendar, args?: BootstrapCalendarEventMap[K]) => void): this; } interface BootstrapCalendarEventMap extends BootstrapClientEditEventMap { "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "customDisabledDate": CalendarCustomDisabledDateEventArgs; "endCallback": EndCallbackEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "selectionChanged": ProcessingModeEventArgs; "visibleMonthChanged": ProcessingModeEventArgs; } interface GridToolbarItemClickEventArgs extends ProcessingModeEventArgs { readonly item: BootstrapMenuItem; readonly toolbarIndex: number; readonly toolbarName: string; usePostBack: boolean; } class BootstrapGridBase extends Control { getToolbar(index: number): BootstrapMenu | null; getToolbarByName(name: string): BootstrapMenu | null; on<K extends keyof BootstrapGridBaseEventMap>(eventName: K, callback: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; once<K extends keyof BootstrapGridBaseEventMap>(eventName: K, callback: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; off<K extends keyof BootstrapGridBaseEventMap>(eventName?: K, callback?: (this: BootstrapGridBase, args?: BootstrapGridBaseEventMap[K]) => void): this; } interface BootstrapGridBaseEventMap extends ControlEventMap { "toolbarItemClick": GridToolbarItemClickEventArgs; } interface CardViewColumnCancelEventArgs extends CancelEventArgs { readonly column: BootstrapCardViewColumn; } interface CardViewCardFocusingEventArgs extends CancelEventArgs { readonly htmlEvent: any; readonly visibleIndex: number; } interface CardViewCardClickEventArgs extends CancelEventArgs { readonly htmlEvent: any; readonly visibleIndex: number; } interface CardViewCustomButtonEventArgs extends ProcessingModeEventArgs { readonly buttonID: string; readonly visibleIndex: number; } interface CardViewSelectionEventArgs extends ProcessingModeEventArgs { readonly isAllRecordsOnPage: boolean; readonly isChangedOnServer: boolean; readonly isSelected: boolean; readonly visibleIndex: number; } interface CardViewFocusEventArgs extends ProcessingModeEventArgs { readonly isChangedOnServer: boolean; } interface CardViewBatchEditStartEditingEventArgs extends CancelEventArgs { readonly cardValues: any; focusedColumn: BootstrapCardViewColumn; readonly visibleIndex: number; } interface CardViewBatchEditEndEditingEventArgs extends CancelEventArgs { readonly cardValues: any; readonly visibleIndex: number; } interface CardViewBatchEditCardValidatingEventArgs extends EventArgs { readonly validationInfo: any; readonly visibleIndex: number; } interface CardViewBatchEditConfirmShowingEventArgs extends CancelEventArgs { readonly requestTriggerID: string; } interface CardViewBatchEditTemplateCellFocusedEventArgs extends EventArgs { readonly column: BootstrapCardViewColumn; handled: boolean; } interface CardViewBatchEditChangesSavingEventArgs extends CancelEventArgs { readonly deletedValues: any; readonly insertedValues: any; readonly updatedValues: any; } interface CardViewBatchEditChangesCancelingEventArgs extends CancelEventArgs { readonly deletedValues: any; readonly insertedValues: any; readonly updatedValues: any; } interface CardViewBatchEditCardInsertingEventArgs extends CancelEventArgs { readonly visibleIndex: number; } interface CardViewBatchEditCardDeletingEventArgs extends CancelEventArgs { readonly cardValues: any; readonly visibleIndex: number; } interface CardViewFocusedCellChangingEventArgs extends CancelEventArgs { readonly cellInfo: BootstrapCardViewCellInfo; } class BootstrapCardView extends BootstrapGridBase { readonly batchEditApi: BootstrapCardViewBatchEditApi | null; addNewCard(): void; applyFilter(filterExpression: string): void; applySearchPanelFilter(value: string): void; cancelEdit(): void; clearFilter(): void; closeFilterControl(): void; deleteCard(visibleIndex: number): void; deleteCardByKey(key: any): void; focus(): void; focusEditor(column: BootstrapCardViewColumn): void; focusEditor(columnIndex: number): void; // tslint:disable-line:unified-signatures focusEditor(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures getCardKey(visibleIndex: number): string; getColumn(columnIndex: number): BootstrapCardViewColumn | null; getColumnByField(columnFieldName: string): BootstrapCardViewColumn | null; getColumnById(columnId: string): BootstrapCardViewColumn | null; getColumnCount(): number; getEditValue(column: BootstrapCardViewColumn): string; getEditValue(columnIndex: number): string; // tslint:disable-line:unified-signatures getEditValue(columnFieldNameOrId: string): string; // tslint:disable-line:unified-signatures unified-signatures getEditor(column: BootstrapCardViewColumn): BootstrapClientEdit; getEditor(columnIndex: number): BootstrapClientEdit; // tslint:disable-line:unified-signatures getEditor(columnFieldNameOrId: string): BootstrapClientEdit; // tslint:disable-line:unified-signatures unified-signatures getFocusedCardIndex(): number; getFocusedCell(): BootstrapCardViewCellInfo | null; getPageCount(): number; getPageIndex(): number; getPopupEditForm(): BootstrapPopupControl | null; getSelectedCardCount(): number; getSelectedKeysOnPage(): any[]; getTopVisibleIndex(): number; getVerticalScrollPosition(): number; getVisibleCardsOnPage(): number; gotoPage(pageIndex: number): void; hideCustomizationWindow(): void; isCardSelectedOnPage(visibleIndex: number): boolean; isCustomizationWindowVisible(): boolean; isEditing(): boolean; isNewCardEditing(): boolean; moveColumn(column: BootstrapCardViewColumn): void; moveColumn(columnIndex: number): void; // tslint:disable-line:unified-signatures moveColumn(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures moveColumn(column: BootstrapCardViewColumn, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures moveColumn(columnIndex: number, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures moveColumn(columnFieldNameOrId: string, moveToColumnVisibleIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures moveColumn(column: BootstrapCardViewColumn, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures moveColumn(columnIndex: number, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures unified-signatures moveColumn(columnFieldNameOrId: string, moveToColumnVisibleIndex: number, moveBefore: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures nextPage(): void; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; prevPage(): void; refresh(): void; selectAllCardsOnPage(): void; selectCardOnPage(visibleIndex: number): void; selectCardOnPage(visibleIndex: number, selected: boolean): void; // tslint:disable-line:unified-signatures selectCards(): void; selectCardsByKey(keys: any[]): void; selectCardsByKey(key: any): void; // tslint:disable-line:unified-signatures selectCardsByKey(keys: any[], selected: boolean): void; // tslint:disable-line:unified-signatures selectCardsByKey(key: any, selected: boolean): void; // tslint:disable-line:unified-signatures unified-signatures setEditValue(column: BootstrapCardViewColumn, value: string): void; setEditValue(columnIndex: number, value: string): void; // tslint:disable-line:unified-signatures setEditValue(columnFieldNameOrId: string, value: string): void; // tslint:disable-line:unified-signatures unified-signatures setFilterEnabled(isFilterEnabled: boolean): void; setFocusedCardIndex(visibleIndex: number): void; setFocusedCell(cardVisibleIndex: number, columnIndex: number): void; setSearchPanelCustomEditor(editor: BootstrapClientEdit): void; setVerticalScrollPosition(position: number): void; showCustomizationWindow(): void; showFilterControl(): void; sortBy(column: BootstrapCardViewColumn): void; sortBy(columnIndex: number): void; // tslint:disable-line:unified-signatures sortBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(column: BootstrapCardViewColumn, sortOrder: string): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures sortBy(column: BootstrapCardViewColumn, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures sortBy(column: BootstrapCardViewColumn, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures startEditCard(visibleIndex: number): void; startEditCardByKey(key: any): void; unselectAllCardsOnPage(): void; unselectCardOnPage(visibleIndex: number): void; unselectCards(): void; unselectCardsByKey(keys: any[]): void; unselectCardsByKey(key: any): void; // tslint:disable-line:unified-signatures unselectFilteredCards(): void; updateEdit(): void; on<K extends keyof BootstrapCardViewEventMap>(eventName: K, callback: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; once<K extends keyof BootstrapCardViewEventMap>(eventName: K, callback: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; off<K extends keyof BootstrapCardViewEventMap>(eventName?: K, callback?: (this: BootstrapCardView, args?: BootstrapCardViewEventMap[K]) => void): this; } interface BootstrapCardViewEventMap extends BootstrapGridBaseEventMap { "batchEditCardDeleting": CardViewBatchEditCardDeletingEventArgs; "batchEditCardInserting": CardViewBatchEditCardInsertingEventArgs; "batchEditCardValidating": CardViewBatchEditCardValidatingEventArgs; "batchEditChangesCanceling": CardViewBatchEditChangesCancelingEventArgs; "batchEditChangesSaving": CardViewBatchEditChangesSavingEventArgs; "batchEditConfirmShowing": CardViewBatchEditConfirmShowingEventArgs; "batchEditEndEditing": CardViewBatchEditEndEditingEventArgs; "batchEditStartEditing": CardViewBatchEditStartEditingEventArgs; "batchEditTemplateCellFocused": CardViewBatchEditTemplateCellFocusedEventArgs; "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "cardClick": CardViewCardClickEventArgs; "cardDblClick": CardViewCardClickEventArgs; "cardFocusing": CardViewCardFocusingEventArgs; "columnSorting": CardViewColumnCancelEventArgs; "customButtonClick": CardViewCustomButtonEventArgs; "customizationWindowCloseUp": EventArgs; "endCallback": EndCallbackEventArgs; "focusedCardChanged": CardViewFocusEventArgs; "focusedCellChanging": CardViewFocusedCellChangingEventArgs; "selectionChanged": CardViewSelectionEventArgs; } class BootstrapCardViewBatchEditApi { protected readonly instance: any; protected constructor(instance: any); addNewCard(): void; deleteCard(visibleIndex: number): void; deleteCardByKey(key: any): void; getCardVisibleIndices(includeDeleted: boolean): number[]; getDeletedCardIndices(): number[]; getInsertedCardIndices(): number[]; isDeletedCard(visibleIndex: number): boolean; isNewCard(visibleIndex: number): boolean; recoverCard(visibleIndex: number): void; recoverCardByKey(key: any): void; validateCard(visibleIndex: number): boolean; validateCards(validateOnlyModified: boolean): boolean; } class BootstrapCardViewColumn { protected readonly instance: any; protected constructor(instance: any); } class BootstrapCardViewCellInfo { protected readonly instance: any; protected constructor(instance: any); readonly cardVisibleIndex: number; endEdit(): void; getCellTextContainer(visibleIndex: number, columnFieldNameOrId: string): any; getCellValue(visibleIndex: number, columnFieldNameOrId: string, initial: boolean): any; getColumnDisplayText(columnFieldNameOrId: string, value: any): string; getEditCellInfo(): BootstrapCardViewCellInfo | null; hasChanges(): boolean; moveFocusBackward(): boolean; moveFocusForward(): boolean; resetChanges(visibleIndex: number): void; resetChanges(visibleIndex: number, columnIndex: number): void; // tslint:disable-line:unified-signatures setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any): void; setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any, displayText: string, cancelCellHighlighting: boolean): void; startEdit(visibleIndex: number, columnIndex: number): void; } interface BootstrapChartEventArgsBase extends EventArgs { readonly component: any; readonly element: any; } interface BootstrapChartErrorEventArgs extends BootstrapChartEventArgsBase { readonly target: any; } interface BootstrapChartElementActionEventArgs extends BootstrapChartEventArgsBase { readonly target: any; } interface BootstrapChartElementClickEventArgs extends BootstrapChartElementActionEventArgs { readonly jQueryEvent: any; } interface BootstrapChartExportEventArgs extends BootstrapChartEventArgsBase { cancel: boolean; readonly data: any; readonly fileName: string; readonly format: string; } interface BootstrapChartOptionChangedEventArgs extends BootstrapChartEventArgsBase { readonly fullName: string; readonly name: string; readonly previousValue: any; readonly value: any; } interface BootstrapChartZoomEndEventArgs extends BootstrapChartEventArgsBase { readonly rangeEnd: any; readonly rangeStart: any; } class BootstrapChart extends Control { exportTo(format: string, fileName: string): void; getDataSource(): any; getInstance(): any; print(): void; setDataSource(dataSource: any): void; setOptions(options: any): void; on<K extends keyof BootstrapChartEventMap>(eventName: K, callback: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; once<K extends keyof BootstrapChartEventMap>(eventName: K, callback: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; off<K extends keyof BootstrapChartEventMap>(eventName?: K, callback?: (this: BootstrapChart, args?: BootstrapChartEventMap[K]) => void): this; } interface BootstrapChartEventMap extends ControlEventMap { "argumentAxisClick": BootstrapChartElementClickEventArgs; "disposing": BootstrapChartEventArgsBase; "done": BootstrapChartEventArgsBase; "drawn": BootstrapChartEventArgsBase; "exported": BootstrapChartEventArgsBase; "exporting": BootstrapChartExportEventArgs; "fileSaving": BootstrapChartExportEventArgs; "incidentOccurred": BootstrapChartErrorEventArgs; "init": BootstrapChartEventArgsBase; "legendClick": BootstrapChartElementClickEventArgs; "optionChanged": BootstrapChartOptionChangedEventArgs; "pointClick": BootstrapChartElementClickEventArgs; "pointHoverChanged": BootstrapChartElementActionEventArgs; "pointSelectionChanged": BootstrapChartElementActionEventArgs; "seriesClick": BootstrapChartElementClickEventArgs; "seriesHoverChanged": BootstrapChartElementActionEventArgs; "seriesSelectionChanged": BootstrapChartElementActionEventArgs; "tooltipHidden": BootstrapChartElementActionEventArgs; "tooltipShown": BootstrapChartElementActionEventArgs; "zoomEnd": BootstrapChartZoomEndEventArgs; "zoomStart": BootstrapChartEventArgsBase; } class BootstrapPolarChart extends Control { exportTo(format: string, fileName: string): void; getDataSource(): any; getInstance(): any; print(): void; setDataSource(dataSource: any): void; setOptions(options: any): void; on<K extends keyof BootstrapPolarChartEventMap>(eventName: K, callback: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; once<K extends keyof BootstrapPolarChartEventMap>(eventName: K, callback: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; off<K extends keyof BootstrapPolarChartEventMap>(eventName?: K, callback?: (this: BootstrapPolarChart, args?: BootstrapPolarChartEventMap[K]) => void): this; } interface BootstrapPolarChartEventMap extends ControlEventMap { "argumentAxisClick": BootstrapChartElementClickEventArgs; "disposing": BootstrapChartEventArgsBase; "done": BootstrapChartEventArgsBase; "drawn": BootstrapChartEventArgsBase; "exported": BootstrapChartEventArgsBase; "exporting": BootstrapChartExportEventArgs; "fileSaving": BootstrapChartExportEventArgs; "incidentOccurred": BootstrapChartErrorEventArgs; "init": BootstrapChartEventArgsBase; "legendClick": BootstrapChartElementClickEventArgs; "optionChanged": BootstrapChartOptionChangedEventArgs; "pointClick": BootstrapChartElementClickEventArgs; "pointHoverChanged": BootstrapChartElementActionEventArgs; "pointSelectionChanged": BootstrapChartElementActionEventArgs; "seriesClick": BootstrapChartElementClickEventArgs; "seriesHoverChanged": BootstrapChartElementActionEventArgs; "seriesSelectionChanged": BootstrapChartElementActionEventArgs; "tooltipHidden": BootstrapChartElementActionEventArgs; "tooltipShown": BootstrapChartElementActionEventArgs; } class BootstrapPieChart extends Control { exportTo(format: string, fileName: string): void; getDataSource(): any; getInstance(): any; print(): void; setDataSource(dataSource: any): void; setOptions(options: any): void; on<K extends keyof BootstrapPieChartEventMap>(eventName: K, callback: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; once<K extends keyof BootstrapPieChartEventMap>(eventName: K, callback: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; off<K extends keyof BootstrapPieChartEventMap>(eventName?: K, callback?: (this: BootstrapPieChart, args?: BootstrapPieChartEventMap[K]) => void): this; } interface BootstrapPieChartEventMap extends ControlEventMap { "disposing": BootstrapChartEventArgsBase; "done": BootstrapChartEventArgsBase; "drawn": BootstrapChartEventArgsBase; "exported": BootstrapChartEventArgsBase; "exporting": BootstrapChartExportEventArgs; "fileSaving": BootstrapChartExportEventArgs; "incidentOccurred": BootstrapChartErrorEventArgs; "init": BootstrapChartEventArgsBase; "legendClick": BootstrapChartElementClickEventArgs; "optionChanged": BootstrapChartOptionChangedEventArgs; "pointClick": BootstrapChartElementClickEventArgs; "pointHoverChanged": BootstrapChartElementActionEventArgs; "pointSelectionChanged": BootstrapChartElementActionEventArgs; "tooltipHidden": BootstrapChartElementActionEventArgs; "tooltipShown": BootstrapChartElementActionEventArgs; } class BootstrapCheckBox extends BootstrapClientEdit { getCheckState(): string; getChecked(): boolean; getText(): string; setCheckState(checkState: string): void; setChecked(isChecked: boolean): void; setText(text: string): void; on<K extends keyof BootstrapCheckBoxEventMap>(eventName: K, callback: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; once<K extends keyof BootstrapCheckBoxEventMap>(eventName: K, callback: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; off<K extends keyof BootstrapCheckBoxEventMap>(eventName?: K, callback?: (this: BootstrapCheckBox, args?: BootstrapCheckBoxEventMap[K]) => void): this; } interface BootstrapCheckBoxEventMap extends BootstrapClientEditEventMap { "checkedChanged": ProcessingModeEventArgs; } class BootstrapRadioButton extends BootstrapClientEdit { getCheckState(): string; getChecked(): boolean; getText(): string; setCheckState(checkState: string): void; setChecked(isChecked: boolean): void; setText(text: string): void; on<K extends keyof BootstrapRadioButtonEventMap>(eventName: K, callback: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; once<K extends keyof BootstrapRadioButtonEventMap>(eventName: K, callback: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; off<K extends keyof BootstrapRadioButtonEventMap>(eventName?: K, callback?: (this: BootstrapRadioButton, args?: BootstrapRadioButtonEventMap[K]) => void): this; } interface BootstrapRadioButtonEventMap extends BootstrapClientEditEventMap { "checkedChanged": ProcessingModeEventArgs; } class BootstrapComboBox extends BootstrapClientEdit { addItem(texts: string[]): number; addItem(text: string): number; // tslint:disable-line:unified-signatures addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures addItemCssClass(index: number, className: string): void; addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; adjustDropDownWindow(): void; beginUpdate(): void; clearItems(): void; endUpdate(): void; ensureDropDownLoaded(callbackFunction: any): void; findItemByText(text: string): BootstrapListBoxItem | null; findItemByValue(value: any): BootstrapListBoxItem | null; getButtonVisible(number: number): boolean; getCaretPosition(): number; getItem(index: number): BootstrapListBoxItem | null; getItemBadgeIconCssClass(index: number): string; getItemBadgeText(index: number): string; getItemCount(): number; getSelectedIndex(): number; getSelectedItem(): BootstrapListBoxItem | null; getText(): string; hideDropDown(): void; insertItem(index: number, texts: string[]): void; insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures makeItemVisible(index: number): void; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; removeItem(index: number): void; removeItemCssClass(index: number, className: string): void; removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setItemBadgeIconCssClass(index: number, cssClass: string): void; setItemBadgeText(index: number, text: string): void; setItemHtml(index: number, html: string): void; setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; setItemTooltip(index: number, tooltip: string): void; setSelectedIndex(index: number): void; setSelectedItem(item: BootstrapListBoxItem): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string, applyFilter: boolean): void; showDropDown(): void; on<K extends keyof BootstrapComboBoxEventMap>(eventName: K, callback: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; once<K extends keyof BootstrapComboBoxEventMap>(eventName: K, callback: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; off<K extends keyof BootstrapComboBoxEventMap>(eventName?: K, callback?: (this: BootstrapComboBox, args?: BootstrapComboBoxEventMap[K]) => void): this; } interface BootstrapComboBoxEventMap extends BootstrapClientEditEventMap { "beginCallback": BeginCallbackEventArgs; "buttonClick": ButtonEditClickEventArgs; "callbackError": CallbackErrorEventArgs; "closeUp": EventArgs; "customHighlighting": ListEditCustomHighlightingEventArgs; "dropDown": EventArgs; "endCallback": EndCallbackEventArgs; "itemFiltering": ListEditItemFilteringEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "queryCloseUp": CancelEventArgs; "selectedIndexChanged": ProcessingModeEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } interface ParseDateEventArgs extends EventArgs { readonly date: Date; readonly handled: boolean; readonly value: string; } class BootstrapDateEdit extends BootstrapClientEdit { adjustDropDownWindow(): void; getButtonVisible(number: number): boolean; getCalendar(): BootstrapCalendar | null; getCaretPosition(): number; getDate(): Date; getMaxDate(): Date; getMinDate(): Date; getRangeDayCount(): number; getText(): string; getTimeEdit(): BootstrapTimeEdit | null; hideDropDown(): void; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setDate(date: Date): void; setMaxDate(date: Date): void; setMinDate(date: Date): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; showDropDown(): void; on<K extends keyof BootstrapDateEditEventMap>(eventName: K, callback: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; once<K extends keyof BootstrapDateEditEventMap>(eventName: K, callback: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; off<K extends keyof BootstrapDateEditEventMap>(eventName?: K, callback?: (this: BootstrapDateEdit, args?: BootstrapDateEditEventMap[K]) => void): this; } interface BootstrapDateEditEventMap extends BootstrapClientEditEventMap { "buttonClick": ButtonEditClickEventArgs; "calendarCustomDisabledDate": CalendarCustomDisabledDateEventArgs; "closeUp": EventArgs; "dateChanged": ProcessingModeEventArgs; "dropDown": EventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "parseDate": ParseDateEventArgs; "queryCloseUp": CancelEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapDropDownEdit extends BootstrapClientEdit { adjustDropDownWindow(): void; getButtonVisible(number: number): boolean; getCaretPosition(): number; getKeyValue(): string; getText(): string; hideDropDown(): void; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setKeyValue(keyValue: string): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; showDropDown(): void; on<K extends keyof BootstrapDropDownEditEventMap>(eventName: K, callback: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; once<K extends keyof BootstrapDropDownEditEventMap>(eventName: K, callback: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; off<K extends keyof BootstrapDropDownEditEventMap>(eventName?: K, callback?: (this: BootstrapDropDownEdit, args?: BootstrapDropDownEditEventMap[K]) => void): this; } interface BootstrapDropDownEditEventMap extends BootstrapClientEditEventMap { "buttonClick": ButtonEditClickEventArgs; "closeUp": EventArgs; "dropDown": EventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "queryCloseUp": CancelEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapFormLayout extends Control { getItemByName(name: string): BootstrapFormLayoutItem | null; on<K extends keyof BootstrapFormLayoutEventMap>(eventName: K, callback: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; once<K extends keyof BootstrapFormLayoutEventMap>(eventName: K, callback: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; off<K extends keyof BootstrapFormLayoutEventMap>(eventName?: K, callback?: (this: BootstrapFormLayout, args?: BootstrapFormLayoutEventMap[K]) => void): this; } interface BootstrapFormLayoutEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } class BootstrapFormLayoutItem { protected readonly instance: any; protected constructor(instance: any); readonly formLayout: BootstrapFormLayout | null; readonly name: string; readonly parent: BootstrapFormLayoutItem | null; getCaption(): string; getItemByName(name: string): BootstrapFormLayoutItem | null; getVisible(): boolean; setCaption(caption: string): void; setVisible(value: boolean): void; } interface GridViewColumnCancelEventArgs extends CancelEventArgs { readonly column: BootstrapGridViewColumn; } interface GridViewColumnProcessingModeEventArgs extends ProcessingModeEventArgs { readonly column: BootstrapGridViewColumn; } interface GridViewRowCancelEventArgs extends CancelEventArgs { readonly visibleIndex: number; } interface GridViewSelectionEventArgs extends ProcessingModeEventArgs { readonly isAllRecordsOnPage: boolean; readonly isChangedOnServer: boolean; readonly isSelected: boolean; readonly visibleIndex: number; } interface GridViewFocusEventArgs extends ProcessingModeEventArgs { readonly isChangedOnServer: boolean; } interface GridViewRowFocusingEventArgs extends GridViewRowCancelEventArgs { readonly htmlEvent: any; } interface GridViewRowClickEventArgs extends GridViewRowCancelEventArgs { readonly htmlEvent: any; } interface GridViewContextMenuEventArgs extends EventArgs { readonly htmlEvent: any; readonly index: number; readonly menu: any; readonly objectType: string; showBrowserMenu: boolean; } interface GridViewContextMenuItemClickEventArgs extends ProcessingModeEventArgs { readonly elementIndex: number; handled: boolean; readonly item: BootstrapMenuItem; readonly objectType: string; usePostBack: boolean; } interface GridViewCustomButtonEventArgs extends ProcessingModeEventArgs { readonly buttonID: string; readonly visibleIndex: number; } interface GridViewColumnMovingEventArgs extends EventArgs { allow: boolean; readonly destinationColumn: BootstrapGridViewColumn; readonly isDropBefore: boolean; readonly isGroupPanel: boolean; readonly sourceColumn: BootstrapGridViewColumn; } interface GridViewBatchEditConfirmShowingEventArgs extends CancelEventArgs { readonly requestTriggerID: string; } interface GridViewBatchEditStartEditingEventArgs extends CancelEventArgs { focusedColumn: BootstrapGridViewColumn; readonly rowValues: any; readonly visibleIndex: number; } interface GridViewBatchEditEndEditingEventArgs extends CancelEventArgs { readonly rowValues: any; readonly visibleIndex: number; } interface GridViewBatchEditRowValidatingEventArgs extends EventArgs { readonly validationInfo: any; readonly visibleIndex: number; } interface GridViewBatchEditTemplateCellFocusedEventArgs extends EventArgs { readonly column: BootstrapGridViewColumn; handled: boolean; } interface GridViewBatchEditChangesSavingEventArgs extends CancelEventArgs { readonly deletedValues: any; readonly insertedValues: any; readonly updatedValues: any; } interface GridViewBatchEditChangesCancelingEventArgs extends CancelEventArgs { readonly deletedValues: any; readonly insertedValues: any; readonly updatedValues: any; } interface GridViewBatchEditRowInsertingEventArgs extends CancelEventArgs { readonly visibleIndex: number; } interface GridViewBatchEditRowDeletingEventArgs extends CancelEventArgs { readonly rowValues: any; readonly visibleIndex: number; } interface GridViewFocusedCellChangingEventArgs extends CancelEventArgs { readonly cellInfo: BootstrapGridViewCellInfo; } class BootstrapGridView extends BootstrapGridBase { readonly batchEditApi: BootstrapGridViewBatchEditApi | null; addNewRow(): void; applyFilter(filterExpression: string): void; applyOnClickRowFilter(): void; applySearchPanelFilter(value: string): void; autoFilterByColumn(column: BootstrapGridViewColumn, val: string): void; autoFilterByColumn(columnIndex: number, val: string): void; // tslint:disable-line:unified-signatures autoFilterByColumn(columnFieldNameOrId: string, val: string): void; // tslint:disable-line:unified-signatures unified-signatures cancelEdit(): void; clearFilter(): void; closeFilterControl(): void; collapseAll(): void; collapseAllDetailRows(): void; collapseDetailRow(visibleIndex: number): void; collapseRow(visibleIndex: number): void; collapseRow(visibleIndex: number, recursive: boolean): void; // tslint:disable-line:unified-signatures deleteRow(visibleIndex: number): void; deleteRowByKey(key: any): void; expandAll(): void; expandAllDetailRows(): void; expandDetailRow(visibleIndex: number): void; expandRow(visibleIndex: number): void; expandRow(visibleIndex: number, recursive: boolean): void; // tslint:disable-line:unified-signatures focus(): void; focusEditor(column: BootstrapGridViewColumn): void; focusEditor(columnIndex: number): void; // tslint:disable-line:unified-signatures focusEditor(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures getAutoFilterEditor(column: BootstrapGridViewColumn): any; getAutoFilterEditor(columnIndex: number): any; // tslint:disable-line:unified-signatures getAutoFilterEditor(columnFieldNameOrId: string): any; // tslint:disable-line:unified-signatures unified-signatures getColumn(columnIndex: number): BootstrapGridViewColumn | null; getColumnByField(columnFieldName: string): BootstrapGridViewColumn | null; getColumnById(columnId: string): BootstrapGridViewColumn | null; getColumnCount(): number; getColumnLayout(): any; getEditValue(column: BootstrapGridViewColumn): string; getEditValue(columnIndex: number): string; // tslint:disable-line:unified-signatures getEditValue(columnFieldNameOrId: string): string; // tslint:disable-line:unified-signatures unified-signatures getEditor(column: BootstrapGridViewColumn): BootstrapClientEdit; getEditor(columnIndex: number): BootstrapClientEdit; // tslint:disable-line:unified-signatures getEditor(columnFieldNameOrId: string): BootstrapClientEdit; // tslint:disable-line:unified-signatures unified-signatures getFocusedCell(): BootstrapGridViewCellInfo | null; getFocusedRowIndex(): number; getHorizontalScrollPosition(): number; getPageCount(): number; getPageIndex(): number; getPopupEditForm(): BootstrapPopupControl | null; getRowIndicesVisibleInViewPort(includePartiallyVisible: boolean): number[]; getRowKey(visibleIndex: number): string; getSelectedKeysOnPage(): any[]; getSelectedRowCount(): number; getTopVisibleIndex(): number; getVerticalScrollPosition(): number; getVisibleRowsOnPage(): number; gotoPage(pageIndex: number): void; groupBy(column: BootstrapGridViewColumn): void; groupBy(columnIndex: number): void; // tslint:disable-line:unified-signatures groupBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures groupBy(column: BootstrapGridViewColumn, groupIndex: number): void; // tslint:disable-line:unified-signatures groupBy(columnIndex: number, groupIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures groupBy(columnFieldNameOrId: string, groupIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures groupBy(column: BootstrapGridViewColumn, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures groupBy(columnIndex: number, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures groupBy(columnFieldNameOrId: string, groupIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures hideCustomizationWindow(): void; isCustomizationWindowVisible(): boolean; isDataRow(visibleIndex: number): boolean; isEditing(): boolean; isGroupRow(visibleIndex: number): boolean; isGroupRowExpanded(visibleIndex: number): boolean; isNewRowEditing(): boolean; isRowSelectedOnPage(visibleIndex: number): boolean; makeRowVisible(visibleIndex: number): void; nextPage(): void; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; prevPage(): void; refresh(): void; selectAllRowsOnPage(): void; selectRowOnPage(visibleIndex: number): void; selectRowOnPage(visibleIndex: number, selected: boolean): void; // tslint:disable-line:unified-signatures selectRows(): void; selectRowsByKey(keys: any[]): void; selectRowsByKey(key: any): void; // tslint:disable-line:unified-signatures selectRowsByKey(keys: any[], selected: boolean): void; // tslint:disable-line:unified-signatures selectRowsByKey(key: any, selected: boolean): void; // tslint:disable-line:unified-signatures unified-signatures setColumnLayout(columnLayout: any): void; setEditValue(column: BootstrapGridViewColumn, value: string): void; setEditValue(columnIndex: number, value: string): void; // tslint:disable-line:unified-signatures setEditValue(columnFieldNameOrId: string, value: string): void; // tslint:disable-line:unified-signatures unified-signatures setFilterEnabled(isFilterEnabled: boolean): void; setFixedColumnScrollableRows(scrollableRowSettings: any): void; setFocusedCell(rowVisibleIndex: number, columnIndex: number): void; setFocusedRowIndex(visibleIndex: number): void; setHorizontalScrollPosition(position: number): void; setSearchPanelCustomEditor(editor: BootstrapClientEdit): void; setVerticalScrollPosition(position: number): void; showCustomizationDialog(): void; showCustomizationWindow(): void; showFilterControl(): void; sortBy(column: BootstrapGridViewColumn): void; sortBy(columnIndex: number): void; // tslint:disable-line:unified-signatures sortBy(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(column: BootstrapGridViewColumn, sortOrder: string): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures sortBy(column: BootstrapGridViewColumn, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures sortBy(column: BootstrapGridViewColumn, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures sortBy(columnIndex: number, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures sortBy(columnFieldNameOrId: string, sortOrder: string, reset: boolean, sortIndex: number): void; // tslint:disable-line:unified-signatures unified-signatures unified-signatures startEditRow(visibleIndex: number): void; startEditRowByKey(key: any): void; ungroup(column: BootstrapGridViewColumn): void; ungroup(columnIndex: number): void; // tslint:disable-line:unified-signatures ungroup(columnFieldNameOrId: string): void; // tslint:disable-line:unified-signatures unified-signatures unselectAllRowsOnPage(): void; unselectFilteredRows(): void; unselectRowOnPage(visibleIndex: number): void; unselectRows(): void; unselectRowsByKey(keys: any[]): void; unselectRowsByKey(key: any): void; // tslint:disable-line:unified-signatures updateEdit(): void; on<K extends keyof BootstrapGridViewEventMap>(eventName: K, callback: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; once<K extends keyof BootstrapGridViewEventMap>(eventName: K, callback: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; off<K extends keyof BootstrapGridViewEventMap>(eventName?: K, callback?: (this: BootstrapGridView, args?: BootstrapGridViewEventMap[K]) => void): this; } interface BootstrapGridViewEventMap extends BootstrapGridBaseEventMap { "batchEditChangesCanceling": GridViewBatchEditChangesCancelingEventArgs; "batchEditChangesSaving": GridViewBatchEditChangesSavingEventArgs; "batchEditConfirmShowing": GridViewBatchEditConfirmShowingEventArgs; "batchEditEndEditing": GridViewBatchEditEndEditingEventArgs; "batchEditRowDeleting": GridViewBatchEditRowDeletingEventArgs; "batchEditRowInserting": GridViewBatchEditRowInsertingEventArgs; "batchEditRowValidating": GridViewBatchEditRowValidatingEventArgs; "batchEditStartEditing": GridViewBatchEditStartEditingEventArgs; "batchEditTemplateCellFocused": GridViewBatchEditTemplateCellFocusedEventArgs; "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "columnGrouping": GridViewColumnCancelEventArgs; "columnMoving": GridViewColumnMovingEventArgs; "columnResized": GridViewColumnProcessingModeEventArgs; "columnResizing": GridViewColumnCancelEventArgs; "columnSorting": GridViewColumnCancelEventArgs; "columnStartDragging": GridViewColumnCancelEventArgs; "contextMenu": GridViewContextMenuEventArgs; "contextMenuItemClick": GridViewContextMenuItemClickEventArgs; "customButtonClick": GridViewCustomButtonEventArgs; "customizationWindowCloseUp": EventArgs; "detailRowCollapsing": GridViewRowCancelEventArgs; "detailRowExpanding": GridViewRowCancelEventArgs; "endCallback": EndCallbackEventArgs; "focusedCellChanging": GridViewFocusedCellChangingEventArgs; "focusedRowChanged": GridViewFocusEventArgs; "rowClick": GridViewRowClickEventArgs; "rowCollapsing": GridViewRowCancelEventArgs; "rowDblClick": GridViewRowClickEventArgs; "rowExpanding": GridViewRowCancelEventArgs; "rowFocusing": GridViewRowFocusingEventArgs; "selectionChanged": GridViewSelectionEventArgs; } class BootstrapGridViewBatchEditApi { protected readonly instance: any; protected constructor(instance: any); addNewRow(): void; deleteRow(visibleIndex: number): void; deleteRowByKey(key: any): void; endEdit(): void; getCellTextContainer(visibleIndex: number, columnFieldNameOrId: string): any; getCellValue(visibleIndex: number, columnFieldNameOrId: string, initial: boolean): any; getColumnDisplayText(columnFieldNameOrId: string, value: any): string; getDeletedRowIndices(): number[]; getEditCellInfo(): BootstrapGridViewCellInfo | null; getInsertedRowIndices(): number[]; getRowVisibleIndices(includeDeleted: boolean): number[]; hasChanges(): boolean; isDeletedRow(visibleIndex: number): boolean; isNewRow(visibleIndex: number): boolean; moveFocusBackward(): boolean; moveFocusForward(): boolean; recoverRow(visibleIndex: number): void; recoverRowByKey(key: any): void; resetChanges(visibleIndex: number): void; resetChanges(visibleIndex: number, columnIndex: number): void; // tslint:disable-line:unified-signatures setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any): void; setCellValue(visibleIndex: number, columnFieldNameOrId: string, value: any, displayText: string, cancelCellHighlighting: boolean): void; startEdit(visibleIndex: number, columnIndex: number): void; validateRow(visibleIndex: number): boolean; validateRows(validateOnlyModified: boolean): boolean; } class BootstrapGridViewColumn { protected readonly instance: any; protected constructor(instance: any); readonly fieldName: string; readonly index: number; readonly name: string; readonly visible: boolean; } class BootstrapGridViewCellInfo { protected readonly instance: any; protected constructor(instance: any); readonly rowVisibleIndex: number; } class BootstrapHyperLink extends Control { getBadgeIconCssClass(): string; getBadgeText(): string; getCaption(): string; getEnabled(): boolean; getNavigateUrl(): string; getText(): string; getValue(): any; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setCaption(caption: string): void; setEnabled(value: boolean): void; setNavigateUrl(url: string): void; setText(text: string): void; setValue(value: any): void; on<K extends keyof BootstrapHyperLinkEventMap>(eventName: K, callback: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; once<K extends keyof BootstrapHyperLinkEventMap>(eventName: K, callback: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; off<K extends keyof BootstrapHyperLinkEventMap>(eventName?: K, callback?: (this: BootstrapHyperLink, args?: BootstrapHyperLinkEventMap[K]) => void): this; } interface BootstrapHyperLinkEventMap extends ControlEventMap { "click": EditClickEventArgs; } interface ListEditItemSelectedChangedEventArgs extends ProcessingModeEventArgs { readonly index: number; readonly isSelected: boolean; } interface ListEditCustomHighlightingEventArgs extends EventArgs { readonly filter: string; highlighting: any; } interface ListEditItemFilteringEventArgs extends EventArgs { readonly filter: string; isFit: boolean; readonly item: BootstrapListBoxItem; } class BootstrapListBox extends BootstrapClientEdit { addItem(texts: string[]): number; addItem(text: string): number; // tslint:disable-line:unified-signatures addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures addItemCssClass(index: number, className: string): void; addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; beginUpdate(): void; clearItems(): void; endUpdate(): void; findItemByText(text: string): BootstrapListBoxItem | null; findItemByValue(value: any): BootstrapListBoxItem | null; getItem(index: number): BootstrapListBoxItem | null; getItemBadgeIconCssClass(index: number): string; getItemBadgeText(index: number): string; getItemCount(): number; getSelectedIndex(): number; getSelectedIndices(): number[]; getSelectedItem(): BootstrapListBoxItem | null; getSelectedItems(): BootstrapListBoxItem[]; getSelectedValues(): any[]; insertItem(index: number, texts: string[]): void; insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures makeItemVisible(index: number): void; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; removeItem(index: number): void; removeItemCssClass(index: number, className: string): void; removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; selectAll(): void; selectIndices(indices: number[]): void; selectItems(items: BootstrapListBoxItem[]): void; selectValues(values: any[]): void; setItemBadgeIconCssClass(index: number, cssClass: string): void; setItemBadgeText(index: number, text: string): void; setItemHtml(index: number, html: string): void; setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; setItemTooltip(index: number, tooltip: string): void; setSelectedIndex(index: number): void; setSelectedItem(item: BootstrapListBoxItem): void; unselectAll(): void; unselectIndices(indices: number[]): void; unselectItems(items: BootstrapListBoxItem[]): void; unselectValues(values: any[]): void; on<K extends keyof BootstrapListBoxEventMap>(eventName: K, callback: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; once<K extends keyof BootstrapListBoxEventMap>(eventName: K, callback: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; off<K extends keyof BootstrapListBoxEventMap>(eventName?: K, callback?: (this: BootstrapListBox, args?: BootstrapListBoxEventMap[K]) => void): this; } interface BootstrapListBoxEventMap extends BootstrapClientEditEventMap { "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "customHighlighting": ListEditCustomHighlightingEventArgs; "endCallback": EndCallbackEventArgs; "itemDoubleClick": EventArgs; "itemFiltering": ListEditItemFilteringEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "selectedIndexChanged": ProcessingModeEventArgs; } class BootstrapListBoxItem { protected readonly instance: any; protected constructor(instance: any); readonly iconCssClass: string; readonly imageUrl: string; readonly index: number; readonly listEditBase: BootstrapListBox | null; readonly text: string; readonly value: any; getColumnText(columnIndex: number): string; getColumnText(columnName: string): string; // tslint:disable-line:unified-signatures getFieldText(fieldIndex: number): string; getFieldText(fieldName: string): string; // tslint:disable-line:unified-signatures } class BootstrapCheckBoxList extends BootstrapListBox { getItem(index: number): BootstrapListBoxItem | null; getItemCount(): number; getSelectedIndices(): number[]; getSelectedItems(): BootstrapListBoxItem[]; getSelectedValues(): any[]; selectAll(): void; selectIndices(indices: number[]): void; selectItems(items: BootstrapListBoxItem[]): void; selectValues(values: any[]): void; unselectAll(): void; unselectIndices(indices: number[]): void; unselectItems(items: BootstrapListBoxItem[]): void; unselectValues(values: any[]): void; on<K extends keyof BootstrapCheckBoxListEventMap>(eventName: K, callback: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; once<K extends keyof BootstrapCheckBoxListEventMap>(eventName: K, callback: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; off<K extends keyof BootstrapCheckBoxListEventMap>(eventName?: K, callback?: (this: BootstrapCheckBoxList, args?: BootstrapCheckBoxListEventMap[K]) => void): this; } interface BootstrapCheckBoxListEventMap extends BootstrapListBoxEventMap { // tslint:disable-line:no-empty-interface } class BootstrapRadioButtonList extends BootstrapListBox { getItem(index: number): BootstrapListBoxItem | null; getItemCount(): number; on<K extends keyof BootstrapRadioButtonListEventMap>(eventName: K, callback: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; once<K extends keyof BootstrapRadioButtonListEventMap>(eventName: K, callback: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; off<K extends keyof BootstrapRadioButtonListEventMap>(eventName?: K, callback?: (this: BootstrapRadioButtonList, args?: BootstrapRadioButtonListEventMap[K]) => void): this; } interface BootstrapRadioButtonListEventMap extends BootstrapListBoxEventMap { // tslint:disable-line:no-empty-interface } interface MenuItemEventArgs extends EventArgs { readonly item: BootstrapMenuItem; } interface MenuItemMouseEventArgs extends MenuItemEventArgs { // tslint:disable-line:no-empty-interface } interface MenuItemClickEventArgs extends ProcessingModeEventArgs { readonly htmlElement: object; readonly htmlEvent: object; readonly item: BootstrapMenuItem; } class BootstrapMenu extends Control { getItem(index: number): BootstrapMenuItem | null; getItemByName(name: string): BootstrapMenuItem | null; getItemCount(): number; getOrientation(): string; getRootItem(): BootstrapMenuItem | null; getSelectedItem(): BootstrapMenuItem | null; setOrientation(orientation: string): void; setSelectedItem(item: BootstrapMenuItem): void; on<K extends keyof BootstrapMenuEventMap>(eventName: K, callback: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; once<K extends keyof BootstrapMenuEventMap>(eventName: K, callback: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; off<K extends keyof BootstrapMenuEventMap>(eventName?: K, callback?: (this: BootstrapMenu, args?: BootstrapMenuEventMap[K]) => void): this; } interface BootstrapMenuEventMap extends ControlEventMap { "closeUp": MenuItemEventArgs; "itemClick": MenuItemClickEventArgs; "itemMouseOut": MenuItemMouseEventArgs; "itemMouseOver": MenuItemMouseEventArgs; "popUp": MenuItemEventArgs; } class BootstrapMenuItem { protected readonly instance: any; protected constructor(instance: any); readonly index: number; readonly indexPath: string; readonly menu: BootstrapMenu | null; readonly name: string; readonly parent: BootstrapMenuItem | null; getBadgeIconCssClass(): string; getBadgeText(): string; getChecked(): boolean; getEnabled(): boolean; getIconCssClass(): string; getImageUrl(): string; getItem(index: number): BootstrapMenuItem | null; getItemByName(name: string): BootstrapMenuItem | null; getItemCount(): number; getNavigateUrl(): string; getText(): string; getVisible(): boolean; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setChecked(value: boolean): void; setEnabled(value: boolean): void; setIconCssClass(cssClass: string): void; setImageUrl(value: string): void; setNavigateUrl(value: string): void; setText(value: string): void; setVisible(value: boolean): void; } interface PopupWindowEventArgs extends EventArgs { readonly window: BootstrapPopupWindow; } interface PopupWindowCloseUpEventArgs extends PopupWindowEventArgs { readonly closeReason: BootstrapPopupControlCloseReason; } interface PopupWindowCancelEventArgs extends CancelEventArgs { readonly closeReason: BootstrapPopupControlCloseReason; readonly window: BootstrapPopupWindow; } interface PopupWindowPinnedChangedEventArgs extends PopupWindowEventArgs { readonly pinned: boolean; } interface PopupWindowResizeEventArgs extends PopupWindowEventArgs { readonly resizeState: number; } class BootstrapPopupControl extends Control { adjustSize(): void; bringToFront(): void; bringWindowToFront(window: BootstrapPopupWindow): void; getCollapsed(): boolean; getContentHeight(): number; getContentHtml(): string; getContentIFrame(): any; getContentIFrameWindow(): any; getContentUrl(): string; getContentWidth(): number; getCurrentPopupElement(): any; getCurrentPopupElementIndex(): number; getFooterImageUrl(): string; getFooterNavigateUrl(): string; getFooterText(): string; getHeaderImageUrl(): string; getHeaderNavigateUrl(): string; getHeaderText(): string; getMainElement(): any; getMaximized(): boolean; getPinned(): boolean; getPopUpReasonMouseEvent(): any; getWindow(index: number): BootstrapPopupWindow | null; getWindowByName(name: string): BootstrapPopupWindow | null; getWindowCollapsed(window: BootstrapPopupWindow): boolean; getWindowContentHeight(window: BootstrapPopupWindow): number; getWindowContentHtml(window: BootstrapPopupWindow): string; getWindowContentIFrame(window: BootstrapPopupWindow): any; getWindowContentUrl(window: BootstrapPopupWindow): string; getWindowContentWidth(window: BootstrapPopupWindow): number; getWindowCount(): number; getWindowCurrentPopupElement(window: BootstrapPopupWindow): any; getWindowCurrentPopupElementIndex(window: BootstrapPopupWindow): number; getWindowHeight(window: BootstrapPopupWindow): number; getWindowMaximized(window: BootstrapPopupWindow): boolean; getWindowPinned(window: BootstrapPopupWindow): boolean; getWindowPopUpReasonMouseEvent(window: BootstrapPopupWindow): any; getWindowWidth(window: BootstrapPopupWindow): number; hide(): void; hideWindow(window: BootstrapPopupWindow): void; isVisible(): boolean; isWindowVisible(window: BootstrapPopupWindow): boolean; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; refreshContentUrl(): void; refreshPopupElementConnection(): void; refreshWindowContentUrl(window: BootstrapPopupWindow): void; setAdaptiveMaxHeight(maxHeight: number): void; setAdaptiveMaxHeight(maxHeight: string): void; // tslint:disable-line:unified-signatures setAdaptiveMaxWidth(maxWidth: number): void; setAdaptiveMaxWidth(maxWidth: string): void; // tslint:disable-line:unified-signatures setAdaptiveMinHeight(minHeight: number): void; setAdaptiveMinHeight(minHeight: string): void; // tslint:disable-line:unified-signatures setAdaptiveMinWidth(minWidth: number): void; setAdaptiveMinWidth(minWidth: string): void; // tslint:disable-line:unified-signatures setCollapsed(value: boolean): void; setContentHtml(html: string): void; setContentUrl(url: string): void; setFooterImageUrl(value: string): void; setFooterNavigateUrl(value: string): void; setFooterText(value: string): void; setHeaderImageUrl(value: string): void; setHeaderNavigateUrl(value: string): void; setHeaderText(value: string): void; setMaximized(value: boolean): void; setPinned(value: boolean): void; setPopupElementCssSelector(selector: string): void; setPopupElementID(popupElementId: string): void; setSize(width: number, height: number): void; setWindowAdaptiveMaxHeight(window: BootstrapPopupWindow, maxHeight: number): void; setWindowAdaptiveMaxHeight(window: BootstrapPopupWindow, maxHeight: string): void; // tslint:disable-line:unified-signatures setWindowAdaptiveMaxWidth(window: BootstrapPopupWindow, maxWidth: number): void; setWindowAdaptiveMaxWidth(window: BootstrapPopupWindow, maxWidth: string): void; // tslint:disable-line:unified-signatures setWindowAdaptiveMinHeight(window: BootstrapPopupWindow, minHeight: number): void; setWindowAdaptiveMinHeight(window: BootstrapPopupWindow, minHeight: string): void; // tslint:disable-line:unified-signatures setWindowAdaptiveMinWidth(window: BootstrapPopupWindow, minWidth: number): void; setWindowAdaptiveMinWidth(window: BootstrapPopupWindow, minWidth: string): void; // tslint:disable-line:unified-signatures setWindowCollapsed(window: BootstrapPopupWindow, value: boolean): void; setWindowContentHtml(window: BootstrapPopupWindow, html: string): void; setWindowContentUrl(window: BootstrapPopupWindow, url: string): void; setWindowMaximized(window: BootstrapPopupWindow, value: boolean): void; setWindowPinned(window: BootstrapPopupWindow, value: boolean): void; setWindowPopupElementID(window: BootstrapPopupWindow, popupElementId: string): void; setWindowSize(window: BootstrapPopupWindow, width: number, height: number): void; show(): void; showAtElement(htmlElement: any): void; showAtElementByID(id: string): void; showAtPos(x: number, y: number): void; showWindow(window: BootstrapPopupWindow): void; showWindow(window: BootstrapPopupWindow, popupElementIndex: number): void; // tslint:disable-line:unified-signatures showWindowAtElement(window: BootstrapPopupWindow, htmlElement: any): void; showWindowAtElementByID(window: BootstrapPopupWindow, id: string): void; showWindowAtPos(window: BootstrapPopupWindow, x: number, y: number): void; stretchVertically(): void; updatePosition(): void; updatePositionAtElement(htmlElement: any): void; updateWindowPosition(window: BootstrapPopupWindow): void; updateWindowPositionAtElement(window: BootstrapPopupWindow, htmlElement: any): void; windowStretchVertically(window: BootstrapPopupWindow): void; on<K extends keyof BootstrapPopupControlEventMap>(eventName: K, callback: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; once<K extends keyof BootstrapPopupControlEventMap>(eventName: K, callback: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; off<K extends keyof BootstrapPopupControlEventMap>(eventName?: K, callback?: (this: BootstrapPopupControl, args?: BootstrapPopupControlEventMap[K]) => void): this; } interface BootstrapPopupControlEventMap extends ControlEventMap { "afterResizing": PopupWindowEventArgs; "beforeResizing": PopupWindowEventArgs; "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "closeUp": PopupWindowCloseUpEventArgs; "closing": PopupWindowCancelEventArgs; "endCallback": EndCallbackEventArgs; "pinnedChanged": PopupWindowPinnedChangedEventArgs; "popUp": PopupWindowEventArgs; "resize": PopupWindowResizeEventArgs; "shown": PopupWindowEventArgs; } class BootstrapPopupWindow { protected readonly instance: any; protected constructor(instance: any); readonly index: number; readonly name: string; readonly popupControl: BootstrapPopupControl | null; getFooterImageUrl(): string; getFooterNavigateUrl(): string; getFooterText(): string; getHeaderImageUrl(): string; getHeaderNavigateUrl(): string; getHeaderText(): string; setFooterImageUrl(value: string): void; setFooterNavigateUrl(value: string): void; setFooterText(value: string): void; setHeaderImageUrl(value: string): void; setHeaderNavigateUrl(value: string): void; setHeaderText(value: string): void; } class BootstrapPopupMenu extends BootstrapMenu { getCurrentPopupElement(): any; getCurrentPopupElementIndex(): number; getItem(index: number): BootstrapMenuItem | null; getItemByName(name: string): BootstrapMenuItem | null; getRootItem(): BootstrapMenuItem | null; getSelectedItem(): BootstrapMenuItem | null; hide(): void; refreshPopupElementConnection(): void; setPopupElementCssSelector(selector: string): void; setPopupElementID(popupElementId: string): void; setSelectedItem(item: BootstrapMenuItem): void; show(): void; showAtElement(htmlElement: any): void; showAtElementByID(id: string): void; showAtPos(x: number, y: number): void; on<K extends keyof BootstrapPopupMenuEventMap>(eventName: K, callback: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; once<K extends keyof BootstrapPopupMenuEventMap>(eventName: K, callback: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; off<K extends keyof BootstrapPopupMenuEventMap>(eventName?: K, callback?: (this: BootstrapPopupMenu, args?: BootstrapPopupMenuEventMap[K]) => void): this; } interface BootstrapPopupMenuEventMap extends BootstrapMenuEventMap { // tslint:disable-line:no-empty-interface } class BootstrapProgressBar extends Control { getCaption(): string; getDisplayText(): string; getEnabled(): boolean; getMaximum(): number; getMinimum(): number; getPercent(): number; getPosition(): number; getValue(): any; setCaption(caption: string): void; setCustomDisplayFormat(text: string): void; setEnabled(value: boolean): void; setMaximum(max: number): void; setMinMaxValues(minValue: number, maxValue: number): void; setMinimum(min: number): void; setPosition(position: number): void; setValue(value: any): void; on<K extends keyof BootstrapProgressBarEventMap>(eventName: K, callback: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; once<K extends keyof BootstrapProgressBarEventMap>(eventName: K, callback: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; off<K extends keyof BootstrapProgressBarEventMap>(eventName?: K, callback?: (this: BootstrapProgressBar, args?: BootstrapProgressBarEventMap[K]) => void): this; } interface BootstrapProgressBarEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } interface ActiveViewChangingEventArgs extends EventArgs { cancel: boolean; readonly newView: BootstrapSchedulerViewType; readonly oldView: BootstrapSchedulerViewType; } interface AppointmentClickEventArgs extends EventArgs { readonly appointmentId: string; readonly handled: boolean; readonly htmlElement: object; } interface AppointmentDeletingEventArgs extends CancelEventArgs { readonly appointmentIds: object[]; } interface AppointmentDragEventArgs extends EventArgs { allow: boolean; readonly dragInformation: BootstrapSchedulerAppointmentDragInfo[]; readonly mouseEvent: any; } interface AppointmentDropEventArgs extends EventArgs { readonly dragInformation: BootstrapSchedulerAppointmentDragInfo[]; handled: boolean; readonly operation: BootstrapSchedulerAppointmentOperation; } interface AppointmentResizeEventArgs extends EventArgs { readonly appointmentId: string; handled: boolean; readonly newInterval: BootstrapTimeInterval; readonly oldInterval: BootstrapTimeInterval; readonly operation: BootstrapSchedulerAppointmentOperation; } interface AppointmentResizingEventArgs extends EventArgs { allow: boolean; readonly appointmentId: string; readonly mouseEvent: any; readonly newInterval: BootstrapTimeInterval; readonly oldInterval: BootstrapTimeInterval; } interface AppointmentToolTipShowingEventArgs extends CancelEventArgs { readonly appointment: BootstrapSchedulerAppointment; } interface AppointmentsSelectionEventArgs extends EventArgs { readonly appointmentIds: string[]; } interface CellClickEventArgs extends EventArgs { readonly htmlElement: object; readonly interval: BootstrapTimeInterval; readonly resource: string; } interface MenuItemClickedEventArgs extends EventArgs { handled: boolean; readonly itemName: string; } interface MoreButtonClickedEventArgs extends ProcessingModeEventArgs { handled: boolean; readonly interval: BootstrapTimeInterval; readonly resource: string; readonly targetDateTime: Date; } interface ShortcutEventArgs extends EventArgs { readonly commandName: string; readonly handled: boolean; readonly htmlEvent: object; } class BootstrapScheduler extends Control { appointmentFormCancel(): void; appointmentFormDelete(): void; appointmentFormSave(): void; changeFormContainer(container: any): void; changePopupMenuContainer(container: any): void; changeTimeZoneId(timeZoneId: string): void; changeToolTipContainer(container: any): void; deleteAppointment(apt: BootstrapSchedulerAppointment): void; deselectAppointmentById(aptId: any): void; getActiveViewType(): BootstrapSchedulerViewType; getAllDayAreaHeight(): number; getAppointmentById(id: any): BootstrapSchedulerAppointment | null; getAppointmentProperties(aptId: number, propertyNames: string[], onCallBack: any): string[]; getGroupType(): BootstrapSchedulerGroupType; getResourceNavigatorVisible(): boolean; getScrollAreaHeight(): number; getSelectedAppointmentIds(): string[]; getSelectedInterval(): BootstrapTimeInterval | null; getSelectedResource(): string; getToolbarVisible(): boolean; getTopRowTime(viewType: BootstrapSchedulerViewType): number; getVisibleAppointments(): BootstrapSchedulerAppointment[]; getVisibleIntervals(): BootstrapTimeInterval[]; goToDateFormApply(): void; goToDateFormCancel(): void; gotoDate(date: Date): void; gotoToday(): void; hideLoadingPanel(): void; inplaceEditFormCancel(): void; inplaceEditFormSave(): void; inplaceEditFormShowMore(): void; insertAppointment(apt: BootstrapSchedulerAppointment): void; navigateBackward(): void; navigateForward(): void; performCallback(parameter: string): void; refresh(): void; refreshClientAppointmentProperties(clientAppointment: BootstrapSchedulerAppointment, propertyNames: string[], onCallBack: any): void; reminderFormCancel(): void; reminderFormDismiss(): void; reminderFormDismissAll(): void; reminderFormSnooze(): void; selectAppointmentById(aptId: any): void; selectAppointmentById(aptId: any, scrollToSelection: boolean): void; // tslint:disable-line:unified-signatures setActiveViewType(value: BootstrapSchedulerViewType): void; setAllDayAreaHeight(height: number): void; setGroupType(value: BootstrapSchedulerGroupType): void; setHeight(height: number): void; setResourceNavigatorVisible(visible: boolean): void; setSelection(interval: BootstrapTimeInterval): void; setSelection(interval: BootstrapTimeInterval, resourceId: string): void; // tslint:disable-line:unified-signatures setSelection(interval: BootstrapTimeInterval, resourceId: string, scrollToSelection: boolean): void; // tslint:disable-line:unified-signatures setToolbarVisible(visible: boolean): void; setTopRowTime(duration: number): void; setTopRowTime(duration: number, viewType: BootstrapSchedulerViewType): void; // tslint:disable-line:unified-signatures setVisibleResources(resourceIds: string[]): void; showAppointmentFormByClientId(aptClientId: string): void; showAppointmentFormByServerId(aptServerId: string): void; showInplaceEditor(start: Date, end: Date): void; showInplaceEditor(start: Date, end: Date, resourceId: string): void; // tslint:disable-line:unified-signatures showLoadingPanel(): void; showSelectionToolTip(x: number, y: number): void; updateAppointment(apt: BootstrapSchedulerAppointment): void; on<K extends keyof BootstrapSchedulerEventMap>(eventName: K, callback: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; once<K extends keyof BootstrapSchedulerEventMap>(eventName: K, callback: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; off<K extends keyof BootstrapSchedulerEventMap>(eventName?: K, callback?: (this: BootstrapScheduler, args?: BootstrapSchedulerEventMap[K]) => void): this; } interface BootstrapSchedulerEventMap extends ControlEventMap { "activeViewChanged": EventArgs; "activeViewChanging": ActiveViewChangingEventArgs; "appointmentClick": AppointmentClickEventArgs; "appointmentDeleting": AppointmentDeletingEventArgs; "appointmentDoubleClick": AppointmentClickEventArgs; "appointmentDrag": AppointmentDragEventArgs; "appointmentDrop": AppointmentDropEventArgs; "appointmentResize": AppointmentResizeEventArgs; "appointmentResizing": AppointmentResizingEventArgs; "appointmentToolTipShowing": AppointmentToolTipShowingEventArgs; "appointmentsSelectionChanged": AppointmentsSelectionEventArgs; "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "cellClick": CellClickEventArgs; "cellDoubleClick": CellClickEventArgs; "endCallback": EndCallbackEventArgs; "menuItemClicked": MenuItemClickedEventArgs; "moreButtonClicked": MoreButtonClickedEventArgs; "selectionChanged": EventArgs; "selectionChanging": EventArgs; "shortcut": ShortcutEventArgs; "visibleIntervalChanged": EventArgs; } class BootstrapTimeInterval { protected readonly instance: any; protected constructor(instance: any); contains(interval: BootstrapTimeInterval): boolean; equals(interval: BootstrapTimeInterval): boolean; getAllDay(): boolean; getDuration(): number; getEnd(): Date; getStart(): Date; intersectsWith(interval: BootstrapTimeInterval): boolean; intersectsWithExcludingBounds(interval: BootstrapTimeInterval): boolean; setAllDay(allDayValue: boolean): void; setDuration(value: number): void; setEnd(value: Date): void; setStart(value: Date): void; } class BootstrapSchedulerAppointment { protected readonly instance: any; protected constructor(instance: any); readonly appointmentId: string; readonly appointmentType: BootstrapSchedulerAppointmentType; readonly interval: BootstrapTimeInterval | null; readonly labelIndex: number; readonly resources: string[]; readonly statusIndex: number; addResource(resourceId: object): void; getAllDay(): boolean; getAppointmentType(): BootstrapSchedulerAppointmentType; getDescription(): string; getDuration(): number; getEnd(): Date; getId(): any; getLabelId(): number; getLocation(): string; getRecurrenceInfo(): BootstrapSchedulerRecurrenceInfo | null; getRecurrencePattern(): BootstrapSchedulerAppointment | null; getResource(index: number): any; getStart(): Date; getStatusId(): number; getSubject(): string; setAllDay(allDay: boolean): void; setAppointmentType(type: BootstrapSchedulerAppointmentType): void; setDescription(description: string): void; setDuration(duration: number): void; setEnd(end: Date): void; setId(id: any): void; setLabelId(statusId: number): void; setLocation(location: string): void; setRecurrenceInfo(recurrenceInfo: BootstrapSchedulerRecurrenceInfo): void; setStart(start: Date): void; setStatusId(statusId: number): void; setSubject(subject: string): void; } class BootstrapSchedulerAppointmentDragInfo { protected readonly instance: any; protected constructor(instance: any); readonly appointmentId: string; readonly newInterval: BootstrapTimeInterval | null; readonly oldInterval: BootstrapTimeInterval | null; } class BootstrapSchedulerAppointmentOperation { protected readonly instance: any; protected constructor(instance: any); apply(): void; cancel(): void; } class BootstrapSchedulerRecurrenceInfo { protected readonly instance: any; protected constructor(instance: any); getDayNumber(): number; getDuration(): number; getEnd(): Date; getMonth(): number; getOccurrenceCount(): number; getPeriodicity(): number; getRange(): BootstrapSchedulerRecurrenceRange; getRecurrenceType(): BootstrapSchedulerRecurrenceType; getStart(): Date; getWeekDays(): WeekDays; getWeekOfMonth(): WeekOfMonth; setDayNumber(dayNumber: number): void; setDuration(duration: number): void; setEnd(end: Date): void; setMonth(month: number): void; setOccurrenceCount(occurrenceCount: number): void; setPeriodicity(periodicity: number): void; setRange(range: BootstrapSchedulerRecurrenceRange): void; setRecurrenceType(type: BootstrapSchedulerRecurrenceType): void; setStart(start: Date): void; setWeekDays(weekDays: WeekDays): void; setWeekOfMonth(weekOfMonth: WeekOfMonth): void; } class BootstrapSparkline extends Control { exportTo(fileName: string, format: string): void; getDataSource(): any; getInstance(): any; print(): void; setDataSource(dataSource: any): void; setOptions(options: any): void; on<K extends keyof BootstrapSparklineEventMap>(eventName: K, callback: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; once<K extends keyof BootstrapSparklineEventMap>(eventName: K, callback: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; off<K extends keyof BootstrapSparklineEventMap>(eventName?: K, callback?: (this: BootstrapSparkline, args?: BootstrapSparklineEventMap[K]) => void): this; } interface BootstrapSparklineEventMap extends ControlEventMap { "disposing": BootstrapChartEventArgsBase; "drawn": BootstrapChartEventArgsBase; "exported": BootstrapChartEventArgsBase; "exporting": BootstrapChartExportEventArgs; "fileSaving": BootstrapChartExportEventArgs; "incidentOccurred": BootstrapChartErrorEventArgs; "init": BootstrapChartEventArgsBase; "optionChanged": BootstrapChartOptionChangedEventArgs; "tooltipHidden": BootstrapChartEventArgsBase; "tooltipShown": BootstrapChartEventArgsBase; } class BootstrapTimeEdit extends BootstrapClientEdit { getButtonVisible(number: number): boolean; getCaretPosition(): number; getDate(): Date; getText(): string; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setDate(date: Date): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; on<K extends keyof BootstrapTimeEditEventMap>(eventName: K, callback: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; once<K extends keyof BootstrapTimeEditEventMap>(eventName: K, callback: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; off<K extends keyof BootstrapTimeEditEventMap>(eventName?: K, callback?: (this: BootstrapTimeEdit, args?: BootstrapTimeEditEventMap[K]) => void): this; } interface BootstrapTimeEditEventMap extends BootstrapClientEditEventMap { "buttonClick": ButtonEditClickEventArgs; "dateChanged": ProcessingModeEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapSpinEdit extends BootstrapClientEdit { getButtonVisible(number: number): boolean; getCaretPosition(): number; getMaxValue(): number; getMinValue(): number; getNumber(): number; getText(): string; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setMaxValue(value: number): void; setMinValue(value: number): void; setNumber(number: number): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; setValue(number: number): void; on<K extends keyof BootstrapSpinEditEventMap>(eventName: K, callback: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; once<K extends keyof BootstrapSpinEditEventMap>(eventName: K, callback: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; off<K extends keyof BootstrapSpinEditEventMap>(eventName?: K, callback?: (this: BootstrapSpinEdit, args?: BootstrapSpinEditEventMap[K]) => void): this; } interface BootstrapSpinEditEventMap extends BootstrapClientEditEventMap { "buttonClick": ButtonEditClickEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "numberChanged": ProcessingModeEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } interface TabControlTabEventArgs extends EventArgs { readonly tab: BootstrapTab; } interface TabControlTabCancelEventArgs extends ProcessingModeCancelEventArgs { reloadContentOnCallback: boolean; readonly tab: BootstrapTab; } interface TabControlTabClickEventArgs extends TabControlTabCancelEventArgs { readonly htmlElement: object; readonly htmlEvent: object; } class BootstrapTabControl extends Control { adjustSize(): void; getActiveTab(): BootstrapTab | null; getActiveTabIndex(): number; getTab(index: number): BootstrapTab | null; getTabByName(name: string): BootstrapTab | null; getTabCount(): number; setActiveTab(tab: BootstrapTab): void; setActiveTabIndex(index: number): void; on<K extends keyof BootstrapTabControlEventMap>(eventName: K, callback: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; once<K extends keyof BootstrapTabControlEventMap>(eventName: K, callback: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; off<K extends keyof BootstrapTabControlEventMap>(eventName?: K, callback?: (this: BootstrapTabControl, args?: BootstrapTabControlEventMap[K]) => void): this; } interface BootstrapTabControlEventMap extends ControlEventMap { "activeTabChanged": TabControlTabEventArgs; "activeTabChanging": TabControlTabCancelEventArgs; "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "endCallback": EndCallbackEventArgs; "tabClick": TabControlTabClickEventArgs; } class BootstrapTab { protected readonly instance: any; protected constructor(instance: any); readonly index: number; readonly name: string; readonly tabControl: BootstrapTabControl | null; getActiveIconCssClass(): string; getActiveImageUrl(): string; getBadgeIconCssClass(): string; getBadgeText(): string; getEnabled(): boolean; getIconCssClass(): string; getImageUrl(): string; getNavigateUrl(): string; getText(): string; getVisible(): boolean; setActiveIconCssClass(cssClass: string): void; setActiveImageUrl(value: string): void; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setEnabled(value: boolean): void; setIconCssClass(cssClass: string): void; setImageUrl(value: string): void; setNavigateUrl(value: string): void; setText(value: string): void; setVisible(value: boolean): void; } class BootstrapPageControl extends BootstrapTabControl { getActiveTab(): BootstrapTab | null; getTab(index: number): BootstrapTab | null; getTabByName(name: string): BootstrapTab | null; getTabContentHTML(tab: BootstrapTab): string; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; setActiveTab(tab: BootstrapTab): void; setTabContentHTML(tab: BootstrapTab, html: string): void; on<K extends keyof BootstrapPageControlEventMap>(eventName: K, callback: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; once<K extends keyof BootstrapPageControlEventMap>(eventName: K, callback: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; off<K extends keyof BootstrapPageControlEventMap>(eventName?: K, callback?: (this: BootstrapPageControl, args?: BootstrapPageControlEventMap[K]) => void): this; } interface BootstrapPageControlEventMap extends BootstrapTabControlEventMap { // tslint:disable-line:no-empty-interface } class BootstrapTagBox extends BootstrapClientEdit { addItem(texts: string[]): number; addItem(text: string): number; // tslint:disable-line:unified-signatures addItem(texts: string[], value: any): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any): number; // tslint:disable-line:unified-signatures unified-signatures addItem(texts: string[], value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures addItem(text: string, value: any, iconCssClass: string): number; // tslint:disable-line:unified-signatures unified-signatures addItemCssClass(index: number, className: string): void; addItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; addTag(text: string): void; adjustDropDownWindow(): void; beginUpdate(): void; clearItems(): void; clearTagCollection(): void; endUpdate(): void; ensureDropDownLoaded(callbackFunction: any): void; findItemByText(text: string): BootstrapListBoxItem | null; findItemByValue(value: any): BootstrapListBoxItem | null; getButtonVisible(number: number): boolean; getCaretPosition(): number; getItem(index: number): BootstrapListBoxItem | null; getItemBadgeIconCssClass(index: number): string; getItemBadgeText(index: number): string; getItemCount(): number; getSelectedIndex(): number; getSelectedItem(): BootstrapListBoxItem | null; getTagCollection(): string[]; getTagHtmlElement(index: number): any; getTagIndexByText(text: string): number; getTagRemoveButtonHtmlElement(index: number): any; getTagTextHtmlElement(index: number): any; getText(): string; getValue(): string; hideDropDown(): void; insertItem(index: number, texts: string[]): void; insertItem(index: number, text: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, texts: string[], value: any): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any): void; // tslint:disable-line:unified-signatures unified-signatures insertItem(index: number, texts: string[], value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures insertItem(index: number, text: string, value: any, iconCssClass: string): void; // tslint:disable-line:unified-signatures unified-signatures isCustomTag(text: string, caseSensitive: boolean): boolean; makeItemVisible(index: number): void; performCallback(data: any): Promise<void>; performCallback(data: any, onSuccess: () => void): void; removeItem(index: number): void; removeItemCssClass(index: number, className: string): void; removeItemTextCellCssClass(itemIndex: number, textCellIndex: number, className: string): void; removeTag(index: number): void; removeTagByText(text: string): void; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setItemBadgeIconCssClass(index: number, cssClass: string): void; setItemBadgeText(index: number, text: string): void; setItemHtml(index: number, html: string): void; setItemTextCellHtml(itemIndex: number, textCellIndex: number, html: string): void; setItemTextCellTooltip(itemIndex: number, textCellIndex: number, tooltip: string): void; setItemTooltip(index: number, tooltip: string): void; setSelectedIndex(index: number): void; setSelectedItem(item: BootstrapListBoxItem): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setTagCollection(collection: string[]): void; setText(text: string): void; setValue(value: string): void; showDropDown(): void; on<K extends keyof BootstrapTagBoxEventMap>(eventName: K, callback: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; once<K extends keyof BootstrapTagBoxEventMap>(eventName: K, callback: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; off<K extends keyof BootstrapTagBoxEventMap>(eventName?: K, callback?: (this: BootstrapTagBox, args?: BootstrapTagBoxEventMap[K]) => void): this; } interface BootstrapTagBoxEventMap extends BootstrapClientEditEventMap { "beginCallback": BeginCallbackEventArgs; "buttonClick": ButtonEditClickEventArgs; "callbackError": CallbackErrorEventArgs; "closeUp": EventArgs; "customHighlighting": ListEditCustomHighlightingEventArgs; "dropDown": EventArgs; "endCallback": EndCallbackEventArgs; "itemFiltering": ListEditItemFilteringEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "queryCloseUp": CancelEventArgs; "selectedIndexChanged": ProcessingModeEventArgs; "tagsChanged": EventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } interface ButtonEditClickEventArgs extends ProcessingModeEventArgs { readonly buttonIndex: number; } class BootstrapButtonEdit extends BootstrapClientEdit { getButtonVisible(number: number): boolean; getCaretPosition(): number; getText(): string; selectAll(): void; setButtonVisible(number: number, value: boolean): void; setCaretPosition(position: number): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; on<K extends keyof BootstrapButtonEditEventMap>(eventName: K, callback: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; once<K extends keyof BootstrapButtonEditEventMap>(eventName: K, callback: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; off<K extends keyof BootstrapButtonEditEventMap>(eventName?: K, callback?: (this: BootstrapButtonEdit, args?: BootstrapButtonEditEventMap[K]) => void): this; } interface BootstrapButtonEditEventMap extends BootstrapClientEditEventMap { "buttonClick": ButtonEditClickEventArgs; "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapMemo extends BootstrapClientEdit { getCaretPosition(): number; getText(): string; selectAll(): void; setCaretPosition(position: number): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; on<K extends keyof BootstrapMemoEventMap>(eventName: K, callback: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; once<K extends keyof BootstrapMemoEventMap>(eventName: K, callback: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; off<K extends keyof BootstrapMemoEventMap>(eventName?: K, callback?: (this: BootstrapMemo, args?: BootstrapMemoEventMap[K]) => void): this; } interface BootstrapMemoEventMap extends BootstrapClientEditEventMap { "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapTextBox extends BootstrapClientEdit { getCaretPosition(): number; getText(): string; selectAll(): void; setCaretPosition(position: number): void; setSelection(startPos: number, endPos: number, scrollToSelection: boolean): void; setText(text: string): void; on<K extends keyof BootstrapTextBoxEventMap>(eventName: K, callback: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; once<K extends keyof BootstrapTextBoxEventMap>(eventName: K, callback: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; off<K extends keyof BootstrapTextBoxEventMap>(eventName?: K, callback?: (this: BootstrapTextBox, args?: BootstrapTextBoxEventMap[K]) => void): this; } interface BootstrapTextBoxEventMap extends BootstrapClientEditEventMap { "keyDown": EditKeyEventArgs; "keyPress": EditKeyEventArgs; "keyUp": EditKeyEventArgs; "textChanged": ProcessingModeEventArgs; "userInput": EventArgs; } class BootstrapToolbar extends BootstrapMenu { on<K extends keyof BootstrapToolbarEventMap>(eventName: K, callback: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; once<K extends keyof BootstrapToolbarEventMap>(eventName: K, callback: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; off<K extends keyof BootstrapToolbarEventMap>(eventName?: K, callback?: (this: BootstrapToolbar, args?: BootstrapToolbarEventMap[K]) => void): this; } interface BootstrapToolbarEventMap extends BootstrapMenuEventMap { // tslint:disable-line:no-empty-interface } interface TreeViewNodeProcessingModeEventArgs extends ProcessingModeEventArgs { readonly node: BootstrapTreeViewNode; } interface TreeViewNodeClickEventArgs extends TreeViewNodeProcessingModeEventArgs { readonly htmlElement: any; readonly htmlEvent: any; } interface TreeViewNodeEventArgs extends EventArgs { readonly node: BootstrapTreeViewNode; } interface TreeViewNodeCancelEventArgs extends ProcessingModeCancelEventArgs { readonly node: BootstrapTreeViewNode; } class BootstrapTreeView extends Control { collapseAll(): void; expandAll(): void; getNode(index: number): BootstrapTreeViewNode | null; getNodeByName(name: string): BootstrapTreeViewNode | null; getNodeByText(text: string): BootstrapTreeViewNode | null; getNodeCount(): number; getRootNode(): BootstrapTreeViewNode | null; getSelectedNode(): BootstrapTreeViewNode | null; setSelectedNode(node: BootstrapTreeViewNode): void; on<K extends keyof BootstrapTreeViewEventMap>(eventName: K, callback: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; once<K extends keyof BootstrapTreeViewEventMap>(eventName: K, callback: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; off<K extends keyof BootstrapTreeViewEventMap>(eventName?: K, callback?: (this: BootstrapTreeView, args?: BootstrapTreeViewEventMap[K]) => void): this; } interface BootstrapTreeViewEventMap extends ControlEventMap { "beginCallback": BeginCallbackEventArgs; "callbackError": CallbackErrorEventArgs; "checkedChanged": TreeViewNodeProcessingModeEventArgs; "endCallback": EndCallbackEventArgs; "expandedChanged": TreeViewNodeEventArgs; "expandedChanging": TreeViewNodeCancelEventArgs; "nodeClick": TreeViewNodeClickEventArgs; } class BootstrapTreeViewNode extends Control { readonly index: number; readonly name: string; readonly parent: BootstrapTreeViewNode | null; readonly treeView: BootstrapTreeView | null; getBadgeIconCssClass(): string; getBadgeText(): string; getCheckState(): string; getChecked(): boolean; getEnabled(): boolean; getExpanded(): boolean; getHtmlElement(): any; getIconCssClass(): string; getImageUrl(): string; getNavigateUrl(): string; getNode(index: number): BootstrapTreeViewNode | null; getNodeByName(name: string): BootstrapTreeViewNode | null; getNodeByText(text: string): BootstrapTreeViewNode | null; getNodeCount(): number; getText(): string; getVisible(): boolean; setBadgeIconCssClass(cssClass: string): void; setBadgeText(text: string): void; setChecked(value: boolean): void; setEnabled(value: boolean): void; setExpanded(value: boolean): void; setIconCssClass(cssClass: string): void; setImageUrl(value: string): void; setNavigateUrl(value: string): void; setText(value: string): void; setVisible(value: boolean): void; on<K extends keyof BootstrapTreeViewNodeEventMap>(eventName: K, callback: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; once<K extends keyof BootstrapTreeViewNodeEventMap>(eventName: K, callback: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; off<K extends keyof BootstrapTreeViewNodeEventMap>(eventName?: K, callback?: (this: BootstrapTreeViewNode, args?: BootstrapTreeViewNodeEventMap[K]) => void): this; } interface BootstrapTreeViewNodeEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } interface UploadControlFilesUploadStartEventArgs extends EventArgs { readonly cancel: boolean; } interface UploadControlFileUploadCompleteEventArgs extends EventArgs { readonly callbackData: string; readonly errorText: string; readonly inputIndex: number; readonly isValid: boolean; } interface UploadControlFilesUploadCompleteEventArgs extends EventArgs { readonly callbackData: string; readonly errorText: string; } interface UploadControlTextChangedEventArgs extends EventArgs { readonly inputIndex: number; } interface UploadControlUploadingProgressChangedEventArgs extends EventArgs { readonly currentFileContentLength: number; readonly currentFileName: string; readonly currentFileProgress: number; readonly currentFileUploadedContentLength: number; readonly fileCount: number; readonly progress: number; readonly totalContentLength: number; readonly uploadedContentLength: number; } interface UploadControlValidationErrorOccurredEventArgs extends EventArgs { errorText: string; readonly invalidFiles: BootstrapUploadControlInvalidFileInfo[]; showAlert: boolean; readonly validationSettings: BootstrapUploadControlValidationSettings; } interface UploadControlDropZoneEnterEventArgs extends EventArgs { readonly dropZone: any; } interface UploadControlDropZoneLeaveEventArgs extends EventArgs { readonly dropZone: any; } class BootstrapUploadControl extends Control { addFileInput(): void; cancel(): void; clearText(): void; getAddButtonText(): string; getEnabled(): boolean; getFileInputCount(): number; getSelectedFiles(inputIndex: number): BootstrapUploadControlFile[]; getText(index: number): string; getUploadButtonText(): string; removeFileFromSelection(fileIndex: number): void; removeFileFromSelection(file: BootstrapUploadControlFile): void; // tslint:disable-line:unified-signatures removeFileInput(index: number): void; setAddButtonText(text: string): void; setDialogTriggerID(ids: string): void; setEnabled(enabled: boolean): void; setFileInputCount(count: number): void; setUploadButtonText(text: string): void; upload(): void; on<K extends keyof BootstrapUploadControlEventMap>(eventName: K, callback: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; once<K extends keyof BootstrapUploadControlEventMap>(eventName: K, callback: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; off<K extends keyof BootstrapUploadControlEventMap>(eventName?: K, callback?: (this: BootstrapUploadControl, args?: BootstrapUploadControlEventMap[K]) => void): this; } interface BootstrapUploadControlEventMap extends ControlEventMap { "dropZoneEnter": UploadControlDropZoneEnterEventArgs; "dropZoneLeave": UploadControlDropZoneLeaveEventArgs; "fileInputCountChanged": EventArgs; "fileUploadComplete": UploadControlFileUploadCompleteEventArgs; "filesUploadComplete": UploadControlFilesUploadCompleteEventArgs; "filesUploadStart": UploadControlFilesUploadStartEventArgs; "textChanged": UploadControlTextChangedEventArgs; "uploadingProgressChanged": UploadControlUploadingProgressChangedEventArgs; "validationErrorOccurred": UploadControlValidationErrorOccurredEventArgs; } class BootstrapUploadControlFile extends Control { readonly name: string; readonly size: number; readonly sourceFileObject: any; on<K extends keyof BootstrapUploadControlFileEventMap>(eventName: K, callback: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; once<K extends keyof BootstrapUploadControlFileEventMap>(eventName: K, callback: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; off<K extends keyof BootstrapUploadControlFileEventMap>(eventName?: K, callback?: (this: BootstrapUploadControlFile, args?: BootstrapUploadControlFileEventMap[K]) => void): this; } interface BootstrapUploadControlFileEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } class BootstrapUploadControlInvalidFileInfo extends Control { readonly fileName: string; readonly fileSize: number; on<K extends keyof BootstrapUploadControlInvalidFileInfoEventMap>(eventName: K, callback: (this: BootstrapUploadControlInvalidFileInfo, args?: BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; once<K extends keyof BootstrapUploadControlInvalidFileInfoEventMap>(eventName: K, callback: (this: BootstrapUploadControlInvalidFileInfo, args?: BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; off<K extends keyof BootstrapUploadControlInvalidFileInfoEventMap>(eventName?: K, callback?: (this: BootstrapUploadControlInvalidFileInfo, args?: BootstrapUploadControlInvalidFileInfoEventMap[K]) => void): this; } interface BootstrapUploadControlInvalidFileInfoEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } class BootstrapUploadControlValidationSettings extends Control { readonly allowedFileExtensions: string[]; readonly invalidFileNameCharacters: string[]; readonly maxFileCount: number; readonly maxFileSize: number; on<K extends keyof BootstrapUploadControlValidationSettingsEventMap>(eventName: K, callback: (this: BootstrapUploadControlValidationSettings, args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; once<K extends keyof BootstrapUploadControlValidationSettingsEventMap>(eventName: K, callback: (this: BootstrapUploadControlValidationSettings, args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; off<K extends keyof BootstrapUploadControlValidationSettingsEventMap>(eventName?: K, callback?: (this: BootstrapUploadControlValidationSettings, args?: BootstrapUploadControlValidationSettingsEventMap[K]) => void): this; } interface BootstrapUploadControlValidationSettingsEventMap extends ControlEventMap { // tslint:disable-line:no-empty-interface } }
the_stack
import fetch from "node-fetch"; import { getTokenInfo, TwitchServiceConfig, normalizeToken } from "nodecg-io-twitch-auth"; export class TwitchAddonsClient { private readonly clientId: string; private readonly token: string; constructor(clientId: string, token: string) { this.clientId = clientId; this.token = token; } /** * Gets the global emotes of BetterTTV */ async getBetterTTVGlobalEmotes(): Promise<BetterTTVEmote[]> { return await (await fetch("https://api.betterttv.net/3/cached/emotes/global")).json(); } /** * Gets the BetterTTV channel data associated with a twitch channel or undefined if that twitch user has * not registered for BetterTTV. */ async getBetterTTVChannel(channel: string): Promise<BetterTTVChannel | undefined> { const channelId = await this.getUserId(channel); if (channelId === undefined) { throw new Error(`Unknown twitch channel: ${channel}`); } const response = await (await fetch(`https://api.betterttv.net/3/cached/users/twitch/${channelId}`)).json(); if (response.message === "user not found") { // The user has no channel at BTTV (probably never logged in there) return undefined; } else if (response.message !== undefined) { throw new Error(`Failed to get BTTV channel: ${response.message}`); } return response; } /** * Gets the FFZ global emotes */ async getFFZGlobalEmotes(): Promise<FFZGlobalEmotes> { return await (await fetch("https://api.frankerfacez.com/v1/set/global")).json(); } /** * Gets the FFZ channel data associated with a twitch channel or undefined if that twitch user has * not registered for FFZ. */ async getFFZChannel(channel: string): Promise<FFZChannel | undefined> { const channelId = await this.getUserId(channel); if (channelId === undefined) { throw new Error(`Unknown twitch channel: ${channel}`); } const response = await (await fetch(`https://api.frankerfacez.com/v1/room/id/${channelId}`)).json(); if (response.error !== undefined) { if (response.message === "No such room") { // The user has no room at FFZ (probably never logged in there) return undefined; } else { throw new Error(`Failed to get FFZ channel: ${response.message}`); } } return response; } /** * Gets an emote collection for a channel. Here all emotes are stored so you can access all of them * without always sending requests to the APIs and caring about undefined values. (If someone is not * registered somewhere, there'll just be empty lists here). */ async getEmoteCollection(channel: string, includeGlobal: boolean): Promise<EmoteCollection> { const bttv = await this.getBetterTTVChannel(channel); const ffz = await this.getFFZChannel(channel); const bttvGlobal = includeGlobal ? await this.getBetterTTVGlobalEmotes() : undefined; const ffzGlobal = includeGlobal ? await this.getFFZGlobalEmotes() : undefined; const ffzGlobalSets: FFZEmoteSet[] = []; if (ffzGlobal !== undefined) { for (const set of ffzGlobal.default_sets) { const setObj = ffzGlobal.sets[set.toString()]; if (setObj !== undefined) { ffzGlobalSets.push(setObj); } } } return { bttvChannel: bttv === undefined ? [] : bttv.channelEmotes, bttvShared: bttv === undefined ? [] : bttv.sharedEmotes, bttvGlobal: bttvGlobal === undefined ? [] : bttvGlobal, ffz: ffz === undefined ? [] : Object.values(ffz.sets), ffzGlobal: ffzGlobalSets, }; } /** * Gets all emote names from an emote collection. */ getEmoteNames(emotes: EmoteCollection): string[] { const emotes_list: Set<string> = new Set(); for (const emote of emotes.bttvChannel) { emotes_list.add(emote.code); } for (const emote of emotes.bttvShared) { emotes_list.add(emote.code); } for (const set of emotes.ffz) { for (const emote of set.emoticons) { emotes_list.add(emote.name); } } for (const emote of emotes.bttvGlobal) { emotes_list.add(emote.code); } for (const set of emotes.ffzGlobal) { for (const emote of set.emoticons) { emotes_list.add(emote.name); } } return [...emotes_list]; } /** * Gets the emote URL for an emote name from an emote collection. If the requested resolution is * not available, you'll get the next available resolution that is smaller than the one you gave. * If there's no smaller resolution, you'll get the next bigger one. */ async getEmoteURL( emote: string, emotes: EmoteCollection, resolution: EmoteResolution, ): Promise<string | undefined> { // BTTV has resolutions 1, 2 and 3, ffz and twitch use 1, 2, and 4 const bttvResolution = resolution === 4 ? "3" : resolution.toString(); for (const entry of emotes.bttvChannel) { if (entry.code === emote) { return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`; } } for (const entry of emotes.bttvShared) { if (entry.code === emote) { return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`; } } for (const set of emotes.ffz) { for (const entry of set.emoticons) { if (entry.name === emote) { const url: FFZUrl | undefined = TwitchAddonsClient.getFFZUrl(entry.urls, resolution); if (url !== undefined) { return this.getURL(url); } } } } for (const entry of emotes.bttvGlobal) { if (entry.code === emote) { return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`; } } for (const set of emotes.ffzGlobal) { for (const entry of set.emoticons) { if (entry.name === emote) { const url: FFZUrl | undefined = TwitchAddonsClient.getFFZUrl(entry.urls, resolution); if (url !== undefined) { return this.getURL(url); } } } } return undefined; } /** * Gets a complete URL from a ffz URL. (This prepends `https:` to the ffz url) * @param part */ getURL(part: FFZUrl): string { return "https:" + part; } private async getUserId(channelId: string): Promise<string | undefined> { const username = channelId.startsWith("#") ? channelId.substr(1) : channelId; const response = await ( await fetch(`https://api.twitch.tv/helix/users?login=${username}`, { headers: { "Client-ID": this.clientId, Authorization: `Bearer ${this.token}`, }, }) ).json(); if ((response.data as unknown[]).length > 0) { return response.data[0].id; } else { return undefined; } } private static getFFZUrl(urls: Record<string, FFZUrl>, resolution: EmoteResolution): FFZUrl | undefined { for (let i = resolution; i > 0; i--) { const resolutionStr = resolution.toString(); if (resolutionStr in urls) { return urls[resolutionStr]; } } for (let i = resolution + 1; i <= 4; i++) { const resolutionStr = resolution.toString(); if (resolutionStr in urls) { return urls[resolutionStr]; } } // Should not happen... return undefined; } static async createClient(config: TwitchServiceConfig): Promise<TwitchAddonsClient> { const tokenInfo = await getTokenInfo(config); return new TwitchAddonsClient(tokenInfo.clientId, normalizeToken(config)); } } /** * The data the better twitch tv API gives for a twitch channel */ export type BetterTTVChannel = { /** * UUID used by BetterTTV for this channel */ id: string; /** * A list of names of accounts marked as bots in this channel. */ bots: string[]; /** * A list of emotes that were created by this channel's owner and uploaded to BetterTTV */ channelEmotes: BetterTTVChannelEmote[]; /** * A list of emotes that are not uploaded by this channel's owner but are available on this channel. */ sharedEmotes: BetterTTVSharedEmote[]; }; /** * One emote from BetterTTV */ export type BetterTTVEmote = { /** * A UUID used to identify this emote */ id: string; /** * The text in chat that trigger this emote to show up */ code: string; /** * The type of the image. */ imageType: "png" | "gif"; }; /** * One channel emote from BetterTTV */ export type BetterTTVChannelEmote = BetterTTVEmote & { /** * UUID of the user who created this emote. Pretty useless as it seems to be * always the same id that is also available in BetterTTVChannel */ userId: string; }; /** * One shared emote from BetterTTV */ export type BetterTTVSharedEmote = BetterTTVEmote & { /** * The user who created this emote */ user: BetterTTVUser; }; /** * A BetterTTV user */ export type BetterTTVUser = { /** * UUID used by BetterTTV for this user */ id: string; /** * The login name of this user */ name: string; /** * The display name (name with capitalisation) of this user */ displayName: string; /** * This seems to be the helix id of the user. */ providerId: string; }; /** * A FFZ URL is always only a part of a URL. Use getURL() to get a complete URL. */ export type FFZUrl = string; /** * A channel in the FrankerFaceZ API */ export type FFZChannel = { /** * Generic information about the channel */ room: FFZRoom; /** * A record containing emote sets. The key of the record is the id of the emote set. */ sets: Record<string, FFZEmoteSet>; }; /** * Generic information abou a FFZ channel. */ export type FFZRoom = { /** * The helix id of the user */ twitch_id: number; /** * The login name of the user */ id: string; /** * I can not really say what this is and it seems to be false in most cases. */ is_group: boolean; /** * The display name (name with capitalisation) of the user */ display_name: string; /** * The custom moderator badge url. */ moderatorBadge: string | null; // If anyone can tell what the next four are, please extend the type definition. // They were always null or empty for the channels I tested it with mod_urls: unknown; user_badges: Record<string, unknown>; user_badge_ids: Record<string, unknown>; css: unknown; }; /** * A set of FFZ emotes */ export type FFZEmoteSet = { /** * The id of the emote set. */ id: number; /** * The title of the emote set. */ title: string; // If anyone can tell what the next two are, please extend the type definition. // They were always null or empty for the channels I tested it with icon: unknown; css: unknown; emoticons: FFZEmote[]; }; /** * One FFZ emote */ export type FFZEmote = { /** * The id of the emote */ id: number; /** * The code used in chat to display this emote */ name: string; // Whatever this means. There are different resolutions anyways. width: number; height: number; public: boolean; offset: unknown; margins: unknown; css: unknown; owner: FFZUser; status: number; usage_count: number; // The next two are date strings created_at: string; last_updated: string; /** * URLS of the emote. The key is the resolution, which is always a number string. */ urls: Record<string, FFZUrl>; }; /** * A FFZ user */ export type FFZUser = { /** * The login name of the user */ name: string; /** * The display name (name with capitalisation) of the user */ display_name: string; }; /** * Global emotes from FFZ */ export type FFZGlobalEmotes = { /** * Contains the ids of sets that everyone can use. */ default_sets: number[]; /** * The global emote sets. The key of the record is the id of the emote set. */ sets: Record<string, FFZEmoteSet>; }; /** * Contains a list of emote sets from BTTV and / or FFZ */ export type EmoteCollection = { bttvChannel: BetterTTVChannelEmote[]; bttvShared: BetterTTVSharedEmote[]; bttvGlobal: BetterTTVEmote[]; ffz: FFZEmoteSet[]; ffzGlobal: FFZEmoteSet[]; }; /** * Resolution of an emote image */ export type EmoteResolution = 1 | 2 | 4;
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/containersMappers"; import * as Parameters from "../models/parameters"; import { DataBoxEdgeManagementClientContext } from "../dataBoxEdgeManagementClientContext"; /** Class representing a Containers. */ export class Containers { private readonly client: DataBoxEdgeManagementClientContext; /** * Create a Containers. * @param {DataBoxEdgeManagementClientContext} client Reference to the service client. */ constructor(client: DataBoxEdgeManagementClientContext) { this.client = client; } /** * @summary Lists all the containers of a storage Account in a Data Box Edge/Data Box Gateway * device. * @param deviceName The device name. * @param storageAccountName The storage Account name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.ContainersListByStorageAccountResponse> */ listByStorageAccount(deviceName: string, storageAccountName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ContainersListByStorageAccountResponse>; /** * @param deviceName The device name. * @param storageAccountName The storage Account name. * @param resourceGroupName The resource group name. * @param callback The callback */ listByStorageAccount(deviceName: string, storageAccountName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.ContainerList>): void; /** * @param deviceName The device name. * @param storageAccountName The storage Account name. * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ listByStorageAccount(deviceName: string, storageAccountName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ContainerList>): void; listByStorageAccount(deviceName: string, storageAccountName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ContainerList>, callback?: msRest.ServiceCallback<Models.ContainerList>): Promise<Models.ContainersListByStorageAccountResponse> { return this.client.sendOperationRequest( { deviceName, storageAccountName, resourceGroupName, options }, listByStorageAccountOperationSpec, callback) as Promise<Models.ContainersListByStorageAccountResponse>; } /** * @summary Gets a container by name. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container Name * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.ContainersGetResponse> */ get(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ContainersGetResponse>; /** * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container Name * @param resourceGroupName The resource group name. * @param callback The callback */ get(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.Container>): void; /** * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container Name * @param resourceGroupName The resource group name. * @param options The optional parameters * @param callback The callback */ get(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Container>): void; get(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Container>, callback?: msRest.ServiceCallback<Models.Container>): Promise<Models.ContainersGetResponse> { return this.client.sendOperationRequest( { deviceName, storageAccountName, containerName, resourceGroupName, options }, getOperationSpec, callback) as Promise<Models.ContainersGetResponse>; } /** * @summary Creates a new container or updates an existing container on the device. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param container The container properties. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<Models.ContainersCreateOrUpdateResponse> */ createOrUpdate(deviceName: string, storageAccountName: string, containerName: string, container: Models.Container, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ContainersCreateOrUpdateResponse> { return this.beginCreateOrUpdate(deviceName,storageAccountName,containerName,container,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ContainersCreateOrUpdateResponse>; } /** * Deletes the container on the Data Box Edge/Data Box Gateway device. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,storageAccountName,containerName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * @summary Refreshes the container metadata with the data from the cloud. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ refresh(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginRefresh(deviceName,storageAccountName,containerName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * @summary Creates a new container or updates an existing container on the device. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param container The container properties. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(deviceName: string, storageAccountName: string, containerName: string, container: Models.Container, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, storageAccountName, containerName, container, resourceGroupName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the container on the Data Box Edge/Data Box Gateway device. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, storageAccountName, containerName, resourceGroupName, options }, beginDeleteMethodOperationSpec, options); } /** * @summary Refreshes the container metadata with the data from the cloud. * @param deviceName The device name. * @param storageAccountName The Storage Account Name * @param containerName The container name. * @param resourceGroupName The resource group name. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginRefresh(deviceName: string, storageAccountName: string, containerName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, storageAccountName, containerName, resourceGroupName, options }, beginRefreshOperationSpec, options); } /** * @summary Lists all the containers of a storage Account in a Data Box Edge/Data Box Gateway * device. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ContainersListByStorageAccountNextResponse> */ listByStorageAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ContainersListByStorageAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByStorageAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ContainerList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByStorageAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ContainerList>): void; listByStorageAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ContainerList>, callback?: msRest.ServiceCallback<Models.ContainerList>): Promise<Models.ContainersListByStorageAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByStorageAccountNextOperationSpec, callback) as Promise<Models.ContainersListByStorageAccountNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByStorageAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccounts/{storageAccountName}/containers", urlParameters: [ Parameters.deviceName, Parameters.storageAccountName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ContainerList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccounts/{storageAccountName}/containers/{containerName}", urlParameters: [ Parameters.deviceName, Parameters.storageAccountName, Parameters.containerName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Container }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccounts/{storageAccountName}/containers/{containerName}", urlParameters: [ Parameters.deviceName, Parameters.storageAccountName, Parameters.containerName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "container", mapper: { ...Mappers.Container, required: true } }, responses: { 200: { bodyMapper: Mappers.Container }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccounts/{storageAccountName}/containers/{containerName}", urlParameters: [ Parameters.deviceName, Parameters.storageAccountName, Parameters.containerName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginRefreshOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/storageAccounts/{storageAccountName}/containers/{containerName}/refresh", urlParameters: [ Parameters.deviceName, Parameters.storageAccountName, Parameters.containerName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByStorageAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ContainerList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
'use strict'; import { anHourFromNow, errors, SharedAccessSignature, X509 } from 'azure-iot-common'; import { Http as HttpBase, HttpRequestOptions } from './http'; import { AccessToken, TokenCredential } from '@azure/core-http'; import * as uuid from 'uuid'; import { ClientRequest } from 'http'; import dbg = require('debug'); const debug = dbg('azure-iot-http-base.RestApiClient'); /** * @private */ export type HttpMethodVerb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** * @private */ export interface HttpTransportError extends Error { response?: any; responseBody?: any; } /** * @private * @class module:azure-iothub.RestApiClient * @classdesc Constructs an {@linkcode RestApiClient} object that can be used to make REST calls to the IoT Hub service. * * @instance {Object} config The configuration object that should be used to connect to the IoT Hub service. * @instance {Object} httpRequestBuilder OPTIONAL: The base http transport object. `azure-iot-common.Http` will be used if no argument is provided. * * @throws {ReferenceError} If the config argument is falsy * @throws {ArgumentError} If the config argument is missing a host or sharedAccessSignature error */ export class RestApiClient { private _BearerTokenPrefix: string = 'Bearer '; private _MinutesBeforeProactiveRenewal: number = 9; private _MillisecsBeforeProactiveRenewal: number = this._MinutesBeforeProactiveRenewal * 60000; private _config: RestApiClient.TransportConfig; private _accessToken: AccessToken; private _http: HttpBase; private _userAgent: string; constructor(config: RestApiClient.TransportConfig, userAgent: string, httpRequestBuilder?: HttpBase) { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_001: [The `RestApiClient` constructor shall throw a `ReferenceError` if config is falsy.]*/ if (!config) throw new ReferenceError('config cannot be \'' + config + '\''); /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_002: [The `RestApiClient` constructor shall throw an `ArgumentError` if config is missing a `host` property.]*/ if (!config.host) throw new errors.ArgumentError('config.host cannot be \'' + config.host + '\''); /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_18_001: [The `RestApiClient` constructor shall throw a `ReferenceError` if `userAgent` is falsy.]*/ if (!userAgent) throw new ReferenceError('userAgent cannot be \'' + userAgent + '\''); if (config.tokenCredential && !config.tokenScope) throw new errors.ArgumentError('config.tokenScope must be defined if config.tokenCredential is defined'); this._config = config; this._userAgent = userAgent; /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_003: [The `RestApiClient` constructor shall use `azure-iot-common.Http` as the internal HTTP client if the `httpBase` argument is `undefined`.]*/ /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_004: [The `RestApiClient` constructor shall use the value of the `httpBase` argument as the internal HTTP client if present.]*/ this._http = httpRequestBuilder || new HttpBase(); } /** * @method module:azure-iothub.RestApiClient.executeApiCall * @description Creates an HTTP request, sends it and parses the response, then call the callback with the resulting object. * * @param {Function} method The HTTP method that should be used. * @param {Function} path The path for the HTTP request. * @param {Function} headers Headers to add to the request on top of the defaults (Authorization, Request-Id and User-Agent will be populated automatically). * @param {Function} requestBody Body of the HTTP request. * @param {Function} timeout [optional] Custom timeout value. * @param {Function} done Called when a response has been received or if an error happened. * * @throws {ReferenceError} If the method or path arguments are falsy. * @throws {TypeError} If the type of the requestBody is not a string when Content-Type is text/plain */ executeApiCall( method: HttpMethodVerb, path: string, headers: { [key: string]: any }, requestBody: any, timeout?: number | HttpRequestOptions | RestApiClient.ResponseCallback, requestOptions?: HttpRequestOptions | number | RestApiClient.ResponseCallback, done?: RestApiClient.ResponseCallback): void { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_005: [The `executeApiCall` method shall throw a `ReferenceError` if the `method` argument is falsy.]*/ if (!method) throw new ReferenceError('method cannot be \'' + method + '\''); /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_006: [The `executeApiCall` method shall throw a `ReferenceError` if the `path` argument is falsy.]*/ if (!path) throw new ReferenceError('path cannot be \'' + path + '\''); /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_029: [If `done` is `undefined` and the `timeout` argument is a function, `timeout` should be used as the callback and mark `requestOptions` and `timeout` as `undefined`.]*/ if (done === undefined && typeof(timeout) === 'function') { done = timeout; requestOptions = timeout = undefined; } /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_13_001: [** If `done` is `undefined` and the `requestOptions` argument is a function, then `requestOptions` should be used as the callback and mark `requestOptions` as `undefined`.*/ if (done === undefined && typeof(requestOptions) === 'function') { done = requestOptions; requestOptions = undefined; } /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_13_002: [** If `timeout` is an object and `requestOptions` is `undefined`, then assign `timeout` to `requestOptions` and mark `timeout` as `undefined`.*/ if (typeof(timeout) === 'object' && requestOptions === undefined) { requestOptions = timeout; timeout = undefined; } /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_007: [The `executeApiCall` method shall add the following headers to the request: - Authorization: <this.sharedAccessSignature> - Request-Id: <guid> - User-Agent: <version string>]*/ let httpHeaders: any = headers || {}; if (this._config.tokenCredential) { this.getToken().then((accessToken) => { httpHeaders.Authorization = accessToken; this.executeBody(requestBody, httpHeaders, headers, method, path, timeout, requestOptions, done); }).catch((err) => { done(err); }); } else { if (this._config.sharedAccessSignature) { httpHeaders.Authorization = (typeof(this._config.sharedAccessSignature) === 'string') ? this._config.sharedAccessSignature as string : (this._config.sharedAccessSignature as SharedAccessSignature).extend(anHourFromNow()); } this.executeBody(requestBody, httpHeaders, headers, method, path, timeout, requestOptions, done); } } /** * @method module:azure-iothub.RestApiClient.updateSharedAccessSignature * @description Updates the shared access signature used to authenticate API calls. * * @param {string} sharedAccessSignature The new shared access signature that should be used. * * @throws {ReferenceError} If the new sharedAccessSignature is falsy. */ updateSharedAccessSignature(sharedAccessSignature: string | SharedAccessSignature): void { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_034: [The `updateSharedAccessSignature` method shall throw a `ReferenceError` if the `sharedAccessSignature` argument is falsy.]*/ if (!sharedAccessSignature) throw new ReferenceError('sharedAccessSignature cannot be \'' + sharedAccessSignature + '\''); /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_028: [The `updateSharedAccessSignature` method shall update the `sharedAccessSignature` configuration parameter that is used in the `Authorization` header of all HTTP requests.]*/ this._config.sharedAccessSignature = sharedAccessSignature; } /** * @private */ setOptions(options: any): void { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_18_003: [ `setOptions` shall call `this._http.setOptions` passing the same parameters ]*/ this._http.setOptions(options); } /** * @private * Calculates if the AccessToken's remaining time to live * is shorter than the proactive renewal time. * @param accessToken The AccessToken. * @returns {Boolean} True if the token's remaining time is shorter than the * proactive renewal time, false otherwise. */ isAccessTokenCloseToExpiry(accessToken: AccessToken): Boolean { const remainingTimeToLive = accessToken.expiresOnTimestamp - Date.now(); return remainingTimeToLive <= this._MillisecsBeforeProactiveRenewal; } /** * @private * Returns the current AccessToken if it is still valid * or a new AccessToken if the current token is close to expire. * @returns {Promise<string>} The access token string. */ async getToken(): Promise<string> { if ((!this._accessToken) || this.isAccessTokenCloseToExpiry(this._accessToken)) { this._accessToken = await this._config.tokenCredential.getToken(this._config.tokenScope) as any; } if (!this._accessToken) { throw new Error('AccessToken creation failed'); } return this._BearerTokenPrefix + this._accessToken.token; } private executeBody( requestBody: any, httpHeaders: any, headers: { [key: string]: any }, method: HttpMethodVerb, path: string, timeout?: number | HttpRequestOptions | RestApiClient.ResponseCallback, requestOptions?: HttpRequestOptions | number | RestApiClient.ResponseCallback, done?: RestApiClient.ResponseCallback): void { httpHeaders['Request-Id'] = uuid.v4(); httpHeaders['User-Agent'] = this._userAgent; let requestBodyString: string; if (requestBody) { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_035: [If there's is a `Content-Type` header and its value is `application/json; charset=utf-8` and the `requestBody` argument is a `string` it shall be used as is as the body of the request.]*/ /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_031: [If there's is a `Content-Type` header and its value is `application/json; charset=utf-8` and the `requestBody` argument is not a `string`, the body of the request shall be stringified using `JSON.stringify()`.]*/ if (!!headers['Content-Type'] && headers['Content-Type'].indexOf('application/json') >= 0) { if (typeof requestBody === 'string') { requestBodyString = requestBody; } else { requestBodyString = JSON.stringify(requestBody); } } else if (!!headers['Content-Type'] && headers['Content-Type'].indexOf('text/plain') >= 0) { if (typeof requestBody !== 'string') { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_033: [The `executeApiCall` shall throw a `TypeError` if there's is a `Content-Type` header and its value is `text/plain; charset=utf-8` and the `body` argument is not a string.]*/ throw new TypeError('requestBody must be a string'); } else { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_032: [If there's is a `Content-Type` header and its value is `text/plain; charset=utf-8`, the `requestBody` argument shall be used.]*/ requestBodyString = requestBody; } } /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_036: [The `executeApiCall` shall set the `Content-Length` header to the length of the serialized value of `requestBody` if it is truthy.]*/ const requestBodyStringSizeInBytes = Buffer.byteLength(requestBodyString, 'utf8'); headers['Content-Length'] = requestBodyStringSizeInBytes; } const requestCallback = (err, responseBody, response) => { debug(method + ' call to ' + path + ' returned ' + (err ? err : 'success')); if (err) { if (response) { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_010: [If the HTTP request fails with an error code >= 300 the `executeApiCall` method shall translate the HTTP error into a transport-agnostic error using the `translateError` method and call the `done` callback with the resulting error as the only argument.]*/ done(RestApiClient.translateError(responseBody, response)); } else { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_011: [If the HTTP request fails without an HTTP error code the `executeApiCall` shall call the `done` callback with the error itself as the only argument.]*/ done(err); } } else { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_009: [If the HTTP request is successful and the content-type header contains `application/json` the `executeApiCall` method shall parse the JSON response received and call the `done` callback with a `null` first argument, the parsed result as a second argument and the HTTP response object itself as a third argument.]*/ let result = ''; let parseError = null; /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_037: [If parsing the body of the HTTP response as JSON fails, the `done` callback shall be called with the SyntaxError thrown as a first argument, an `undefined` second argument, and the HTTP response object itself as a third argument.]*/ const expectJson = response.headers && response.headers['content-type'] && response.headers['content-type'].indexOf('application/json') >= 0; if (responseBody && expectJson) { try { result = JSON.parse(responseBody); } catch (ex) { if (ex instanceof SyntaxError) { parseError = ex; result = undefined; } else { throw ex; } } } done(parseError, result, response); } }; /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_008: [The `executeApiCall` method shall build the HTTP request using the arguments passed by the caller.]*/ let request: ClientRequest; if (!!this._config.x509) { /* Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_18_002: [ If an `x509` cert was passed into the constructor via the `config` object, `executeApiCall` shall use it to establish the TLS connection. ] */ request = this._http.buildRequest(method, path, httpHeaders, this._config.host, this._config.x509, requestCallback); } else { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_13_003: [** If `requestOptions` is not falsy then it shall be passed to the `buildRequest` function.*/ if (requestOptions) { request = this._http.buildRequest( method, path, httpHeaders, this._config.host, requestOptions as HttpRequestOptions, requestCallback ); } else { request = this._http.buildRequest(method, path, httpHeaders, this._config.host, requestCallback); } } /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_030: [If `timeout` is defined and is not a function, the HTTP request timeout shall be adjusted to match the value of the argument.]*/ if (timeout) { request.setTimeout(timeout as number); } debug('sending ' + method + ' call to ' + path); if (requestBodyString) { debug('with body ' + requestBodyString); request.write(requestBodyString); } request.end(); } /** * @method module:azure-iothub.RestApiClient.translateError * @description Translates an HTTP error into a transport-agnostic error. * * @param {string} body The HTTP error response body. * @param {string} response The HTTP response itself. * */ /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_027: [`translateError` shall accept 2 arguments: - the body of the HTTP response, containing the explanation of why the request failed. - the HTTP response object itself.]*/ static translateError(body: any, response: any): HttpTransportError { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_012: [Any error object returned by `translateError` shall inherit from the generic `Error` Javascript object and have 3 properties: - `response` shall contain the `IncomingMessage` object returned by the HTTP layer. - `responseBody` shall contain the content of the HTTP response. - `message` shall contain a human-readable error message.]*/ let error: HttpTransportError; const errorContent = HttpBase.parseErrorBody(body); const message = errorContent ? errorContent.message : 'Error: ' + body; switch (response.statusCode) { case 400: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_014: [`translateError` shall return an `ArgumentError` if the HTTP response status code is `400`.]*/ error = new errors.ArgumentError(message); break; case 401: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_015: [`translateError` shall return an `UnauthorizedError` if the HTTP response status code is `401`.]*/ error = new errors.UnauthorizedError(message); break; case 403: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_016: [`translateError` shall return an `TooManyDevicesError` if the HTTP response status code is `403`.]*/ error = new errors.TooManyDevicesError(message); break; case 404: if (errorContent && errorContent.code === 'DeviceNotFound') { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_018: [`translateError` shall return an `DeviceNotFoundError` if the HTTP response status code is `404` and if the error code within the body of the error response is `DeviceNotFound`.]*/ error = new errors.DeviceNotFoundError(message); } else if (errorContent && errorContent.code === 'IotHubNotFound') { /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_017: [`translateError` shall return an `IotHubNotFoundError` if the HTTP response status code is `404` and if the error code within the body of the error response is `IotHubNotFound`.]*/ error = new errors.IotHubNotFoundError(message); } else { error = new Error('Not found'); } break; case 408: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_019: [`translateError` shall return a `DeviceTimeoutError` if the HTTP response status code is `408`.]*/ error = new errors.DeviceTimeoutError(message); break; case 409: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_020: [`translateError` shall return an `DeviceAlreadyExistsError` if the HTTP response status code is `409`.]*/ error = new errors.DeviceAlreadyExistsError(message); break; case 412: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_021: [`translateError` shall return an `InvalidEtagError` if the HTTP response status code is `412`.]*/ error = new errors.InvalidEtagError(message); break; case 429: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_022: [`translateError` shall return an `ThrottlingError` if the HTTP response status code is `429`.]*/ error = new errors.ThrottlingError(message); break; case 500: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_023: [`translateError` shall return an `InternalServerError` if the HTTP response status code is `500`.]*/ error = new errors.InternalServerError(message); break; case 502: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_024: [`translateError` shall return a `BadDeviceResponseError` if the HTTP response status code is `502`.]*/ error = new errors.BadDeviceResponseError(message); break; case 503: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_025: [`translateError` shall return an `ServiceUnavailableError` if the HTTP response status code is `503`.]*/ error = new errors.ServiceUnavailableError(message); break; case 504: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_026: [`translateError` shall return a `GatewayTimeoutError` if the HTTP response status code is `504`.]*/ error = new errors.GatewayTimeoutError(message); break; default: /*Codes_SRS_NODE_IOTHUB_REST_API_CLIENT_16_013: [If the HTTP error code is unknown, `translateError` should return a generic Javascript `Error` object.]*/ error = new Error(message); } error.response = response; error.responseBody = body; return error; } } export namespace RestApiClient { export interface TransportConfig { host: string | { socketPath: string }; sharedAccessSignature?: string | SharedAccessSignature; x509?: X509; tokenCredential?: TokenCredential; tokenScope?: string | string[]; } export type ResponseCallback = (err: Error, responseBody?: any, response?: any) => void; }
the_stack
export default function makeDashboard(integrationId: string) { return { __inputs: [], __requires: [], annotations: { list: [] }, editable: false, gnetId: null, graphTooltip: 1, hideControls: false, id: null, links: [], refresh: false, panels: [ { datasource: null, gridPos: { h: 1, w: 24, x: 0, y: 0 }, id: 31, title: "Resources", type: "row" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 0, y: 1 }, id: 23, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `irate(container_cpu_usage_seconds_total{cpu="total",name="",pod!="",integration_id="${integrationId}"}[5m])`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Container CPU", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 12, y: 1 }, id: 25, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_cpu_usage_seconds_total{cpu="total",name="",pod!="",integration_id="${integrationId}"}[5m])) by (instance)`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], title: "Node CPU", type: "timeseries" }, { datasource: "$datasource", description: "", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "bytes" }, overrides: [] }, gridPos: { h: 8, w: 12, x: 0, y: 9 }, id: 2, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `container_memory_rss{container="",pod!="",name="",integration_id="${integrationId}"} < container_memory_working_set_bytes{container="",pod!="",name="",integration_id="${integrationId}"} or container_memory_working_set_bytes{container="",pod!="",name="",integration_id="${integrationId}"}`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Pod memory usage", type: "timeseries" }, { datasource: "$datasource", description: "Doesn't include host processes", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], min: 0, thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "percentunit" }, overrides: [] }, gridPos: { h: 8, w: 12, x: 12, y: 9 }, id: 4, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `(container_memory_rss{id="/",integration_id="${integrationId}"} < container_memory_working_set_bytes{id="/",integration_id="${integrationId}"} or container_memory_working_set_bytes{id="/",integration_id="${integrationId}"}) / on(instance) machine_memory_bytes{integration_id="${integrationId}"}`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], title: "Node memory usage by pods", type: "timeseries" }, { datasource: null, gridPos: { h: 1, w: 24, x: 0, y: 17 }, id: 29, title: "I/O", type: "row" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "binBps" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 0, y: 18 }, id: 11, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_fs_reads_bytes_total{container!="",pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, hide: false, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Disk Reads (bytes)", type: "timeseries" }, { datasource: "$datasource", description: "", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "short" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 6, y: 18 }, id: 12, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_fs_reads_total{container!="",pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, hide: false, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Disk Reads (iops)", type: "timeseries" }, { datasource: "$datasource", description: "", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "binBps" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 12, y: 18 }, id: 13, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_fs_writes_bytes_total{container!="",pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Disk Writes (bytes)", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "short" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 18, y: 18 }, id: 14, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_fs_writes_total{container!="",pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Disk Writes (iops)", type: "timeseries" }, { datasource: "$datasource", description: "", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "binBps" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 0, y: 26 }, id: 20, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_network_receive_bytes_total{pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Network RX (bytes)", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "short" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 6, y: 26 }, id: 21, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_network_receive_packets_total{pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Network RX (packets)", type: "timeseries" }, { datasource: "$datasource", description: "", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "binBps" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 12, y: 26 }, id: 19, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_network_transmit_bytes_total{pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Network TX (bytes)", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMax: -1, axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] }, unit: "short" }, overrides: [] }, gridPos: { h: 8, w: 6, x: 18, y: 26 }, id: 18, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(irate(container_network_transmit_packets_total{pod!="",integration_id="${integrationId}"}[5m])) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Network TX (packets)", type: "timeseries" }, { collapsed: false, datasource: null, gridPos: { h: 1, w: 24, x: 0, y: 34 }, id: 27, panels: [], title: "Limits", type: "row" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 0, y: 35 }, id: 6, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(container_file_descriptors{container!="",pod!="",integration_id="${integrationId}"}) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Open file descriptors", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 12, y: 35 }, id: 7, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(container_sockets{container!="",pod!="",integration_id="${integrationId}"}) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Open sockets", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 0, y: 43 }, id: 9, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(container_processes{container!="",pod!="",integration_id="${integrationId}"}) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Running processes", type: "timeseries" }, { datasource: "$datasource", fieldConfig: { defaults: { color: { mode: "palette-classic" }, custom: { axisLabel: "", axisPlacement: "auto", axisSoftMin: 0, barAlignment: 0, drawStyle: "line", fillOpacity: 0, gradientMode: "none", hideFrom: { legend: false, tooltip: false, viz: false }, lineInterpolation: "linear", lineWidth: 1, pointSize: 5, scaleDistribution: { type: "linear" }, showPoints: "auto", spanNulls: false, stacking: { group: "A", mode: "none" }, thresholdsStyle: { mode: "off" } }, mappings: [], thresholds: { mode: "absolute", steps: [ { color: "green", value: null }, { color: "red", value: 80 } ] } }, overrides: [] }, gridPos: { h: 8, w: 12, x: 12, y: 43 }, id: 8, options: { legend: { calcs: [], displayMode: "list", placement: "bottom" }, tooltip: { mode: "single" } }, targets: [ { exemplar: true, expr: `sum(container_threads{container!="",pod!="",integration_id="${integrationId}"}) by (namespace, pod)`, interval: "", legendFormat: "{{namespace}}/{{pod}}", refId: "A" } ], title: "Running threads", type: "timeseries" } ], schemaVersion: 30, style: "dark", tags: ["kubernetes-integration"], templating: { list: [ { current: { text: "Prometheus", value: "Prometheus" }, hide: 0, label: null, name: "datasource", options: [], query: "prometheus", refresh: 1, regex: "", type: "datasource" } ] }, time: { from: "now-1h", to: "now" }, timepicker: { refresh_intervals: [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], time_options: ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"] }, timezone: "", title: "Kubernetes / Resource metrics", uid: `res-${integrationId}`, version: 0 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import { Tournament, Player } from '..'; import { DeepPartial } from '../../utils/DeepPartial'; import { Design } from '../../Design'; import { deepMerge } from '../../utils/DeepMerge'; import { MatchDestroyedError, TournamentError, NotSupportedError, TournamentPlayerDoesNotExistError, AgentCompileError, AgentInstallError, FatalError, } from '../../DimensionError'; import { Agent } from '../../Agent'; import { Logger } from '../../Logger'; import { Dimension, NanoID } from '../../Dimension'; import { Database } from '../../Plugin/Database'; import { TournamentStatus } from '../TournamentStatus'; import { RankSystem } from '../RankSystem'; import { TournamentType } from '../TournamentTypes'; import { TrueSkillSystem } from '../RankSystem/TrueSkillSystem'; import { ELOSystem } from '../RankSystem/ELOSystem'; import LadderState = Ladder.State; import LadderConfigs = Ladder.Configs; import LadderPlayerStat = Ladder.PlayerStat; import { nanoid } from '../..'; import { deepCopy } from '../../utils/DeepCopy'; import { Scheduler } from '../Scheduler'; import { WinsSystem } from '../RankSystem/WinsSystem'; const REFRESH_RATE = 10000; /** * The Ladder Tournament class and namespace. */ export class Ladder extends Tournament { configs: Tournament.TournamentConfigs<LadderConfigs> = { defaultMatchConfigs: {}, type: TournamentType.LADDER, rankSystem: null, rankSystemConfigs: null, tournamentConfigs: { maxConcurrentMatches: 1, endDate: null, storePastResults: true, maxTotalMatches: null, matchMake: null, configSyncRefreshRate: 6000, syncConfigs: true, selfMatchMake: true, }, resultHandler: null, agentsPerMatch: [2], consoleDisplay: true, id: 'z3plg', }; state: LadderState = { playerStats: new Map(), currentRanks: [], results: [], statistics: { totalMatches: 0, }, }; type = Tournament.Type.LADDER; // lock matchqueue for concurrency private matchQueueLocked = false; /** * The ranksystem object being used to update, initialize, etc. ranks */ private ranksystem: RankSystem<any, any>; /** * tournament runner interval, periodically calls tourneyRunner to start up new matches */ private runInterval = null; /** * Configuration synchronization interval. Periodically makes a request to the DB if there is one and syncs configs */ private configSyncInterval = null; /** * Last modification date of configs */ private configLastModificationDate = new Date(0); // queue of the results to process resultProcessingQueue: Array<{ result: RankSystem.Results; mapAgentIDtoTournamentID: Map<Agent.ID, Tournament.ID>; }> = []; constructor( design: Design, files: | Array<string> | Array<{ file: string; name: string; existingID?: string }>, tournamentConfigs: Tournament.TournamentConfigsBase, id: NanoID, dimension: Dimension ) { super(design, id, tournamentConfigs, dimension); this.configs = deepMerge(this.configs, tournamentConfigs, true); if (typeof this.configs.rankSystem === 'string') { if (this.configs.rankSystemConfigs === null) { this.configs.rankSystemConfigs = {}; } switch (this.configs.rankSystem) { case Tournament.RankSystemTypes.TRUESKILL: this.ranksystem = new TrueSkillSystem(this.configs.rankSystemConfigs); break; case Tournament.RankSystemTypes.ELO: this.ranksystem = new ELOSystem(this.configs.rankSystemConfigs); break; case Tournament.RankSystemTypes.WINS: this.ranksystem = new WinsSystem(this.configs.rankSystemConfigs); break; default: throw new NotSupportedError( 'We currently do not support this rank system for ladder tournaments' ); } } else { this.ranksystem = this.configs.rankSystem; } if (this.ranksystem === null) { throw new FatalError('Did not supply a rank system'); } files.forEach((file) => { if (typeof file === 'string') { this.initialAddPlayerPromises.push( this.addplayer(file, undefined, true) ); } else { this.initialAddPlayerPromises.push( this.addplayer(file, file.existingID, true) ); } }); Promise.all(this.initialAddPlayerPromises).then(() => { this.emit(Tournament.Events.INITIAL_PLAYERS_INITIALIZED); }); this.status = TournamentStatus.INITIALIZED; // setup config syncing if DB is enabled and store configs if not stored already if (this.dimension.hasDatabase()) { if (this.configs.tournamentConfigs.syncConfigs) { this.syncConfigs(); this.setupConfigSyncInterval(); this.dimension.databasePlugin .getTournamentConfigs(this.id) .then((data) => { if (!data) { this.configLastModificationDate = new Date(); // store tournament configs if no configs found this.dimension.databasePlugin .storeTournamentConfigs( this.id, this.getConfigsStrippedOfFunctionFields(this.configs), this.status ) .then(() => { this.log.info( 'Storing initial tournament configuration data' ); }); } }); } } // setup matchmaking algorithm to default if not provided if (!this.configs.tournamentConfigs.matchMake) { let max = this.configs.agentsPerMatch[0]; this.configs.agentsPerMatch.forEach((v) => { max = Math.max(max, v); }); this.configs.tournamentConfigs.matchMake = Scheduler.RankRangeRandom({ agentsPerMatch: this.configs.agentsPerMatch, range: Math.ceil(max * 2.5), }); } this.log.info('Initialized Ladder Tournament'); } private getConfigsStrippedOfFunctionFields( object: Tournament.TournamentConfigs<LadderConfigs> ) { const obj = deepCopy(object); delete obj.resultHandler; delete obj.rankSystem; delete obj.tournamentConfigs.matchMake; return obj; } /** * Sync configs from DB */ private async syncConfigs() { const modDate = await this.dimension.databasePlugin.getTournamentConfigsModificationDate( this.id ); // if modDate exists, and mod date is past the last mode date. if ( modDate && modDate.getTime() > this.configLastModificationDate.getTime() ) { const { configs, status, } = await this.dimension.databasePlugin.getTournamentConfigs(this.id); this.log.info(`Received new configurations, mod date - ${modDate}`); this.log.detail(configs); this.configLastModificationDate = modDate; this.configs = deepMerge(this.configs, configs, true); // update status and run/stop/resume tourney as needed if (status !== this.status) { if (status === Tournament.Status.STOPPED) { if (this.status === Tournament.Status.RUNNING) { this.stop(); } } else if (status === Tournament.Status.RUNNING) { if (this.status === Tournament.Status.INITIALIZED) { this.run(); } else if (this.status === Tournament.Status.STOPPED) { this.resume(); } } } } } private setupConfigSyncInterval() { this.configSyncInterval = setInterval(() => { this.syncConfigs(); }, this.configs.tournamentConfigs.configSyncRefreshRate); } /** * Retrieves the local configurations */ public getConfigs(): Tournament.TournamentConfigs<LadderConfigs> { return this.configs; } /** * Set tournament status and updates DB / propagates the message to every other tournament instance */ public async setStatus(status: Tournament.Status): Promise<void> { if ( this.dimension.hasDatabase() && this.configs.tournamentConfigs.syncConfigs ) { await this.syncConfigs(); await this.dimension.databasePlugin.storeTournamentConfigs( this.id, this.getConfigsStrippedOfFunctionFields(this.configs), status ); this.status = status; } else { this.status = status; } } /** * Sets configs and updates DB / propagates the message to every other tournament instance */ public async setConfigs( configs: DeepPartial<Tournament.TournamentConfigs<LadderConfigs>> = {} ): Promise<void> { if (configs.id) { throw new TournamentError( 'You cannot change the tournament ID after constructing the tournament' ); } if (configs.rankSystem) { throw new TournamentError( 'You cannot change the rank system after constructing the tournament' ); } if ( this.dimension.hasDatabase() && this.configs.tournamentConfigs.syncConfigs ) { const plugin = this.dimension.databasePlugin; // ensure configs are up to date first, then set configs this.syncConfigs().then(() => { const newconfigs = deepMerge(deepCopy(this.configs), configs, true); plugin .storeTournamentConfigs( this.id, this.getConfigsStrippedOfFunctionFields(newconfigs), this.status ) .then(() => { // set configs locally as well if we succesfully store into DB this.configs = newconfigs; }); }); } else { // if sync off or no database, edit configs in memory this.configs = deepMerge(this.configs, configs, true); } } /** * Gets all rankings with the given offset from rank 1 and limit. Note this it's not recommended to use this * function if there are many users. It is suggested to create your own (aggregation) query to get rankings directly * from the DB. * @param offset * @param limit */ public async getRankings( offset = 0, limit = -1 ): Promise<Array<LadderPlayerStat>> { let rankings: Array<LadderPlayerStat> = []; if (this.dimension.hasDatabase()) { const users = await this.dimension.databasePlugin.getUsersInTournament( this.getKeyName(), 0, -1 ); rankings = users.map((user) => { const stat = user.statistics[this.getKeyName()]; const rankState = stat.rankState; return { player: stat.player, matchesPlayed: stat.matchesPlayed, rankState, }; }); if (this.anonymousCompetitors.size > 0) { this.anonymousCompetitors.forEach((player) => { const stat = this.state.playerStats.get(player.tournamentID.id); const rankState = stat.rankState; rankings.push({ player: stat.player, matchesPlayed: stat.matchesPlayed, rankState, }); }); } } else { this.state.playerStats.forEach((stat) => { rankings.push({ player: stat.player, matchesPlayed: stat.matchesPlayed, rankState: stat.rankState, }); }); } rankings.sort((a, b) => { return this.ranksystem.rankComparator(a.rankState, b.rankState); }); const end = limit === -1 ? rankings.length : offset + limit; return rankings.slice(offset, end); } /** * Resets rankings of all competitors loaded to initial scores */ public async resetRankings(): Promise<void> { // TODO: Some instances of tournament might still be running once this one is stopped, and reset won't work // correctly if (this.status == TournamentStatus.RUNNING) { throw new TournamentError('Cannot reset while tournament is running!'); } const updatePromises: Array<Promise<void>> = []; let playerStatsList: Array<Ladder.PlayerStat> = []; let userList: Array<Database.User> = []; if (this.dimension.hasDatabase()) { // get every user userList = await this.dimension.databasePlugin.getUsersInTournament( this.getKeyName(), 0, -1 ); playerStatsList = userList.map( (user) => user.statistics[this.getKeyName()] ); // add anonymous users playerStatsList.push(...Array.from(this.state.playerStats.values())); } else { playerStatsList = Array.from(this.state.playerStats.values()); } playerStatsList.forEach((stats, i) => { const resetPlayer = async () => { stats.matchesPlayed = 0; stats.rankState = this.ranksystem.resetRank(stats.rankState); if (this.dimension.hasDatabase()) { await this.updateDatabasePlayerStats(stats, userList[i]); } }; updatePromises.push(resetPlayer()); }); await Promise.all(updatePromises); } /** * Stops the tournament if it was running. * @param primary - whether or not the instance calling stop was the first one, the "primary" instance */ public async stop(primary = false): Promise<void> { if (this.status !== TournamentStatus.RUNNING) { throw new TournamentError(`Can't stop a tournament that isn't running`); } this.log.info('Stopping Tournament...'); clearInterval(this.runInterval); if (primary) { await this.setStatus(TournamentStatus.STOPPED); } else { this.status = TournamentStatus.STOPPED; } } /** * Resumes the tournament if it was stopped. * @param primary - whether or not the instance calling stop was the first one, the "primary" instance */ public async resume(primary = false): Promise<void> { if (this.status !== TournamentStatus.STOPPED) { throw new TournamentError(`Can't resume a tournament that isn't stopped`); } this.log.info('Resuming Tournament...'); if (primary) { await this.setStatus(TournamentStatus.RUNNING); } else { this.status = TournamentStatus.RUNNING; } this.tourneyRunner(); this.runInterval = setInterval(() => { this.tourneyRunner(); }, REFRESH_RATE); } /** * Begin the tournament. Resolves once the tournament is started * @param configs - tournament configurations to use * @param master - whether or not the instance calling stop was the first one, the "master" instance */ public async run( configs?: DeepPartial<Tournament.TournamentConfigs<LadderConfigs>>, master = false ): Promise<void> { this.log.info('Running Tournament'); this.configs = deepMerge(this.configs, configs, true); await this.initialize(); this.configs.tournamentConfigs.selfMatchMake ? await this.schedule() : this.log.info( 'Self match make turned off, tournament will only run matches stored in match queue' ); if (master) { this.setStatus(TournamentStatus.RUNNING); } else { this.status = TournamentStatus.RUNNING; } this.tourneyRunner(); this.runInterval = setInterval(() => { this.tourneyRunner(); }, REFRESH_RATE); } private async tourneyRunner() { if (this.matchQueueLocked) { return; } this.matchQueueLocked = true; if ( this.matches.size >= this.configs.tournamentConfigs.maxConcurrentMatches ) { this.matchQueueLocked = false; return; } const maxTotalMatches = this.configs.tournamentConfigs.maxTotalMatches; if (this.configs.tournamentConfigs.endDate) { const currDate = new Date(); if ( currDate.getTime() > this.configs.tournamentConfigs.endDate.getTime() ) { this.log.info( 'Reached past Tournament marked End Date, shutting down tournament...' ); // stop the tournament this.stop(); return; } } if (maxTotalMatches) { if (this.state.statistics.totalMatches >= maxTotalMatches) { this.log.info('Reached max matches, shutting down tournament...'); this.stop(); this.matchQueueLocked = false; return; } } const matchPromises = []; // if too little matches, schedule another set provided tournament is set to schedule its own matches if ( this.configs.tournamentConfigs.selfMatchMake && this.matchQueue.length < this.configs.tournamentConfigs.maxConcurrentMatches * 2 ) { await this.schedule(); } // run as many matches as allowed by maxConcurrentMatches, maxTotalMatches, and how many matches left in queue allow for ( let i = 0; i < Math.min( this.matchQueue.length, this.configs.tournamentConfigs.maxConcurrentMatches - this.matches.size ); i++ ) { if ( maxTotalMatches && maxTotalMatches - this.state.statistics.totalMatches - this.matches.size <= 0 ) { break; } const matchInfo = this.matchQueue.shift(); matchPromises.push(this.handleMatch(matchInfo)); } // as soon as one match finished, call it again Promise.race(matchPromises) .then(() => { if (this.status == TournamentStatus.RUNNING) { this.tourneyRunner(); } }) .catch((error) => { this.log.error(error); if (error instanceof MatchDestroyedError) { // keep running even if a match is destroyed and the tournament is marked as to keep running if (this.status == TournamentStatus.RUNNING) { this.tourneyRunner(); } } else { if (this.status == TournamentStatus.RUNNING) { this.tourneyRunner(); } } }); this.matchQueueLocked = false; } /** * Updates database with new player stats * * If failure occurs, we ignore it and just log it as we will likely in the future perform an update operation * on the database again anyway */ private async updateDatabasePlayerStats( playerStat: LadderPlayerStat, user?: Database.User ) { const player = playerStat.player; if (!player.anonymous) { const keyName = this.getKeyName(); const update = { statistics: {}, }; // if there exists stats already, keep them if (user && user.statistics) { update.statistics = user.statistics; } // perform update const plainPlayer = {}; Object.entries(player).forEach(([key, value]) => { plainPlayer[key] = value; }); update.statistics[keyName] = { ...playerStat, player: plainPlayer }; try { await this.dimension.databasePlugin.updateUser( player.tournamentID.id, update ); } catch (err) { this.log.error(`Failed to update user with player stats`, err); } } } private async initializePlayerStats(player: Player) { let playerStat: any = null; let user: Database.User; const keyName = this.getKeyName(); if (!player.anonymous && this.dimension.hasDatabase()) { user = await this.dimension.databasePlugin.getUser( player.tournamentID.id ); if (user) { // if there are stats if (user.statistics) { playerStat = user.statistics[keyName]; if (playerStat) { // if player stats exist already, we can return as we dont need to initialize anything and store to DB // we don't store anything locally because this is a user and we have DB return; } } } } // Initialize to default values if (!playerStat) { playerStat = { player: player, matchesPlayed: 0, rankState: this.ranksystem.initializeRankState(), }; await this.updateDatabasePlayerStats(playerStat, user); } // only store locally if not in DB if (!user) { this.state.playerStats.set(player.tournamentID.id, playerStat); } } /** * Initialize competition with given players, which can be local or stored in DB * * Does not read in any DB players, only uses those that are given at construction of tourney */ async initialize(): Promise<void> { // wait for all players to add in. await Promise.all(this.initialAddPlayerPromises); this.state.playerStats = new Map(); this.state.results = []; const promises: Array<Promise<void>> = []; this.competitors.forEach((player) => { promises.push(this.initializePlayerStats(player)); }); await Promise.all(promises); if (this.configs.consoleDisplay) { await this.printTournamentStatus(); } } /** * Schedules matches to play. By default uses {@link Scheduler.RankRangeRandom} * * If a {@link Ladder.Configs.matchMake | matchMake} function is provided, that will be used instead of the default. * * For users who want to host larger scale competitions with 1000+ competitors, its recommended to turn self match * make off and setup a separate match scheduling server that tournament servers can pull queued matches from */ private async schedule() { const rankings = await this.getRankings(0, -1); if (this.configs.tournamentConfigs.matchMake) { const newMatches = this.configs.tournamentConfigs.matchMake(rankings); this.matchQueue.push(...newMatches); return; } } /** Schedule a match using match info */ public scheduleMatches(...matchInfos: Array<Tournament.QueuedMatch>): void { this.matchQueue.push(...matchInfos); // kick off the runner to process any matches this.tourneyRunner(); } // called adding a new player async internalAddPlayer(player: Player): Promise<void> { await this.initializePlayerStats(player); } // should be called only for DB users async updatePlayer(player: Player): Promise<void> { const { user, playerStat } = await this.getPlayerStat( player.tournamentID.id ); const playerStats = <Ladder.PlayerStat>playerStat; playerStats.player = player; playerStats.matchesPlayed = 0; playerStats.rankState = this.ranksystem.onPlayerUpdate( playerStats.rankState ); if (this.dimension.hasDatabase()) { if (!player.anonymous) { await this.updateDatabasePlayerStats(playerStats, user); } } } /** * Removes player from tournament. Removes from state and stats from database * @param playerID */ async internalRemovePlayer(playerID: nanoid): Promise<void> { // TODO: we sometimes do a redudant call to get player stats when we really just need to check for existence const { user, playerStat } = await this.getPlayerStat(playerID); if (playerStat) { this.state.playerStats.delete(playerID); this.log.info('Removed player ' + playerID); if (this.dimension.hasDatabase()) { if (user) { const keyName = this.getKeyName(); const update = { statistics: {}, }; // if there exists stats already, keep them if (user && user.statistics) { update.statistics = user.statistics; } // delete stats for this tournament to remove player delete update.statistics[keyName]; await this.dimension.databasePlugin.updateUser(playerID, update); this.log.info('Removed player ' + playerID + ' from DB'); } } } else { throw new TournamentPlayerDoesNotExistError( `Could not find player with ID: ${playerID}` ); } } /** * Print tournament status to display */ /* istanbul ignore next */ private async printTournamentStatus() { if (this.log.level > Logger.LEVEL.NONE) { const ranks: Array<LadderPlayerStat> = await this.getRankings(0, -1); console.clear(); console.log(this.log.bar()); console.log( `Tournament - ID: ${this.id}, Name: ${this.name} | Dimension - ID: ${this.dimension.id}, Name: ${this.dimension.name}\nStatus: ${this.status} | Competitors: ${this.competitors.size} | Rank System: ${this.configs.rankSystem}\n` ); console.log( 'Total Matches: ' + this.state.statistics.totalMatches + ' | Matches Queued: ' + this.matchQueue.length ); console.log(this.ranksystem.getRankStatesHeaderString()); ranks.forEach((info) => { console.log( this.ranksystem.getRankStateString( info.player, info.rankState, info.matchesPlayed ) ); }); console.log(); console.log('Current Matches: ' + this.matches.size); this.matches.forEach((match) => { const names = []; match.agents.forEach((agent) => { names.push(agent.name); }); console.log(names); }); } } /** * Checks whether match can still be run * * If there are no stats, player was removed and match can't be run. If player is disabled, then it won't run */ private async checkMatchIntegrity(matchInfo: Array<Player>) { const checkIntegrity = async (id: nanoid) => { const stat = await this.getPlayerStat(id); if (!stat.playerStat) { return false; } else if (stat.playerStat.player.disabled) { return false; } return true; }; const promises: Array<Promise<boolean>> = []; for (let i = 0; i < matchInfo.length; i++) { const player = matchInfo[i]; promises.push(checkIntegrity(player.tournamentID.id)); } return Promise.all(promises).then((integritys) => { for (let i = 0; i < integritys.length; i++) { if (integritys[i] === false) return false; } return true; }); } /** * Handles the start and end of a match, and updates state accrding to match results and the given result handler * @param matchInfo */ private async handleMatch(queuedMatchInfo: Tournament.QueuedMatch) { // Consider adding possibility to use cached player meta data const matchInfo = await this.getMatchInfoFromQueuedMatch(queuedMatchInfo); if (!(await this.checkMatchIntegrity(matchInfo))) { // quit this.log.detail('Match queued cannot be run anymore'); return; } if (this.configs.consoleDisplay) { await this.printTournamentStatus(); } this.log.detail( 'Running match - Competitors: ', matchInfo.map((player) => { return player.tournamentID.name; }) ); const matchRes = await this.runMatch(matchInfo); if (matchRes.err) { if (matchRes.err instanceof AgentCompileError) { const tournamentID = matchRes.match.mapAgentIDtoTournamentID.get( matchRes.err.agentID ); this.log.warn( `Match couldn't run. Player ${tournamentID.id} got a compile error` ); await this.disablePlayer(tournamentID.id); } else if (matchRes.err instanceof AgentInstallError) { const tournamentID = matchRes.match.mapAgentIDtoTournamentID.get( matchRes.err.agentID ); this.log.warn( `Match couldn't run. Player ${tournamentID.id} got an install error` ); await this.disablePlayer(tournamentID.id); } else { this.log.error(`Match couldn't run, aborting... `, matchRes.err); } // remove the match from the active matches list this.matches.delete(matchRes.match.id); return; } // update total matches this.state.statistics.totalMatches++; const resInfo = this.configs.resultHandler(matchRes.results); // push to result processing queue this.resultProcessingQueue.push({ result: resInfo, mapAgentIDtoTournamentID: matchRes.match.mapAgentIDtoTournamentID, }); // make a call to handle match with trueskill to process the next result in the processing queue this.handleMatchResults(); // store past results if (this.configs.tournamentConfigs.storePastResults) { if ( !( this.dimension.hasDatabase() && this.dimension.databasePlugin.configs.saveTournamentMatches ) ) { // if we have don't have a database that is set to actively store tournament matches we store locally this.state.results.push(matchRes.results); } } } /** * Update player stats for whoever stats owns this player stat. Determined by checking the player field of * {@link Ladder.PlayerStat} */ private async updatePlayerStat(currentStats: Ladder.PlayerStat) { // store locally if not in db if (currentStats.player.anonymous) { this.state.playerStats.set( currentStats.player.tournamentID.id, currentStats ); } else { try { const user = await this.dimension.databasePlugin.getUser( currentStats.player.tournamentID.id ); // if user is still in tourney, update it if (user && user.statistics[this.getKeyName()]) { await this.updateDatabasePlayerStats(currentStats, user); } } catch (err) { // don't stop tourney if this happens this.log.error(`Issue with using database`, err); } } } private async handleMatchResults() { const toProcess = this.resultProcessingQueue.shift(); const mapAgentIDtoTournamentID = toProcess.mapAgentIDtoTournamentID; const result = toProcess.result; // stop if no ranks provided, meaning match not successful and we throw result away if (result.ranks.length === 0) { this.emit(Tournament.Events.MATCH_HANDLED); return; } result.ranks.sort((a, b) => a.rank - b.rank); const rankStatePromises: Array<Promise<void>> = []; // the following 3 arrays are parallel const ranks: Array<number> = []; const currentRankStates: Array<any> = []; const tourneyIDs: Array<{ id: Tournament.ID; stats: LadderPlayerStat; }> = []; result.ranks.forEach((rankInfo) => { const fetchRankState = async () => { const tournamentID = mapAgentIDtoTournamentID.get(rankInfo.agentID); const { playerStat } = await this.getPlayerStat(tournamentID.id); if (!playerStat) { throw new TournamentPlayerDoesNotExistError( `Player ${tournamentID.id} doesn't exist anymore, likely was removed` ); } const currentplayerStats = <Ladder.PlayerStat>playerStat; currentplayerStats.matchesPlayed++; ranks.push(rankInfo.rank); tourneyIDs.push({ id: tournamentID, stats: currentplayerStats }); currentRankStates.push(currentplayerStats.rankState); }; rankStatePromises.push(fetchRankState()); }); try { await Promise.all(rankStatePromises); } catch (err) { this.log.error('Probably due to player being removed: ', err); this.emit(Tournament.Events.MATCH_HANDLED); return; } const newRankStates = this.ranksystem.updateRanks(currentRankStates, ranks); const updatePlayerStatsPromises: Array<Promise<void>> = []; tourneyIDs.forEach((info, i) => { const updateStat = async () => { const currentStats: Ladder.PlayerStat = info.stats; currentStats.rankState = newRankStates[i]; await this.updatePlayerStat(currentStats); }; updatePlayerStatsPromises.push(updateStat()); }); await Promise.all(updatePlayerStatsPromises); if (this.configs.consoleDisplay) { await this.printTournamentStatus(); } this.emit(Tournament.Events.MATCH_HANDLED); } protected async preInternalDestroy(): Promise<void> { if (this.runInterval) clearInterval(this.runInterval); if (this.configSyncInterval) clearInterval(this.configSyncInterval); } } /** * The Ladder Tournament namespace */ export namespace Ladder { /** * Configuration interface for Ladder Tournaments */ export interface Configs extends Tournament.TournamentTypeConfig { /** Max matches that can run concurrently on one node instance * @default 1 */ maxConcurrentMatches: number; /** The date to stop running this tournament once it is started. If null, no end date * @default null */ endDate: Date; /** The max matches to run before stopping the tournament. If null, then no maximum * @default null */ maxTotalMatches: number; /** * Custom match making scheduler function. User can provide a custom function here to create matches to store * into the matchqueue for {@link Match} making. This function will be called every time the number of queued * matches is below a threshold of {@link maxConcurrentMatches} * 2. * * It should return an array of {@link Player } arrays, a list of all the new matches to append to the matchQueue. * A player array represents a queued match and the players that will compete in that match. * * * Default function is described in {@link schedule} * */ matchMake: /** * @param playerStats - an array of all player stats in the tournament. See {@link PlayerStat} for what variables * are exposed to use to help schedule matches */ (playerStats: Array<PlayerStat>) => Array<Tournament.QueuedMatch>; /** * Rate in ms of how fast to sync the configs. Used for synchronizing configs in a distributed system. * * @default `6000` */ configSyncRefreshRate: number; /** * Whether or not to sync configs with database and other tournaments of the same id * * @default `true` */ syncConfigs: boolean; /** * Whether or not this tournament will schedule its own matches using its own {@link Ladder.Configs.matchMake | matchMake} function * * @default `true` */ selfMatchMake: boolean; } /** * The Ladder Tournament state, consisting of the current player statistics and past results */ export interface State extends Tournament.TournamentTypeState { /** * A map from a {@link Player} Tournament ID string to statistics */ playerStats: Map<NanoID, PlayerStat>; /** * Stats for this Tournament in this instance. Intended to be constant memory usage */ statistics: { totalMatches: number; }; currentRanks: Array<{ player: Player; rankState: any }>; } /** * Player stat interface for ladder tournaments */ export interface PlayerStat extends Tournament.PlayerStatBase { /** * total matches played with current bot */ matchesPlayed: number; /** * the ranking statistics for the player. the type of this variable is dependent on the ranking system you use for * the tournament. If the ranking system is {@link RankSystem.TrueSkill | TrueSkill}, then see * {@link RankSystem.TrueSkill.RankState} for the rank state typings. */ rankState: any; } }
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GLib from 'glib'; import * as Meta from 'meta'; import * as Shell from 'shell'; import { MsWindow } from 'src/layout/msWorkspace/msWindow'; import { MsWorkspace, MsWorkspaceState, } from 'src/layout/msWorkspace/msWorkspace'; import { MsManager } from 'src/manager/msManager'; import { assert, assertNotNull } from 'src/utils/assert'; import { isNonNull } from 'src/utils/predicates'; import { getSettings } from 'src/utils/settings'; import { layout, main as Main, windowManager } from 'ui'; import { MetaWindowWithMsProperties } from './msWindowManager'; import Monitor = layout.Monitor; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); const WorkspaceTracker = windowManager.WorkspaceTracker; interface MsWorkspaceManagerState { msWorkspaceList: MsWorkspaceState[]; primaryWorkspaceActiveIndex: number; } export class MsWorkspaceManager extends MsManager { workspaceManager: Meta.WorkspaceManager; private _state: MsWorkspaceManagerState; windowTracker: any; msWorkspaceList: MsWorkspace[]; settings: Gio.Settings; metaWindowFocused: Meta.Window | null; numOfMonitors: number; primaryIndex: number; workspaceTracker: windowManager.WorkspaceTracker; private _updatingMonitors: boolean | undefined; restoringState: any; stateChangedTriggered: any; constructor(state = {}) { super(); this.workspaceManager = global.workspace_manager; this._state = Object.assign( { msWorkspaceList: [], primaryWorkspaceActiveIndex: this.workspaceManager.get_active_workspace_index(), }, state ); this.windowTracker = Shell.WindowTracker.get_default(); this.msWorkspaceList = []; this.settings = getSettings('tweaks'); this.metaWindowFocused = null; this.numOfMonitors = global.display.get_n_monitors(); this.primaryIndex = global.display.get_primary_monitor(); this.workspaceTracker = Main.wm._workspaceTracker; (WorkspaceTracker.prototype as any)._oldCheckWorkspaces = WorkspaceTracker.prototype._checkWorkspaces; WorkspaceTracker.prototype._checkWorkspaces = function () { const workspaceManager = global.workspace_manager; let i; const emptyWorkspaces: boolean[] = []; if (!Meta.prefs_get_dynamic_workspaces()) { this._checkWorkspacesId = 0; const msWorkspaceManager = global.ms.msWorkspaceManager; while ( workspaceManager.get_n_workspaces() < msWorkspaceManager.primaryMsWorkspaces.length ) { const workspaceIndex = msWorkspaceManager.msWorkspaceList.indexOf( msWorkspaceManager.primaryMsWorkspaces[ msWorkspaceManager.primaryMsWorkspaces.length - 1 ] ); msWorkspaceManager.removeMsWorkspaceAtIndex(workspaceIndex); } return false; } for (i = 0; i < this._workspaces.length; i++) { const lastRemoved = this._workspaces[i]._lastRemovedWindow; if ( (lastRemoved && (lastRemoved.get_window_type() == Meta.WindowType.SPLASHSCREEN || lastRemoved.get_window_type() == Meta.WindowType.DIALOG || lastRemoved.get_window_type() == Meta.WindowType.MODAL_DIALOG)) || this._workspaces[i]._keepAliveId ) emptyWorkspaces[i] = false; else emptyWorkspaces[i] = true; } const sequences = Shell.WindowTracker.get_default().get_startup_sequences(); for (i = 0; i < sequences.length; i++) { const index = sequences[i].get_workspace(); if (index >= 0 && index <= workspaceManager.n_workspaces) emptyWorkspaces[index] = false; } const msWindowList = global.ms.msWindowManager.msWindowList; for (i = 0; i < msWindowList.length; i++) { const msWindow = msWindowList[i]; if ( msWindow.msWorkspace.monitor != Main.layoutManager.primaryMonitor ) continue; const workspace = global.ms.msWorkspaceManager.getWorkspaceOfMsWorkspace( msWindow.msWorkspace ); assert(workspace !== null, 'Workspace does not exist'); emptyWorkspaces[workspace.index()] = false; } // If we don't have an empty workspace at the end, add one if (!emptyWorkspaces[emptyWorkspaces.length - 1]) { workspaceManager.append_new_workspace( false, global.get_current_time() ); emptyWorkspaces.push(true); } const lastIndex = emptyWorkspaces.length - 1; const lastEmptyIndex = emptyWorkspaces.lastIndexOf(false) + 1; const activeWorkspaceIndex = workspaceManager.get_active_workspace_index(); emptyWorkspaces[activeWorkspaceIndex] = false; // Delete empty workspaces except for the last one; do it from the end // to avoid index changes for (i = lastIndex; i >= 0; i--) { if (emptyWorkspaces[i] && i != lastEmptyIndex) { workspaceManager.remove_workspace( this._workspaces[i], global.get_current_time() ); } } this._checkWorkspacesId = 0; return false; }; // If a _queueCheckWorkspaces is already pending it's will would use the previous _checkWorkspaces method we need to kill it and add a new one if (this.workspaceTracker._checkWorkspacesId !== 0) { Meta.later_remove(this.workspaceTracker._checkWorkspacesId); this.workspaceTracker._queueCheckWorkspaces(); } this.observe(Main.layoutManager, 'monitors-changed', () => { this.onMonitorsChanged(); }); this.observe( Me.msWindowManager.msFocusManager, 'focus-changed', (_, msWindow) => { if (msWindow && msWindow.msWorkspace) { msWindow.msWorkspace.focusTileable(msWindow); } } ); this.observe( global.display, 'window-entered-monitor', (display, monitorIndex, window) => { //Ignore unHandle window and window on primary screens this.windowEnteredMonitor(window, monitorIndex); } ); this.observe( this.workspaceManager, 'workspace-added', (_, workspaceIndex) => { if (this.restoringState) return; const workspace = this.workspaceManager.get_workspace_by_index( workspaceIndex ); assert(workspace !== null, 'Workspace does not exist'); this.setupNewWorkspace(workspace); } ); this.observe( this.workspaceManager, 'workspace-removed', (_, workspaceIndex) => { this.removeMsWorkspaceAtIndex(workspaceIndex); } ); this.observe( global.window_manager, 'switch-workspace', (_, from: number, to: number) => { if (!this.restoringState) { this.emit('switch-workspace', from, to); this.stateChanged(); } } ); } init() { this.refreshMsWorkspaceUI(); } destroy() { super.destroy(); WorkspaceTracker.prototype._checkWorkspaces = ( WorkspaceTracker.prototype as any )._oldCheckWorkspaces; delete (WorkspaceTracker.prototype as any)._oldCheckWorkspaces; for (let i = 0; i < this.workspaceManager.n_workspaces; i++) { // _keepAliveId is an internal field in gnome-shell const workspace = this.workspaceManager.get_workspace_by_index( i ) as Meta.Workspace & { _keepAliveId?: number }; delete workspace._keepAliveId; } for (const msWorkspace of this.msWorkspaceList) { msWorkspace.destroy(); } } get updatingMonitors() { return ( this._updatingMonitors || global.display.get_n_monitors() !== this.numOfMonitors || this.primaryIndex !== global.display.get_primary_monitor() ); } initState() { Main.layoutManager.monitors .filter((monitor) => monitor != Main.layoutManager.primaryMonitor) .forEach((monitor) => { this.createNewMsWorkspace(monitor); }); for (let i = 0; i < this.workspaceManager.n_workspaces; i++) { if (!this.primaryMsWorkspaces[i]) { const workspace = this.workspaceManager.get_workspace_by_index(i); assert(workspace !== null, 'Workspace does not exist'); this.setupNewWorkspace(workspace); } } } restorePreviousState(): void { this.restoringState = true; this.removeEmptyWorkspaces(); const msWorkspaceListToRestore = [...this._state.msWorkspaceList]; // First restore the external monitors Main.layoutManager.monitors .filter((monitor) => monitor != Main.layoutManager.primaryMonitor) .forEach((monitor) => { const firstExternalStateIndex = msWorkspaceListToRestore.findIndex( (msWorkspaceState) => msWorkspaceState.external ); this.createNewMsWorkspace( monitor, firstExternalStateIndex > -1 ? msWorkspaceListToRestore.splice( firstExternalStateIndex, 1 )[0] : undefined ); }); // Then restore all the others msWorkspaces if (msWorkspaceListToRestore.length) { msWorkspaceListToRestore.forEach((msWorkspaceState, index) => { const workspace = this.workspaceManager.get_workspace_by_index(index) || this.workspaceManager.append_new_workspace( false, global.get_current_time() ); this.setupNewWorkspace(workspace, msWorkspaceState); }); } for (let i = 0; i < this.workspaceManager.n_workspaces; i++) { if (!this.primaryMsWorkspaces[i]) { const workspace = this.workspaceManager.get_workspace_by_index(i); assert(workspace !== null, 'Workspace does not exist'); this.setupNewWorkspace(workspace); } } // Add empty workspace at the end if (Meta.prefs_get_dynamic_workspaces()) { const workspace = this.workspaceManager.append_new_workspace( false, global.get_current_time() ); this.setupNewWorkspace(workspace); } // Activate the saved workspace, if valid if (this._state && this._state.primaryWorkspaceActiveIndex) { const savedIndex = this._state.primaryWorkspaceActiveIndex; if ( savedIndex && savedIndex >= 0 && savedIndex < this.workspaceManager.n_workspaces ) { // TODO: Use this for validation instead of the above indices const workspace = this.workspaceManager.get_workspace_by_index(savedIndex); assert(workspace !== null, 'Workspace does not exist'); workspace.activate(global.get_current_time()); } } delete this.restoringState; } removeEmptyWorkspaces(): void { const emptyWorkspacesSlots: boolean[] = []; for (let i = 0; i < this.workspaceManager.n_workspaces; i++) { emptyWorkspacesSlots[i] = true; } const windows = global.get_window_actors(); for (let i = 0; i < windows.length; i++) { const actor = windows[i]; const win = actor.get_meta_window(); if (win.is_on_all_workspaces()) continue; const workspaceIndex = win.get_workspace().index(); emptyWorkspacesSlots[workspaceIndex] = false; } const emptyWorkspaces = emptyWorkspacesSlots .map((empty, index) => { return empty ? this.workspaceManager.get_workspace_by_index(index) : null; }) .filter(isNonNull); emptyWorkspaces.forEach((workspace) => { this.workspaceManager.remove_workspace( workspace, global.get_current_time() ); }); } onMonitorsChanged(): void { this._updatingMonitors = true; this.numOfMonitors = global.display.get_n_monitors(); this.primaryIndex = global.display.get_primary_monitor(); // First manage external screen const externalMonitors: Monitor[] = Main.layoutManager.monitors.filter( (monitor: Monitor) => monitor != Main.layoutManager.primaryMonitor ); externalMonitors.forEach((externalMonitor) => { // try to find an unused external msWorkspace for this external Monitor const msWorkspace = this.msWorkspaceList.find((msWorkspace) => { return ( msWorkspace.state.external && !Main.layoutManager.monitors.includes(msWorkspace.monitor) ); }); // if there is not external msWorkspace available create one if (msWorkspace) { const workspace = assertNotNull( this.getWorkspaceOfMsWorkspace(msWorkspace) ); msWorkspace.setMonitor(externalMonitor); if (!Meta.prefs_get_dynamic_workspaces()) { this.workspaceManager.remove_workspace( workspace, global.get_current_time() ); } } else { this.createNewMsWorkspace(externalMonitor); } }); // Then reassign monitors to each msWorkspaces this.msWorkspaceList .filter( (msWorkspace) => !Main.layoutManager.monitors.includes(msWorkspace.monitor) ) .forEach((msWorkspace) => { if (!msWorkspace.monitorIsExternal) { msWorkspace.setMonitor( assertNotNull(Main.layoutManager.primaryMonitor) ); } else { const monitorIsNowPrimary = msWorkspace.monitor === Main.layoutManager.primaryMonitor; // If the current monitor of the external msWorkspace is the new primary one or if the current monitor is missing we need to replace it const needToReplaceMonitor = monitorIsNowPrimary || !Main.layoutManager.monitors.includes( msWorkspace.monitor ); // Try to find an unused monitor; const availableMonitor = Main.layoutManager.monitors.find( (monitor: any) => { return ( monitor != Main.layoutManager.primaryMonitor && !this.msWorkspaceList.find((msWorkspace) => { return msWorkspace.monitor === monitor; }) ); } ); // If we need to replace the current monitor and there isn't any available just add the workspace to the primary ones if (needToReplaceMonitor && availableMonitor) { msWorkspace.setMonitor(availableMonitor); } else { // To add the msWorkspace to the end of the primary we need to add it at the end this.msWorkspaceList.splice( this.msWorkspaceList.indexOf(msWorkspace), 1 ); if (Meta.prefs_get_dynamic_workspaces()) { this.msWorkspaceList.splice( this.msWorkspaceList.indexOf( this.primaryMsWorkspaces[ this.primaryMsWorkspaces.length - 1 ] ), 1, msWorkspace ); } else { this.restoringState = true; this.workspaceManager.append_new_workspace( false, global.get_current_time() ); this.msWorkspaceList.push(msWorkspace); this.restoringState = false; } msWorkspace.setMonitor( assertNotNull(Main.layoutManager.primaryMonitor) ); /* this.setMsWorkspaceAt( msWorkspace, this.primaryMsWorkspaces.length - 2 ); */ //this.restoringState = false; } } }); this._updatingMonitors = false; this.stateChanged(); this.emit('dynamic-super-workspaces-changed'); } get primaryMsWorkspaces(): MsWorkspace[] { if (!this.msWorkspaceList) return []; return this.msWorkspaceList.filter((msWorkspace) => { return !msWorkspace.monitorIsExternal; }); } setupNewWorkspace( workspace: Meta.Workspace, initialState?: Partial<MsWorkspaceState> ) { this.createNewMsWorkspace( assertNotNull(Main.layoutManager.primaryMonitor), initialState ); this.observe(workspace, 'window-added', (workspace, window) => { this.metaWindowEnteredWorkspace(window, workspace); }); } createNewMsWorkspace( monitor: Monitor, initialState?: Partial<MsWorkspaceState> ) { const msWorkspace = new MsWorkspace(this, monitor, initialState); msWorkspace.connect('tileableList-changed', (_) => { this.stateChanged(); }); msWorkspace.connect('tiling-layout-changed', (_) => { Me.stateManager.stateChanged(); }); msWorkspace.connect('readyToBeClosed', () => { const index = this.primaryMsWorkspaces.indexOf(msWorkspace); if ( this.getActivePrimaryMsWorkspace() === msWorkspace && !msWorkspace.msWindowList.length ) { // Try to switch to the prev workspace is there is no next one before kill it if (this.primaryMsWorkspaces[index - 1]) { this.primaryMsWorkspaces[index - 1].activate(); } else if (this.primaryMsWorkspaces[index + 1]) { // Try to switch to the next workspace before kill it this.primaryMsWorkspaces[index + 1].activate(); } } }); this.msWorkspaceList.push(msWorkspace); this.stateChanged(); this.emit('dynamic-super-workspaces-changed'); } removeMsWorkspaceAtIndex(index: number) { const msWorkspaceToDelete = this.primaryMsWorkspaces[index]; if (msWorkspaceToDelete) { const globalIndex = this.msWorkspaceList.indexOf(msWorkspaceToDelete); this.msWorkspaceList.splice(globalIndex, 1); msWorkspaceToDelete.destroy(); this.stateChanged(); this.emit('dynamic-super-workspaces-changed'); } } stateChanged() { if ( this.restoringState || this.updatingMonitors || this.stateChangedTriggered ) return; this.stateChangedTriggered = true; GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { this.workspaceTracker._checkWorkspaces(); Me.stateManager.stateChanged(); this.stateChangedTriggered = false; return GLib.SOURCE_REMOVE; }); } setMsWorkspaceAt(msWorkspaceToMove: MsWorkspace, toIndex: number) { const sourceIndex = this.msWorkspaceList.indexOf(msWorkspaceToMove); const realIndex = this.msWorkspaceList.indexOf( this.primaryMsWorkspaces[toIndex] ); const workspace = this.workspaceManager.get_workspace_by_index( this.primaryMsWorkspaces.indexOf(msWorkspaceToMove) ); assert(workspace !== null, 'Workspace does not exist'); this.workspaceManager.reorder_workspace(workspace, toIndex); this.msWorkspaceList.splice(sourceIndex, 1); this.msWorkspaceList.splice(realIndex, 0, msWorkspaceToMove); this.stateChanged(); this.emit('dynamic-super-workspaces-changed'); } get state(): MsWorkspaceManagerState { let msWorkspaceList = this.msWorkspaceList; if (Meta.prefs_get_dynamic_workspaces()) { msWorkspaceList = msWorkspaceList.filter((msWorkspace) => { return msWorkspace.msWindowList.length; }); } this._state.msWorkspaceList = msWorkspaceList.map((msWorkspace) => { return msWorkspace.state; }); this._state.primaryWorkspaceActiveIndex = this.workspaceManager.get_active_workspace_index(); return this._state; } refreshMsWorkspaceUI() { this.msWorkspaceList.forEach((msWorkspace) => { msWorkspace.msWorkspaceActor.updateUI(); }); } getActiveMsWorkspace(): MsWorkspace { const currentMonitorIndex = global.display.get_current_monitor(); const activeWorkspaceIndex = this.workspaceManager.get_active_workspace_index(); const msWorkspace = currentMonitorIndex === Main.layoutManager.primaryIndex ? this.primaryMsWorkspaces[activeWorkspaceIndex] : Me.msWorkspaceManager.getMsWorkspacesOfMonitorIndex( currentMonitorIndex )[0]; return msWorkspace; } getActivePrimaryMsWorkspace(): MsWorkspace { const activeWorkspaceIndex = this.workspaceManager.get_active_workspace_index(); return this.primaryMsWorkspaces[activeWorkspaceIndex]; } getWorkspaceOfMsWorkspace(msWorkspace: MsWorkspace): Meta.Workspace | null { return this.workspaceManager.get_workspace_by_index( this.primaryMsWorkspaces.indexOf(msWorkspace) ); } getActiveMsWorkspaceOfMonitor(monitorIndex: number): MsWorkspace { if (monitorIndex === Main.layoutManager.primaryIndex) { return this.getActivePrimaryMsWorkspace(); } else { return this.getMsWorkspacesOfMonitorIndex(monitorIndex)[0]; } } getMsWorkspacesOfMonitorIndex(monitorIndex: number): MsWorkspace[] { return this.msWorkspaceList.filter((msWorkspace) => { return msWorkspace.monitor.index === monitorIndex; }); } getMsWorkspaceOfMetaWindow(metaWindow: Meta.Window): MsWorkspace { const windowMonitorIndex = metaWindow.get_monitor(); if (windowMonitorIndex !== Main.layoutManager.primaryIndex) { return this.getMsWorkspacesOfMonitorIndex(windowMonitorIndex)[0]; } else { return this.primaryMsWorkspaces[metaWindow.get_workspace().index()]; } } getMsWorkspaceOfMsWindow(msWindow: MsWindow): MsWorkspace | undefined { return this.msWorkspaceList.find((msWorkspace) => { return msWorkspace.msWindowList.includes(msWindow); }); } determineAppropriateMsWorkspace(metaWindow: Meta.Window) { const windowMonitorIndex = metaWindow.get_monitor(); const currentWindowWorkspace = metaWindow.get_workspace(); if (windowMonitorIndex !== Main.layoutManager.primaryIndex) { return this.getMsWorkspacesOfMonitorIndex(windowMonitorIndex)[0]; } else { return this.primaryMsWorkspaces[currentWindowWorkspace.index()]; } } metaWindowEnteredWorkspace( metaWindow: MetaWindowWithMsProperties, workspace: Meta.Workspace ) { if ( this.updatingMonitors || !metaWindow.get_compositor_private<Meta.WindowActor>() ) return; const msWindow = metaWindow.msWindow; if (!msWindow) return; const msWorkspace = this.primaryMsWorkspaces[workspace.index()]; if ( metaWindow.on_all_workspaces || msWindow.msWorkspace === msWorkspace ) { return; } assert( metaWindow.createdAt !== undefined, "Can't tell when this window was created" ); /** * Discard all the workspace changed of a window during the 2 seconds after creation to prevent the window changing it's workspace for the current one. */ if ( msWindow.msWorkspace && msWindow.msWorkspace.workspace && msWindow.msWorkspace != msWorkspace && global.display.get_current_time_roundtrip() - metaWindow.createdAt < 2000 ) { return metaWindow.change_workspace(msWindow.msWorkspace.workspace); } this.setWindowToMsWorkspace(msWindow, msWorkspace); } windowEnteredMonitor( metaWindow: MetaWindowWithMsProperties, monitorIndex: number ) { if (this.updatingMonitors) return; const currentMsWorkspaceOfMetaWindow = metaWindow.msWindow ? metaWindow.msWindow.msWorkspace : null; //Ignore unHandle metaWindow and metaWindow on secondary screens const msWorkspace = this.getMsWorkspacesOfMonitorIndex(monitorIndex)[0]; if ( !metaWindow.handledByMaterialShell || global.display.get_n_monitors() !== this.numOfMonitors || currentMsWorkspaceOfMetaWindow === msWorkspace || monitorIndex === Main.layoutManager.primaryIndex ) { return; } if (!msWorkspace || !metaWindow.msWindow) { return; } this.setWindowToMsWorkspace(metaWindow.msWindow, msWorkspace); } setWindowToMsWorkspace( msWindow: MsWindow, newMsWorkspace: MsWorkspace, insert = false ) { const oldMsWorkspace = msWindow.msWorkspace; if (oldMsWorkspace) { if (oldMsWorkspace === newMsWorkspace) { return; } else { oldMsWorkspace.removeMsWindow(msWindow); } } newMsWorkspace.addMsWindow(msWindow, true, insert); this.stateChanged(); } shouldCycleWorkspacesNavigation() { return getSettings('tweaks').get_boolean('cycle-through-workspaces'); } _handleWindow(metaWindow: Meta.Window) { const meta = Meta.WindowType; const types = [ meta.NORMAL, meta.DIALOG, meta.MODAL_DIALOG, meta.UTILITY, ]; return types.includes(metaWindow.window_type); } activateNextMsWorkspace() { const currentIndex = this.workspaceManager.get_active_workspace_index(); if (currentIndex < this.workspaceManager.n_workspaces - 1) { this.primaryMsWorkspaces[currentIndex + 1].activate(); return; } if (this.shouldCycleWorkspacesNavigation()) { this.primaryMsWorkspaces[0].activate(); } } activatePreviousMsWorkspace() { const currentIndex = this.workspaceManager.get_active_workspace_index(); if (currentIndex > 0) { this.primaryMsWorkspaces[currentIndex - 1].activate(); return; } if (this.shouldCycleWorkspacesNavigation()) { this.primaryMsWorkspaces[ this.workspaceManager.n_workspaces - 1 ].activate(); } } focusMsWorkspace(msWorkspace: MsWorkspace) { if (!msWorkspace) return; const backend = Clutter.get_default_backend(); const seat = backend.get_default_seat(); const [containerX, containerY] = msWorkspace.msWorkspaceActor.tileableContainer.get_transformed_position() as [ number, number ]; seat.warp_pointer( containerX + Math.floor( msWorkspace.msWorkspaceActor.tileableContainer.width / 2 ), containerY + Math.floor( msWorkspace.msWorkspaceActor.tileableContainer.height / 2 ) ); msWorkspace.refreshFocus(); } }
the_stack
import BaseTask from "./task/BaseTask"; import DirectTask from "./task/DirectTask"; import {ChunkTask} from "./task/ChunkTask"; import TokenFunc from "./TokenFunc"; import UUID from "./uuid/UUID"; import UploaderBuilder from "./UploaderBuilder"; import log from "../util/Log"; import Interceptor from "./interceptor/UploadInterceptor"; import UploadListener from "./hook/UploadListener"; import SimpleUploadListener from "./hook/SimpleUploadListener"; import DirectUploadPattern from "./pattren/DirectUploadPattern"; import ChunkUploadPattern from "./pattren/ChunkUploadPattern"; import "../util/Polyfill"; class Uploader { private FILE_INPUT_EL_ID: string = 'qiniu4js-input'; private _fileInputId: string; private _fileInput: HTMLInputElement;//input 元素 private _token: string;//token private _taskQueue: BaseTask[] = [];//任务队列 private _tasking: boolean = false;//任务执行中 private _retry: number;//最大重试次数 private _size: number;//分片大小,单位字节,最大4mb,不能为0 private _chunk: boolean;//分块上传,该选项开启后,只有在文件大于4mb的时候才会分块上传 private _auto: boolean;//自动上传,每次选择文件后 private _multiple: boolean;//是否支持多文件 private _accept: string[];//接受的文件类型 private _button: string;//上传按钮 private _buttonEventName: string;//上传按钮的监听事件名称 private _compress: number;//图片压缩质量 private _scale: number[] = [];//缩放大小,限定高度等比缩放[h:200,w:0],限定宽度等比缩放[h:0,w:100],限定长宽[h:200,w:100] private _listener: UploadListener;//监听器 private _saveKey: boolean | string = false; private _tokenFunc: TokenFunc;//token获取函数 private _tokenShare: boolean;//分享token,如果为false,每一次HTTP请求都需要新获取Token private _interceptors: Interceptor[];//任务拦截器 private _domain: string;//上传域名 constructor(builder: UploaderBuilder) { this._retry = builder.getRetry; this._size = builder.getSize; this._chunk = builder.getChunk; this._auto = builder.getAuto; this._multiple = builder.getMultiple; this._accept = builder.getAccept; this._button = builder.getButton; this._buttonEventName = builder.getButtonEventName; this._compress = builder.getCompress; this._scale = builder.getScale; this._saveKey = builder.getSaveKey; this._tokenFunc = builder.getTokenFunc; this._tokenShare = builder.getTokenShare; this._listener = Object.assign(new SimpleUploadListener(), builder.getListener); this._interceptors = builder.getInterceptors; this._domain = builder.getDomain; this._fileInputId = `${this.FILE_INPUT_EL_ID}_${new Date().getTime()}`; log.enable = builder.getIsDebug; this.validateOptions(); this.init(); } /** * 初始化操作 */ private init(): void { this.initFileInputEl(); } /** * 初始化file input element */ private initFileInputEl(): void { //查询已经存在的file input let exist: HTMLInputElement = <HTMLInputElement> document.getElementById(this._fileInputId); //创建input元素 this._fileInput = exist ? exist : document.createElement('input'); this.fileInput.type = 'file';//type file this.fileInput.id = this._fileInputId;//id 方便后面查找 this.fileInput.style.display = 'none';//隐藏file input //多文件 if (this.multiple) { //多文件 this.fileInput.multiple = true; } //文件类型 if (this.accept && this.accept.length != 0) { let acceptValue: string = ''; for (let value of this.accept) { acceptValue += value; acceptValue += ','; } if (acceptValue.endsWith(',')) { acceptValue = acceptValue.substring(0, acceptValue.length - 1); } this.fileInput.accept = acceptValue; log.d(`accept类型 ${acceptValue}`); } //将input元素添加到body子节点的末尾 document.body.appendChild(this.fileInput); //选择文件监听器 this.fileInput.addEventListener('change', this.handleFiles, false); if (this._button != undefined) { let button: any = document.getElementById(this._button); button.addEventListener(this._buttonEventName, this.chooseFile.bind(this)); } } /** * 上传完成或者失败后,对本次上传任务进行清扫 */ private resetUploader(): void { log.d("开始重置 uploader"); this.taskQueue.length = 0; log.d("任务队列已清空"); this._token = null; log.d("token已清空"); log.d("uploader 重置完毕"); } /** * 处理文件 */ private handleFiles = () => { //如果没有选中文件就返回 if (this.fileInput.files.length == 0) { return; } //生成task this.generateTask(); //是否中断任务 let isInterrupt: boolean = false; let interceptedTasks: BaseTask[] = []; //任务拦截器过滤 for (let task of this.taskQueue) { for (let interceptor of this.interceptors) { //拦截生效 if (interceptor.onIntercept(task, this.taskQueue)) { interceptedTasks.push(task); log.d("任务拦截器拦截了任务:"); log.d(task); } //打断生效 if (interceptor.onInterrupt(task, this.taskQueue)) { //将打断标志位设为true isInterrupt = true; break; } } } if (isInterrupt) { log.w("任务拦截器中断了任务队列"); return; } //从任务队列中去除任务 for (let task of interceptedTasks) { let index = this.taskQueue.indexOf(task); if (index != -1) { this.taskQueue.splice(index, 1); } } //回调函数函数 this.listener.onReady(this.taskQueue); //处理图片 this.handleImages().then(() => { //自动上传 if (this.auto) { log.d("开始自动上传"); this.start(); } }); }; /** * 是否是分块任务 * @param task * @returns {boolean} */ private static isChunkTask(task: BaseTask): boolean { return task.constructor.name === ChunkTask.name && task instanceof ChunkTask; } /** * 是否是直传任务 * @param task * @returns {boolean} */ private static isDirectTask(task: BaseTask): boolean { return task.constructor.name === DirectTask.name && task instanceof DirectTask; } /** * 生成task */ private generateTask() { this.resetUploader(); let files: FileList = this.fileInput.files; //遍历files 创建上传任务 for (let i: number = 0; i < this.fileInput.files.length; i++) { let file: File = files[i]; let task: BaseTask; //只有在开启分块上传,并且文件大小大于4mb的时候才进行分块上传 if (this.chunk && file.size > UploaderBuilder.BLOCK_SIZE) { task = new ChunkTask(file, UploaderBuilder.BLOCK_SIZE, this.size); } else { task = new DirectTask(file); } if (this._saveKey == false) { task.key = this.listener.onTaskGetKey(task); } this.taskQueue.push(task); } } /** * 处理图片-缩放-质量压缩 */ private handleImages(): Promise<any> { let promises: Promise<any>[] = []; if (this.compress != 1 || this.scale[0] != 0 || this.scale[1] != 0) { for (let task of this.taskQueue) { if (!task.file.type.match('image.*')) { continue; } log.d(`${task.file.name} 处理前的图片大小:${task.file.size / 1024} kb`); let canvas: HTMLCanvasElement = <HTMLCanvasElement> document.createElement('canvas'); let img: HTMLImageElement = new Image(); let ctx: CanvasRenderingContext2D = <CanvasRenderingContext2D>canvas.getContext('2d'); img.src = URL.createObjectURL(task.file); let _this = this; promises.push(new Promise<Blob>((resolve) => img.onload = () => { let imgW = img.width; let imgH = img.height; let scaleW = _this.scale[0]; let scaleH = _this.scale[1]; if (scaleW == 0 && scaleH > 0) { canvas.width = imgW / imgH * scaleH; canvas.height = scaleH; } else if (scaleH == 0 && scaleW > 0) { canvas.width = scaleW; canvas.height = imgH / imgW * scaleW; } else if (scaleW > 0 && scaleH > 0) { canvas.width = scaleW; canvas.height = scaleH; } else { canvas.width = img.width; canvas.height = img.height; } //这里的长宽是绘制到画布上的图片的长宽 ctx.drawImage(img, 0, 0, canvas.width, canvas.height); console.log(canvas); console.log(canvas.toBlob); //0.95是最接近原图大小,如果质量为1的话会导致比原图大几倍。 canvas.toBlob((blob: Blob) => { resolve(blob); log.d(`${task.file.name} 处理后的图片大小:${blob.size / 1024} kb`); }, "image/jpeg", _this.compress * 0.95); } ).then((blob: any) => { blob.name = task.file.name; task.file = blob; if (Uploader.isChunkTask(task)) { (<ChunkTask>task).spliceFile2Block(); } })); } } return Promise.all(promises); } /** * 检验选项合法性 */ private validateOptions(): void { log.d("开始检查构建参数合法性"); if (!this._tokenFunc) { throw new Error('你必须提供一个获取Token的回调函数'); } if (!this.scale || !(this.scale instanceof Array) || this.scale.length != 2 || this.scale[0] < 0 || this.scale[1] < 0) { throw new Error('scale必须是长度为2的number类型的数组,scale[0]为宽度,scale[1]为长度,必须大于等于0'); } log.d("构建参数检查完毕"); } /** * 开始上传 */ public start(): void { log.d(`上传任务遍历开始`); if (this.fileInput.files.length == 0) { throw new Error('没有选中的文件,无法开始上传'); } if (this.tasking) { throw new Error('任务执行中,请不要重复上传'); } this.listener.onStart(this.taskQueue); //遍历任务队列 for (let task of this.taskQueue) { log.d(`上传文件名:${task.file.name}`); log.d(`上传文件大小:${task.file.size}字节,${task.file.size / 1024} kb,${task.file.size / 1024 / 1024} mb`); //根据任务的类型调用不同的上传模式进行上传 if (Uploader.isDirectTask(task)) { log.d('该上传任务为直传任务'); //直传 new DirectUploadPattern(this).upload(<DirectTask>task); } else if (Uploader.isChunkTask(task)) { log.d('该上传任务为分片任务'); //分块上传 new ChunkUploadPattern(this).upload(<ChunkTask>task); } else { throw new Error('非法的task类型'); } } } /** * 所有任务是否完成 * @returns {boolean} */ public isTaskQueueFinish() { for (let task of this.taskQueue) { if (!task.isFinish) { return false; } } return true; } /** * 选择文件 */ public chooseFile() { this.fileInput.click(); } public getToken(task: BaseTask): Promise<string> { if (this._tokenShare && this._token != undefined) { return Promise.resolve(this._token); } log.d(`开始获取上传token`); return Promise.resolve(this._tokenFunc(this, task)).then((token: string): string => { log.d(`上传token获取成功: ${token}`); this._token = token; return token; }); } public requestTaskToken(task: BaseTask, url: string): Promise<string> { return this.resolveSaveKey(task).then((saveKey: string) => { return this.requestToken(url, saveKey); }); } private requestToken(url: string, saveKey: string): Promise<string> { return new Promise((resolve, reject) => { if (typeof saveKey == "string") { url += ((/\?/).test(url) ? "&" : "?") + "saveKey=" + encodeURIComponent(saveKey); } url += ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(); let xhr: XMLHttpRequest = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = () => { if (xhr.readyState != XMLHttpRequest.DONE) { return; } if (xhr.status == 200) { resolve(xhr.response.uptoken); return; } reject(xhr.response); }; xhr.onabort = () => { reject('aborted'); }; xhr.responseType = 'json'; xhr.send(); }); } private resolveSaveKey(task: BaseTask): Promise<string> { let saveKey = this._saveKey; if (typeof saveKey != "string") { return Promise.resolve(undefined); } return Promise.resolve(saveKey) .then(this.resolveUUID) .then(saveKey => this.resolveImageInfo(task.file, saveKey)) .then(this.onSaveKeyResolved); } private resolveUUID = (s: string): string => { let re = /\$\(uuid\)/; if (re.test(s)) { return s.replace(re, UUID.uuid()); } return s; }; private resolveImageInfo = (blob: Blob, s: string): Promise<string> => { let widthRe = /\$\(imageInfo\.width\)/; let heightRe = /\$\(imageInfo\.height\)/; if (!widthRe.test(s) && !heightRe.test(s)) { return Promise.resolve(s); } return new Promise<string>((resolve) => { let img = new Image(); img.src = URL.createObjectURL(blob); img.onload = () => { s = s.replace(widthRe, img.width.toString()); s = s.replace(heightRe, img.height.toString()); resolve(s); }; }); }; private onSaveKeyResolved = (saveKey: string): string => { this._tokenShare = this._tokenShare && this._saveKey == saveKey; return saveKey; }; get retry(): number { return this._retry; } get size(): number { return this._size; } get auto(): boolean { return this._auto; } get multiple(): boolean { return this._multiple; } get accept(): string[] { return this._accept; } get compress(): number { return this._compress; } get scale(): number[] { return this._scale; } get listener(): UploadListener { return this._listener; } get fileInput(): HTMLInputElement { return this._fileInput; } get chunk(): boolean { return this._chunk; } get taskQueue(): BaseTask[] { return this._taskQueue; } get tasking(): boolean { return this._tasking; } set tasking(value: boolean) { this._tasking = value; } get interceptors(): Interceptor[] { return this._interceptors; } get domain(): string { return this._domain; } } export default Uploader;
the_stack
import * as fs from "fs-plus"; import * as path from "path"; import * as vscode from "vscode"; import { IoTCubeCommands } from "../common/Commands"; import { ArgumentEmptyOrNullError } from "../common/Error/OperationFailedErrors/ArgumentEmptyOrNullError"; import { WorkspaceConfigNotFoundError } from "../common/Error/SystemErrors/WorkspaceConfigNotFoundError"; import { TypeNotSupportedError } from "../common/Error/SystemErrors/TypeNotSupportedError"; import { ConfigHandler } from "../configHandler"; import { ConfigKey, EventNames, FileNames, ScaffoldType } from "../constants"; import { FileUtility } from "../FileUtility"; import { TelemetryContext, TelemetryWorker } from "../telemetry"; import { getWorkspaceFile, updateProjectHostTypeConfig } from "../utils"; import { AzureComponentConfig } from "./AzureComponentConfig"; import { Component, ComponentType } from "./Interfaces/Component"; import { ProjectHostType } from "./Interfaces/ProjectHostType"; import { ProjectTemplateType, TemplateFileInfo } from "./Interfaces/ProjectTemplate"; import { Workspace } from "./Interfaces/Workspace"; import { IoTWorkbenchProjectBase, OpenScenario } from "./IoTWorkbenchProjectBase"; import { DirectoryNotFoundError } from "../common/Error/OperationFailedErrors/DirectoryNotFoundError"; import { FileNotFoundError } from "../common/Error/OperationFailedErrors/FileNotFound"; const importLazy = require("import-lazy"); const az3166DeviceModule = importLazy(() => require("./AZ3166Device"))(); const azureComponentConfigModule = importLazy(() => require("./AzureComponentConfig"))(); const azureFunctionsModule = importLazy(() => require("./AzureFunctions"))(); const esp32DeviceModule = importLazy(() => require("./Esp32Device"))(); const ioTHubModule = importLazy(() => require("./IoTHub"))(); const ioTHubDeviceModule = importLazy(() => require("./IoTHubDevice"))(); export class IoTWorkspaceProject extends IoTWorkbenchProjectBase { private deviceRootPath = ""; private workspaceConfigFilePath = ""; static folderName = { deviceDefaultFolderName: "Device", functionDefaultFolderName: "Functions" }; constructor( context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext, rootFolderPath: string ) { super(context, channel, telemetryContext); this.projectHostType = ProjectHostType.Workspace; if (!rootFolderPath) { throw new ArgumentEmptyOrNullError( "construct iot workspace project", "root folder path", "Please initialize iot workspace project with root folder path." ); } this.projectRootPath = rootFolderPath; this.telemetryContext.properties.projectHostType = this.projectHostType; } async load(scaffoldType: ScaffoldType, initLoad = false): Promise<void> { await this.validateProjectRootPathExists("load project", scaffoldType); // Init device root path const devicePath = ConfigHandler.get<string>(ConfigKey.devicePath); if (!devicePath) { throw new WorkspaceConfigNotFoundError(ConfigKey.devicePath); } this.deviceRootPath = path.join(this.projectRootPath, devicePath); if (!(await FileUtility.directoryExists(scaffoldType, this.deviceRootPath))) { throw new DirectoryNotFoundError( "load iot workspace project", `device root path ${this.deviceRootPath}`, "Please initialize the project first." ); } // Init and update iot workbench project file this.iotWorkbenchProjectFilePath = path.join(this.deviceRootPath, FileNames.iotWorkbenchProjectFileName); await updateProjectHostTypeConfig(scaffoldType, this.iotWorkbenchProjectFilePath, this.projectHostType); // Init workspace config file path await this.loadWorkspaceConfigFilePath(scaffoldType); // Send load project event telemetry only if the IoT project is loaded // when VS Code opens. if (initLoad) { this.sendLoadEventTelemetry(this.extensionContext); } const boardId = ConfigHandler.get<string>(ConfigKey.boardId); if (!boardId) { throw new WorkspaceConfigNotFoundError(ConfigKey.boardId); } // Init device component this.initDeviceComponents(boardId, this.deviceRootPath); // Load device component await Promise.all( this.componentList.map(async component => { await component.load(); }) ); // Init and load azure components await this.loadAzureConfigAndComponents(scaffoldType); // Check components prerequisites await Promise.all( this.componentList.map(async component => { await component.checkPrerequisites("load project"); }) ); } async create( templateFilesInfo: TemplateFileInfo[], projectType: ProjectTemplateType, boardId: string, openInNewWindow: boolean ): Promise<void> { const createTimeScaffoldType = ScaffoldType.Local; const workspace: Workspace = { folders: [], settings: {} }; // Init device root path this.deviceRootPath = path.join(this.projectRootPath, IoTWorkspaceProject.folderName.deviceDefaultFolderName); // Init iot workbench project file path this.iotWorkbenchProjectFilePath = path.join(this.deviceRootPath, FileNames.iotWorkbenchProjectFileName); // Init device components this.initDeviceComponents(boardId, this.deviceRootPath, templateFilesInfo); // init azure components this.initAzureComponents(projectType, workspace); workspace.folders.push({ path: IoTWorkspaceProject.folderName.deviceDefaultFolderName }); workspace.settings[`IoTWorkbench.${ConfigKey.boardId}`] = boardId; workspace.settings[`IoTWorkbench.${ConfigKey.devicePath}`] = IoTWorkspaceProject.folderName.deviceDefaultFolderName; // Check components' prerequisites await Promise.all( this.componentList.map(async component => { await component.checkPrerequisites("create project"); }) ); // Create azure config file const azureConfigFileHandler = new azureComponentConfigModule.AzureConfigFileHandler(this.projectRootPath); await azureConfigFileHandler.createIfNotExists(createTimeScaffoldType); // Update iot workbench project file await updateProjectHostTypeConfig(createTimeScaffoldType, this.iotWorkbenchProjectFilePath, this.projectHostType); // Create workspace config file this.workspaceConfigFilePath = path.join( this.projectRootPath, `${path.basename(this.projectRootPath)}${FileNames.workspaceExtensionName}` ); await FileUtility.writeJsonFile(createTimeScaffoldType, this.workspaceConfigFilePath, workspace); // Create components try { await Promise.all( this.componentList.map(async component => { await component.create(); }) ); } catch (error) { fs.removeSync(this.projectRootPath); throw error; } // Open project await this.openProject(createTimeScaffoldType, openInNewWindow, OpenScenario.createNewProject); } async openProject(scaffoldType: ScaffoldType, openInNewWindow: boolean, openScenario: OpenScenario): Promise<void> { await this.loadWorkspaceConfigFilePath(scaffoldType); if (!(await FileUtility.fileExists(scaffoldType, this.workspaceConfigFilePath))) { throw new FileNotFoundError( "open project", `workspace configuration file ${this.workspaceConfigFilePath}`, "Please initialize the project first.`" ); } if (!openInNewWindow) { // If open in current window, VSCode will restart. Need to send telemetry // before VSCode restart to advoid data lost. try { const telemetryWorker = TelemetryWorker.getInstance(this.extensionContext); const eventNames = openScenario === OpenScenario.createNewProject ? EventNames.createNewProjectEvent : EventNames.configProjectEnvironmentEvent; telemetryWorker.sendEvent(eventNames, this.telemetryContext); } catch { // If sending telemetry failed, skip the error to avoid blocking user. } } vscode.commands.executeCommand(IoTCubeCommands.OpenLocally, this.workspaceConfigFilePath, openInNewWindow); } /** * Init device components according to board id. * Update component list with device. * @param boardId board id * @param deviceRootPath device root path * @param scaffoldType scaffold type * @param templateFilesInfo template files info to scaffold files for device */ private initDeviceComponents(boardId: string, deviceRootPath: string, templateFilesInfo?: TemplateFileInfo[]): void { if (!deviceRootPath) { throw new ArgumentEmptyOrNullError( "initialize device", `device root path: ${deviceRootPath}`, "Please initialize the project first." ); } let device: Component; if (boardId === az3166DeviceModule.AZ3166Device.boardId) { device = new az3166DeviceModule.AZ3166Device( this.extensionContext, this.channel, this.telemetryContext, deviceRootPath, templateFilesInfo ); } else if (boardId === esp32DeviceModule.Esp32Device.boardId) { device = new esp32DeviceModule.Esp32Device( this.extensionContext, this.channel, this.telemetryContext, deviceRootPath, templateFilesInfo ); } else { throw new TypeNotSupportedError("board type", boardId); } if (device) { this.componentList.push(device); } } /** * For backward compatibility. * If no azure components configs found in azure config files, * init azure components and update component lists and azure configs. * @param scaffoldType Scaffold type */ private async initAzureComponentsWithoutConfig(scaffoldType: ScaffoldType): Promise<void> { // Init iotHub const iotHub = new ioTHubModule.IoTHub(this.projectRootPath, this.channel); await iotHub.updateConfigSettings(scaffoldType); this.componentList.push(iotHub); // Init iotHub Device const iotHubDevice = new ioTHubDeviceModule.IoTHubDevice(this.projectRootPath, this.channel, [ { component: iotHub, type: azureComponentConfigModule.DependencyType.Input } ]); await iotHubDevice.updateConfigSettings(scaffoldType); this.componentList.push(iotHubDevice); // Init azure function const functionPath = ConfigHandler.get<string>(ConfigKey.functionPath); if (functionPath) { const functionLocation = path.join(this.projectRootPath, functionPath); const functionApp = new azureFunctionsModule.AzureFunctions( this.projectRootPath, functionLocation, functionPath, this.channel, null, [ { component: iotHub, type: azureComponentConfigModule.DependencyType.Input } ] ); await functionApp.updateConfigSettings(scaffoldType); this.componentList.push(functionApp); } } /** * load Azure components from configs. * Update component list with azure components. * @param scaffoldType scaffold type * @param componentConfigs azure component configs */ private async loadAzureComponentsByConfig(componentConfigs: AzureComponentConfig[]): Promise<void> { for (const componentConfig of componentConfigs) { switch (componentConfig.type) { case ComponentType.IoTHub: { const iotHub = new ioTHubModule.IoTHub(this.projectRootPath, this.channel); await iotHub.load(); this.componentList.push(iotHub); const iothubDevice = new ioTHubDeviceModule.IoTHubDevice(this.projectRootPath, this.channel, [ { component: iotHub, type: azureComponentConfigModule.DependencyType.Input } ]); await iothubDevice.load(); this.componentList.push(iothubDevice); break; } case ComponentType.IoTHubDevice: { break; } case ComponentType.AzureFunctions: { const functionPath = ConfigHandler.get<string>(ConfigKey.functionPath); if (!functionPath) { throw new WorkspaceConfigNotFoundError(ConfigKey.functionPath); } const functionLocation = path.join(this.projectRootPath, functionPath); if (functionLocation) { const functionApp = new azureFunctionsModule.AzureFunctions( this.projectRootPath, functionLocation, functionPath, this.channel ); await functionApp.load(); this.componentList.push(functionApp); } break; } default: { throw new TypeNotSupportedError("component type", `${componentConfig.type}`); } } } } /** * Load project config and init Azure components. * @param scaffoldType scaffold type */ private async loadAzureConfigAndComponents(scaffoldType: ScaffoldType): Promise<void> { const azureConfigFileHandler = new azureComponentConfigModule.AzureConfigFileHandler(this.projectRootPath); await azureConfigFileHandler.createIfNotExists(scaffoldType); const componentConfigs = await azureConfigFileHandler.getSortedComponents(scaffoldType); if (componentConfigs.length === 0) { // Support backward compact await this.initAzureComponentsWithoutConfig(scaffoldType); } else { await this.loadAzureComponentsByConfig(componentConfigs); } } /** * Init azure components based on project template type. * Update component list with azure components. * Update azure components information in workspace configuration. * @param projectType project template type * @param workspaceConfig workspace configuration */ private initAzureComponents(projectType: ProjectTemplateType, workspaceConfig: Workspace): void { if (!this.projectRootPath) { throw new ArgumentEmptyOrNullError( "init azure components", `project root path: ${this.projectRootPath}`, "Please initialize the project first." ); } switch (projectType) { case ProjectTemplateType.Basic: // Save data to configFile break; case ProjectTemplateType.IotHub: { const iothub = new ioTHubModule.IoTHub(this.projectRootPath, this.channel); this.componentList.push(iothub); break; } case ProjectTemplateType.AzureFunctions: { const iothub = new ioTHubModule.IoTHub(this.projectRootPath, this.channel); const functionDir = path.join(this.projectRootPath, IoTWorkspaceProject.folderName.functionDefaultFolderName); const azureFunctions = new azureFunctionsModule.AzureFunctions( this.projectRootPath, functionDir, IoTWorkspaceProject.folderName.functionDefaultFolderName, this.channel, null, [ { component: iothub, type: azureComponentConfigModule.DependencyType.Input } ] /*Dependencies*/ ); workspaceConfig.folders.push({ path: IoTWorkspaceProject.folderName.functionDefaultFolderName }); workspaceConfig.settings[`IoTWorkbench.${ConfigKey.functionPath}`] = IoTWorkspaceProject.folderName.functionDefaultFolderName; this.componentList.push(iothub); this.componentList.push(azureFunctions); break; } default: break; } } /** * Find the workspace config file under project root path and init workspace config file path. * Throw error if workspace config file not exists. * @param scaffoldType scaffold type */ private async loadWorkspaceConfigFilePath(scaffoldType: ScaffoldType): Promise<void> { await this.validateProjectRootPathExists("init workspace config file path", scaffoldType); const workspaceFile = getWorkspaceFile(this.projectRootPath); if (!workspaceFile) { throw new FileNotFoundError( "init iot project workspace file path", `workspace file under project root path: ${this.projectRootPath}.`, "" ); } this.workspaceConfigFilePath = path.join(this.projectRootPath, workspaceFile); } }
the_stack
import { metadata } from 'aurelia-metadata'; import { AggregateError } from 'aurelia-pal'; import { resolver, StrategyResolver, Resolver, Strategy, StrategyState } from './resolvers'; import { Invoker } from './invokers'; import { DependencyCtorOrFunctor, DependencyCtor, PrimitiveOrDependencyCtor, PrimitiveOrDependencyCtorOrFunctor, ImplOrAny, Impl, Args, Primitive } from './types'; function validateKey(key: any) { if (key === null || key === undefined) { throw new Error( 'key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?' ); } } export const _emptyParameters = Object.freeze([]) as []; metadata.registration = 'aurelia:registration'; metadata.invoker = 'aurelia:invoker'; const resolverDecorates = resolver.decorates; /** * Stores the information needed to invoke a function. */ export class InvocationHandler< TBase, TImpl extends Impl<TBase>, TArgs extends Args<TBase> > { /** * The function to be invoked by this handler. */ public fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>; /** * The invoker implementation that will be used to actually invoke the function. */ public invoker: Invoker<TBase, TImpl, TArgs>; /** * The statically known dependencies of this function invocation. */ public dependencies: TArgs; /** * Instantiates an InvocationDescription. * @param fn The Function described by this description object. * @param invoker The strategy for invoking the function. * @param dependencies The static dependencies of the function call. */ constructor( fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>, invoker: Invoker<TBase, TImpl, TArgs>, dependencies: TArgs ) { this.fn = fn; this.invoker = invoker; this.dependencies = dependencies; } /** * Invokes the function. * @param container The calling container. * @param dynamicDependencies Additional dependencies to use during invocation. * @return The result of the function invocation. */ public invoke(container: Container, dynamicDependencies?: TArgs[]): TImpl { return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies( container, this.fn, this.dependencies, dynamicDependencies ) : this.invoker.invoke(container, this.fn, this.dependencies); } } /** * Used to configure a Container instance. */ export interface ContainerConfiguration { /** * An optional callback which will be called when any function needs an * InvocationHandler created (called once per Function). */ onHandlerCreated?: ( handler: InvocationHandler<any, any, any> ) => InvocationHandler<any, any, any>; handlers?: Map<any, any>; } function invokeWithDynamicDependencies< TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase> >( container: Container, fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>, staticDependencies: TArgs[number][], dynamicDependencies: TArgs[number][] ) { let i = staticDependencies.length; let args = new Array(i); let lookup; while (i--) { lookup = staticDependencies[i]; if (lookup === null || lookup === undefined) { throw new Error( 'Constructor Parameter with index ' + i + ' cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?' ); } else { args[i] = container.get(lookup); } } if (dynamicDependencies !== undefined) { args = args.concat(dynamicDependencies); } return Reflect.construct(fn, args); } const classInvoker: Invoker<any, any, any> = { invoke(container, Type: DependencyCtor<any, any, any>, deps) { const instances = deps.map((dep) => container.get(dep)); return Reflect.construct(Type, instances); }, invokeWithDynamicDependencies }; function getDependencies(f) { if (!f.hasOwnProperty('inject')) { return []; } if (typeof f.inject === 'function') { return f.inject(); } return f.inject; } /** * A lightweight, extensible dependency injection container. */ export class Container { /** * The global root Container instance. Available if makeGlobal() has been * called. Aurelia Framework calls makeGlobal(). */ public static instance: Container; /** * The parent container in the DI hierarchy. */ public parent: Container; /** * The root container in the DI hierarchy. */ public root: Container; /** @internal */ public _configuration: ContainerConfiguration; /** @internal */ public _onHandlerCreated: ( handler: InvocationHandler<any, any, any> ) => InvocationHandler<any, any, any>; /** @internal */ public _handlers: Map<any, any>; /** @internal */ public _resolvers: Map<any, any>; /** * Creates an instance of Container. * @param configuration Provides some configuration for the new Container instance. */ constructor(configuration?: ContainerConfiguration) { if (configuration === undefined) { configuration = {}; } this._configuration = configuration; this._onHandlerCreated = configuration.onHandlerCreated; this._handlers = configuration.handlers || (configuration.handlers = new Map()); this._resolvers = new Map(); this.root = this; this.parent = null; } /** * Makes this container instance globally reachable through Container.instance. */ public makeGlobal(): Container { Container.instance = this; return this; } /** * Sets an invocation handler creation callback that will be called when new * InvocationsHandlers are created (called once per Function). * @param onHandlerCreated The callback to be called when an * InvocationsHandler is created. */ public setHandlerCreatedCallback< TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( onHandlerCreated: ( handler: InvocationHandler<TBase, TImpl, TArgs> ) => InvocationHandler<TBase, TImpl, TArgs> ) { this._onHandlerCreated = onHandlerCreated; this._configuration.onHandlerCreated = onHandlerCreated; } /** * Registers an existing object instance with the container. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param instance The instance that will be resolved when the key is matched. * This defaults to the key value when instance is not supplied. * @return The resolver that was registered. */ public registerInstance<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, instance?: TImpl): Resolver { return this.registerResolver( key, new StrategyResolver(0, instance === undefined ? key : instance) ); } /** * Registers a type (constructor function) such that the container always * returns the same instance for each request. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param fn The constructor function to use when the dependency needs to be * instantiated. This defaults to the key value when fn is not supplied. * @return The resolver that was registered. */ public registerSingleton<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: Primitive, fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public registerSingleton<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: DependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public registerSingleton<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver { return this.registerResolver( key, new StrategyResolver(Strategy.singleton, fn === undefined ? key as DependencyCtor<TBase, TImpl, TArgs> : fn) ); } /** * Registers a type (constructor function) such that the container returns a * new instance for each request. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param fn The constructor function to use when the dependency needs to be * instantiated. This defaults to the key value when fn is not supplied. * @return The resolver that was registered. */ public registerTransient<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: Primitive, fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public registerTransient<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: DependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public registerTransient<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver { return this.registerResolver( key, new StrategyResolver(2, fn === undefined ? key as DependencyCtor<TBase, TImpl, TArgs> : fn) ); } /** * Registers a custom resolution function such that the container calls this * function for each request to obtain the instance. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param handler The resolution function to use when the dependency is * needed. * @return The resolver that was registered. */ public registerHandler<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, handler: (container?: Container, key?: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, resolver?: Resolver) => any ): Resolver { return this.registerResolver( key, new StrategyResolver<TBase, TImpl, TArgs, Strategy.function>(Strategy.function, handler) ); } /** * Registers an additional key that serves as an alias to the original DI key. * @param originalKey The key that originally identified the dependency; usually a constructor function. * @param aliasKey An alternate key which can also be used to resolve the same dependency as the original. * @return The resolver that was registered. */ public registerAlias<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( originalKey: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, aliasKey: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>): Resolver { return this.registerResolver( aliasKey, new StrategyResolver(5, originalKey) ); } /** * Registers a custom resolution function such that the container calls this * function for each request to obtain the instance. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param resolver The resolver to use when the dependency is needed. * @return The resolver that was registered. */ public registerResolver<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, resolver: Resolver ): Resolver { validateKey(key); const allResolvers = this._resolvers; const result = allResolvers.get(key); if (result === undefined) { allResolvers.set(key, resolver); } else if (result.strategy === 4) { result.state.push(resolver); } else { allResolvers.set(key, new StrategyResolver(4, [result, resolver])); } return resolver; } /** * Registers a type (constructor function) by inspecting its registration * annotations. If none are found, then the default singleton registration is * used. * @param key The key that identifies the dependency at resolution time; * usually a constructor function. * @param fn The constructor function to use when the dependency needs to be * instantiated. This defaults to the key value when fn is not supplied. */ public autoRegister<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: Primitive, fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public autoRegister<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: DependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver; public autoRegister<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, fn?: DependencyCtorOrFunctor<TBase, TImpl, TArgs>): Resolver { fn = fn === undefined ? key as DependencyCtor<TBase, TImpl, TArgs> : fn; if (typeof fn === 'function') { const registration = metadata.get(metadata.registration, fn); if (registration === undefined) { return this.registerResolver(key, new StrategyResolver(1, fn)); } return registration.registerResolver(this, key, fn); } return this.registerResolver(key, new StrategyResolver(0, fn)); } /** * Registers an array of types (constructor functions) by inspecting their * registration annotations. If none are found, then the default singleton * registration is used. * @param fns The constructor function to use when the dependency needs to be instantiated. */ public autoRegisterAll(fns: DependencyCtor<any, any, any>[]): void { let i = fns.length; while (i--) { this.autoRegister<any, any, any>(fns[i]); } } /** * Unregisters based on key. * @param key The key that identifies the dependency at resolution time; usually a constructor function. */ public unregister(key: any): void { this._resolvers.delete(key); } /** * Inspects the container to determine if a particular key has been registred. * @param key The key that identifies the dependency at resolution time; usually a constructor function. * @param checkParent Indicates whether or not to check the parent container hierarchy. * @return Returns true if the key has been registred; false otherwise. */ public hasResolver<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>, checkParent: boolean = false): boolean { validateKey(key); return ( this._resolvers.has(key) || (checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent)) ); } /** * Gets the resolver for the particular key, if it has been registered. * @param key The key that identifies the dependency at resolution time; usually a constructor function. * @return Returns the resolver, if registred, otherwise undefined. */ public getResolver< TStrategyKey extends keyof StrategyState<TBase, TImpl, TArgs>, TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase> >( key: PrimitiveOrDependencyCtorOrFunctor<TBase, TImpl, TArgs> ): StrategyResolver<TBase, TImpl, TArgs, TStrategyKey> { return this._resolvers.get(key); } /** * Resolves a single instance based on the provided key. * @param key The key that identifies the object to resolve. * @return Returns the resolved instance. */ public get<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>): ImplOrAny<TImpl>; public get<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: typeof Container): Container; public get<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs> | typeof Container): ImplOrAny<TImpl> | Container { validateKey(key); if (key === Container) { return this; } if (resolverDecorates(key)) { return key.get(this, key); } const resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key as DependencyCtor<TBase, TImpl, TArgs>).get(this, key); } const registration = metadata.get(metadata.registration, key); if (registration === undefined) { return this.parent._get(key); } return registration.registerResolver( this, key, key as DependencyCtorOrFunctor<TBase, TImpl, TArgs>).get(this, key); } return resolver.get(this, key); } public _get(key) { const resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key).get(this, key); } return this.parent._get(key); } return resolver.get(this, key); } /** * Resolves all instance registered under the provided key. * @param key The key that identifies the objects to resolve. * @return Returns an array of the resolved instances. */ public getAll<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( key: PrimitiveOrDependencyCtor<TBase, TImpl, TArgs>): ImplOrAny<TImpl>[] { validateKey(key); const resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return _emptyParameters; } return this.parent.getAll(key); } if (resolver.strategy === 4) { const state = resolver.state; let i = state.length; const results = new Array(i); while (i--) { results[i] = state[i].get(this, key); } return results; } return [resolver.get(this, key)]; } /** * Creates a new dependency injection container whose parent is the current container. * @return Returns a new container instance parented to this. */ public createChild(): Container { const child = new Container(this._configuration); child.root = this.root; child.parent = this; return child; } /** * Invokes a function, recursively resolving its dependencies. * @param fn The function to invoke with the auto-resolved dependencies. * @param dynamicDependencies Additional function dependencies to use during invocation. * @return Returns the instance resulting from calling the function. */ public invoke<TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs>, dynamicDependencies?: TArgs[number][] ): ImplOrAny<TImpl> { try { let handler = this._handlers.get(fn); if (handler === undefined) { handler = this._createInvocationHandler(fn); this._handlers.set(fn, handler); } return handler.invoke(this, dynamicDependencies); } catch (e) { // @ts-ignore throw new AggregateError( `Error invoking ${fn.name}. Check the inner error for details.`, e, true ); } } public _createInvocationHandler <TBase, TImpl extends Impl<TBase> = Impl<TBase>, TArgs extends Args<TBase> = Args<TBase>>( fn: DependencyCtorOrFunctor<TBase, TImpl, TArgs> & { inject?: any; } ): InvocationHandler<TBase, TImpl, TArgs> { let dependencies; if (fn.inject === undefined) { dependencies = metadata.getOwn(metadata.paramTypes, fn) || _emptyParameters; } else { dependencies = []; let ctor = fn; while (typeof ctor === 'function') { dependencies.push(...getDependencies(ctor)); ctor = Object.getPrototypeOf(ctor); } } const invoker = metadata.getOwn(metadata.invoker, fn) || classInvoker; const handler = new InvocationHandler(fn, invoker, dependencies); return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler; } }
the_stack
import { genMountFn, testPropClassAndStyle } from '@taro-ui-vue3/test-utils/helper' import { hyphenate } from '@vue/shared' import { ref } from 'vue' import AtInput from '../index.vue' const mountFn = genMountFn(AtInput) describe('AtInput', () => { testPropClassAndStyle(mountFn) it('should render all nodes and match snapshot', async () => { const wrapper = mountFn({ title: 'title', modelValue: 'test', clear: true, error: true, }, { default: ['slot'] }) expect(wrapper.element).toMatchSnapshot() }) it.skip('should render prop value', async () => { const wrapper = mountFn({ modelValue: 'value' }) expect( wrapper .find('.at-input__input') .attributes('value') ).toEqual('value') }) it.each([ 'name', 'placeholder', 'placeholderStyle', 'placeholderClass' ])('should render prop %s', async (propName) => { const wrapper = mountFn({ [`${propName}`]: propName }) expect( wrapper .find('.at-input__input') .attributes(hyphenate(propName)) ).toEqual( propName !== 'placeholderClass' ? propName : `placeholder ${propName}` ) }) it.each([ 'cursor', 'maxLength', 'cursorSpacing' ])('should render prop %s', async (propName) => { const wrapper = mountFn({ [`${propName}`]: 10 }) const attrName = propName === 'cursorSpacing' ? hyphenate(propName) : propName.toLowerCase() expect( wrapper .find('.at-input__input') .attributes(attrName) ).toEqual('10') }) it.each([ // 'focus', 'autoFocus', 'adjustPosition' ])('should render prop %s', async (propName) => { const wrapper = mountFn({ [`${propName}`]: true }) expect( wrapper .find('.at-input__input') .attributes(hyphenate(propName)) ).toEqual('true') }) it.each([ "go", "send", "next", "done", "search" ])('should render prop confirmType -- %s', async (confirmTypeOption) => { const wrapper = mountFn({ confirmType: confirmTypeOption }) expect( wrapper .find('.at-input__input') .attributes('confirm-type') ).toEqual(confirmTypeOption) }) it('should render prop title', async () => { const wrapper = mountFn({ title: 'title' }) const titleEl = wrapper.find('.at-input__title') expect(titleEl.exists()).toBe(true) expect(titleEl.text()).toEqual('title') }) it.each([ "number", "password", "text", "phone", "idcard", "digit" ])('should render prop type -- %s', async (typeOption) => { const wrapper = mountFn({ type: typeOption }) const inputEl = wrapper.find('.at-input__input') switch (typeOption) { case 'phone': expect(inputEl.attributes('type')).toEqual('number') expect(inputEl.attributes('maxlength')).toEqual('11') // expect( // '[Vue warn]: Failed setting prop \"selectionStart\" on <input>: value -1 is invalid.' // ).toHaveBeenWarned() // expect( // '[Vue warn]: Failed setting prop \"selectionEnd\" on <input>: value -1 is invalid.' // ).toHaveBeenWarned() break case 'password': expect(inputEl.attributes('type')).toEqual('text') expect(inputEl.attributes('password')).toEqual('true') break default: expect(inputEl.attributes('type')).toEqual(typeOption) if (typeOption === 'number') { // expect( // '[Vue warn]: Failed setting prop \"selectionStart\" on <input>: value -1 is invalid.' // ).toHaveBeenWarned() // expect( // '[Vue warn]: Failed setting prop \"selectionEnd\" on <input>: value -1 is invalid.' // ).toHaveBeenWarned() } break } }) it('should render prop border', async () => { const wrapper = mountFn() expect(wrapper.find('.at-input--without-border').exists()).toBeFalsy() await wrapper.setProps({ border: false }) expect(wrapper.find('.at-input--without-border').exists()).toBeTruthy() }) it('should render prop editable', async () => { const wrapper = mountFn({ editable: false }) expect(wrapper.find('.at-input--disabled').exists()).toBeTruthy() expect(wrapper.find('.at-input__overlay--hidden').exists()).toBeFalsy() }) it('should render prop disabled', async () => { const wrapper = mountFn() expect(wrapper.find('.at-input--disabled').exists()).toBeFalsy() expect(wrapper.find('.at-input__overlay--hidden').exists()).toBeTruthy() await wrapper.setProps({ disabled: true }) expect(wrapper.find('.at-input--disabled').exists()).toBeTruthy() expect(wrapper.find('.at-input__overlay--hidden').exists()).toBeFalsy() }) it('should render prop error', async () => { const wrapper = mountFn({ error: true }) expect(wrapper.find('.at-input--error').exists()).toBeTruthy() const errorIconEl = wrapper.find('.at-input__icon') expect(errorIconEl.exists()).toBeTruthy() }) it('should render clear icon', async () => { const wrapper = mountFn() expect(wrapper.find('.at-input__icon').exists()).toBeFalsy() await wrapper.setProps({ clear: true, modelValue: 'value' }) expect(wrapper.find('.at-input__icon').exists()).toBeTruthy() expect(wrapper.find('.at-input__icon').element).toMatchSnapshot() }) it('should render prop required when title exists', async () => { const wrapper = mountFn({ required: true }) expect(wrapper.find('.at-input__title--required').exists()).toBeFalsy() await wrapper.setProps({ title: 'title' }) expect(wrapper.find('.at-input__title--required').exists()).toBeTruthy() }) it('should render slot content', async () => { const wrapper = mountFn({}, { default: ['slot'] }) const slotContainer = wrapper.find('.at-input__children') expect(slotContainer.exists()).toBeTruthy() expect(slotContainer.text()).toBe('slot') }) }) describe('AtInput events', () => { it('should emit update:modelValue during input', async () => { const modelValue = ref('test') const onUpdateValue = jest.fn((e) => { modelValue.value = e }) const wrapper = mountFn({ modelValue, 'onUpdate:modelValue': onUpdateValue }) await wrapper .find('.at-input__input') .trigger('input', { detail: { value: 'value' } }) expect(wrapper.emitted()).toHaveProperty('update:modelValue') expect(onUpdateValue).toBeCalled() expect(modelValue.value).toEqual('value') }) it('should emit update:modelValue by clicking clear icon', async () => { const modelValue = ref('test') const onUpdateValue = jest.fn((e) => { modelValue.value = e }) const wrapper = mountFn({ clear: true, modelValue: modelValue.value, 'onUpdate:modelValue': onUpdateValue, }) await wrapper .find('.at-input .at-input__icon') .trigger('touchend') expect(wrapper.emitted()).toHaveProperty('update:modelValue') expect(onUpdateValue).toBeCalled() expect(modelValue.value).toEqual('') }) it('should emit focus', async () => { const onFocus = jest.fn() const wrapper = mountFn({ onFocus }) await wrapper .find('.at-input__input') .trigger('focus', { height: 30 }) expect(wrapper.emitted()).toHaveProperty('focus') expect(onFocus).toBeCalled() }) it('should emit blur', async () => { const onBlur = jest.fn() const wrapper = mountFn({ onBlur }) await wrapper .find('.at-input__input') .trigger('blur', { value: 'value' }) expect(wrapper.emitted()).toHaveProperty('blur') expect(onBlur).toBeCalled() }) it('should emit keyboardHeightChange', async () => { const onKeyboardHeightChange = jest.fn() const wrapper = mountFn({ onKeyboardHeightChange }) await wrapper .find('.at-input__input') .trigger('keyboardheightchange', { height: 30, duration: 400 }) expect(wrapper.emitted()).toHaveProperty('keyboard-height-change') expect(onKeyboardHeightChange).toBeCalled() }) it('should emit confirm', async () => { const onConfirm = jest.fn() const wrapper = mountFn({ onConfirm }) await wrapper .find('.at-input__input') .trigger('confirm', { detail: { value: 'value' } }) expect(wrapper.emitted()).toHaveProperty('confirm') expect(onConfirm).toBeCalled() }) it('should emit click when not editable', async () => { const onClick = jest.fn() const wrapper = mountFn({ onClick, editable: false }) await wrapper .find('.at-input .at-input__overlay') .trigger('tap') expect(wrapper.emitted()).toHaveProperty('click') expect(onClick).toBeCalled() }) it('should emit error-click when error is true', async () => { const onErrorClick = jest.fn() const wrapper = mountFn({ error: true, modelValue: 'value', onErrorClick: onErrorClick, }) await wrapper .find('.at-input .at-input__icon') .trigger('touchend') expect(wrapper.emitted()).toHaveProperty('error-click') expect(onErrorClick).toBeCalled() }) it.each([ { editable: false }, { disabled: true } ])(`should not emit any input event handler when %o`, async (props) => { const onBlur = jest.fn() const onFocus = jest.fn() const onConfirm = jest.fn() const onKeyboardHeightChange = jest.fn() const wrapper = mountFn({ ...props, onBlur, onFocus, onConfirm, onKeyboardHeightChange }) const inputEl = wrapper.find('.at-input__input') const eventNames = { 'blur': { handler: onBlur, emitted: 'blur' }, 'focus': { handler: onBlur, emitted: 'focus' }, 'confirm': { handler: onBlur, emitted: 'confirm' }, 'keyboardheightchange': { handler: onBlur, emitted: 'keyboard-height-change' } } for (const key of Object.keys(eventNames)) { await inputEl.trigger(key) expect(wrapper.emitted()).not.toHaveProperty(eventNames[key].emitted) expect(eventNames[key].handler).not.toBeCalled() } }) })
the_stack
* Pyrra * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { MultiBurnrateAlert, MultiBurnrateAlertFromJSON, MultiBurnrateAlertToJSON, Objective, ObjectiveFromJSON, ObjectiveToJSON, ObjectiveStatus, ObjectiveStatusFromJSON, ObjectiveStatusToJSON, QueryRange, QueryRangeFromJSON, QueryRangeToJSON, } from '../models'; export interface GetMultiBurnrateAlertsRequest { expr: string; grouping?: string; } export interface GetObjectiveErrorBudgetRequest { expr: string; grouping?: string; start?: number; end?: number; } export interface GetObjectiveStatusRequest { expr: string; grouping?: string; } export interface GetREDErrorsRequest { expr: string; grouping?: string; start?: number; end?: number; } export interface GetREDRequestsRequest { expr: string; grouping?: string; start?: number; end?: number; } export interface ListObjectivesRequest { expr?: string; } /** * */ export class ObjectivesApi extends runtime.BaseAPI { /** * Get the MultiBurnrateAlerts for the Objective */ async getMultiBurnrateAlertsRaw(requestParameters: GetMultiBurnrateAlertsRequest): Promise<runtime.ApiResponse<Array<MultiBurnrateAlert>>> { if (requestParameters.expr === null || requestParameters.expr === undefined) { throw new runtime.RequiredError('expr','Required parameter requestParameters.expr was null or undefined when calling getMultiBurnrateAlerts.'); } const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } if (requestParameters.grouping !== undefined) { queryParameters['grouping'] = requestParameters.grouping; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives/alerts`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(MultiBurnrateAlertFromJSON)); } /** * Get the MultiBurnrateAlerts for the Objective */ async getMultiBurnrateAlerts(requestParameters: GetMultiBurnrateAlertsRequest): Promise<Array<MultiBurnrateAlert>> { const response = await this.getMultiBurnrateAlertsRaw(requestParameters); return await response.value(); } /** * Get ErrorBudget graph sample pairs */ async getObjectiveErrorBudgetRaw(requestParameters: GetObjectiveErrorBudgetRequest): Promise<runtime.ApiResponse<QueryRange>> { if (requestParameters.expr === null || requestParameters.expr === undefined) { throw new runtime.RequiredError('expr','Required parameter requestParameters.expr was null or undefined when calling getObjectiveErrorBudget.'); } const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } if (requestParameters.grouping !== undefined) { queryParameters['grouping'] = requestParameters.grouping; } if (requestParameters.start !== undefined) { queryParameters['start'] = requestParameters.start; } if (requestParameters.end !== undefined) { queryParameters['end'] = requestParameters.end; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives/errorbudget`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => QueryRangeFromJSON(jsonValue)); } /** * Get ErrorBudget graph sample pairs */ async getObjectiveErrorBudget(requestParameters: GetObjectiveErrorBudgetRequest): Promise<QueryRange> { const response = await this.getObjectiveErrorBudgetRaw(requestParameters); return await response.value(); } /** * Get objective status */ async getObjectiveStatusRaw(requestParameters: GetObjectiveStatusRequest): Promise<runtime.ApiResponse<Array<ObjectiveStatus>>> { if (requestParameters.expr === null || requestParameters.expr === undefined) { throw new runtime.RequiredError('expr','Required parameter requestParameters.expr was null or undefined when calling getObjectiveStatus.'); } const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } if (requestParameters.grouping !== undefined) { queryParameters['grouping'] = requestParameters.grouping; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives/status`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(ObjectiveStatusFromJSON)); } /** * Get objective status */ async getObjectiveStatus(requestParameters: GetObjectiveStatusRequest): Promise<Array<ObjectiveStatus>> { const response = await this.getObjectiveStatusRaw(requestParameters); return await response.value(); } /** * Get a matrix of error percentage by label */ async getREDErrorsRaw(requestParameters: GetREDErrorsRequest): Promise<runtime.ApiResponse<QueryRange>> { if (requestParameters.expr === null || requestParameters.expr === undefined) { throw new runtime.RequiredError('expr','Required parameter requestParameters.expr was null or undefined when calling getREDErrors.'); } const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } if (requestParameters.grouping !== undefined) { queryParameters['grouping'] = requestParameters.grouping; } if (requestParameters.start !== undefined) { queryParameters['start'] = requestParameters.start; } if (requestParameters.end !== undefined) { queryParameters['end'] = requestParameters.end; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives/red/errors`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => QueryRangeFromJSON(jsonValue)); } /** * Get a matrix of error percentage by label */ async getREDErrors(requestParameters: GetREDErrorsRequest): Promise<QueryRange> { const response = await this.getREDErrorsRaw(requestParameters); return await response.value(); } /** * Get a matrix of requests by label */ async getREDRequestsRaw(requestParameters: GetREDRequestsRequest): Promise<runtime.ApiResponse<QueryRange>> { if (requestParameters.expr === null || requestParameters.expr === undefined) { throw new runtime.RequiredError('expr','Required parameter requestParameters.expr was null or undefined when calling getREDRequests.'); } const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } if (requestParameters.grouping !== undefined) { queryParameters['grouping'] = requestParameters.grouping; } if (requestParameters.start !== undefined) { queryParameters['start'] = requestParameters.start; } if (requestParameters.end !== undefined) { queryParameters['end'] = requestParameters.end; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives/red/requests`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => QueryRangeFromJSON(jsonValue)); } /** * Get a matrix of requests by label */ async getREDRequests(requestParameters: GetREDRequestsRequest): Promise<QueryRange> { const response = await this.getREDRequestsRaw(requestParameters); return await response.value(); } /** * List Objectives */ async listObjectivesRaw(requestParameters: ListObjectivesRequest): Promise<runtime.ApiResponse<Array<Objective>>> { const queryParameters: any = {}; if (requestParameters.expr !== undefined) { queryParameters['expr'] = requestParameters.expr; } const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/objectives`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(ObjectiveFromJSON)); } /** * List Objectives */ async listObjectives(requestParameters: ListObjectivesRequest): Promise<Array<Objective>> { const response = await this.listObjectivesRaw(requestParameters); return await response.value(); } }
the_stack
import * as Svgo from 'svgo' import * as Path from 'path' import * as rollup from 'rollup' import { gifInfoBuf } from './gif' import { jpegInfoBuf } from './jpeg' import * as typescript from 'typescript' import { readfile } from './fs' import { dirname, basename } from 'path' let _svgoInstance :Svgo|null = null function getSvgo() :Svgo { return _svgoInstance || (_svgoInstance = new Svgo({ full: true, plugins: [ { cleanupAttrs: true }, { removeDoctype: true }, { removeXMLProcInst: true }, { removeComments: true }, { removeMetadata: true }, { removeTitle: true }, { removeDesc: true }, { removeUselessDefs: true }, { removeEditorsNSData: true }, { removeEmptyAttrs: true }, { removeHiddenElems: true }, { removeEmptyText: true }, { removeEmptyContainers: true }, { removeViewBox: false }, { cleanupEnableBackground: true }, { convertStyleToAttrs: true }, { convertColors: true }, { convertPathData: true }, { convertTransform: true }, { removeUnknownsAndDefaults: true }, { removeNonInheritableGroupAttrs: true }, { removeUselessStrokeAndFill: true }, { removeUnusedNS: true }, { cleanupIDs: true }, { cleanupNumericValues: true }, { moveElemsAttrsToGroup: true }, { moveGroupAttrsToElems: true }, { collapseGroups: true }, { removeRasterImages: false }, { mergePaths: true }, { convertShapeToPath: true }, { sortAttrs: true }, //{ removeDimensions: true }, ], })) } export class AssetInfo { // one of these are set, depending on encoding b64data :string = "" textData :string = "" urlPrefix :string = "" mimeType :string = "" // file-type dependent attributes, like width and height for images attrs :{[key:string]:any} = {} // cache _url :string = "" get url() :string { if (!this._url) { this._url = this.urlPrefix + (this.textData || this.b64data) } return this._url } getTextData() :string { return this.textData || this.getData().toString("utf8") } getData() :Buffer { return this.textData ? Buffer.from(this.textData, "utf8") : Buffer.from(this.b64data, "base64") } } export class AssetBundler { mimeTypes = new Map([ ['.jpg', 'image/jpeg'], ['.jpeg', 'image/jpeg'], ['.png', 'image/png'], ['.gif', 'image/gif'], ['.svg', 'image/svg+xml'], ['.dat', 'application/octet-stream'], ]) assetCache = new Map() // .d.ts path => {meta, mimeType, file} // the following properties are updated on each compilation, even in // watch mode. tsService :typescript.LanguageService|null = null tsCompilerOptions = {} as typescript.CompilerOptions _typescriptProxy :typeof typescript|null = null _rollupPlugin :rollup.Plugin|null = null mimeTypeIsText(mimeType :string) :bool { // TODO: expand this when we expand this.mimeTypes return mimeType == "image/svg+xml" } mimeTypeIsJSXCompatible(mimeType :string) :bool { return mimeType == "image/svg+xml" } mimeTypeIsImage(mimeType :string) :bool { return mimeType.startsWith("image/") } extractPathQueryString(path :string) :[string,string] { // [path, query] let qi = path.lastIndexOf("?") if (qi != -1) { let si = path.lastIndexOf("/") if (si < qi) { return [ path.substr(0, qi), path.substr(qi + 1) ] } } return [ path, "" ] } // Wrap typescript to allow virtualized .d.ts asset files // getTypescriptProxy() :typeof typescript { const a = this return this._typescriptProxy || (this._typescriptProxy = { __proto__: typescript, sys: { __proto__: typescript.sys, fileExists(path :string) :bool { if (a.assetCache.has(path) || typescript.sys.fileExists(path)) { return true } if (path.endsWith(".d.ts")) { let srcpath = path.substr(0, path.length - 5) // strip ".d.ts" let [file, meta] = a.extractPathQueryString(srcpath) let ext = Path.extname(file).toLowerCase() let mimeType = a.mimeTypes.get(ext) if (mimeType && typescript.sys.fileExists(file)) { a.assetCache.set(path, { meta, mimeType, file }) return true } } return false }, readFile(path :string, encoding? :string) :string | undefined { let ent = a.assetCache.get(path) if (ent !== undefined) { let { meta, mimeType, file } = ent if (meta == "jsx") { if (a.mimeTypeIsJSXCompatible(mimeType)) { return ( "import React from 'react';\n" + "const s :React.StatelessComponent<" + "React.SVGAttributes<SVGElement>>;\n" + "export default s;\n" ) } else { console.error(`${file}: not valid JSX`) } } if (a.mimeTypeIsImage(mimeType)) { return "const a :{url:string,width:number,height:number};\nexport default a;\n" } return "const a :{url:string};\nexport default a;\n" } return typescript.sys.readFile(path, encoding) }, }, // createLanguageService( // host: LanguageServiceHost, // documentRegistry?: DocumentRegistry, // syntaxOnly?: boolean // ): LanguageService createLanguageService( host :typescript.LanguageServiceHost, documentRegistry? :typescript.DocumentRegistry, syntaxOnly? :bool ) :typescript.LanguageService { // provide trace function in case tracing is enabled this.tsCompilerOptions = host.getCompilationSettings() if (this.tsCompilerOptions.traceResolution) { host.trace = msg => print(">>", msg) } const ts = this // Patch the TS rollup plugin to work around // https://github.com/ezolenko/rollup-plugin-typescript2/issues/154 // getScriptSnapshot(fileName: string): // tsTypes.IScriptSnapshot | undefined host.getScriptSnapshot = function(fileName) { fileName = fileName.replace(/\\+/g, "/") let snapshot = (host as any).snapshots[fileName] if (!snapshot) { snapshot = ts.ScriptSnapshot.fromString(ts.sys.readFile(fileName)) ;(host as any).snapshots[fileName] = snapshot ;(host as any).versions[fileName] = ((host as any).versions[fileName] || 0) + 1 } return snapshot } let s = typescript.createLanguageService( host, documentRegistry, syntaxOnly ) a.tsService = s return s }, } as any as typeof typescript) } // getTypescriptProxy getRollupPlugin() { const a = this return this._rollupPlugin || (this._rollupPlugin = { name: 'asset', buildEnd(err?: Error) :Promise<void>|void { a.assetCache.clear() }, resolveId(id: string, parentId: string | undefined) :rollup.ResolveIdResult { if (id.indexOf("?") != -1) { let [file, meta] = a.extractPathQueryString(id) if (meta && a.mimeTypes.has(Path.extname(file).toLowerCase())) { return ( parentId ? Path.resolve(dirname(parentId), id) : Path.resolve(id) ) } } return undefined }, load(id :string) :Promise<string|null> { let ext = Path.extname(id) if (ext == ".json") { return readfile(id, "utf8").then(json => `export default ${JSON.stringify(JSON.parse(json))}` ) } let [id2, mimeType, meta] = a.parseFilename(id) id = id2 if (!mimeType) { return Promise.resolve(null) } this.addWatchFile(id) let jsid = basename(id) jsid = jsid.substr(0, jsid.length - ext.length) .replace(/[^A-Za-z0-9_]+/g, "_") // print("LOAD", id, {meta}) if (meta == "jsx") { // generate JSX virtual dom instead of data url return a.readAsJSXModule(id, jsid) } return a.loadAssetInfo(id, mimeType).then(obj => `const asset_${jsid} = ${JSON.stringify(obj)};\n` + `export default asset_${jsid};` ) } }) } // getRollupPlugin // parseFilename returns [filename, mimeType?, queryString] parseFilename(filename :string) :[string, string|undefined, string] { const a = this let [fn, queryString] = a.extractPathQueryString(filename) let ext = Path.extname(fn) let mimeType = a.mimeTypes.get(ext.toLowerCase()) return [fn, mimeType, queryString] } // readAsJSX reads a resource which contents is valid JSX, like an SVG, // and parses it as JSX, returning ESNext JavaScript module code. async readAsJSXModule(path :string, jsid :string) :Promise<string> { let svg = await readfile(path, "utf8") let jsxSource = ( `import React from "react";\n` + `const asset_${jsid} = ${svg};\n` + `export default asset_${jsid};\n` ) // transpile( // input: string, // compilerOptions?: CompilerOptions, // fileName?: string, // diagnostics?: Diagnostic[], // moduleName?: string // ): string; let compilerOptions = { jsx: this.tsCompilerOptions.jsx || typescript.JsxEmit.React, module: typescript.ModuleKind.ESNext, // "esnext" target: typescript.ScriptTarget.ESNext, // "esnext" } as typescript.CompilerOptions return typescript.transpile(jsxSource, compilerOptions, path+".jsx") } async loadAssetInfo(path :string, mimeType? :string) :Promise<AssetInfo> { let obj = new AssetInfo() if (mimeType) { obj.mimeType = mimeType if (mimeType == "image/gif") { let data = await readfile(path, "base64") let head = Buffer.from(data.substr(0,16), "base64") try { obj.attrs = gifInfoBuf(head) } catch(err) { console.error(`${path}: not a GIF image (${err})`) obj.attrs.width = 0 obj.attrs.height = 0 } obj.urlPrefix = `data:${mimeType};base64,` obj.b64data = data } else if (mimeType == "image/jpeg") { let data = await readfile(path) try { obj.attrs = jpegInfoBuf(data) } catch(err) { console.error(`${path}: not a JPEG image (${err})`) obj.attrs.width = 0 obj.attrs.height = 0 } obj.urlPrefix = `data:${mimeType};base64,` obj.b64data = data.toString("base64") } else if (this.mimeTypeIsText(mimeType)) { // for text types, attempt text encoding let data = await readfile(path, "utf8") if (mimeType == "image/svg+xml") { let res = await getSvgo().optimize(data, {path}) if (res.data.match(/^[^\r\n\t]+$/)) { obj.attrs = res.info as {[k:string]:any} if (obj.attrs.width) { obj.attrs.width = parseInt(obj.attrs.width) if (isNaN(obj.attrs.width)) { obj.attrs.width = 0 } } else { obj.attrs.width = 0 } if (obj.attrs.height) { obj.attrs.height = parseInt(obj.attrs.height) if (isNaN(obj.attrs.height)) { obj.attrs.height = 0 } } else { obj.attrs.height = 0 } obj.urlPrefix = `data:${mimeType};utf8,` obj.textData = res.data } } } } if (!obj.urlPrefix) { // fallback to base-64 encoding the data let data = await readfile(path, "base64") obj.urlPrefix = `data:${mimeType};base64,` obj.b64data = data } return obj } }
the_stack
import Event from './utils/Event'; import shouldStopAnimation from './shouldStopAnimation'; import shouldUseBezier from './shouldUseBezier'; import stripStyle from './stripStyle'; import stepper from './stepper'; import mapToZero from './mapToZero'; import wrapValue from './wrapValue'; const now = () => Date.now(); const msPerFrame = 1000 / 60; /** * @summary * * Lifecycle hook: * start, pause, resume, stop, frame, rest * * Binding method: * const animation = new Animation (); animation.on ('start | frame | rest ', () => {}); */ export default class Animation extends Event { _config: Record<string, any>; _props: Record<string, any>; _from: Record<string, any>; _to: Record<string, any>; _delay: number; _currentVelocity: Record<string, any>; _currentStyle: Record<string, any>; _lastIdealStyle: Record<string, any>; _lastIdealVelocity: Record<string, any>; _frameCount: number; _prevTime: number; _timer: any; _startedTime: number; _ended: boolean; _stopped: boolean; _wasAnimating: boolean; _started: boolean; _paused: boolean; _accumulatedTime: Record<string, any>; _pausedTime: number; _destroyed: boolean; constructor(props = {}, config = {}) { super(); this._props = { ...props }; this._config = { ...config }; this.initStates(); } _wrapConfig(object: { [x: string]: any }, config: { delay?: string }) { config = config && typeof config === 'object' ? config : this._config; const ret = {}; for (const key of Object.keys(object)) { ret[key] = wrapValue(object[key], config); } return ret; } initStates(props?: Record<string, any>, config?: Record<string, any>) { props = props && typeof props === 'object' ? props : this._props; config = config && typeof config === 'object' ? config : this._config; const { from, to } = props; this._from = {}; if (from && typeof from) { for (const key of Object.keys(from)) { this._from[key] = typeof from[key] === 'object' && from[key].val ? from[key].val : from[key]; } } this._to = this._wrapConfig(to, config); this._delay = parseInt(config.delay) || 0; const currentStyle = (this._from && stripStyle(this._from)) || stripStyle(this._to); const currentVelocity = mapToZero(currentStyle); this._currentStyle = { ...currentStyle }; this._currentVelocity = { ...currentVelocity }; this._lastIdealStyle = { ...currentStyle }; this._lastIdealVelocity = { ...currentVelocity }; this.resetPlayStates(); this._frameCount = 0; this._prevTime = 0; } animate() { if (this._timer != null) { return; } this._timer = requestAnimationFrame(timestamp => { const nowTime = now(); // stop animation and emit onRest event if ( shouldStopAnimation( this._currentStyle, this._to, this._currentVelocity, this._startedTime || nowTime, nowTime ) || this._ended || this._stopped ) { if (this._wasAnimating && !this._ended && !this._stopped) { // should emit reset in settimeout for delay msPerframe this._timer = setTimeout(() => { clearTimeout(this._timer); this._timer = null; this._ended = true; this.emit('rest', this.getCurrentStates()); }, msPerFrame); } this.resetPlayStates(); return; } if (!this._started) { this._started = true; this.emit('start', this.getCurrentStates()); } this._stopped = false; this._paused = false; this._wasAnimating = true; if (this._startedTime === 0) { this._startedTime = nowTime; } const currentTime = nowTime; const timeDelta = currentTime - this._prevTime; this._prevTime = currentTime; if (currentTime - this._startedTime < this._delay) { this._timer = null; this.animate(); } const newLastIdealStyle = {}; const newLastIdealVelocity = {}; const newCurrentStyle = {}; const newCurrentVelocity = {}; const toKeys = (this._to && Object.keys(this._to)) || []; for (const key of toKeys) { const styleValue = this._to[key]; this._accumulatedTime[key] = typeof this._accumulatedTime[key] !== 'number' ? timeDelta : this._accumulatedTime[key] + timeDelta; const from = this._from[key] != null && typeof this._from[key] === 'object' ? this._from[key].val : this._from[key]; const to = styleValue.val; if (typeof styleValue === 'number') { newCurrentStyle[key] = styleValue; newCurrentVelocity[key] = 0; newLastIdealStyle[key] = styleValue; newLastIdealVelocity[key] = 0; } else { let newLastIdealStyleValue = this._lastIdealStyle[key]; let newLastIdealVelocityValue = this._lastIdealVelocity[key]; if (shouldUseBezier(this._config) || shouldUseBezier(styleValue)) { // easing const { easing, duration } = styleValue; newLastIdealStyleValue = from + easing((currentTime - this._startedTime) / duration) * (to - from); if (currentTime >= this._startedTime + duration) { newLastIdealStyleValue = to; styleValue.done = true; } newLastIdealStyle[key] = newLastIdealStyleValue; newCurrentStyle[key] = newLastIdealStyleValue; } else if (to != null && to === this._currentStyle[key]) { newCurrentStyle[key] = to; newCurrentVelocity[key] = 0; newLastIdealStyle[key] = to; newLastIdealVelocity[key] = 0; } else { // spring const currentFrameCompletion = (this._accumulatedTime[key] - Math.floor(this._accumulatedTime[key] / msPerFrame) * msPerFrame) / msPerFrame; const framesToCatchUp = Math.floor(this._accumulatedTime[key] / msPerFrame); for (let i = 0; i < framesToCatchUp; i++) { [newLastIdealStyleValue, newLastIdealVelocityValue] = stepper( msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.tension, styleValue.friction, styleValue.precision ); } const [nextIdealX, nextIdealV] = stepper( msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.tension, styleValue.friction, styleValue.precision ); newCurrentStyle[key] = newLastIdealStyleValue + (nextIdealX - newLastIdealStyleValue) * currentFrameCompletion; newCurrentVelocity[key] = newLastIdealVelocityValue + (nextIdealV - newLastIdealVelocityValue) * currentFrameCompletion; newLastIdealStyle[key] = newLastIdealStyleValue; newLastIdealVelocity[key] = newLastIdealVelocityValue; this._accumulatedTime[key] -= framesToCatchUp * msPerFrame; } } } this._timer = null; this._currentStyle = { ...newCurrentStyle }; this._currentVelocity = { ...newCurrentVelocity }; this._lastIdealStyle = { ...newLastIdealStyle }; this._lastIdealVelocity = { ...newLastIdealVelocity }; // console.log(newCurrentStyle); if (!this._destroyed) { this.emit('frame', this.getCurrentStates()); this.animate(); } }); } start() { this._prevTime = now(); this._startedTime = now(); this.animate(); } end() { if (!this._ended) { this._ended = true; this._currentStyle = this.getFinalStates(); this.emit('frame', this.getFinalStates()); this.emit('rest', this.getFinalStates()); } this.destroy(); } pause() { if (!this._paused) { this._pausedTime = now(); this._paused = true; this.emit('pause', this.getCurrentStates()); this.destroy(); this._destroyed = false; } } resume() { if (this._started && this._paused) { const nowTime = now(); const pausedDuration = nowTime - this._pausedTime; this._paused = false; // should add with pausedDuration this._startedTime += pausedDuration; this._prevTime += pausedDuration; this._pausedTime = 0; this.emit('resume', this.getCurrentStates()); this.animate(); } } stop() { this.destroy(); if (!this._stopped) { this._stopped = true; // this.emit('frame', this.getInitialStates()); this.emit('stop', this.getInitialStates()); this.initStates(); } } destroy() { cancelAnimationFrame(this._timer); clearTimeout(this._timer); this._timer = null; this._destroyed = true; } resetPlayStates() { this._started = false; this._stopped = false; this._ended = false; this._paused = false; this._destroyed = false; this._timer = null; this._wasAnimating = false; this._accumulatedTime = {}; this._startedTime = 0; this._pausedTime = 0; } reset() { this.destroy(); this.initStates(); } reverse() { this.destroy(); const props = { ...this._props }; const [from, to] = [props.to, props.from]; props.from = from; props.to = to; this._props = { ...props }; this.initStates(); } getCurrentStates() { return { ...this._currentStyle }; } getInitialStates() { return { ...stripStyle(this._props.from) }; } getFinalStates() { return { ...stripStyle(this._props.to) }; } }
the_stack
import {OpenYoloInternalError} from '../protocol/errors'; import {PostMessageType, verifyAckMessage, verifyPingMessage} from '../protocol/post_messages'; import {MockWindow} from '../test_utils/frames'; import {createMessageEvent} from '../test_utils/messages'; import {JasmineTimeoutManager} from '../test_utils/timeout'; import {AncestorOriginVerifier} from './ancestor_origin_verifier'; describe('AncestorOriginVerifier', () => { const TIMEOUT = 1000; let parentFrame: MockWindow; let providerFrame: MockWindow; let permittedOrigins: string[]; let verifier: AncestorOriginVerifier; let timeoutManager = new JasmineTimeoutManager(); beforeEach(() => { parentFrame = new MockWindow(); providerFrame = new MockWindow(parentFrame); permittedOrigins = ['https://www.example.com', 'https://auth.example.com']; verifier = new AncestorOriginVerifier(providerFrame, permittedOrigins, TIMEOUT); timeoutManager.install(); }); afterEach(() => { timeoutManager.uninstall(); }); describe('verifyAncestorOrigin', () => { it('should post a ping message and listen for response', () => { let addEventListenerSpy = spyOn(providerFrame, 'addEventListener'); let postMessageSpy = spyOn(parentFrame, 'postMessage'); verifier.verifyAncestorOrigin(parentFrame, 0); // a listener should be registered to capture the verification // acknowledgement message expect(addEventListenerSpy) .toHaveBeenCalledWith('message', jasmine.anything()); // the verification message should be sent expect(postMessageSpy) .toHaveBeenCalledWith( jasmine.objectContaining( {type: PostMessageType.verifyPing, data: jasmine.anything()}), '*'); }); it('should timeout if no response arrives', (done) => { let expectFailNow = false; verifier.verifyAncestorOrigin(parentFrame, 0) .then( () => { done.fail('Verification should not succeed'); }, (err) => { expect(expectFailNow).toBeTruthy('Failed too early'); expect(err).toEqual( OpenYoloInternalError.parentVerifyTimeout()); done(); }); // advance clock to just before the timeout jasmine.clock().tick(TIMEOUT - 1); expectFailNow = true; jasmine.clock().tick(1); }); it('should resolve if a valid response arrives', async function(done) { let parentOrigin = permittedOrigins[0]; parentFrame.addEventListener('message', (ev: MessageEvent) => { expect(ev.data.type).toBe(PostMessageType.verifyPing); // simulate the response message from the valid parent origin, and // with the received nonce value providerFrame.postMessageFromOrigin( verifyAckMessage(ev.data.data), null, parentOrigin, parentFrame); }); let result = await verifier.verifyAncestorOrigin(parentFrame, 0); expect(result).toEqual(parentOrigin); done(); }); it('should reject the promise if the response comes from an invalid origin', async function(done) { let parentOrigin = 'https://www.3vil.com'; let pingReceived = false; parentFrame.addEventListener('message', (ev: MessageEvent) => { expect(ev.data.type).toBe(PostMessageType.verifyPing); pingReceived = true; // simulate the response message from the wrong origin providerFrame.postMessageFromOrigin( verifyAckMessage(ev.data.data), null, parentOrigin, parentFrame); }); let verifyPromise = verifier.verifyAncestorOrigin(parentFrame, 0); try { await verifyPromise; done.fail('Verification should not succeed'); } catch (err) { expect(pingReceived).toBeTruthy(); expect(err).toEqual( OpenYoloInternalError.untrustedOrigin(parentOrigin)); done(); } }); it('should ignore different verification nonces', async function(done) { let parentOrigin = permittedOrigins[0]; parentFrame.addEventListener('message', (ev: MessageEvent) => { expect(ev.data.type).toBe(PostMessageType.verifyPing); // simulate the response message from the valid parent origin, // but with a different nonce providerFrame.postMessageFromOrigin( verifyAckMessage('differentNonce'), null, parentOrigin, parentFrame); }); let verifyPromise = verifier.verifyAncestorOrigin(parentFrame, 0); jasmine.clock().tick(TIMEOUT); try { await verifyPromise; done.fail('Verification should not succeed'); } catch (err) { expect(err).toEqual(OpenYoloInternalError.parentVerifyTimeout()); done(); } }); it('should ignore messages of the wrong type', async function(done) { let parentOrigin = permittedOrigins[0]; parentFrame.addEventListener('message', (ev: MessageEvent) => { expect(ev.data.type).toBe(PostMessageType.verifyPing); // simulate the response message from the valid parent origin, // but with another ping instead of an ack providerFrame.postMessageFromOrigin( verifyPingMessage(ev.data.data), null, parentOrigin, parentFrame); }); let verifyPromise = verifier.verifyAncestorOrigin(parentFrame, 0); jasmine.clock().tick(TIMEOUT); try { await verifyPromise; done.fail('Verification should not succeed'); } catch (err) { expect(err).toEqual(OpenYoloInternalError.parentVerifyTimeout()); done(); } }); it('should ignore messages that are not sourced from the window', async function(done) { let parentOrigin = permittedOrigins[0]; let pingReceived = false; parentFrame.addEventListener('message', (ev: MessageEvent) => { expect(ev.data.type).toBe(PostMessageType.verifyPing); pingReceived = true; // simulate the response message from the valid parent origin, // but with a source that is not the provider frame providerFrame.dispatchEvent(createMessageEvent( verifyAckMessage(ev.data.data), parentOrigin, undefined, new MockWindow())); }); let verifyPromise = verifier.verifyAncestorOrigin(parentFrame, 0); jasmine.clock().tick(TIMEOUT); try { await verifyPromise; done.fail('Verification should not succeed'); } catch (err) { expect(pingReceived).toBeTruthy(); expect(err).toEqual(OpenYoloInternalError.parentVerifyTimeout()); done(); } }); }); describe('verify', () => { describe('single parent allowed', () => { it('should resolve the promise when parent is valid', async function(done) { let parentOrigin = permittedOrigins[0]; spyOn(verifier, 'verifyAncestorOrigin') .and.returnValue(Promise.resolve(parentOrigin)); try { let result = await verifier.verify(false); expect(result).toEqual([parentOrigin]); done(); } catch (err) { done.fail('Promise was rejected'); } }); it('should reject the promise when the parent is invalid', async function(done) { let parentOrigin = 'https://www.3vil.com'; let expectedError = OpenYoloInternalError.untrustedOrigin(parentOrigin); spyOn(verifier, 'verifyAncestorOrigin') .and.returnValue(Promise.reject(expectedError)); try { await verifier.verify(false); done.fail('Promise should not resolve'); } catch (err) { expect(err).toEqual(expectedError); done(); } }); it('should reject the promise if more than one ancestor frame', async function(done) { let ancestorFrame = new MockWindow(); parentFrame.parent = ancestorFrame; try { await verifier.verify(false); done.fail('Promise should not resolve'); } catch (err) { expect(err).toEqual(OpenYoloInternalError.parentIsNotRoot()); done(); } }); }); describe('multiple ancestors allowed', () => { let ancestorFrame: MockWindow; beforeEach(() => { ancestorFrame = new MockWindow(); parentFrame.parent = ancestorFrame; }); it('should resolve the promise if all ancestors valid', async function(done) { spyOn(verifier, 'verifyAncestorOrigin') .and.callFake((ancestor: any) => { if (ancestor === parentFrame) { return Promise.resolve(permittedOrigins[1]); } else if (ancestor === ancestorFrame) { return Promise.resolve(permittedOrigins[0]); } done.fail('unknown frame'); }); try { let result = await verifier.verify(true); expect(result).toEqual([permittedOrigins[1], permittedOrigins[0]]); done(); } catch (err) { done.fail('Promise rejected'); } }); it('should reject the promise if any ancestor is invalid', async function(done) { let expectedError = OpenYoloInternalError.untrustedOrigin('https://www.3vil.com'); spyOn(verifier, 'verifyAncestorOrigin') .and.callFake((ancestor: any) => { if (ancestor === parentFrame) { return Promise.resolve(permittedOrigins[0]); } else if (ancestor === ancestorFrame) { return Promise.reject(expectedError); } done.fail('unknown frame'); }); try { await verifier.verify(true); done.fail('Promise should not resolve'); } catch (err) { expect(err).toEqual(expectedError); done(); } }); }); }); });
the_stack
import type {Pointer} from '@theatre/dataverse' import {val} from '@theatre/dataverse' import type {KeyboardEvent} from 'react' import React, { useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react' import styled from 'styled-components' import fuzzy from 'fuzzy' import type {SequenceEditorPanelLayout} from '@theatre/studio/panels/SequenceEditorPanel/layout/layout' import getStudio from '@theatre/studio/getStudio' import type {CommitOrDiscard} from '@theatre/studio/StudioStore/StudioStore' import type KeyframeEditor from '@theatre/studio/panels/SequenceEditorPanel/DopeSheet/Right/BasicKeyframedTrack/KeyframeEditor/KeyframeEditor' import CurveSegmentEditor from './CurveSegmentEditor' import EasingOption from './EasingOption' import type {CSSCubicBezierArgsString, CubicBezierHandles} from './shared' import { cssCubicBezierArgsFromHandles, handlesFromCssCubicBezierArgs, EASING_PRESETS, areEasingsSimilar, } from './shared' import {COLOR_BASE, COLOR_POPOVER_BACK} from './colors' import useRefAndState from '@theatre/studio/utils/useRefAndState' import type {Keyframe} from '@theatre/core/projects/store/types/SheetState_Historic' import {useUIOptionGrid, Outcome} from './useUIOptionGrid' const PRESET_COLUMNS = 3 const PRESET_SIZE = 53 const APPROX_TOOLTIP_HEIGHT = 25 const Grid = styled.div` background: ${COLOR_POPOVER_BACK}; display: grid; grid-template-areas: 'search tween' 'presets tween'; grid-template-rows: 32px 1fr; grid-template-columns: ${PRESET_COLUMNS * PRESET_SIZE}px 120px; gap: 1px; height: 120px; ` const OptionsContainer = styled.div` overflow: auto; grid-area: presets; display: grid; grid-template-columns: repeat(${PRESET_COLUMNS}, 1fr); grid-auto-rows: min-content; gap: 1px; overflow-y: scroll; scrollbar-width: none; /* Firefox */ -ms-overflow-style: none; /* Internet Explorer 10+ */ &::-webkit-scrollbar { /* WebKit */ width: 0; height: 0; } ` const SearchBox = styled.input.attrs({type: 'text'})` background-color: ${COLOR_BASE}; border: none; border-radius: 2px; color: rgba(255, 255, 255, 0.8); padding: 6px; font-size: 12px; outline: none; cursor: text; text-align: left; width: 100%; height: 100%; box-sizing: border-box; grid-area: search; &:hover { background-color: #212121; } &:focus { background-color: rgba(16, 16, 16, 0.26); outline: 1px solid rgba(0, 0, 0, 0.35); } ` const CurveEditorContainer = styled.div` grid-area: tween; background: ${COLOR_BASE}; ` const NoResultsFoundContainer = styled.div` grid-column: 1 / 4; padding: 6px; color: #888888; ` enum TextInputMode { user, auto, } type IProps = { layoutP: Pointer<SequenceEditorPanelLayout> /** * Called when user hits enter/escape */ onRequestClose: () => void } & Parameters<typeof KeyframeEditor>[0] const CurveEditorPopover: React.FC<IProps> = (props) => { ////// `tempTransaction` ////// /* * `tempTransaction` is used for all edits in this popover. The transaction * is discared if the user presses escape, otherwise it is committed when the * popover closes. */ const tempTransaction = useRef<CommitOrDiscard | null>(null) useEffect( () => // Clean-up function, called when this React component unmounts. // When it unmounts, we want to commit edits that are outstanding () => { tempTransaction.current?.commit() }, [tempTransaction], ) ////// Keyframe and trackdata ////// const {index, trackData} = props const cur = trackData.keyframes[index] const next = trackData.keyframes[index + 1] const easing: CubicBezierHandles = [ trackData.keyframes[index].handles[2], trackData.keyframes[index].handles[3], trackData.keyframes[index + 1].handles[0], trackData.keyframes[index + 1].handles[1], ] ////// Text input data and reactivity ////// const inputRef = useRef<HTMLInputElement>(null) // Select the easing string on popover open for quick copy&paste useLayoutEffect(() => { inputRef.current?.select() inputRef.current?.focus() }, [inputRef.current]) const [inputValue, setInputValue] = useState<string>('') const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { setTextInputMode(TextInputMode.user) setInputValue(e.target.value) const maybeHandles = handlesFromCssCubicBezierArgs(inputValue) if (maybeHandles) setEdit(inputValue) } const onSearchKeyDown = (e: KeyboardEvent<HTMLInputElement>) => { setTextInputMode(TextInputMode.user) // Prevent scrolling on arrow key press if (e.key === 'ArrowDown' || e.key === 'ArrowUp') e.preventDefault() if (e.key === 'ArrowDown') { grid.focusFirstItem() optionsRef.current[displayedPresets[0].label]?.current?.focus() } else if (e.key === 'Escape') { discardTempValue(tempTransaction) props.onRequestClose() } else if (e.key === 'Enter') { props.onRequestClose() } } // In auto mode, the text input field is continually updated to // a CSS cubic bezier args string to reflect the state of the curve; // in user mode, the text input field does not update when the curve // changes so that the user's search is preserved. const [textInputMode, setTextInputMode] = useState<TextInputMode>( TextInputMode.auto, ) useEffect(() => { if (textInputMode === TextInputMode.auto) setInputValue(cssCubicBezierArgsFromHandles(easing)) }, [trackData]) // `edit` keeps track of the current edited state of the curve. const [edit, setEdit] = useState<CSSCubicBezierArgsString | null>(null) // `preview` is used when hovering over a curve to preview it. const [preview, setPreview] = useState<CSSCubicBezierArgsString | null>(null) // When `preview` or `edit` change, use the `tempTransaction` to change the // curve in Theate's data. useMemo( () => setTempValue(tempTransaction, props, cur, next, preview ?? edit ?? ''), [preview, edit], ) ////// Curve editing reactivity ////// const onCurveChange = (newHandles: CubicBezierHandles) => { setTextInputMode(TextInputMode.auto) const value = cssCubicBezierArgsFromHandles(newHandles) setInputValue(value) setEdit(value) } const onCancelCurveChange = () => {} ////// Preset reactivity ////// const displayedPresets = useMemo(() => { const presetSearchResults = fuzzy.filter(inputValue, EASING_PRESETS, { extract: (el) => el.label, }) const isInputValueAQuery = /^[A-Za-z]/.test(inputValue) return isInputValueAQuery ? presetSearchResults.map((result) => result.original) : EASING_PRESETS }, [inputValue]) // Use the first preset in the search when the displayed presets change useEffect(() => { if (displayedPresets[0]) setEdit(displayedPresets[0].value) }, [displayedPresets]) ////// Option grid specification and reactivity ////// const onEasingOptionKeydown = (e: KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Escape') { discardTempValue(tempTransaction) props.onRequestClose() e.stopPropagation() } else if (e.key === 'Enter') { props.onRequestClose() e.stopPropagation() } } const onEasingOptionMouseOver = (item: {label: string; value: string}) => setPreview(item.value) const onEasingOptionMouseOut = () => setPreview(null) const onSelectEasingOption = (item: {label: string; value: string}) => { setTextInputMode(TextInputMode.auto) setEdit(item.value) } // A map to store all html elements corresponding to easing options const optionsRef = useRef( EASING_PRESETS.reduce((acc, curr) => { acc[curr.label] = {current: null} return acc }, {} as {[key: string]: {current: HTMLDivElement | null}}), ) const [optionsContainerRef, optionsContainer] = useRefAndState<HTMLDivElement | null>(null) // Keep track of option container scroll position const [optionsScrollPosition, setOptionsScrollPosition] = useState(0) useEffect(() => { const listener = () => { setOptionsScrollPosition(optionsContainer?.scrollTop ?? 0) } optionsContainer?.addEventListener('scroll', listener) return () => optionsContainer?.removeEventListener('scroll', listener) }, [optionsContainer]) const grid = useUIOptionGrid({ items: displayedPresets, uiColumns: 3, onSelectItem: onSelectEasingOption, canVerticleExit(exitSide) { if (exitSide === 'top') { inputRef.current?.select() inputRef.current?.focus() return Outcome.Handled } return Outcome.Passthrough }, renderItem: ({item: preset, select}) => ( <EasingOption key={preset.label} easing={preset} tabIndex={0} onKeyDown={onEasingOptionKeydown} ref={optionsRef.current[preset.label]} onMouseOver={() => onEasingOptionMouseOver(preset)} onMouseOut={onEasingOptionMouseOut} onClick={select} tooltipPlacement={ (optionsRef.current[preset.label].current?.offsetTop ?? 0) - (optionsScrollPosition ?? 0) < PRESET_SIZE + APPROX_TOOLTIP_HEIGHT ? 'bottom' : 'top' } isSelected={areEasingsSimilar( easing, handlesFromCssCubicBezierArgs(preset.value), )} /> ), }) // When the user navigates highlight between presets, focus the preset el and set the // easing data to match the highlighted preset useLayoutEffect(() => { if ( grid.currentSelection !== null && document.activeElement !== inputRef.current // prevents taking focus away from input ) { const maybePresetEl = optionsRef.current?.[grid.currentSelection.label]?.current maybePresetEl?.focus() setEdit(grid.currentSelection.value) } }, [grid.currentSelection]) return ( <Grid> <SearchBox value={inputValue} placeholder="Search presets..." onPaste={setTimeoutFunction(onInputChange)} onChange={onInputChange} ref={inputRef} onKeyDown={onSearchKeyDown} /> <OptionsContainer ref={optionsContainerRef} onKeyDown={(evt) => grid.onParentEltKeyDown(evt)} > {grid.gridItems} {grid.gridItems.length === 0 ? ( <NoResultsFoundContainer>No results found</NoResultsFoundContainer> ) : undefined} </OptionsContainer> <CurveEditorContainer onClick={() => inputRef.current?.focus()}> <CurveSegmentEditor {...props} onCurveChange={onCurveChange} onCancelCurveChange={onCancelCurveChange} /> </CurveEditorContainer> </Grid> ) } export default CurveEditorPopover function setTempValue( tempTransaction: React.MutableRefObject<CommitOrDiscard | null>, props: IProps, cur: Keyframe, next: Keyframe, newCurve: string, ): void { tempTransaction.current?.discard() tempTransaction.current = null const handles = handlesFromCssCubicBezierArgs(newCurve) if (handles === null) return tempTransaction.current = transactionSetCubicBezier(props, cur, next, handles) } function discardTempValue( tempTransaction: React.MutableRefObject<CommitOrDiscard | null>, ): void { tempTransaction.current?.discard() tempTransaction.current = null } function transactionSetCubicBezier( props: IProps, cur: Keyframe, next: Keyframe, newHandles: CubicBezierHandles, ): CommitOrDiscard { return getStudio().tempTransaction(({stateEditors}) => { const {replaceKeyframes} = stateEditors.coreByProject.historic.sheetsById.sequence replaceKeyframes({ ...props.leaf.sheetObject.address, snappingFunction: val(props.layoutP.sheet).getSequence() .closestGridPosition, trackId: props.leaf.trackId, keyframes: [ { ...cur, handles: [ cur.handles[0], cur.handles[1], newHandles[0], newHandles[1], ], }, { ...next, handles: [ newHandles[2], newHandles[3], next.handles[2], next.handles[3], ], }, ], }) }) } /** * n mod m without negative results e.g. `mod(-1,5) = 4` contrasted with `-1 % 5 = -1`. * * ref: https://web.archive.org/web/20090717035140if_/javascript.about.com/od/problemsolving/a/modulobug.htm */ export function mod(n: number, m: number) { return ((n % m) + m) % m } function setTimeoutFunction(f: Function, timeout?: number) { return () => setTimeout(f, timeout) }
the_stack
import {AbstractJigsawComponent} from "../../common/common"; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, forwardRef, HostListener, Injector, Input, NgModule, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR} from '@angular/forms'; import {GrItem, MarkDate, Shortcut} from "./date-picker"; import {CommonModule} from '@angular/common'; import {TimeGr, TimeService, TimeUnit, TimeWeekStart} from "../../common/service/time.service"; import {Time, WeekTime} from "../../common/service/time.types"; import {JigsawDateTimePicker, JigsawDateTimePickerModule} from "./date-time-picker"; import {TimeStep} from "./time-picker"; import {Subscription} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {RequireMarkForCheck} from "../../common/decorator/mark-for-check"; import {CommonUtils} from "../../common/core/utils/common-utils"; declare const moment: any; /** * 用于在界面上提供一个时间范围选择,支持多种时间粒度切换,支持年月日时分秒及其各种组合, * 通过切换不同的粒度,可以控制时刻选择器只能选到年月日时分秒中的任何一段 * 如下是关于时间的一些常见的场景及其建议: * * - 如果需要选择的是一个时刻,则请使用`JigsawDateTimePicker`; * - 如果需要选择的是一个时分秒,不带日期,则请使用`JigsawTimePicker`; * - 如果你需要的是一个日历的功能,那请参考[这个demo]($demo=table/calendar),通过表格+渲染器的方式来模拟; * - 时间选择器常常是收纳到下拉框中以解决视图空间,则请使用 `JigsawDateTimeSelect` 和 `JigsawRangeDateTimeSelect`, * 参考[这个demo]($demo=range-date-time-picker/with-combo-select); * * 时间控件是对表单友好的,你可以给时间控件编写表单校验器,参考[这个demo]($demo=form/template-driven)。 * * $demo = range-date-time-picker/basic * $demo = range-date-time-picker/range-date-time-select */ @Component({ selector: 'jigsaw-range-date-time-picker, j-range-date-time-picker, jigsaw-range-time, j-range-time', templateUrl: './range-date-time-picker.html', host: { '[class.jigsaw-range-date-time-picker-host]': 'true', '[class.jigsaw-range-date-time-picker-error]': '!valid', '[class.jigsaw-range-date-time-picker-disabled]': 'disabled' }, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawRangeDateTimePicker), multi: true}, ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawRangeDateTimePicker extends AbstractJigsawComponent implements ControlValueAccessor, OnInit, OnDestroy { constructor(protected _zone: NgZone, private _cdr: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(_zone); this._removeUpdateValueSubscriber = this._updateValue.pipe(debounceTime(100)).subscribe(() => { if (!this.beginDate || !this.endDate || this.endDate < this.beginDate || this.endDate > TimeService.getDateByGr(this._$endTimeLimitEnd, this._$gr)) return; this.writeValue({beginDate: this.beginDate, endDate: this.endDate}); this._propagateChange({beginDate: this.beginDate, endDate: this.endDate}); }) } /** * 参考`JigsawDateTimePicker.disabled` * * @NoMarkForCheckRequired * * $demo = date-time-picker/disabled */ @Input() public disabled: boolean; /** * 参考`JigsawDateTimePicker.valid` * * @NoMarkForCheckRequired * * $demo = date-time-picker/valid */ @Input() public valid: boolean = true; /** * @internal */ public _$gr: TimeGr = TimeGr.date; /** * 参考`JigsawDateTimePicker.gr` * $demo = range-date-time-picker/gr */ @Input("gr") @RequireMarkForCheck() public get gr(): TimeGr | string { return (this._$gr || this._$gr === 0) ? this._$gr : TimeGr.date; } public set gr(value: TimeGr | string) { if (typeof value === 'string') { value = TimeGr[value]; } if (<TimeGr>value != this._$gr) { this._$gr = <TimeGr>value; this.grChange.emit(this._$gr); } } /** * 参考`JigsawDateTimePicker.grChange` * $demo = range-date-time-picker/gr */ @Output() public grChange = new EventEmitter<TimeGr>(); /** * @internal */ public _$dateChange(key: string, value: WeekTime) { if (key == 'beginDate') { this._beginDate = value; this._$endTimeLimitEnd = this._calculateLimitEnd(); } else if (key == 'endDate') { this._endDate = value; } this._updateValue.emit(); this._cdr.markForCheck(); } private _beginDate: WeekTime; /** * 时间段的开始时刻,在双绑模式下,更新这个值可以让时间控件选中对应的时刻。 * $demo = range-date-time-picker/basic */ @RequireMarkForCheck() @Input() public get beginDate(): WeekTime { return this._beginDate; } public set beginDate(value: WeekTime) { if (!value || value == this._beginDate) return; if (this.initialized) { let date = TimeService.getDateByGr(value, this._$gr); if (date == this._beginDate) return; this._beginDate = date; this._$endTimeLimitEnd = this._calculateLimitEnd(); this._updateValue.emit(); } else { this._beginDate = value; } } private _endDate: WeekTime; /** * 时间段的结束时刻,在双绑模式下,更新这个值可以让时间控件选中对应的时刻。 * $demo = range-date-time-picker/basic */ @RequireMarkForCheck() @Input() public get endDate(): WeekTime { return this._endDate; } public set endDate(value: WeekTime) { if (!value || value == this._endDate) return; if (this.initialized) { let date = TimeService.getDateByGr(value, this._$gr); if (date == this._endDate) return; this._endDate = date; this._updateValue.emit(); } else { this._endDate = value; } } /** * @internal */ public _$limitStart: WeekTime; /** * 参考`JigsawDateTimePicker.limitStart` * * @NoMarkForCheckRequired * * $demo = range-date-time-picker/limit */ @Input() public get limitStart(): WeekTime { return this._$limitStart; } public set limitStart(value: WeekTime) { if (value) { this._$limitStart = value; } } /** * @internal */ public _$limitEnd: WeekTime; /** * 参考`JigsawDateTimePicker.limitEnd` * * @NoMarkForCheckRequired * * $demo = range-date-time-picker/limit */ @Input() public get limitEnd(): WeekTime { return this._$limitEnd; } public set limitEnd(value: WeekTime) { if (value) { this._$limitEnd = value; this._$endTimeLimitEnd = this._calculateLimitEnd(); } } /** * 参考`JigsawDateTimePicker.grItems` * $demo = range-date-time-picker/gr-items */ @Input() @RequireMarkForCheck() public grItems: GrItem[]; /** * 对选定的日期做标记,用于提示用户这些日期具有特定含义 * $demo = date-time-picker/mark */ @Input() @RequireMarkForCheck() public markDates: MarkDate[]; /** * 分钟、秒钟选择面板的默认有60个数字可以挑选,显得比较凌乱,你可以设置此值为5/10来减少面板上的可选项 * * @NoMarkForCheckRequired * * $demo = range-date-time-picker/step */ @Input() public step: TimeStep; private _weekStart: TimeWeekStart; /** * 设置周开始日期,可选值 sun mon tue wed thu fri sat。 * $demo = range-date-time-picker/week-start */ @Input() @RequireMarkForCheck() public get weekStart(): string | TimeWeekStart { return this._weekStart; } public set weekStart(value: string | TimeWeekStart) { if (CommonUtils.isUndefined(value)) return; if (typeof value === 'string') { this._weekStart = TimeWeekStart[value]; } else { this._weekStart = value; } // weekStart/janX必须预先设置好,用于初始化之后的计算 TimeService.setWeekStart(this._weekStart); } private _firstWeekMustContains: number; /** * 设置一年的第一周要包含一月几号 * $demo = range-date-time-picker/week-start */ @Input() @RequireMarkForCheck() public get firstWeekMustContains(): number { return this._firstWeekMustContains; } public set firstWeekMustContains(value: number) { if (CommonUtils.isUndefined(value)) return; value = isNaN(value) || Number(value) < 1 ? 1 : Number(value); this._firstWeekMustContains = value; // weekStart/janX必须预先设置好,用于初始化之后的计算 TimeService.setFirstWeekOfYear(this._firstWeekMustContains); } /** * 是否显示确认按钮 * @NoMarkForCheckRequired */ @Input() public showConfirmButton: boolean = false; /** * 当用户选择时间时,Jigsaw发出此事件。 * $demo = date-time-picker/with-combo-select */ @Output() public change = new EventEmitter<any>(); /** * 当开始时间被用户切换之后,Jigsaw会发出此事件。 * $demo = range-date-time-picker/basic */ @Output() public beginDateChange = new EventEmitter<WeekTime>(); /** * 当结束时间被用户切换之后,Jigsaw会发出此事件。 * $demo = range-date-time-picker/basic */ @Output() public endDateChange = new EventEmitter<WeekTime>(); private _updateValue = new EventEmitter(); private _removeUpdateValueSubscriber: Subscription; /** * @internal */ public _$shortcuts: Shortcut[]; /** * @internal */ public _$endTimeLimitEnd: WeekTime; private _init() { let isUpdate = false; if (this._beginDate) { let date = TimeService.getDateByGr(this._beginDate, this._$gr); if (date != this._beginDate) { this._beginDate = date; isUpdate = true; } } if (this._endDate) { let date = TimeService.getDateByGr(this._endDate, this._$gr); if (date != this._endDate) { this._endDate = date; isUpdate = true; } } this._$shortcuts = this._getShortcuts(); this._$endTimeLimitEnd = this._calculateLimitEnd(); if (this._endDate < this._beginDate) { this._endDate = this._beginDate; isUpdate = true; } if (this._endDate > TimeService.getDateByGr(this._$endTimeLimitEnd, this._$gr)) { this._endDate = TimeService.getDateByGr(this._$endTimeLimitEnd, this._$gr); isUpdate = true; } if (isUpdate) { this._updateValue.emit(); } this._cdr.markForCheck(); } private _calculateLimitEnd(): WeekTime { let item: GrItem = this.grItems && this.grItems.find(item => item.value == this._$gr); let endTime: WeekTime = null; if (this._$limitEnd) { endTime = TimeService.isMacro(<Time>this._$limitEnd) ? this._$limitEnd : TimeService.getDate(TimeService.convertValue( this._$limitEnd, this._$gr), this._$gr); } if (item && item.span) { let calculateTime: WeekTime = JigsawRangeDateTimePicker._calculateLimitEnd(TimeService.convertValue(this._beginDate, this._$gr), item.span, this._$gr); calculateTime = TimeService.getDate(calculateTime, this._$gr); if (!endTime || endTime > calculateTime) { endTime = calculateTime; } } return endTime; } private static _calculateLimitEnd(startDate: string, span: string, gr: TimeGr): Date { let endTime: Date = new Date(TimeService.format(TimeService.getDate(startDate, gr), 'YYYY-MM-DD')); endTime.setHours(23); endTime.setMinutes(59); endTime.setSeconds(59); switch (span) { case "inday": break; case "inweek": endTime.setDate(endTime.getDate() + 6 - endTime.getDay()); break; case "inmonth": endTime.setMonth(endTime.getMonth() + 1); endTime.setDate(1); endTime.setDate(endTime.getDate() - 1); break; case "inyear": endTime.setMonth(11); endTime.setDate(31); break; default: startDate = TimeService.convertValue(startDate, gr); let spanReg: RegExp = /([\d]+)([a-z]+)?/i; span = span.replace(/\s+/g, ""); let gapArr: string[] = spanReg.exec(span); let endTimeFormat = TimeService.format(TimeService.addDate(startDate, gapArr[1], TimeUnit[gapArr[2].toLowerCase()]), 'YYYY-MM-DD,HH:mm:ss'); let endTimeParse = moment(endTimeFormat, "YYYY-MM-DD HH:mm:ss"); endTime = new Date(endTimeParse); switch (gapArr[2]) { case "d": case "D": break; case "w": case "W": endTime.setDate(endTime.getDate() - 1 - endTime.getDay()); break; case "m": case "M": endTime.setDate(1); endTime.setDate(endTime.getDate() - 1); break; case "y": case "Y": endTime.setMonth(0); endTime.setDate(1); endTime.setDate(endTime.getDate() - 1); break; } } return endTime; } private _getShortcuts(): Shortcut[] { let item: GrItem = this.grItems && this.grItems.find(item => item.value == this._$gr); if (item && item.shortcuts && item.shortcuts.length != 0) { return item.shortcuts; } return null; } /** * @internal */ public _$grChange(value: TimeGr) { this._init(); this.grChange.emit(value); this._cdr.markForCheck(); this._$selectedShortcutLabel = ""; } /** * @internal */ public _$selectedShortcutLabel: string; /** * @internal */ public _changeShortcut(selectedShortcut: Shortcut): void { if (!selectedShortcut.dateRange) { return; } let [beginDate, endDate] = typeof selectedShortcut.dateRange === "function" ? selectedShortcut.dateRange.call(this) : selectedShortcut.dateRange; beginDate = TimeService.convertValue(beginDate, this._$gr); const limitStart = this._$limitStart && TimeService.convertValue(this._$limitStart, this._$gr); const limitEnd = this._$limitEnd && TimeService.convertValue(this._$limitEnd, this._$gr); if (!((limitStart && beginDate < limitStart) || (limitEnd && beginDate > limitEnd))) { this._beginDate = beginDate; } else { this._beginDate = limitStart; } this._$selectedShortcutLabel = selectedShortcut.label; this._$endTimeLimitEnd = this._calculateLimitEnd(); this._endDate = TimeService.convertValue(endDate, this._$gr); this._updateValue.emit(); this._cdr.markForCheck(); } /** * @internal */ @ViewChild('timeStart') public _$timeStart: JigsawDateTimePicker; /** * @internal */ public _$updateBeginDate() { if (!this.showConfirmButton || !this._$timeStart) { return; } // 当配置了确认按钮时,如果只改变了开始时间,没有改变结束时间,此时点击确认按钮,需要通知开始时间的更新 this._$timeStart._$handleDateChange(true); this._$timeStart._$handleTimeChange(true); } public writeValue(value: any): void { if (!value) { return; } this.beginDateChange.emit(value.beginDate); this.endDateChange.emit(value.endDate); this.change.emit(value); } private _propagateChange: any = () => { }; private _onTouched: any = () => { }; public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { this._onTouched(); } @HostListener('click') onClickTrigger(): void { if (this.disabled) { return; } this._onTouched(); } public setDisabledState(disabled: boolean): void { this.disabled = disabled; } ngOnInit() { super.ngOnInit(); this._init(); } ngOnDestroy() { super.ngOnDestroy(); if (this._removeUpdateValueSubscriber) { this._removeUpdateValueSubscriber.unsubscribe(); this._removeUpdateValueSubscriber = null; } } } @NgModule({ imports: [CommonModule, FormsModule, JigsawDateTimePickerModule], declarations: [JigsawRangeDateTimePicker], exports: [JigsawRangeDateTimePicker], }) export class JigsawRangeDateTimePickerModule { }
the_stack
import { ConvarKind, IConvarCategoryMap, IConvarEntry, ProjectVariableSetter } from "fxdk/project/common/project.types"; export enum ResourceManifestKind { none, __resource, fxmanifest, } export type ResourceManifestRecord = [string, unknown][]; export const ResourceManifestGame = { gta5: 'gta5', rdr3: 'rdr3', common: 'common', }; export const ResourceManifestVersion = { /** * Requires `game` to be specified, and is mandatory for RedM. */ adamant: 'adamant', /** * Implies `clr_disable_task_scheduler` being specified for server library compatibility. * Does not define window in JS contexts for library compatibility. */ bodacious: 'bodacious', /** * Requires `https://` callbacks in NUI/DUI. * Adds WASM and `fetch` support. */ cerulean: 'cerulean', }; export class ResourceManifest { fxVersion: string = ResourceManifestVersion.bodacious; games: string[] = [ResourceManifestGame.gta5]; files: string[] = []; clientScripts: string[] = []; serverScripts: string[] = []; sharedScripts: string[] = []; author: string = 'You'; version: string = '1.0.0'; description: string = ''; uiPage: string = ''; loadScreen: string = ''; /** * Marks the current resource as a replacement for the specified resource. * This means it'll start instead of the specified resource, * if another resource requires it, * and will act as if it is said resource if started. */ provide: string = ''; exports: string[] = []; serverExports: string[] = []; /** * @deprecated use data files instead */ beforeLevelMeta: string = ''; /** * @deprecated use data files instead */ afterLevelMeta: string = ''; replaceLevelMeta: string = ''; dataFiles: ResourceManifestRecord = []; /** * Marks this resource as being a GTA map, and reloads the map storage when the resource gets loaded. */ isMap: boolean = false; /** * Marks the resource as being server-only. This stops clients from downloading anything of this resource. */ serverOnly: boolean = false; /** * Requires the specified resource to load before the current resource. */ dependencies: string[] = []; /** * Enables Lua 5.4 * * @see http://www.lua.org/manual/5.4/manual.html */ lua54: boolean = false; /** * By default, lazy loading of native functions is enabled to drastically reduce resource memory usage. * While not recommended, you can set this option to any value to disable lazy loading. */ disableLazyNatives: boolean = false; /** * When present, disables the custom C# task scheduler on the server. * This will increase compatibility with third-party libraries using the .NET TPL, * but make it more likely you'll have to await Delay(0); to end up back on the main thread. */ clrDisableTaskScheduler: boolean = false; convarCategories: IConvarCategoryMap = {}; fxdkWatchCommands: ResourceManifestRecord = []; fxdkBuildCommands: ResourceManifestRecord = []; getFiles(): string[] { return [...new Set([ ...this.files, this.uiPage, this.loadScreen, ].filter(Boolean))]; } getAllScripts(): string[] { return [ ...this.clientScripts, ...this.serverScripts, ...this.sharedScripts, ]; } toString(): string { const nl = ''; const lines = [ metaFromArrayOrString('fx_version', this.fxVersion), metaFromArrayOrString('game', this.games), nl, metaFromArrayOrString('dependency', this.dependencies), metaFromArrayOrString('provide', this.provide), nl, metaFromArrayOrString('author', this.author), metaFromArrayOrString('version', this.version), metaFromArrayOrString('description', this.description), nl, // ...metaFromRecord('convar_category', this.convarCategories), ...metaFromRecord('fxdk_watch_command', this.fxdkWatchCommands), ...metaFromRecord('fxdk_build_command', this.fxdkBuildCommands), nl, metaFromArrayOrString('export', this.exports), metaFromArrayOrString('server_export', this.serverExports), nl, metaFromArrayOrString('file', this.getFiles()), nl, metaFromArrayOrString('client_script', this.clientScripts), metaFromArrayOrString('server_script', this.serverScripts), metaFromArrayOrString('shared_script', this.sharedScripts), nl, metaFromArrayOrString('ui_page', this.uiPage), metaFromArrayOrString('loadscreen', this.loadScreen), nl, metaFromArrayOrString('before_level_meta', this.beforeLevelMeta), metaFromArrayOrString('after_level_meta', this.afterLevelMeta), metaFromArrayOrString('replace_level_meta', this.replaceLevelMeta), nl, ...metaFromRecord('data_file', this.dataFiles), nl, metaFromBoolean('lua54', this.lua54), metaFromBoolean('server_only', this.serverOnly), metaFromBoolean('this_is_a_map', this.isMap), metaFromBoolean('disable_lazy_natives', this.disableLazyNatives), metaFromBoolean('clr_disable_task_scheduler', this.clrDisableTaskScheduler), ]; return lines .filter((line) => line !== null) .filter((line, i, a) => { if (i > 0 && line === nl && a[i-1] === nl) { return false; } return true; }) .join('\n'); } fromObject(obj: any) { this.fxVersion = stringFromMeta(obj, 'fx_version', ResourceManifestVersion.bodacious); this.games = arrayFromMeta(obj, 'game', [ResourceManifestGame.gta5]); this.dependencies = arrayFromMeta(obj, 'dependency', []); this.provide = stringFromMeta(obj, 'provide', ''); this.author = stringFromMeta(obj, 'author', 'you'); this.version = stringFromMeta(obj, 'version', '1.0.0'); this.description = stringFromMeta(obj, 'description', ''); this.convarCategories = parseConvarCategories(recordFromMeta(obj, 'convar_category', [])); this.fxdkWatchCommands = recordFromMeta(obj, 'fxdk_watch_command', []); this.fxdkBuildCommands = recordFromMeta(obj, 'fxdk_build_command', []); this.exports = arrayFromMeta(obj, 'export', []); this.serverExports = arrayFromMeta(obj, 'server_export', []); this.files = arrayFromMeta(obj, 'file', []); this.clientScripts = arrayFromMeta(obj, 'client_script', []); this.serverScripts = arrayFromMeta(obj, 'server_script', []); this.sharedScripts = arrayFromMeta(obj, 'shared_script', []); this.uiPage = stringFromMeta(obj, 'ui_page', ''); this.loadScreen = stringFromMeta(obj, 'loadscreen', ''); this.beforeLevelMeta = stringFromMeta(obj, 'before_level_meta', ''); this.afterLevelMeta = stringFromMeta(obj, 'after_level_meta', ''); this.replaceLevelMeta = stringFromMeta(obj, 'replace_level_meta', ''); this.dataFiles = recordFromMeta(obj, 'data_file', []); this.lua54 = booleanFromMeta(obj, 'lua54', false); this.serverOnly = booleanFromMeta(obj, 'server_only', false); this.isMap = booleanFromMeta(obj, 'this_is_a_map', false); this.disableLazyNatives = booleanFromMeta(obj, 'disable_lazy_natives', false); this.clrDisableTaskScheduler = booleanFromMeta(obj, 'clr_disable_task_scheduler', false); } } function parseConvarCategories(record: ResourceManifestRecord): IConvarCategoryMap { function parseInteger(n: string | number | boolean | Array<string>): number | undefined { if (typeof n === 'string') { return parseInt(n, 10); } if (typeof n === 'number') { return n; } if (typeof n === 'boolean') { return n ? 1 : 0; } return undefined; } function parseEntry(raw: unknown): IConvarEntry | undefined { if (!Array.isArray(raw)) { return; } // Title, subtitle entry is ignored if (raw.length === 2) { return; } const title: string = (raw[0] || '').toString(); const variableRaw: string = (raw[1] || '').toString(); const kindStr: string = (raw[2] || '').toString(); const setter: ProjectVariableSetter = variableRaw[0] === '#' ? ProjectVariableSetter.INFORMATION : ( variableRaw[0] === '$' ? ProjectVariableSetter.REPLICATED : ProjectVariableSetter.SERVER_ONLY ); const variable = setter !== ProjectVariableSetter.SERVER_ONLY ? variableRaw.substr(1) : variableRaw; const [,,, defaultValue, min, max] = raw; switch (kindStr) { case 'CV_BOOL': return { kind: ConvarKind.Bool, title, setter, variable, defaultValue: Boolean(defaultValue), } case 'CV_PASSWORD': case 'CV_STRING': return { kind: kindStr === 'CV_STRING' ? ConvarKind.String : ConvarKind.Password, title, setter, variable, defaultValue: String(defaultValue), } case 'CV_SLIDER': case 'CV_COMBI': case 'CV_INT': { let kind = ConvarKind.Int; if (kindStr === 'CV_SLIDER') { kind = ConvarKind.Slider; } if (kindStr === 'CV_COMBI') { kind = ConvarKind.Combi; } return { kind, title, setter, variable, defaultValue: parseInteger(defaultValue) || 0, minValue: parseInteger(min), maxValue: parseInteger(max), } } case 'CV_MULTI': return { kind: ConvarKind.Multi, setter, title, variable, entries: Array.isArray(defaultValue) ? defaultValue : [], } } } return record.reduce((categories, category) => { if (!Array.isArray(category)) { return categories; } if (!Array.isArray(category[1])) { return categories; } const [title, [subtitle, entries]] = category; if (!Array.isArray(entries)) { return categories; } categories[title] = { title, subtitle, entries: entries.map(parseEntry).filter(Boolean), }; return categories; }, {}); } function booleanFromMeta(meta: any, key: string, defaultValue: boolean): boolean { if (typeof meta[key] === undefined) { return defaultValue; } return !!meta[key]?.[0]; } function stringFromMeta(meta: any, key: string, defaultValue: string): string { return meta[key]?.[0] || defaultValue; } function arrayFromMeta(meta: any, key: string, defaultValue: string[]): string[] { return meta[key] || defaultValue; } function recordFromMeta(meta: any, key: string, defaultValue: ResourceManifestRecord): ResourceManifestRecord { if (!meta[key]) { return defaultValue; } return meta[key].map((vkey, index) => { return [vkey, JSON.parse(meta[`${key}_extra`]?.[index] || `''`)]; }); } function pluralKey(key: string): string { return key === 'dependency' ? 'dependencies' : key + 's'; } function metaFromRecord(key: string, record: ResourceManifestRecord): string[] { return record.map(([subKey, value]) => `${key} '${subKey}' ${serializeToLua(value)}`); } function metaFromBoolean<T>(key: string, value: T) { if (value) { return `${key} 'yes'`; } return null; } function metaFromArrayOrString(key: string, entries: string[] | string) { if (entries === '') { return null; } if (!Array.isArray(entries)) { return `${key} '${entries}'`; } if (entries.length === 0) { return null; } if (entries.length === 1) { return `${key} '${entries[0]}'`; } const entriesString = entries.filter(Boolean).map((entry) => ` '${entry}'`).join(',\n'); return `${pluralKey(key)} {\n${entriesString}\n}`; } function serializeToLua(val: unknown, indent = 2): string { switch (typeof val) { case 'number': case 'boolean': case 'symbol': case 'bigint': return val.toString(); case 'string': return `'${val}'`; case 'function': return ''; case 'undefined': 'nil'; case 'object': { if (!val) { return 'nil'; } if (Array.isArray(val)) { return `{${val.map((subVal) => serializeToLua(subVal)).join(', ')}}`; } const indentString = Array(indent).fill(' ').join(''); const indentString2 = Array(indent - 2).fill(' ').join(''); const objEntries = Object.entries(val).map(([key, subVal]) => { return `${indentString}['${key}'] = ${serializeToLua(subVal, indent + 2)}`; }).join(',\n'); return `{\n${objEntries}\n${indentString2}}`; } } }
the_stack
import d3 from 'd3' import Emitter from 'component-emitter' import Network from './core/network' import SvgDisplay from './display/svg-display' import CanvasDisplay from './display/canvas-display' import DefaultRenderer from './renderer/default-renderer' import WireframeRenderer from './renderer/wireframe-renderer' import Styler from './styler/styler' import Labeler from './labeler/labeler' import Point from './point/point' import { sm } from './util' // Transitive Data Model /** * A description of the transit pattern that a segment of a journey is using. * * TODO: move to core/journey.js when adding static typing to that file */ type SegmentPattern = { /** * The from stop index within the pattern referenced by the pattern_id */ from_stop_index: number /** * The ID of the pattern */ pattern_id: string /** * The to stop index within the pattern referenced by the pattern_id */ to_stop_index: number } /** * A point where a segment starts or ends. This must be either a place or a stop * and must have a proper reference to a defined place or stop that is defined * in the list of places or stops in the root transitive data object. * * TODO: move to core/journey.js when adding static typing to that file */ type SegmentPoint = { /** * The place_id of this point if it is a place. This MUST be set if the "type" * value is "PLACE" */ place_id?: string /** * The place_id of this point if it is a place. This MUST be set if the "type" * value is "STOP" */ stop_id?: string /** * The type of place that this is. */ type: 'PLACE' | 'STOP' } /** * Information about a particular segment of a journey. * * TODO: move to core/journey.js when adding static typing to that file */ type Segment = { /** * If set to true, instructs the renderer to ignore all other geometry data * and instead draw an arc between the from and to points. */ arc?: boolean /** * The starting point of this segment */ from: SegmentPoint /** * A list of pattern segments identifying how this segment uses certain parts * of the transit network. This should be set when the type of this segment is * "TRANSIT". */ patterns?: SegmentPattern[] /** * A list of strings representing street edge IDs that this journey uses. This * should be set when the type of this segment is not "TRANSIT". */ streetEdges?: string[] /** * The ending point of this segment */ to: SegmentPoint /** * The type of segment. This should be set to "TRANSIT" for transit segments * or the on-street leg mode otherwise. */ type: string } /** * An object describing how a journey uses various parts of the transportation * network. * * This object can additionally have other key/value items added onto the data * model that may or may not be processed with custom styler rules. However, * a few keys might be overwritten by transitive internals, so choose carefully. * * TODO: move to core/journey.js when adding static typing to that file */ type Journey = { /** * The ID of the journey */ journey_id: string /** * The name of the journey */ journey_name: string /** * The segments of a journey */ segments: Segment[] } /** * Information about a sequence of stops that make up a directional segment of * travel that a transit trip or part of a transit trip takes. * * This object can additionally have other key/value items added onto the data * model that may or may not be processed with custom styler rules. However, * a few keys might be overwritten by transitive internals, so choose carefully. * * TODO: move to core/pattern.js when adding static typing to that file */ type Pattern = { /** * The ID of the pattern */ pattern_id: string /** * The name of the pattern */ pattern_name: string /** * If true, unconditionally render the entire pattern. */ render?: boolean /** * The ID of the transit route associated with this pattern */ route_id: string /** * A list of stops in order of the direction of travel and the associated * geometry to that particular stop. The first stop omits the geometry, but * all further stops should include the geometry. It is possible to include * intermediate stops within the pattern or just the final stop. */ stops: Array<{ /** * An encoded polyline string representing the path that the transit trip * took from the previous stop in this list to this current stop. This is * omitted for the first stop, but should be included for all further stops. */ geometry?: string /** * The ID of the stop */ stop_id: string }> } /** * A place is a point *other* than a transit stop/station, e.g. a home/work * location, a point of interest, etc. * * This object can additionally have other key/value items added onto the data * model that may or may not be processed with custom styler rules. However, * a few keys might be overwritten by transitive internals, so choose carefully. * * TODO: move to point/place.js when adding static typing to that file */ type Place = { /** * The ID of the place */ place_id: string /** * The latitude of the place */ place_lat: number /** * The longitude of the place */ place_lon: number /** * The name of the place */ place_name: string } /** * Information about a particular transit route. * * This object can additionally have other key/value items added onto the data * model that may or may not be processed with custom styler rules. However, * a few keys might be overwritten by transitive internals, so choose carefully. * * TODO: move to core/route.js when adding static typing to that file */ type Route = { /** * A string describing the route color in hex color format. If this value is * provided and the first character is not a '#' character, that character * will be added to the front of the string. */ route_color?: string /** * The route's ID */ route_id: string /** * The short name of the route */ route_short_name?: string /** * The GTFS route type number. */ route_type: number } /** * A transit stop. * * This object can additionally have other key/value items added onto the data * model that may or may not be processed with custom styler rules. However, * a few keys might be overwritten by transitive internals, so choose carefully. * * TODO: move to point/stop.js when adding static typing to that file */ type Stop = { /** * The ID of the stop */ stop_id: string /** * The latitude of the stop */ stop_lat: number /** * The longitude of the stop */ stop_lon: number /** * The name of the stop */ stop_name?: string } /** * Edges describing a section of the street network. * * TODO: move to core/network.js when adding static typing to that file */ type StreetEdge = { /** * A unique edge ID */ edge_id: number | string /** * A geometry object, typically from the leg response in an OpenTripPlanner * itinerary */ geometry: { /** * An encoded polyline string */ points: string } } /** * An object with various pieces of data that should be rendered. */ type TransitiveData = { /** * A list of journeys that describing how the transit network is used in * specific journeys (typically OTP itineraries). */ journeys?: Journey[] /** * A list of transit trips that should be rendered or are referenced by * individual journeys */ patterns: Pattern[] /** * A list of places in the transportation network */ places: Place[] /** * A list of transit routes in the transportation network */ routes: Route[] /** * A list of transit stops in the transportation network */ stops: Stop[] /** * A list of street edges in the transportation network that are referenced by * individual journeys. */ streetEdges: StreetEdge[] } // Transitive Style data model /** * A function for calculating the style of a particular feature. */ type TransitiveStyleComputeFn = ( /** * The transtiive display instance currently being used. */ display?: CanvasDisplay | SvgDisplay, /** * The entity instance which the style result will be applied to. * * FIXME add better typing */ entity?: unknown, /** * The index of the entity within some collection. This argument's value may * not always be included when calling this function. */ index?: number, /** * Some util functions for calculating certain styles. * See code: https://github.com/conveyal/transitive.js/blob/6a8932930de003788b9034609697421731e7f812/lib/styler/styles.js#L17-L44 * FIXME add better typing once other files are typed */ styleUtils?: { /** * Creates a svg definition for a marker and returns the string url for the * defined marker */ defineSegmentCircleMarker: ( /** * The display being used to render transitive */ display: unknown, /** * The segment to create a marker for */ segment: unknown, /** * The size of the radius that the marker should have */ radius: number, /** * The fill color of the marker */ fillColor: string ) => string /** * Calculates the font size based on the display's scale */ fontSize: (display: unknown) => number /** * Calculates something as it relates to the zoom in relation to zoom */ pixels: ( zoom: unknown, min: unknown, normal: unknown, max: unknown ) => unknown /** * Calculates a stroke width depending on the display scale */ strokeWidth: (display: unknown) => unknown } ) => number | string /** * A map describing a styling override applied to a particular styling value * noted with the key value. The value for this style can be either a number, * string or result of a custom function. * * The applicability of each key differs between different styling entities. * Example values for the key value include: * - "background" - // background of text * - "border-color" - // used for borders around text * - "border-radius" - // used for borders around text * - "border-width" - // used for borders around text * - "color" - // text color * - "display" - // whether or not to display the entity. Set value or make * function return "none" to not display an entity. * - "envelope" - // used in calculating line width * - "fill" - // fill color * - "font-family" - // font family used when rendering text * - "font-size" - // font size used when rendering text * - "marker-padding" - // Amount of padding to give a marker beyond its radius * - "marker-type" - // for styling stops and maybe places. Valid values * include: "circle", "rectangle" or "roundedrect" * - "orientations" - // a list of possible orientations to try to apply to * labels. Valid values include: "N", "S", "E", "W", "NE", * "NW", "SE", "SW" * - "r" - // a radius in pixels to apply to certain stops or places * - "stroke" - // stroke color * - "stroke-dasharray" - // stroke dasharray * - "stroke-linecap" - // stroke linecap * - "stroke-width" - // stroke width */ type TransitiveStyleConfig = Record< string, number | string | TransitiveStyleComputeFn > /** * A map of transitive features and the associated map of config records that * override transitive default style calculations. */ type TransitiveStyles = { labels?: TransitiveStyleConfig multipoints_merged?: TransitiveStyleConfig multipoints_pattern?: TransitiveStyleConfig places?: TransitiveStyleConfig places_icon?: TransitiveStyleConfig segment_label_containers?: TransitiveStyleConfig segment_labels?: TransitiveStyleConfig segments?: TransitiveStyleConfig segments_front?: TransitiveStyleConfig segments_halo?: TransitiveStyleConfig stops_merged?: TransitiveStyleConfig stops_pattern?: TransitiveStyleConfig wireframe_edges?: TransitiveStyleConfig wireframe_vertices?: TransitiveStyleConfig } type Bounds = [ [ /** * west */ number, /** * south */ number ], [ /** * east */ number, /** * north */ number ] ] type RendererType = 'wireframe' | 'default' /** * An object describing various styling actions that may be taken at a * particular zoom level between the value of the key "minScale" and whatever * value "minScale" is in the next ZoomFactor object in the zoomFactors config * of the TransitiveOptions. */ type ZoomFactor = { /** * The minimum angle degree to use to render curves at this current zoom * level. */ angleConstraint: number /** * The grid cell size to use for snapping purposes at this current zoom level. */ gridCellSize: number /** * A factor used to determine how many vertices should be displayed at this * current zoom level. */ internalVertexFactor: number /** * If above 0, this will result in a point cluster map being used. */ mergeVertexThreshold: number /** * The minimum scale at which to show this zoom factor */ minScale: number /** * Whether or not to use geographic rendering */ useGeographicRendering?: boolean } type TransitiveOptions = { /** * whether the display should listen for window resize events and update * automatically (defaults to true) */ autoResize?: boolean /** * An optional HTMLCanvasElement to render the Transitve display to */ canvas?: HTMLCanvasElement /** * Transitive Data to Render */ data: TransitiveData /** * Set to 'canvas' to use CanvasDisplay. Otherwise SvgDisplay is used. */ display?: string /** * padding to apply to the initial rendered network within the display. * Expressed in pixels for top/bottom/left/right */ displayMargins?: { bottom: number left: number right: number top: number } /** * a list of network element types to enable dragging for */ draggableTypes?: Array<string> /** * An optional HTMLElement to render the Transitve display to */ el?: HTMLElement /** * resolution of the grid in SphericalMercator meters */ gridCellSize?: number /** * whether to consider edges with the same origin/destination equivalent for * rendering, even if intermediate stop sequence is different (defaults to * true) */ groupEdges?: boolean /** * initial lon/lat bounds for the display */ initialBounds?: Bounds /** * Whether to render as a wireframe or default. */ initialRenderer?: RendererType /** * A list of transit mode types that should have labels created on them */ labeledModes?: number[] /** * Custom styling rules that affect rendering behavior */ styles: TransitiveStyles /** * Whether to enable the display's built-in zoom/pan functionality (defaults * to true) */ zoomEnabled?: boolean /** * A list of different styling configurations to show at various zoom levels. * This list of Zoomfactors must be ordered by each object's "minScale" key * with the lowest "minScale" value appearing first and the largest one * appearing last. There must be a "minScale" value below 1 in the list of * definitions. * * Default values for this config item are used, unless overridden by adding * this key and value. The default values can be found here: * https://github.com/conveyal/transitive.js/blob/6a8932930de003788b9034609697421731e7f812/lib/display/display.js#L78-L92 */ zoomFactors?: ZoomFactor[] } /** * No clue what this global Display thing is. :( */ declare class Display { constructor(arg0: Transitive) } /** * A transformation {x, y, k} to the *initial* state of the map., where * (x, y) is the pixel offset and k is a scale factor relative to an initial * zoom level of 1.0. Intended primarily to support D3-style panning/zooming. */ type DisplayTransform = { k: number x: number y: number } // FIXME add better typing once more files are typed type Journeys = { [id: string]: { path: Record<string, unknown> } } export default class Transitive { data: TransitiveData | null | undefined display!: CanvasDisplay | SvgDisplay el?: HTMLElement // FIXME: somehow typing the emit method (which is injected at the end of this // file by component-emitter) causes the emit method to not work. // emit!: (message: string, transitiveInstance: this, el?: HTMLElement) => void labeler!: Labeler options?: TransitiveOptions network: Network | null | undefined renderer!: DefaultRenderer | WireframeRenderer styler!: Styler constructor(options: TransitiveOptions) { if (!(this instanceof Transitive)) return new Transitive(options) this.options = options if (this.options.zoomEnabled === undefined) this.options.zoomEnabled = true if (this.options.autoResize === undefined) this.options.autoResize = true if (this.options.groupEdges === undefined) this.options.groupEdges = true if (options.el) this.el = options.el this.display = this.options.display === 'canvas' ? new CanvasDisplay(this) : new SvgDisplay(this) this.data = options.data this.setRenderer(this.options.initialRenderer || 'default') this.labeler = new Labeler(this) this.styler = new Styler(options.styles, this) if (options.initialBounds) { this.display.fitToWorldBounds([ sm.forward(options.initialBounds[0]), sm.forward(options.initialBounds[1]) ]) } } /** * Clear the Network data and redraw the (empty) map */ clearData() { this.network = this.data = null this.labeler.clear() // @ts-expect-error See notes in constructor about emit method. this.emit('clear data', this) } /** * Update the Network data and redraw the map */ updateData(data: TransitiveData, resetDisplay?: boolean) { this.network = null this.data = data if (resetDisplay) this.display.reset() else if (this.data) this.display.scaleSet = false this.labeler.clear() // @ts-expect-error See notes in constructor about emit method. this.emit('update data', this) } /** * Return the collection of default segment styles for a mode. * * @param {String} an OTP mode string */ getModeStyles(mode: string) { return this.styler.getModeStyles(mode, this.display || new Display(this)) } /** Display/Render Methods **/ /** * Set the DOM element that serves as the main map canvas */ setElement(el?: HTMLElement) { if (this.el) d3.select(this.el).selectAll('*').remove() this.el = el // @ts-expect-error See notes in constructor about emit method. this.emit('set element', this, this.el) return this } /** * Set the DOM element that serves as the main map canvas */ setRenderer(type: RendererType) { switch (type) { case 'wireframe': this.renderer = new WireframeRenderer(this) break case 'default': this.renderer = new DefaultRenderer(this) break } } /** * Render */ render() { if (!this.network) { this.network = new Network(this, this.data) } if (!this.display.scaleSet) { this.display.fitToWorldBounds(this.network.graph.bounds()) } this.renderer.render() // @ts-expect-error See notes in constructor about emit method. this.emit('render', this) } /** * Render to * * @param {Element} el */ renderTo(el: HTMLElement) { this.setElement(el) this.render() // @ts-expect-error See notes in constructor about emit method. this.emit('render to', this) return this } /** * focusJourney */ focusJourney(journeyId: string) { if (!this.network) { console.warn('Transitive network is not defined! Cannot focus journey!') return } const journey = (this.network.journeys as Journeys)[journeyId] const path = journey?.path || null this.renderer.focusPath(path) } /** * Sets the Display bounds * @param {Array} lon/lat bounds expressed as [[west, south], [east, north]] */ setDisplayBounds(llBounds: Bounds) { if (!this.display) return const smWestSouth = sm.forward(llBounds[0]) const smEastNorth = sm.forward(llBounds[1]) // reset the display to make sure the correct display scale is recomputed // see https://github.com/conveyal/transitive.js/pull/50 // FIXME this is a work-around for some other problem that occurs somewhere // else. To investigate further, uncomment this line and compare the // differences near the Putnam Plaza place in the Putnam Bug story. this.display.reset() this.display.setXDomain([smWestSouth[0], smEastNorth[0]]) this.display.setYDomain([smWestSouth[1], smEastNorth[1]]) this.display.computeScale() } /** * Gets the Network bounds * @returns {Array} lon/lat bounds expressed as [[west, south], [east, north]] */ getNetworkBounds() { if (!this.network || !this.network.graph) return null const graphBounds = this.network.graph.bounds() const ll1 = sm.inverse(graphBounds[0]) const ll2 = sm.inverse(graphBounds[1]) return [ [Math.min(ll1[0], ll2[0]), Math.min(ll1[1], ll2[1])], [Math.max(ll1[0], ll2[0]), Math.max(ll1[1], ll2[1])] ] } /** * resize */ resize(width: number, height: number) { if (!this.display) return // @ts-expect-error I have no idea what magic this display object uses to // get an el property. - Evan :( d3.select(this.display.el) .style('width', width + 'px') .style('height', height + 'px') // @ts-expect-error I have no idea what magic this display object uses to // get a resized method. - Evan :( this.display.resized() } /** * trigger a display resize action (for externally-managed SVG containers) */ resized(width: number, height: number) { // @ts-expect-error I have no idea what magic this display object uses to // get a resized method. - Evan :( this.display.resized(width, height) } setTransform(transform: DisplayTransform) { this.display.applyTransform(transform) this.render() } /** editor functions **/ createVertex(wx?: number, wy?: number) { if (!this.network) { console.warn('Transitive network is not defined! Cannot create vertex!') return } this.network.graph.addVertex(new Point(), wx, wy) } } /** * Mixin `Emitter` */ Emitter(Transitive.prototype)
the_stack
declare interface IColumnFormatterWebPartStrings { //Property Pane Property_BasicGroupName: string; Property_HeightLabel: string; Property_EditorGroupName: string; Property_EditorThemeLabel: string; Property_LineNumbersLabel: string; Property_VisibleOn: string; Property_VisibleOff: string; Property_MiniMapLabel: string; Property_IndentGuidesLabel: string; //General FeatureUnavailableFromLocalWorkbench: string; TechnicalDetailsErrorHeader: string; WizardDefaultField: string; //Welcome Welcome_Title: string; Welcome_SubTitle: string; Welcome_NewHeader: string; Welcome_NewDescription: string; Welcome_OpenHeader: string; Welcome_OpenDescription: string; Welcome_ColumnType: string; Welcome_NewWizardOption: string; Welcome_NewBlankOption: string; Welcome_NewNoTemplates: string; Welcome_BackButton: string; Welcome_OKButton: string; Welcome_NextButton: string; Welcome_OpenLoadList: string; Welcome_OpenLoadSiteColumn: string; Welcome_OpenLoadFile: string; Welcome_OpenLoadFileLibrary: string; Welcome_OpenLoadFileUpload: string; Welcome_UploadHeader: string; Welcome_UploadInstructions1: string; Welcome_UploadInstructions2: string; Welcome_UploadUploadButton: string; Welcome_UploadRejectError: string; Welcome_UploadEmptyFileError: string; Welcome_LoadingError: string; //List Field (Load/Apply) ListField_LoadingLists: string; ListField_List: string; ListField_Field: string; ListField_LoadingFromList: string; ListField_ListLoadError: string; ListField_SaveDialogTitle: string; ListField_Saving: string; ListField_SaveError: string; //Site Column (Load/Apply) SiteColumn_LoadingSiteColumns: string; SiteColumn_Group: string; SiteColumn_Field: string; SiteColumn_LoadingFromSiteColumn: string; SiteColumn_SiteColumnsLoadError: string; SiteColumn_SaveDialogTitle: string; SiteColumn_PushToListsOn: string; SiteColumn_PushToListsOff: string; SiteColumn_Saving: string; SiteColumn_SaveError: string; //Library (Load/Save) Library_LoadingLibraries: string; Library_Library: string; Library_FolderPath: string; Library_Filename: string; Library_LoadingFromLibrary: string; Library_LibrariesLoadError: string; Library_LoadFromLibraryError: string; Library_SaveDialogTitle: string; Library_Saving: string; Library_SaveError: string; //Tab Names Tab_Wizard: string; Tab_Tree: string; Tab_Data: string; Tab_Preview: string; Tab_Code: string; Tab_Split: string; //Panel Headers PanelHeader_Data: string; PanelHeader_Preview: string; PanelHeader_Code: string; //Editor CommandBar Command_New: string; Command_Customize: string; Command_Editor: string; Command_SaveAs: string; Command_Download: string; Command_Copy: string; Command_SaveToLibrary: string; Command_ApplyToSiteColumn: string; Command_ApplyToList: string; Command_Save: string; //Dialogs Shared Dialog_Yes: string; Dialog_Cancel: string; Dialog_Save: string; //New Confirmation Dialog NewConfirmationDialog_Title: string; NewConfirmationDialog_Text: string; //Customize Confirmation Dialog CustomizeConfirmationDialog_Title: string; CustomizeConfirmationDialog_Text: string; //Copy CopyToClipboardError: string; //Data Column/Row buttons DataColumn_DeleteRow: string; DataColumn_AddRow: string; DataColumn_DeleteColumn: string; DataColumn_AddColumn: string; //Data Column Editing DataColumn_ColumnNameChangeTooltip: string; DataColumn_ColumnTypeHeadline: string; DataColumn_ColumnTypeMessage: string; DataColumn_ColumnTypeChangeTooltip: string; DataColumn_SubPropertiesHeadline: string; DataColumn_TimeHeadline: string; DataColumn_DefaultName: string; DataColumn_LinkDescriptionLabel: string; DataColumn_LookupIdLabel: string; DataColumn_PersonIdLabel: string; DataColumn_PersonEmailLabel: string; DataColumn_PersonSIPLabel: string; DataColumn_PersonPictureLabel: string; DataColumn_HourLabel: string; DataColumn_MinuteLabel: string; DataColumn_SecondsLabel: string; //Column Type Names ColumnType_Boolean: string; ColumnType_Choice: string; ColumnType_DateTime: string; ColumnType_Link: string; ColumnType_Picture: string; ColumnType_Lookup: string; ColumnType_Number: string; ColumnType_Person: string; ColumnType_Text: string; ColumnType_Unknown: string; //Boolean Values BoolValueStringTrue: string; BoolValueStringFalse: string; //DateTime Editor Strings DateTime_Month1: string; DateTime_Month2: string; DateTime_Month3: string; DateTime_Month4: string; DateTime_Month5: string; DateTime_Month6: string; DateTime_Month7: string; DateTime_Month8: string; DateTime_Month9: string; DateTime_Month10: string; DateTime_Month11: string; DateTime_Month12: string; DateTime_Month1Short: string; DateTime_Month2Short: string; DateTime_Month3Short: string; DateTime_Month4Short: string; DateTime_Month5Short: string; DateTime_Month6Short: string; DateTime_Month7Short: string; DateTime_Month8Short: string; DateTime_Month9Short: string; DateTime_Month10Short: string; DateTime_Month11Short: string; DateTime_Month12Short: string; DateTime_Day1: string; DateTime_Day2: string; DateTime_Day3: string; DateTime_Day4: string; DateTime_Day5: string; DateTime_Day6: string; DateTime_Day7: string; DateTime_Day1Short: string; DateTime_Day2Short: string; DateTime_Day3Short: string; DateTime_Day4Short: string; DateTime_Day5Short: string; DateTime_Day6Short: string; DateTime_Day7Short: string; DateTime_DTgoToToday: string; DateTime_DTprevMonthAriaLabel: string; DateTime_DTnextMonthAriaLabel: string; DateTime_DTprevYearAriaLabel: string; DateTime_DTnextYearAriaLabel: string; //Custom Formatting Error Strings CFS_ariaError: string; CFS_elmTypeInvalid: string; CFS_elmTypeMissing: string; CFS_invalidProtocol: string; CFS_invalidStyleAttribute: string; CFS_invalidStyleValue: string; CFS_nan: string; CFS_operandMissing: string; CFS_operandNOnly: string; CFS_operatorInvalid: string; CFS_operatorMissing: string; CFS_unsupportedType: string; CFS_userFieldError: string; CFS_RowLabel: string; //Format Validation Messages PreviewValidation_Good: string; PreviewValidation_Bad: string; //Tree View TreeView_Header: string; TreeView_Error: string; //Standard Colors Color_Yellow: string; Color_YellowLight: string; Color_Orange: string; Color_OrangeLight: string; Color_OrangeLighter: string; Color_RedDark: string; Color_Red: string; Color_MagentaDark: string; Color_Magenta: string; Color_MagentaLight: string; Color_PurpleDark: string; Color_Purple: string; Color_PurpleLight: string; Color_BlueDark: string; Color_BlueMid: string; Color_Blue: string; Color_BlueLight: string; Color_TealDark: string; Color_Teal: string; Color_TealLight: string; Color_GreenDark: string; Color_Green: string; Color_GreenLight: string; Color_Black: string; Color_NeutralDark: string; Color_NeutralPrimary: string; Color_NeutralPrimaryAlt: string; Color_NeutralSecondary: string; Color_NeutralTertiary: string; Color_NeutralTertiaryAlt: string; Color_NeutralLight: string; Color_NeutralLighter: string; Color_NeutralLighterAlt: string; Color_White: string; Color_Transparent: string; //Wizard Shared Group Labels Wizard_GroupLabelRange: string; Wizard_GroupLabelValueDisplay: string; Wizard_GroupLabelConditionalValues: string; Wizard_GroupLabelDisplay: string; Wizard_GroupLabelParameters: string; //Wizard Shared Field Labels Wizard_PercentRangeEmptyLabel: string; Wizard_PercentRangeEmptyTooltip: string; Wizard_PercentRangeFullLabel: string; Wizard_PercentRangeFullTooltip: string; Wizard_ValueDisplayActual: string; Wizard_ValueDisplayPercentage: string; Wizard_ValueDisplayNone: string; Wizard_ValueVisibleOn: string; Wizard_ValueVisibleOff: string; Wizard_IconVisibleOn: string; Wizard_IconVisibleOff: string; Wizard_Text: string; Wizard_Icon: string; Wizard_Color: string; Wizard_Size: string; Wizard_TooltipOn: string; Wizard_TooltipOff: string; //Wizard Data Bars WizardDataBars_Name: string; WizardDataBars_Description: string; //Wizard Checkboxes WizardCheckboxes_Name: string; WizardCheckboxes_Description: string; //Wizard Overdue WizardOverdue_Name: string; WizardOverdue_Description: string; //Wizard Overdue Status WizardOverdueStatus_Name: string; WizardOverdueStatus_Description: string; WizardOverdueStatus_StatusColumn: string; WizardOverdueStatus_Complete: string; WizardOverdueStatus_InProgress: string; //Wizard Number Trending WizardNumberTrending_Name: string; WizardNumberTrending_Description: string; WizardNumberTrending_Current: string; WizardNumberTrending_Previous: string; //Wizard Action Link WizardActionLink_Name: string; WizardActionLink_Description: string; //Wizard Severity WizardSeverity_Name: string; WizardSeverity_Description: string; WizardSeverity_Good: string; WizardSeverity_Low: string; WizardSeverity_Warning: string; WizardSeverity_SevereWarning: string; WizardSeverity_Blocked: string; WizardSeverity_Other: string; WizardSeverity_GoodLabel: string; WizardSeverity_LowLabel: string; WizardSeverity_WarningLabel: string; WizardSeverity_SevereWarningLabel: string; WizardSeverity_BlockedLabel: string; WizardSeverity_DefaultSeverityLabel: string; //Wizard Current User WizardCurrentUser_Name: string; WizardCurrentUser_Description: string; //Wizard Round Image WizardRoundImage_Name: string; WizardRoundImage_Description: string; //Wizard Mail To WizardMailTo_Name: string; WizardMailTo_Description: string; WizardMailTo_Subject: string; WizardMailTo_DefaultSubject: string; WizardMailTo_Body: string; WizardMailTo_DefaultBody: string; WizardMailTo_BCC: string; WizardMailTo_CC: string; WizardMailTo_IconLink: string; WizardMailTo_TextLink: string; WizardMailTo_DefaultText: string; //Wizard Mini Map WizardMiniMap_Name: string; WizardMiniMap_Description: string; //Wizard Flow WizardFlow_Name: string; WizardFlow_Description: string; WizardFlow_FlowId: string; WizardFlow_FlowIdInstructions: string; //Wizard Donut WizardDonut_Name: string; WizardDonut_Description: string; WizardDonut_Donut: string; WizardDonut_Pie: string; WizardDonut_OuterColor: string; WizardDonut_InnerColor: string; WizardDonut_TextColor: string; //Wizard Twitter WizardTwitter_Name: string; WizardTwitter_Description: string; WizardTwitter_Rounding: string; WizardTwitter_LinkOn: string; WizardTwitter_LinkOff: string; } declare module 'ColumnFormatterWebPartStrings' { const strings: IColumnFormatterWebPartStrings; export = strings; }
the_stack
import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs/Subject"; import {Subscription} from "rxjs/Subscription"; import * as _ from "lodash"; import "rxjs/add/operator/zip"; import "rxjs/add/operator/do"; import "rxjs/add/operator/debounceTime"; import "rxjs/add/operator/distinct"; import "rxjs/add/operator/switch"; import "rxjs/add/operator/finally"; import "rxjs/add/operator/share"; import {NgForm} from "@angular/forms"; import { getNgrxJsonApiZone, NGRX_JSON_API_DEFAULT_ZONE, NgrxJsonApiService, NgrxJsonApiStore, NgrxJsonApiStoreData, NgrxJsonApiZoneService, Resource, ResourceError, ResourceIdentifier, StoreResource } from 'ngrx-json-api'; import {Store} from "@ngrx/store"; import {getNgrxJsonApiStore$, getStoreData$} from './crnk.binding.utils'; import {ReplaySubject} from "rxjs/ReplaySubject"; interface ResourceFieldRef { resourceId: ResourceIdentifier; path: String; } export interface FormBindingConfig { /** * Reference to the forFormElement instance to hook into. */ form: NgForm; /** * Reference to a query from the store to get notified about validation errors. * FormBinding implementation assumes that the query has already been executed * (typically when performing the route to a new page). */ queryId: string; /** * By default a denormalized selectOneResults is used to fetch resources. Any update of those * resources triggers an update of the FormControl states. Set this flag to true to listen to all store changes. */ mapNonResultResources?: boolean; /** * Zone to use within ngrx-json-api. */ zoneId?: string; } /** * Binding between ngrx-jsonapi and angular forms. It serves two purposes: * * <ul> * <li>Updates the JSON API store when forFormElement controls changes their values.</li> * <li>Updates the validation state of forFormElement controls in case of JSON API errors. JSON API errors that cannot be * mapped to a forFormElement control are hold in the errors property * </li> * <ul> * * The binding between resources in the store and forFormElement controls happens trough the naming of the forFormElement * controls. Two naming patterns are supported: * * <ul> * <li>basic binding for all forFormElement controls that start with "attributes." or "relationships.". A forFormElement * control with label "attributes.title" is mapped to the "title" attribute of the JSON API resource in the store. The id of the * resource is obtained from the FormBindingConfig.resource$. * </li> * <li>(not yet supported) advanced binding with the naming pattern * "resource.{type}.{id}.{attributes/relationships}.{label}". * It allows to edit multiple resources in the same forFormElement. * </li> * <ul> * * Similarly, JSON API errors are mapped back to forFormElement controls trougth the source pointer of the error. If such a * mapping is not found, the error is added to the errors attribute of this class. Usually applications show such errors above * all fields in the config. * * You may also have a look at the CrnkExpressionModule. Its ExpressionDirective provides an alternative to NgModel * that binds both a value and sets the label of forFormElement control with a single (type-safe) attribute. */ export class FormBinding { /** * Observable to the resource to be edited. The forFormElement binding is active as long as there is * at least one subscriber to this Observable. */ public resource$: Observable<StoreResource>; /** * Contains all errors that cannot be assigned to a forFormElement control. Usually such errors are shown on top above * all controls. */ public unmappedErrors: Array<ResourceError> = []; /** * the forFormElement also sends out valueChanges upon initialization, we do not want that and filter them out with this flag */ private wasDirty = false; /** * id of the main resource to be edited. */ private primaryResourceId: ResourceIdentifier = null; /** * list of resources edited by this binding. May include related resources next to the primary one. */ private editResourceIds: { [key: string]: ResourceIdentifier } = {}; /** * Subscription to forFormElement changes. Gets automatically cancelled if there are no subscriptions anymore to * resource$. */ private formSubscription: Subscription = null; private storeSubscription: Subscription = null; private formControlsInitialized = false; private _storeDataSnapshot?: NgrxJsonApiStoreData = null; private validSubject = new ReplaySubject<boolean>(1); private dirtySubject = new ReplaySubject<boolean>(1); public valid: Observable<boolean>; public dirty: Observable<boolean>; public readonly zone: NgrxJsonApiZoneService; constructor(ngrxJsonApiService: NgrxJsonApiService, private config: FormBindingConfig, private store: Store<any>) { const zoneId = config.zoneId || NGRX_JSON_API_DEFAULT_ZONE; this.zone = ngrxJsonApiService.getZone(zoneId); this.dirtySubject.next(false); this.validSubject.next(true); this.dirty = this.dirtySubject.asObservable().distinctUntilChanged(); this.valid = this.validSubject.asObservable().distinctUntilChanged(); if (this.config.form === null) { throw new Error('no forFormElement provided'); } if (this.config.queryId === null) { throw new Error('no queryId provided'); } // we make use of share() to keep the this.config.resource$ subscription // as long as there is at least subscriber on this.resource$. this.resource$ = this.zone.selectOneResults(this.config.queryId, true) .filter(it => !_.isEmpty(it)) // ignore deletions .filter(it => !it.loading) .map(it => it.data as StoreResource) .filter(it => !_.isEmpty(it)) // ignore deletions .distinctUntilChanged(function (a, b) { return _.isEqual(a, b); }) .do(() => this.checkSubscriptions()) .do(resource => this.primaryResourceId = {type: resource.type, id: resource.id}) .withLatestFrom(this.store, (resource, state) => { const jsonapiState = getNgrxJsonApiZone(state, zoneId); this._storeDataSnapshot = jsonapiState.data; this.mapResourceToControlErrors(jsonapiState.data); this.updateDirtyState(jsonapiState.data); return resource; }) .finally(() => this.cancelSubscriptions) .share(); } protected cancelSubscriptions() { if (this.formSubscription !== null) { this.formSubscription.unsubscribe(); this.formSubscription = null; } if (this.storeSubscription !== null) { this.storeSubscription.unsubscribe(); this.storeSubscription = null; } } protected checkSubscriptions() { if (this.formSubscription === null) { // update store from value changes, for more information see // https://embed.plnkr.co/9aNuw6DG9VM4X8vUtkAa?show=app%2Fapp.components.ts,preview const formChanges$ = this.config.form.statusChanges .do(valid => this.validSubject.next(valid === 'VALID')) .filter(valid => valid === 'VALID') .do(() => { // it may take a moment for a form with all controls to initialize and register. // there seems no proper Angular lifecycle for this to check(???). Till no // control is found, we perform the mapping also here. // // geting notified about new control would be great... if (!this.formControlsInitialized) { this.mapResourceToControlErrors(this._storeDataSnapshot); } }) .withLatestFrom(this.config.form.valueChanges, (valid, values) => values) .filter(it => this.config.form.dirty || this.wasDirty) .debounceTime(20) .distinctUntilChanged(function (a, b) { return _.isEqual(a, b); }) .do(it => this.wasDirty = true); this.formSubscription = formChanges$.subscribe(formValues => this.updateStoreFromFormValues(formValues)); } if (this.storeSubscription != null && this.config.mapNonResultResources) { this.storeSubscription = this.store .let(getNgrxJsonApiStore$) .let(getStoreData$) .subscribe(data => { this.mapResourceToControlErrors(data); }); } } protected mapResourceToControlErrors(data: NgrxJsonApiStoreData) { const form = this.config.form; if (this.primaryResourceId) { const primaryResource = data[this.primaryResourceId.type][this.primaryResourceId.id]; const newUnmappedErrors = []; for (const resourceError of primaryResource.errors) { let mapped = false; if (resourceError.source && resourceError.source.pointer) { const path = this.toPath(resourceError.source.pointer); const formName = this.toResourceFormName(primaryResource, path); if (form.controls[formName] || form.controls[path]) { mapped = true; } } if (!mapped) { newUnmappedErrors.push(resourceError); } } this.unmappedErrors = newUnmappedErrors; } } protected updateDirtyState(data: NgrxJsonApiStoreData) { function isDirty(resourceId: ResourceIdentifier) { const resource = data[resourceId.type][resourceId.id]; return resource && resource.state !== 'IN_SYNC'; } let newDirty = isDirty(this.primaryResourceId); for (const editedResourceId of _.values(this.editResourceIds)) { newDirty = newDirty || isDirty(editedResourceId); } this.dirtySubject.next(newDirty); } protected toResourceFormName(resource: StoreResource, basicFormName: string) { return '//' + resource.type + '//' + resource.id + '//' + basicFormName; } protected toPath(sourcePointer: string) { let formName = sourcePointer.replace(new RegExp('/', 'g'), '.'); if (formName.startsWith('.')) { formName = formName.substring(1); } if (formName.endsWith('.')) { formName = formName.substring(0, formName.length - 1); } if (formName.startsWith('data.')) { formName = formName.substring(5); } return formName; } public save() { this.zone.apply(); } public delete() { this.zone.deleteResource({ resourceId: this.primaryResourceId, toRemote: true } ); } /** * computes type, id and field path from formName. */ private parseResourceFieldRef(formName: string): ResourceFieldRef { if (formName.startsWith('//')) { const [type, id, path] = formName.substring(2).split('//'); return { resourceId: { type: type, id: id }, path: path }; } else { return { resourceId: { type: this.primaryResourceId.type, id: this.primaryResourceId.id }, path: formName }; } } public updateStoreFromFormValues(values: any) { const patchedResourceMap: { [id: string]: Resource } = {}; for (const formName of Object.keys(values)) { const value = values[formName]; const formRef = this.parseResourceFieldRef(formName); if (formRef.path.startsWith('attributes.') || formRef.path.startsWith('relationships.')) { const key = formRef.resourceId.type + '_' + formRef.resourceId.id; const storeTypeSnapshot = this._storeDataSnapshot[formRef.resourceId.type]; const storeResourceSnapshot = storeTypeSnapshot ? storeTypeSnapshot[formRef.resourceId.id] : undefined; const storeValueSnapshot = storeResourceSnapshot ? _.get(storeResourceSnapshot, formRef.path) : undefined; if (!_.isEqual(storeValueSnapshot, value)) { let patchedResource = patchedResourceMap[key]; if (!patchedResource) { patchedResource = { id: formRef.resourceId.id, type: formRef.resourceId.type, attributes: {} }; patchedResourceMap[key] = patchedResource; const resourceKey = formRef.resourceId.id + "@" + formRef.resourceId.type; if (!this.editResourceIds[resourceKey]) { this.editResourceIds[resourceKey] = formRef.resourceId; } } _.set(patchedResource, formRef.path, value); } } } const patchedResources = _.values(patchedResourceMap); for (const patchedResource of patchedResources) { const cleanedPatchedResource = this.clearPrimeNgMarkers(patchedResource); this.zone.patchResource({resource: cleanedPatchedResource}); } } /** * Prime NG has to annoying habit of adding _$visited. Cleaned up here. Needs to be further investigated * and preferably avoided. * * FIXME move to HTTP layer or fix PrimeNG, preferably the later. */ private clearPrimeNgMarkers(resource: Resource) { const cleanedResource = _.cloneDeep(resource); if (cleanedResource.attributes) { for (const attributeName of Object.keys(cleanedResource.attributes)) { const value = cleanedResource.attributes[attributeName]; if (_.isObject(value)) { delete value['_$visited']; } } } if (cleanedResource.relationships) { for (const relationshipName of Object.keys(cleanedResource.relationships)) { const relationship = cleanedResource.relationships[relationshipName]; if (relationship.data) { const dependencyIds: Array<ResourceIdentifier> = relationship.data instanceof Array ? relationship.data : [relationship.data]; for (const dependencyId of dependencyIds) { delete dependencyId['_$visited']; } } } } return cleanedResource; } }
the_stack
import { act, queryByText, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import * as React from 'react'; import { ApiRelationship, ApiResourceType } from 'src/apis/run'; import { RoutePage, RouteParams } from 'src/components/Router'; import * as v2PipelineSpec from 'src/data/test/mock_lightweight_python_functions_v2_pipeline.json'; import { Apis } from 'src/lib/Apis'; import { Api } from 'src/mlmd/Api'; import { KFP_V2_RUN_CONTEXT_TYPE } from 'src/mlmd/MlmdUtils'; import { mockResizeObserver, testBestPractices } from 'src/TestUtils'; import { CommonTestWrapper } from 'src/TestWrapper'; import { Context, GetContextByTypeAndNameRequest, GetContextByTypeAndNameResponse, GetExecutionsByContextResponse, } from 'src/third_party/mlmd'; import { GetArtifactsByContextResponse, GetEventsByExecutionIDsResponse, } from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_service_pb'; import { PageProps } from './Page'; import { RunDetailsInternalProps } from './RunDetails'; import { RunDetailsV2 } from './RunDetailsV2'; testBestPractices(); describe('RunDetailsV2', () => { const RUN_ID = '1'; let updateBannerSpy: any; let updateDialogSpy: any; let updateSnackbarSpy: any; let updateToolbarSpy: any; let historyPushSpy: any; function generateProps(): RunDetailsInternalProps & PageProps { const pageProps: PageProps = { history: { push: historyPushSpy } as any, location: '' as any, match: { params: { [RouteParams.runId]: RUN_ID, }, isExact: true, path: '', url: '', }, toolbarProps: { actions: {}, breadcrumbs: [], pageTitle: '' }, updateBanner: updateBannerSpy, updateDialog: updateDialogSpy, updateSnackbar: updateSnackbarSpy, updateToolbar: updateToolbarSpy, }; return Object.assign(pageProps, { gkeMetadata: {}, }); } const TEST_RUN = { pipeline_runtime: { workflow_manifest: '{}', }, run: { created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), finished_at: new Date(2018, 8, 7, 4, 3, 2), description: 'test run description', id: 'test-run-id', name: 'test run', pipeline_spec: { parameters: [{ name: 'param1', value: 'value1' }], pipeline_id: 'some-pipeline-id', }, resource_references: [ { key: { id: 'some-experiment-id', type: ApiResourceType.EXPERIMENT }, name: 'some experiment', relationship: ApiRelationship.OWNER, }, { key: { id: 'test-run-id', type: ApiResourceType.PIPELINEVERSION }, name: 'default', relationship: ApiRelationship.CREATOR, }, ], status: 'Succeeded', }, }; const TEST_EXPERIMENT = { created_at: '2021-01-24T18:03:08Z', description: 'All runs will be grouped here.', id: 'some-experiment-id', name: 'Default', storage_state: 'STORAGESTATE_AVAILABLE', }; beforeEach(() => { mockResizeObserver(); updateBannerSpy = jest.fn(); updateToolbarSpy = jest.fn(); }); it('Render detail page with reactflow', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); expect(screen.getByTestId('DagCanvas')).not.toBeNull(); }); it('Shows error banner when disconnected from MLMD', async () => { jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockRejectedValue(new Error('Not connected to MLMD')); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); await waitFor(() => expect(updateBannerSpy).toHaveBeenLastCalledWith( expect.objectContaining({ additionalInfo: 'Cannot find context with {"typeName":"system.PipelineRun","contextName":"1"}: Not connected to MLMD', message: 'Cannot get MLMD objects from Metadata store.', mode: 'error', }), ), ); }); it('Shows no banner when connected from MLMD', async () => { jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockImplementation((request: GetContextByTypeAndNameRequest) => { const response = new GetContextByTypeAndNameResponse(); if ( request.getTypeName() === KFP_V2_RUN_CONTEXT_TYPE && request.getContextName() === RUN_ID ) { response.setContext(new Context()); } return response; }); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); await waitFor(() => expect(updateBannerSpy).toHaveBeenLastCalledWith({})); }); it("shows run title and experiments' links", async () => { const getRunSpy = jest.spyOn(Apis.runServiceApi, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockImplementation((request: GetContextByTypeAndNameRequest) => { return new GetContextByTypeAndNameResponse(); }); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); await act(async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); }); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ pageTitleTooltip: 'test run', }), ), ); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ breadcrumbs: [ { displayName: 'Experiments', href: RoutePage.EXPERIMENTS }, { displayName: 'Default', href: `/experiments/details/some-experiment-id`, }, ], }), ), ); }); it('shows top bar buttons', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApi, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockResolvedValue(new GetContextByTypeAndNameResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); await act(async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); }); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ actions: expect.objectContaining({ archive: expect.objectContaining({ disabled: false, title: 'Archive' }), retry: expect.objectContaining({ disabled: true, title: 'Retry' }), terminateRun: expect.objectContaining({ disabled: true, title: 'Terminate' }), cloneRun: expect.objectContaining({ disabled: false, title: 'Clone run' }), }), }), ), ); }); describe('topbar tabs', () => { it('switches to Detail tab', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); screen.getByText('Run details'); screen.getByText('Run ID'); screen.getByText('Workflow name'); screen.getByText('Status'); screen.getByText('Description'); screen.getByText('Created at'); screen.getByText('Started at'); screen.getByText('Finished at'); screen.getByText('Duration'); }); it('shows content in Detail tab', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); screen.getByText('test-run-id'); // 'Run ID' screen.getByText('test run'); // 'Workflow name' screen.getByText('test run description'); // 'Description' screen.getByText('9/5/2018, 4:03:02 AM'); //'Created at' screen.getByText('9/6/2018, 4:03:02 AM'); // 'Started at' screen.getByText('9/7/2018, 4:03:02 AM'); // 'Finished at' screen.getByText('48:00:00'); // 'Duration' }); it('handles no creation time', async () => { const noCreateTimeRun = { run: { // created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), finished_at: new Date(2018, 8, 7, 4, 3, 2), id: 'test-run-id', name: 'test run', description: 'test run description', status: 'Succeeded', }, }; render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={noCreateTimeRun} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); expect(screen.getAllByText('-').length).toEqual(2); // create time and duration are empty. }); it('handles no finish time', async () => { const noFinsihTimeRun = { run: { created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), // finished_at: new Date(2018, 8, 7, 4, 3, 2), id: 'test-run-id', name: 'test run', description: 'test run description', status: 'Succeeded', }, }; render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={noFinsihTimeRun} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); expect(screen.getAllByText('-').length).toEqual(2); // finish time and duration are empty. }); it('shows Execution Sidepanel', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApi, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); // Default view has no side panel. expect(screen.queryByText('Input/Output')).toBeNull(); expect(screen.queryByText('Task Details')).toBeNull(); // Select execution to open side panel. userEvent.click(screen.getByText('preprocess')); screen.getByText('Input/Output'); screen.getByText('Task Details'); // Close side panel. userEvent.click(screen.getByLabelText('close')); expect(screen.queryByText('Input/Output')).toBeNull(); expect(screen.queryByText('Task Details')).toBeNull(); }); it('shows Artifact Sidepanel', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApi, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={JSON.stringify(v2PipelineSpec)} runDetail={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); // Default view has no side panel. expect(screen.queryByText('Artifact Info')).toBeNull(); expect(screen.queryByText('Visualization')).toBeNull(); // Select artifact to open side panel. userEvent.click(screen.getByText('model')); screen.getByText('Artifact Info'); screen.getByText('Visualization'); // Close side panel. userEvent.click(screen.getByLabelText('close')); expect(screen.queryByText('Artifact Info')).toBeNull(); expect(screen.queryByText('Visualization')).toBeNull(); }); }); });
the_stack
* @module CartesianGeometry */ import { Arc3d } from "../curve/Arc3d"; import { AnnounceNumberNumber, AnnounceNumberNumberCurvePrimitive } from "../curve/CurvePrimitive"; import { Geometry } from "../Geometry"; import { Plane3dByOriginAndUnitNormal } from "../geometry3d/Plane3dByOriginAndUnitNormal"; import { Angle } from "../geometry3d/Angle"; import { GrowableFloat64Array } from "../geometry3d/GrowableFloat64Array"; import { GrowableXYZArray } from "../geometry3d/GrowableXYZArray"; import { Matrix3d } from "../geometry3d/Matrix3d"; import { Point3d, Vector3d } from "../geometry3d/Point3dVector3d"; import { IndexedXYZCollectionPolygonOps, PolygonOps } from "../geometry3d/PolygonOps"; import { Range1d, Range3d } from "../geometry3d/Range"; import { Ray3d } from "../geometry3d/Ray3d"; import { GrowableXYZArrayCache } from "../geometry3d/ReusableObjectCache"; import { Transform } from "../geometry3d/Transform"; import { Matrix4d } from "../geometry4d/Matrix4d"; import { ClipPlane, ClipPlaneProps } from "./ClipPlane"; import { Clipper, ClipPlaneContainment, ClipUtilities, PolygonClipper } from "./ClipUtils"; /** Wire format describing a [[ConvexClipPlaneSet]]. * @public */ export type ConvexClipPlaneSetProps = ClipPlaneProps[]; /** * A ConvexClipPlaneSet is a collection of ClipPlanes, often used for bounding regions of space. * @public */ export class ConvexClipPlaneSet implements Clipper, PolygonClipper { /** Value acting as "at infinity" for coordinates along a ray. */ public static readonly hugeVal = 1e37; private _planes: ClipPlane[]; // private _parity: number; <--- Not yet used // public get parity() { return this._parity; } // public set parity(value: number) { this._parity = value; } private constructor(planes?: ClipPlane[]) { // this._parity = 1; this._planes = planes ? planes : []; } /** Return an array containing all the planes of the convex set. * * Note that this has no leading keyword identifying it as a ConvexClipPlaneSet. */ public toJSON(): ConvexClipPlaneSetProps { const val: ClipPlaneProps[] = []; for (const plane of this._planes) val.push(plane.toJSON()); return val; } /** Extract clip planes from a json array `[ clipPlane, clipPlane ]`. * * Non-clipPlane members are ignored. */ public static fromJSON(json: ConvexClipPlaneSetProps | undefined, result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); result._planes.length = 0; if (!Array.isArray(json)) return result; for (const thisJson of json) { const plane = ClipPlane.fromJSON(thisJson); if (plane) result._planes.push(plane); } return result; } /** * Return true if all members are almostEqual to corresponding members of other. This includes identical order in array. * @param other clip plane to compare */ public isAlmostEqual(other: ConvexClipPlaneSet): boolean { if (this._planes.length !== other._planes.length) return false; for (let i = 0; i < this._planes.length; i++) if (!this._planes[i].isAlmostEqual(other._planes[i])) return false; return true; } /** create from an array of planes. * * Each plane reference in the `planes` array is taken into the result. * * The input array itself is NOT taken into the result. */ public static createPlanes(planes: (ClipPlane | Plane3dByOriginAndUnitNormal)[], result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); for (const plane of planes) { if (plane instanceof ClipPlane) { result._planes.push(plane); } else if (plane instanceof Plane3dByOriginAndUnitNormal) { const clipPlane = ClipPlane.createPlane(plane); result._planes.push(clipPlane); } } return result; } /** * Create new convex set using selected planes of a Range3d. * @param range range with coordinates * @param lowX true to clip at the low x plane * @param highX true to clip at the high x plane * @param lowY true to clip at the low y plane * @param highY true to clip at the high z plane * @param lowZ true to clip at the low z plane * @param highZ true to clip at the high z plane */ public static createRange3dPlanes(range: Range3d, lowX: boolean = true, highX: boolean = true, lowY: boolean = true, highY: boolean = true, lowZ: boolean = true, highZ: boolean = true): ConvexClipPlaneSet { const result = ConvexClipPlaneSet.createEmpty(); if (lowX) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(1, 0, 0, range.low.x, 0, 0)!); if (highX) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(-1, 0, 0, range.high.x, 0, 0)!); if (lowY) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(0, 1, 0, 0, range.low.y, 0)!); if (highY) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(0, -1, 0, 0, range.high.y, 0)!); if (lowZ) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(0, 0, 1, 0, 0, range.low.z)!); if (highZ) result.planes.push(ClipPlane.createNormalAndPointXYZXYZ(0, 0, -1, 0, 0, range.high.z)!); return result; } /** create an empty `ConvexClipPlaneSet` */ public static createEmpty(result?: ConvexClipPlaneSet): ConvexClipPlaneSet { if (result) { result._planes.length = 0; return result; } return new ConvexClipPlaneSet(); } /** negate all planes of the set. */ public negateAllPlanes(): void { for (const plane of this._planes) plane.negateInPlace(); } /** Create a convex clip plane set that clips to `x0 <= x <= x1` and `y0 <= y <= y1`. * * Note that there is no test for the usual ordering `x0 <= x1` or `y0 <= y1`. * * if the usual ordering is violated, the convex set is an empty set. */ public static createXYBox(x0: number, y0: number, x1: number, y1: number, result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); result._planes.length = 0; const clip0 = ClipPlane.createNormalAndDistance(Vector3d.create(-1, 0, 0), -x1, false, true); const clip1 = ClipPlane.createNormalAndDistance(Vector3d.create(1, 0, 0), x0, false, true); const clip2 = ClipPlane.createNormalAndDistance(Vector3d.create(0, -1, 0), -y1, false, true); const clip3 = ClipPlane.createNormalAndDistance(Vector3d.create(0, 1, 0), y0, false, true); if (clip0 && clip1 && clip2 && clip3) { result._planes.push(clip0, clip1, clip2, clip3); } return result; } /** Create a convex set containing a half space for each edge between points of a polyline. * * Caller is responsible for assuring the polyline is convex. * @param points array of points. Only xy parts are considered. * @param interior array whose boolean value is used as both the `interior` and `invisible` bits of the plane for the succeeding segment. If this array is not provided, both are false. * @param leftIsInside if true, the interior is "to the left" of the segments. If false, interior is "to the right" */ public static createXYPolyLine(points: Point3d[], interior: boolean[] | undefined, leftIsInside: boolean, result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); result._planes.length = 0; for (let i0 = 0; (i0 + 1) < points.length; i0++) { const edgeVector: Vector3d = Vector3d.createStartEnd(points[i0], points[i0 + 1]); const perp: Vector3d = edgeVector.unitPerpendicularXY(); perp.z = 0.0; if (!leftIsInside) perp.scaleInPlace(-1.0); const perpNormalized = perp.normalize(); if (perpNormalized) { const flag = interior !== undefined ? interior[i0] : false; const clip = ClipPlane.createNormalAndPoint(perp, points[i0], flag, flag); if (clip) { result._planes.push(clip); } } } return result; } /** * Create a convexClipPlaneSet with planes whose "inside" normal is to the left of each segment. * @param points array of points. */ public static createXYPolyLineInsideLeft(points: Point3d[], result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); result._planes.length = 0; for (let i0 = 0; (i0 + 1) < points.length; i0++) { const edgeVector: Vector3d = Vector3d.createStartEnd(points[i0], points[i0 + 1]); const perp: Vector3d = edgeVector.unitPerpendicularXY(); perp.z = 0.0; const perpNormalized = perp.normalize(); if (perpNormalized) { const clip = ClipPlane.createNormalAndPoint(perp, points[i0], false, false); if (clip) { result._planes.push(clip); } } } return result; } /** * (re)set a plane and ConvexClipPlaneSet for a convex array, such as a convex facet used for xy clip. * * The planeOfPolygon is (re)initialized with the normal from 3 points, but not otherwise referenced. * * The ConvexClipPlaneSet is filled with outward normals of the facet edges as viewed to xy plane. * @param points * @param result */ public static setPlaneAndXYLoopCCW(points: GrowableXYZArray, planeOfPolygon: ClipPlane, frustum: ConvexClipPlaneSet) { const i0 = points.length - 1; const n = points.length; let x0 = points.getXAtUncheckedPointIndex(i0); let y0 = points.getYAtUncheckedPointIndex(i0); let x1, y1, nx, ny; frustum._planes.length = 0; const z0 = points.getZAtUncheckedPointIndex(i0); // z for planes can stay fixed const planeNormal = points.crossProductIndexIndexIndex(0, 2, 1)!; ClipPlane.createNormalAndPointXYZXYZ(planeNormal.x, planeNormal.y, planeNormal.z, x0, y0, z0, false, false, planeOfPolygon); if (planeNormal.normalizeInPlace()) { for (let i1 = 0; i1 < n; i1++, x0 = x1, y0 = y1) { x1 = points.getXAtUncheckedPointIndex(i1); y1 = points.getYAtUncheckedPointIndex(i1); nx = -(y1 - y0); ny = x1 - x0; const clipper = ClipPlane.createNormalAndPointXYZXYZ(nx, ny, 0, x1, y1, z0); if (clipper) frustum._planes.push(clipper); } } } /** Deep clone of all planes. */ public clone(result?: ConvexClipPlaneSet): ConvexClipPlaneSet { result = result ? result : new ConvexClipPlaneSet(); result._planes.length = 0; for (const plane of this._planes) result._planes.push(plane.clone()); return result; } /** Return the (reference to the) array of `ClipPlane` */ public get planes(): ClipPlane[] { return this._planes; } /** Test if there is any intersection with a ray defined by origin and direction. * * Optionally record the range (null or otherwise) in caller-allocated result. * * If the ray is unbounded inside the clip, result can contain positive or negative "Geometry.hugeCoordinate" values * * If no result is provide, there are no object allocations. * @param result optional Range1d to receive parameters along the ray. */ public hasIntersectionWithRay(ray: Ray3d, result?: Range1d): boolean { // form low and high values in locals that do not require allocation. // transfer to caller-supplied result at end let t0 = -Geometry.hugeCoordinate; let t1 = Geometry.hugeCoordinate; if (result) result.setNull(); for (const plane of this._planes) { const vD = plane.velocity(ray.direction); const vN = plane.altitude(ray.origin); if (vD === 0.0) { // Ray is parallel... No need to continue testing if outside halfspace. if (vN < 0.0) return false; // and result is a null range. } else { const rayFraction = - vN / vD; if (vD < 0.0) { if (rayFraction < t1) t1 = rayFraction; } else { if (rayFraction > t0) t0 = rayFraction; } } } if (t1 < t0) return false; // and result is a null range. if (result) { result.extendX(t0); result.extendX(t1); } return true; } /** * Multiply all the ClipPlanes DPoint4d by matrix. * @param matrix matrix to apply. * @param invert if true, use in verse of the matrix. * @param transpose if true, use the transpose of the matrix (or inverse, per invert parameter) * * Note that if matrixA is applied to all of space, the matrix to send to this method to get a corresponding effect on the plane is the inverse transpose of matrixA * * Callers that will apply the same matrix to many planes should pre-invert the matrix for efficiency. * * Both params default to true to get the full effect of transforming space. * @param matrix matrix to apply */ public multiplyPlanesByMatrix4d(matrix: Matrix4d, invert: boolean = true, transpose: boolean = true): boolean { if (invert) { // form inverse once here, reuse for all planes const inverse = matrix.createInverse(); if (!inverse) return false; return this.multiplyPlanesByMatrix4d(inverse, false, transpose); } for (const plane of this._planes) { plane.multiplyPlaneByMatrix4d(matrix, false, transpose); } return true; } /** Return true if `point` satisfies `point.isPointInside` for all planes */ public isPointInside(point: Point3d): boolean { for (const plane of this._planes) { if (!plane.isPointInside(point)) // Defaults to strict inside check. Other clipping classes may use "on or inside" check for the "on" case return false; } return true; } /** Return true if `point` satisfies `point.isPointOnOrInside` for all planes */ public isPointOnOrInside(point: Point3d, tolerance: number): boolean { const interiorTolerance = Math.abs(tolerance); // Interior tolerance should always be positive. (TFS# 246598). for (const plane of this._planes) { if (!plane.isPointOnOrInside(point, (plane.interior ? interiorTolerance : tolerance))) return false; } return true; } /** * Test if a sphere is completely inside the convex set. * @param centerPoint center of sphere * @param radius radius of sphere. */ public isSphereInside(centerPoint: Point3d, radius: number): boolean { const r1 = Math.abs(radius) + Geometry.smallMetricDistance; for (const plane of this._planes) { if (!plane.isPointOnOrInside(centerPoint, r1)) { return false; } } return true; } /** Find the parts of the line segment (if any) that is within the convex clip volume. * * The input fractional interval from fraction0 to fraction1 (increasing!!) is the active part to consider. * * To clip to the usual bounded line segment, starts with fractions (0,1). * If the clip volume is unbounded, the line interval may also be unbounded. * * An unbounded line portion will have fraction coordinates positive or negative Number.MAX_VALUE. * @param fraction0 fraction that is the initial lower fraction of the active interval. (e.g. 0.0 for bounded segment) * @param fraction1 fraction that is the initial upper fraction of the active interval. (e.g. 1.0 for bounded segment) * @param pointA segment start (fraction 0) * @param pointB segment end (fraction 1) * @param announce function to be called to announce a fraction interval that is within the convex clip volume. * @returns true if a segment was announced, false if entirely outside. */ public announceClippedSegmentIntervals(f0: number, f1: number, pointA: Point3d, pointB: Point3d, announce?: AnnounceNumberNumber): boolean { let fraction: number | undefined; if (f1 < f0) return false; for (const plane of this._planes) { const hA = - plane.altitude(pointA); const hB = - plane.altitude(pointB); fraction = Geometry.conditionalDivideFraction(-hA, (hB - hA)); if (fraction === undefined) { // LIne parallel to the plane. If positive, it is all OUT if (hA > 0.0) return false; } else if (hB > hA) { // STRICTLY moving outward if (fraction < f0) return false; if (fraction < f1) f1 = fraction; } else if (hA > hB) { // STRICTLY moving inward if (fraction > f1) return false; if (fraction > f0) f0 = fraction; } else { // Strictly equal evaluations if (hA > 0.0) return false; } } if (f1 >= f0) { if (announce) announce(f0, f1); return true; } return false; } private static _clipArcFractionArray = new GrowableFloat64Array(); /** Find fractional parts of the arc that are within this ClipPlaneSet, and announce each as * * `announce(fraction, fraction, curve)` */ public announceClippedArcIntervals(arc: Arc3d, announce?: AnnounceNumberNumberCurvePrimitive): boolean { const breaks = ConvexClipPlaneSet._clipArcFractionArray; breaks.clear(); for (const clipPlane of this.planes) { clipPlane.appendIntersectionRadians(arc, breaks); } arc.sweep.radiansArrayToPositivePeriodicFractions(breaks); return ClipUtilities.selectIntervals01(arc, breaks, this, announce); } /** Find the parts of the (unbounded) line segment (if any) that is within the convex clip volume. * @param pointA segment start (fraction 0) * @param pointB segment end (fraction 1) * @param announce function to be called to announce a fraction interval that is within the convex clip volume. * @returns true if a segment was announced, false if entirely outside. */ public clipUnboundedSegment(pointA: Point3d, pointB: Point3d, announce?: AnnounceNumberNumber): boolean { return this.announceClippedSegmentIntervals(-Number.MAX_VALUE, Number.MAX_VALUE, pointA, pointB, announce); } /** transform each plane in place. */ public transformInPlace(transform: Transform) { for (const plane of this._planes) { plane.transformInPlace(transform); } } /** * Clip a polygon to the inside of the convex set. * * Results with 2 or fewer points are ignored. * * Other than ensuring capacity in the arrays, there are no object allocations during execution of this function. * @param xyz input points. * @param work work buffer * @param tolerance tolerance for "on plane" decision. */ public clipConvexPolygonInPlace(xyz: GrowableXYZArray, work: GrowableXYZArray, tolerance: number = Geometry.smallMetricDistance) { for (const plane of this._planes) { plane.clipConvexPolygonInPlace(xyz, work, true, tolerance); if (xyz.length < 3) return; } } /** Clip a convex polygon to (a single) inside part and (possibly many) outside parts. * @param xyz input polygon. * @param outsideFragments an array to receive (via push, with no preliminary clear) outside fragments * @param arrayCache cache for work arrays. * @return the surviving inside part (if any) */ public clipInsidePushOutside(xyz: GrowableXYZArray, outsideFragments: GrowableXYZArray[] | undefined, arrayCache: GrowableXYZArrayCache): GrowableXYZArray | undefined { const perpendicularRange = Range1d.createNull(); let newInside = arrayCache.grabFromCache(); let newOutside = arrayCache.grabFromCache(); let insidePart = arrayCache.grabFromCache(); // this is empty ... insidePart.pushFrom(xyz); // While looping through planes . . // the outside part for the current plane is definitely outside and can be stashed to the final outside // the inside part for the current plane passes forward to be further split by the remaining planes. for (const plane of this._planes) { IndexedXYZCollectionPolygonOps.splitConvexPolygonInsideOutsidePlane(plane, insidePart, newInside, newOutside, perpendicularRange); if (newOutside.length > 0) { // the newOutside fragment is definitely outside the ConvexClipPlaneSet if (outsideFragments) // save the definitely outside part as return data. ClipUtilities.captureOrDrop(newOutside, 3, outsideFragments, arrayCache); newOutside = arrayCache.grabFromCache(); if (newInside.length === 0) { insidePart.length = 0; break; } // insideWork is changed ... swap it with insidePart arrayCache.dropToCache(insidePart); insidePart = newInside; newInside = arrayCache.grabFromCache(); } // outside clip was empty .. insideWork is identical to insidePart .. let insidePart feed through to the next clipper. } // at break or fall out ... // ALWAYS drop `newInside` and `newOutside` to the cache arrayCache.dropToCache(newInside); arrayCache.dropToCache(newOutside); // if `insidePart` is alive, return it to caller. Otherwise drop it to cache and return undefined. if (insidePart.length > 0) return insidePart; arrayCache.dropToCache(insidePart); return undefined; } /** Returns 1, 2, or 3 based on whether point array is strongly inside, ambiguous, or strongly outside respectively. * * This has a peculiar expected use case as a very fast pre-filter for more precise clipping. * * The expected point set is for a polygon. * * Hence any clipping will eventually have to consider the lines between the points. * * This method looks for the special case of a single clip plane that has all the points outside. * * In this case the whole polygon must be outside. * * Note that this does not detect a polygon that is outside but "crosses a corner" -- it is mixed with respect to * multiple planes. */ public classifyPointContainment(points: Point3d[], onIsOutside: boolean): ClipPlaneContainment { let allInside = true; const onTolerance = onIsOutside ? 1.0e-8 : -1.0e-8; const interiorTolerance = 1.0e-8; // Interior tolerance should always be positive for (const plane of this._planes) { let nOutside = 0; for (const point of points) { if (plane.altitude(point) < (plane.interior ? interiorTolerance : onTolerance)) { nOutside++; allInside = false; } } if (nOutside === points.length) return ClipPlaneContainment.StronglyOutside; } return allInside ? ClipPlaneContainment.StronglyInside : ClipPlaneContainment.Ambiguous; } /** * * Create a convex clip set for a polygon swept with possible tilt angle. * * planes are constructed by ClipPlane.createEdgeAndUpVector, using successive points from the array. * * If the first and last points match, the polygon area is checked. If the area is negative, points are used in reverse order. * * If first and last points do not match, points are used in order given * @param points polygon points. (Closure point optional) * @param upVector primary sweep direction, as applied by ClipPlane.createEdgeAndUpVector * @param tiltAngle angle to tilt sweep planes away from the sweep direction. */ public static createSweptPolyline(points: Point3d[], upVector: Vector3d, tiltAngle?: Angle): ConvexClipPlaneSet | undefined { const result = ConvexClipPlaneSet.createEmpty(); let reverse = false; if (points.length > 3 && points[0].isAlmostEqual(points[points.length - 1])) { const polygonNormal: Vector3d = PolygonOps.areaNormal(points); const normalDot = polygonNormal.dotProduct(upVector); if (normalDot > 0.0) reverse = true; } for (let i = 0; (i + 1) < points.length; i++) { if (reverse) { const toAdd = ClipPlane.createEdgeAndUpVector(points[i + 1], points[i], upVector, tiltAngle); if (toAdd) { // clipPlane creation could result in undefined result.addPlaneToConvexSet(toAdd); } else { return undefined; } } else { const toAdd = ClipPlane.createEdgeAndUpVector(points[i], points[i + 1], upVector, tiltAngle); if (toAdd) { // clipPlane creation could result in undefined result.addPlaneToConvexSet(toAdd); } else { return undefined; } } } return result; } /** * Add a plane to the convex set. * @param plane plane to add */ public addPlaneToConvexSet(plane: ClipPlane | Plane3dByOriginAndUnitNormal| undefined) { if (plane instanceof ClipPlane) this._planes.push(plane); else if (plane instanceof Plane3dByOriginAndUnitNormal) this._planes.push(ClipPlane.createPlane(plane)); } /** * test many points. Distribute them to arrays depending on in/out result. * @param points points to test * @param inOrOn points that are in or on the set * @param out points that are out. */ public clipPointsOnOrInside(points: Point3d[], inOrOn: Point3d[], out: Point3d[]) { inOrOn.length = 0; out.length = 0; for (const xyz of points) { if (this.isPointOnOrInside(xyz, 0.0)) { inOrOn.push(xyz); } else { out.push(xyz); } } } /** * Clip a polygon to the planes of the clip plane set. * * For a convex input polygon, the output is another convex polygon. * * For a non-convex input, the output may have double-back edges along plane intersections. This is still a valid clip in a parity sense. * * The containingPlane parameter allows callers within ConvexClipPlane set to bypass planes known to contain the polygon * @param input input polygon, usually convex. * @param output output polygon * @param work work array. * @param containingPlane if this plane is found in the convex set, it is NOT applied. */ public polygonClip(input: GrowableXYZArray | Point3d[], output: GrowableXYZArray, work: GrowableXYZArray, planeToSkip?: ClipPlane) { if (input instanceof GrowableXYZArray) input.clone(output); else GrowableXYZArray.create(input, output); for (const plane of this._planes) { if (planeToSkip === plane) continue; if (output.length === 0) break; plane.clipConvexPolygonInPlace(output, work); } } /** * * Define new planes in this ConvexClipPlaneSet so it clips to the inside of a polygon. * * always create planes for the swept edges of the polygon * * optionally (with nonzero sideSelect) create a cap plane using the polygon normal. * @param points Points of a bounding polygon * @param sweepDirection direction to sweep. * @param sideSelect 0 to have no cap polygon, 1 if the sweep vector side is in, -1 if sweep vector side is out. */ public reloadSweptPolygon(points: Point3d[], sweepDirection: Vector3d, sideSelect: number): number { this._planes.length = 0; const n = points.length; if (n <= 2) return 0; const planeNormal: Vector3d = PolygonOps.areaNormal(points); const isCCW = sweepDirection.dotProduct(planeNormal) > 0.0; const delta = isCCW ? 1 : n - 1; for (let i = 0; i < n; i++) { const i1 = (i + delta) % n; const xyz0: Point3d = points[i]; const xyz1: Point3d = points[i1]; if (xyz0.isAlmostEqual(xyz1)) continue; const edgeVector: Vector3d = Vector3d.createStartEnd(xyz0, xyz1); const inwardNormal: Vector3d = Vector3d.createCrossProduct(sweepDirection.x, sweepDirection.y, sweepDirection.z, edgeVector.x, edgeVector.y, edgeVector.z); const inwardNormalNormalized = inwardNormal.normalize(); let distance; if (inwardNormalNormalized) { // Should never fail... simply a check due to the format of the normalize function return distance = inwardNormalNormalized.dotProduct(xyz0); const clipToAdd = ClipPlane.createNormalAndDistance(inwardNormalNormalized, distance, false, false); if (clipToAdd) { this._planes.push(clipToAdd); } // clipPlane creation could result in undefined } } if (sideSelect !== 0.0) { let planeNormalNormalized = planeNormal.normalize(); if (planeNormalNormalized) { // Again.. should never fail const a = sweepDirection.dotProduct(planeNormalNormalized) * sideSelect; if (a < 0.0) planeNormalNormalized = planeNormalNormalized.negate(); const xyz0: Point3d = points[0]; const distance = planeNormalNormalized.dotProduct(xyz0); const clipToAdd = ClipPlane.createNormalAndDistance(planeNormalNormalized, distance, false, false); if (clipToAdd) { this._planes.push(clipToAdd); } // clipPlane creation could result in undefined } } return isCCW ? 1 : -1; } /** * Compute intersections among all combinations of 3 planes in the convex set. * * optionally throw out points that are not in the set. * * optionally push the points in the caller-supplied point array. * * optionally extend a caller supplied range. * * In the common case where the convex set is (a) a slab or (b) a view frustum, there will be 8 points and the range is the range of the convex set. * * If the convex set is unbounded, the range only contains the range of the accepted (corner) points, and the range is not a representative of the "range of all points in the set" . * @param transform (optional) transform to apply to the points. * @param points (optional) array to which computed points are to be added. * @param range (optional) range to be extended by the computed points * @param transform (optional) transform to apply to the accepted points. * @param testContainment if true, test each point to see if it is within the convex set. (Send false if confident that the convex set is rectilinear set such as a slab. Send true if chiseled corners are possible) * @returns number of points. */ public computePlanePlanePlaneIntersections(points: Point3d[] | undefined, rangeToExtend: Range3d | undefined, transform?: Transform, testContainment: boolean = true): number { const normalRows = Matrix3d.createIdentity(); const allPlanes = this._planes; const n = allPlanes.length; let numPoints = 0; // explicitly count points -- can't wait to end for points.length because it may be an optional output. for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) { Matrix3d.createRowValues( allPlanes[i].inwardNormalRef.x, allPlanes[i].inwardNormalRef.y, allPlanes[i].inwardNormalRef.z, allPlanes[j].inwardNormalRef.x, allPlanes[j].inwardNormalRef.y, allPlanes[j].inwardNormalRef.z, allPlanes[k].inwardNormalRef.x, allPlanes[k].inwardNormalRef.y, allPlanes[k].inwardNormalRef.z, normalRows); if (normalRows.computeCachedInverse(false)) { const xyz = normalRows.multiplyInverseXYZAsPoint3d(allPlanes[i].distance, allPlanes[j].distance, allPlanes[k].distance)!; if (!testContainment || this.isPointOnOrInside(xyz, Geometry.smallMetricDistance)) { numPoints++; if (transform) transform.multiplyPoint3d(xyz, xyz); if (points) points.push(xyz); if (rangeToExtend) rangeToExtend.extendPoint(xyz); } } } } return numPoints; } /** * Set the `invisible` property on each plane of the convex set. * @param invisible value to store */ public setInvisible(invisible: boolean) { for (const plane of this._planes) { plane.setInvisible(invisible); } } /** * Add planes for z-direction clip between low and high z levels. * @param invisible value to apply to the `invisible` bit for the new planes * @param zLow low z value. The plane clips out points with z below this. * @param zHigh high z value. The plane clips out points with z above this. */ public addZClipPlanes(invisible: boolean, zLow?: number, zHigh?: number) { if (zLow !== undefined) this._planes.push(ClipPlane.createNormalAndDistance(Vector3d.create(0, 0, 1), zLow, invisible)!); if (zHigh !== undefined) this._planes.push(ClipPlane.createNormalAndDistance(Vector3d.create(0, 0, -1), -zHigh, invisible)!); } /** Implement appendPolygonClip, as defined in interface PolygonClipper. /** * * @param xyz input polygon. This is not changed. * @param insideFragments Array to receive "inside" fragments. Each fragment is a GrowableXYZArray grabbed from the cache. This is NOT cleared. * @param outsideFragments Array to receive "outside" fragments. Each fragment is a GrowableXYZArray grabbed from the cache. This is NOT cleared. * @param arrayCache cache for reusable GrowableXYZArray. */ public appendPolygonClip( xyz: GrowableXYZArray, insideFragments: GrowableXYZArray[], outsideFragments: GrowableXYZArray[], arrayCache: GrowableXYZArrayCache): void { const newInside = this.clipInsidePushOutside(xyz, outsideFragments, arrayCache); if (newInside) insideFragments.push(newInside); } // FUNCTIONS SKIPPED DUE TO BSPLINES, VU, OR NON-USAGE IN NATIVE CODE---------------------------------------------------------------- // Uses bsplines... skipping for now: // public convexAppendIntervalsFromBspline(); // Uses pushing and clearing from/to a cache and added functionality for arrays. . . skipping for now // public convexPolygonClipInsideOutside(input: Point3d[], inside: Point3d[], outside: Point3d[], work1: Point3d[], work2: Point3d[], // clearOutside: boolean, distanceTolerance: number) }
the_stack
import { Container } from 'typedi'; import { getMetadataArgsStorage } from 'typeorm'; import { ColumnMetadata, getMetadataStorage, ModelMetadata } from '../metadata'; import { WhereOperator } from '../torm'; import { columnToGraphQLDataType, columnToGraphQLType, columnToTypeScriptType } from './type-conversion'; const ignoreBaseModels = ['BaseModel', 'BaseModelUUID']; export function getColumnsForModel(model: ModelMetadata) { const models = [model]; const columns: { [key: string]: ColumnMetadata } = {}; let superProto = model.klass ? model.klass.__proto__ : null; while (superProto) { const superModel = getMetadataStorage().getModel(superProto.name); superModel && models.unshift(superModel); superProto = superProto.__proto__; } models.forEach(aModel => { aModel.columns.forEach((col: ColumnMetadata) => { columns[col.propertyName] = col; }); }); return Object.values(columns); } export function filenameToImportPath(filename: string): string { return filename.replace(/\.(j|t)s$/, '').replace(/\\/g, '/'); } export function generateEnumMapImports(): string[] { const imports: string[] = []; const enumMap = getMetadataStorage().enumMap; // Keep track of already imported items so that we don't attempt to import twice in the event the // enum is used in multiple models const imported = new Set(); Object.keys(enumMap).forEach((tableName: string) => { Object.keys(enumMap[tableName]).forEach((columnName: string) => { const enumColumn = enumMap[tableName][columnName]; if (imported.has(enumColumn.name)) { return; } imported.add(enumColumn.name); const filename = filenameToImportPath(enumColumn.filename); imports.push(`import { ${enumColumn.name} } from '${filename}' `); }); }); return imports; } export function generateClassImports(): string[] { const imports: string[] = []; const classMap = getMetadataStorage().classMap; Object.keys(classMap).forEach((tableName: string) => { const classObj = classMap[tableName]; const filename = filenameToImportPath(classObj.filename); // Need to ts-ignore here for when we export compiled code // otherwise, it says we can't find a declaration file for this from the compiled code imports.push('// @ts-ignore\n'); imports.push(`import { ${classObj.name} } from '${filename}' `); }); return imports; } export function entityToWhereUniqueInput(model: ModelMetadata): string { const uniques = getMetadataStorage().uniquesForModel(model); const others = getMetadataArgsStorage().uniques; const modelUniques: { [key: string]: string } = {}; others.forEach(o => { const name = (o.target as Function).name; const columns = o.columns as string[]; if (name === model.name && columns) { columns.forEach((col: string) => { modelUniques[col] = col; }); } }); uniques.forEach(unique => { modelUniques[unique] = unique; }); const distinctUniques = Object.keys(modelUniques); // If there is only one unique field, it should not be nullable const uniqueFieldsAreNullable = distinctUniques.length > 1; let fieldsTemplate = ''; const modelColumns = getColumnsForModel(model); modelColumns.forEach((column: ColumnMetadata) => { // Uniques can be from Field or Unique annotations if (!modelUniques[column.propertyName]) { return; } const nullable = uniqueFieldsAreNullable ? ', { nullable: true }' : ''; let graphQLDataType = columnToGraphQLDataType(column); let tsType = columnToTypeScriptType(column); if (column.array) { tsType = tsType.concat('[]'); graphQLDataType = `[${graphQLDataType}]`; } fieldsTemplate += ` @TypeGraphQLField(() => ${graphQLDataType}${nullable}) ${column.propertyName}?: ${tsType}; `; }); const superName = model.klass ? model.klass.__proto__.name : null; const classDeclaration = superName && !ignoreBaseModels.includes(superName) ? `${model.name}WhereUniqueInput extends ${superName}WhereUniqueInput` : `${model.name}WhereUniqueInput`; const template = ` @TypeGraphQLInputType() export class ${classDeclaration} { ${fieldsTemplate} } `; return template; } export function entityToCreateInput(model: ModelMetadata): string { const idsOnCreate = (Container.get('Config') as any).get('ALLOW_OPTIONAL_ID_ON_CREATE') === 'true'; let fieldTemplates = ''; if (idsOnCreate) { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) id?: string; `; } const modelColumns = getColumnsForModel(model); modelColumns.forEach((column: ColumnMetadata) => { if (!column.editable || column.readonly) { return; } let graphQLDataType = columnToGraphQLDataType(column); const nullable = column.nullable ? '{ nullable: true }' : ''; const tsRequired = column.nullable ? '?' : '!'; let tsType = columnToTypeScriptType(column); if (column.array) { tsType = tsType.concat('[]'); graphQLDataType = `[${graphQLDataType}]`; } if (columnRequiresExplicitGQLType(column)) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, ${nullable}) ${column.propertyName}${tsRequired}: ${tsType}; `; } else { fieldTemplates += ` @TypeGraphQLField(${nullable}) ${column.propertyName}${tsRequired}: ${tsType}; `; } }); const superName = model.klass ? model.klass.__proto__.name : null; const classDeclaration = superName && !ignoreBaseModels.includes(superName) ? `${model.name}CreateInput extends ${superName}CreateInput` : `${model.name}CreateInput`; return ` @TypeGraphQLInputType() export class ${classDeclaration} { ${fieldTemplates} } `; } export function entityToUpdateInput(model: ModelMetadata): string { let fieldTemplates = ''; const modelColumns = getColumnsForModel(model); modelColumns.forEach((column: ColumnMetadata) => { if (!column.editable || column.readonly) { return; } // TODO: also don't allow updated foreign key fields // Example: photo.userId: String let graphQLDataType = columnToGraphQLDataType(column); let tsType = columnToTypeScriptType(column); if (column.array) { tsType = tsType.concat('[]'); graphQLDataType = `[${graphQLDataType}]`; } if (columnRequiresExplicitGQLType(column)) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}?: ${tsType}; `; } else { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) ${column.propertyName}?: ${tsType}; `; } }); const superName = model.klass ? model.klass.__proto__.name : null; const classDeclaration = superName && !ignoreBaseModels.includes(superName) ? `${model.name}UpdateInput extends ${superName}UpdateInput` : `${model.name}UpdateInput`; return ` @TypeGraphQLInputType() export class ${classDeclaration} { ${fieldTemplates} } `; } // Constructs required arguments needed when doing an update export function entityToUpdateInputArgs(model: ModelMetadata): string { return ` @ArgsType() export class ${model.name}UpdateArgs { @TypeGraphQLField() data!: ${model.name}UpdateInput; @TypeGraphQLField() where!: ${model.name}WhereUniqueInput; } `; } function columnToTypes(column: ColumnMetadata) { const graphqlType = columnToGraphQLType(column); const tsType = columnToTypeScriptType(column); return { graphqlType, tsType }; } export function entityToWhereInput(model: ModelMetadata): string { let fieldTemplates = ''; const modelColumns = getColumnsForModel(model); modelColumns.forEach((column: ColumnMetadata) => { // If user specifically says not to filter (filter: false), then don't provide where inputs // Also, if the columns is "write only", then it cannot therefore be read and shouldn't have filters if (!column.filter || column.writeonly) { return; } function allowFilter(op: WhereOperator) { if (column.filter === true) { return true; } if (column.filter === false) { return false; } return !!column.filter?.includes(op); } const { tsType } = columnToTypes(column); const graphQLDataType = columnToGraphQLDataType(column); // TODO: for foreign key fields, only allow the same filters as ID below // Example: photo.userId: String if (column.array) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true }) ${column.propertyName}_containsAll?: [${tsType}]; @TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true }) ${column.propertyName}_containsNone?: [${tsType}]; @TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true }) ${column.propertyName}_containsAny?: [${tsType}]; `; } else if (column.type === 'id') { const graphQlType = 'ID'; if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQlType},{ nullable: true }) ${column.propertyName}_eq?: string; `; } if (allowFilter('in')) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQlType}], { nullable: true }) ${column.propertyName}_in?: string[]; `; } } else if (column.type === 'boolean') { if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType},{ nullable: true }) ${column.propertyName}_eq?: Boolean; `; } // V3: kill the boolean "in" clause if (allowFilter('in')) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQLDataType}], { nullable: true }) ${column.propertyName}_in?: Boolean[]; `; } } else if (column.type === 'string' || column.type === 'email') { // TODO: do we need NOT? // `${column.propertyName}_not` if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) ${column.propertyName}_eq?: ${tsType}; `; } if (allowFilter('contains')) { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) ${column.propertyName}_contains?: ${tsType}; `; } if (allowFilter('startsWith')) { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) ${column.propertyName}_startsWith?: ${tsType}; `; } if (allowFilter('endsWith')) { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) ${column.propertyName}_endsWith?: ${tsType}; `; } if (allowFilter('in')) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQLDataType}], { nullable: true }) ${column.propertyName}_in?: ${tsType}[]; `; } } else if (column.type === 'float' || column.type === 'integer' || column.type === 'numeric') { if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_eq?: ${tsType}; `; } if (allowFilter('gt')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_gt?: ${tsType}; `; } if (allowFilter('gte')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_gte?: ${tsType}; `; } if (allowFilter('lt')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_lt?: ${tsType}; `; } if (allowFilter('lte')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_lte?: ${tsType}; `; } if (allowFilter('in')) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQLDataType}], { nullable: true }) ${column.propertyName}_in?: ${tsType}[]; `; } } else if (column.type === 'date' || column.type === 'datetime' || column.type === 'dateonly') { // I really don't like putting this magic here, but it has to go somewhere // This deletedAt_all turns off the default filtering of soft-deleted items if (column.propertyName === 'deletedAt') { fieldTemplates += ` @TypeGraphQLField({ nullable: true }) deletedAt_all?: Boolean; `; } if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_eq?: ${tsType}; `; } if (allowFilter('lt')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_lt?: ${tsType}; `; } if (allowFilter('lte')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_lte?: ${tsType}; `; } if (allowFilter('gt')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_gt?: ${tsType}; `; } if (allowFilter('gte')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_gte?: ${tsType}; `; } } else if (column.type === 'enum') { if (allowFilter('eq')) { fieldTemplates += ` @TypeGraphQLField(() => ${graphQLDataType}, { nullable: true }) ${column.propertyName}_eq?: ${graphQLDataType}; `; } if (allowFilter('in')) { fieldTemplates += ` @TypeGraphQLField(() => [${graphQLDataType}], { nullable: true }) ${column.propertyName}_in?: ${graphQLDataType}[]; `; } } else if (column.type === 'json') { fieldTemplates += ` @TypeGraphQLField(() => GraphQLJSONObject, { nullable: true }) ${column.propertyName}_json?: JsonObject; `; } }); const superName = model.klass ? model.klass.__proto__.name : null; const classDeclaration = superName && !ignoreBaseModels.includes(superName) ? `${model.name}WhereInput extends ${superName}WhereInput` : `${model.name}WhereInput`; return ` @TypeGraphQLInputType() export class ${classDeclaration} { ${fieldTemplates} } `; } export function entityToWhereArgs(model: ModelMetadata): string { return ` @ArgsType() export class ${model.name}WhereArgs extends PaginationArgs { @TypeGraphQLField(() => ${model.name}WhereInput, { nullable: true }) where?: ${model.name}WhereInput; @TypeGraphQLField(() => ${model.name}OrderByEnum, { nullable: true }) orderBy?: ${model.name}OrderByEnum; } `; } // Note: it would be great to inject a single `Arg` with the [model.nameCreateInput] array arg, // but that is not allowed by TypeGraphQL export function entityToCreateManyArgs(model: ModelMetadata): string { return ` @ArgsType() export class ${model.name}CreateManyArgs { @TypeGraphQLField(() => [${model.name}CreateInput]) data!: ${model.name}CreateInput[]; } `; } export function entityToOrderByEnum(model: ModelMetadata): string { let fieldsTemplate = ''; const modelColumns = getColumnsForModel(model); modelColumns.forEach((column: ColumnMetadata) => { if (column.type === 'json') { return; } // If user says this is not sortable, then don't allow sorting // Also, if the column is "write only", therefore it cannot be read and shouldn't be sortable // Also, doesn't make sense to sort arrays if (column.sort && !column.writeonly && !column.array) { fieldsTemplate += ` ${column.propertyName}_ASC = '${column.propertyName}_ASC', ${column.propertyName}_DESC = '${column.propertyName}_DESC', `; } }); return ` export enum ${model.name}OrderByEnum { ${fieldsTemplate} } registerEnumType(${model.name}OrderByEnum, { name: '${model.name}OrderByInput' }); `; } function columnRequiresExplicitGQLType(column: ColumnMetadata) { return ( column.enum || column.array || column.type === 'json' || column.type === 'id' || column.type === 'date' || column.type === 'datetime' || column.type === 'dateonly' ); }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { class DuplicateRecordApi { /** * DynamicsCrm.DevKit DuplicateRecordApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the system job that created this record. */ AsyncOperationId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_account: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_activityfileattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_activitymonitor: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_adminsettingsentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_applicationuser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_appnotification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_appointment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresource: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcebooking: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcebookingheader: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcecategoryassn: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcecharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookableresourcegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_bookingstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_campaign: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_campaignresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_canvasappextendedmetadata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_catalogassignment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ channelaccessprofile_duplicatebaserecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_characteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_competitor: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_connector: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_contact: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_contract: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_conversationtranscript: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_datalakefolder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_datalakefolderpermission: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_datalakeworkspace: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_datalakeworkspacepermission: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_email: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_emailserverprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_entitlement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_entitlementchannel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_entitlementtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_environmentvariabledefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_environmentvariablevalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_equipment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_exportsolutionupload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_fax: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_feedback: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_flowmachinegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_goal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_goalrollupquery: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_incident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_kbarticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_keyvaultreference: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_knowledgearticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_knowledgebaserecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_lead: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_letter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_list: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_managedidentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_marketingformdisplayattributes: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_accountpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_actioncardregarding: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_actual: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agentstatushistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibdataset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aiodimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aiodlabel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_analysiscomponent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_analysisjob: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_analysisresult: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_analytics: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_appconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_applicationextension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_approval: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_autocapturerule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_autocapturesettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_batchjob: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookingalert: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookingrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_callablecontext: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_cannedmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_capacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_channel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_channelcapability: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_channelprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ciprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_clientextension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_contactpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_conversationaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_conversationdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_customengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_customerasset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_customerassetattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_customerassetcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_dataexport: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_dataflow: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_decisioncontract: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_decisionruleset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_delegation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_dimension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_entitlementapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_entityconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_estimate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_estimateline: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_expense: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_expensecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_fact: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_federatedarticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_fieldcomputation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_findworkevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_flowcardtype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_forecastdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_forecastinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_geofence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_geofenceevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_geofencingsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_geolocationsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_geolocationtracking: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_icebreakersconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inspection: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inspectionattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inspectioninstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inspectionresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inventoryjournal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_inventorytransfer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_invoicefrequency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_iotsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_journal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_journalline: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_kpieventdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_macrosession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_maskingrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_migrationtracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_notificationfield: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_notificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocfbapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocfbpage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_oclanguage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocphonenumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsimltraining: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsitdskill: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_octwitterapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_octwitterhandle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_orderpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_organizationalunit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_paneconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_payment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_paymentdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_paymentmethod: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_paymentterm: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_personalmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_playbookactivity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_playbookcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_playbookinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_playbooktemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_pminferredtask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_pmrecording: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_postalbum: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_postalcode: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_presence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_priority: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_problematicasset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_processnotes: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productinventory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivityagentscript: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_project: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectapproval: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projecttask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectteam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_provider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_purchaseorder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotebookingincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotebookingservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_quotepricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementdependency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementgroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementrelationship: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_requirementstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourcerequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourcerequirement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_resourceterritory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rma: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rmareceipt: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rmasubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_roleutilization: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_routingconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_routingrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rtv: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rtvproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_scenario: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sentimentanalysis: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_servicetasktype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sessiondata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sessionevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sessionparticipant: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_sessiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_shipvia: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_siconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_skillattachmenttarget: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_slakpi: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_smartassistconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_smsnumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_soundfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_taxcode: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_taxcodedetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_templateparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_templatetags: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_timeentrysetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_timegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_timegroupdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_timeoffrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactionconnection: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactionorigin: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_transactiontype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_untrackedappointment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_userworkhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_warehouse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workhourtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderresolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workorderservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workordersubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyn_workordertype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_configuration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_customizationfiles: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_entityassignment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_entitysearch: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_form: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_languagemodule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_scriptlet: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_search: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_sessioninformation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_ucisettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msdyusd_uiievent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msfp_alert: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msfp_alertrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msfp_fileresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_msfp_surveyreminder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_opportunity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_organizationdatasyncsubscription: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_package: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_phonecall: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_publisher: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_queue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_quote: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_ratingmodel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_ratingvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_recurringappointmentmaster: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_resourcegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_service: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_serviceplan: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_sharepointdocumentlocation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_sharepointsite: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_socialactivity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_socialprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_solutioncomponentconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_stagesolutionupload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_systemuser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_task: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_team: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_territory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_transactioncurrency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_action: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_context: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_hostedapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_nonhostedapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_option: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_savedsession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_sessiontransfer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_workflow: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_workflowstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the base record. */ baserecordid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValueReadonly; /** Date and time when the duplicate record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the duplicate record. */ DuplicateId: DevKit.WebApi.GuidValue; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_account: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_activityfileattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_activitymonitor: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_adminsettingsentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_applicationuser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_appnotification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_appointment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresource: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcebooking: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcebookingheader: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcecategoryassn: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcecharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookableresourcegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_bookingstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_campaign: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_campaignresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_canvasappextendedmetadata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_catalogassignment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ channelaccessprofile_duplicatematchingrecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_characteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_competitor: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_connector: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_contact: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_contract: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_conversationtranscript: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_datalakefolder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_datalakefolderpermission: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_datalakeworkspace: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_datalakeworkspacepermission: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_email: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_emailserverprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_entitlement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_entitlementchannel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_entitlementtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_environmentvariabledefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_environmentvariablevalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_equipment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_exportsolutionupload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_fax: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_feedback: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_flowmachinegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_goal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_goalrollupquery: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_incident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_kbarticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_keyvaultreference: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_knowledgearticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_knowledgebaserecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_lead: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_letter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_list: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_managedidentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_marketingformdisplayattributes: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_accountpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_actioncardregarding: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_actual: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agentstatushistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibdataset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aiodimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aiodlabel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_analysiscomponent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_analysisjob: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_analysisresult: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_analytics: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_appconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_applicationextension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_approval: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_autocapturerule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_autocapturesettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_batchjob: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookingalert: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookingrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_callablecontext: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_cannedmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_capacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_channel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_channelcapability: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_channelprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ciprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_clientextension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_contactpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_conversationaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_conversationdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_customengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_customerasset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_customerassetattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_customerassetcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_dataexport: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_dataflow: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_decisioncontract: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_decisionruleset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_delegation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_dimension: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_entitlementapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_entityconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_estimate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_estimateline: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_expense: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_expensecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_fact: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_federatedarticle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_fieldcomputation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_findworkevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_flowcardtype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_forecastdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_forecastinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_geofence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_geofenceevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_geofencingsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_geolocationsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_geolocationtracking: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_icebreakersconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inspection: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inspectionattachment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inspectioninstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inspectionresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inventoryjournal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_inventorytransfer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_invoicefrequency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_iotsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_journal: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_journalline: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_kpieventdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_macrosession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_maskingrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_migrationtracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_notificationfield: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_notificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocfbapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocfbpage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_oclanguage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocphonenumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsimltraining: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsitdskill: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_octwitterapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_octwitterhandle: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_orderpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_organizationalunit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_paneconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_payment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_paymentdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_paymentmethod: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_paymentterm: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_personalmessage: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_playbookactivity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_playbookcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_playbookinstance: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_playbooktemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_pminferredtask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_pmrecording: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_postalbum: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_postalcode: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_presence: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_priority: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_problematicasset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_processnotes: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productinventory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivityagentscript: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_project: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectapproval: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectpricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projecttask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectteam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_provider: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_purchaseorder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotebookingincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotebookingservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_quotepricelist: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementdependency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementgroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementrelationship: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_requirementstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourcerequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourcerequirement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_resourceterritory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rma: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rmareceipt: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rmasubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_roleutilization: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_routingconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_routingrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rtv: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rtvproduct: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_scenario: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sentimentanalysis: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_servicetasktype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sessiondata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sessionevent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sessionparticipant: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_sessiontemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_shipvia: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_siconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_skillattachmenttarget: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_slakpi: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_smartassistconfig: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_smsnumber: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_soundfile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_taxcode: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_taxcodedetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_templateparameter: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_templatetags: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_timeentrysetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_timegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_timegroupdetail: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_timeoffrequest: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactioncategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactionconnection: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactionorigin: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_transactiontype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_untrackedappointment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_userworkhistory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_warehouse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workhourtemplate: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderincident: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderresolution: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderservice: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workorderservicetask: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workordersubstatus: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyn_workordertype: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_configuration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_customizationfiles: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_entityassignment: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_entitysearch: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_form: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_languagemodule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_scriptlet: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_search: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_sessioninformation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_ucisettings: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msdyusd_uiievent: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msfp_alert: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msfp_alertrule: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msfp_fileresponse: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_msfp_surveyreminder: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_opportunity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_organizationdatasyncsubscription: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_package: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_phonecall: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_publisher: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_queue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_quote: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_ratingmodel: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_ratingvalue: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_recurringappointmentmaster: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_resourcegroup: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_service: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_serviceplan: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_sharepointdocumentlocation: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_sharepointsite: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_socialactivity: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_socialprofile: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_solutioncomponentconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_stagesolutionupload: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_systemuser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_task: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_team: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_territory: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_transactioncurrency: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_action: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_context: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_hostedapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_nonhostedapplication: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_option: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_savedsession: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_sessiontransfer: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_workflow: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_workflowstep: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the potential duplicate record. */ duplicaterecordid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the duplicate rule against which this duplicate was found. */ DuplicateRuleId: DevKit.WebApi.LookupValueReadonly; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the business unit that owns the duplicate record. */ OwningBusinessUnit: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of the user who owns the duplicate record. */ OwningUser: DevKit.WebApi.GuidValueReadonly; } } declare namespace OptionSet { namespace DuplicateRecord { enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
export interface Location { /** * One-based line index of the first character */ startLine: number; /** * One-based column index of the first character */ startCol: number; /** * One-based line index of the last character */ endLine: number; /** * One-based column index of the last character */ endCol: number; /** * Zero-based first character index */ startOffset: number; /** * Zero-based last character index */ endOffset: number; } export interface AttributesLocation { [attributeName: string]: Location; } export interface StartTagLocation extends Location { /** * Start tag attributes' location info */ attrs: AttributesLocation; } export interface ElementLocation extends StartTagLocation { /** * Element's start tag location info. */ startTag: StartTagLocation; /** * Element's end tag location info. */ endTag: Location; } export interface ParserOptions { /** * The [scripting flag](https://html.spec.whatwg.org/multipage/parsing.html#scripting-flag). If set * to `true`, `noscript` element content will be parsed as text. * * **Default:** `true` */ scriptingEnabled?: boolean; /** * Enables source code location information. When enabled, each node (except the root node) * will have a `sourceCodeLocation` property. If the node is not an empty element, `sourceCodeLocation` will * be a {@link ElementLocation} object, otherwise it will be {@link Location}. * If the element was implicitly created by the parser (as part of * [tree correction](https://html.spec.whatwg.org/multipage/syntax.html#an-introduction-to-error-handling-and-strange-cases-in-the-parser)), * its `sourceCodeLocation` property will be `undefined`. * * **Default:** `false` */ sourceCodeLocationInfo?: boolean; /** * Specifies the resulting tree format. * * **Default:** `treeAdapters.default` */ treeAdapter?: TreeAdapter; } export interface SerializerOptions { /*** * Specifies input tree format. * * **Default:** `treeAdapters.default` */ treeAdapter?: TreeAdapter; } /** * [Document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks). */ export type DocumentMode = "no-quirks" | "quirks" | "limited-quirks"; // Default tree adapter /** * Element attribute. */ export interface Attribute { /** * The name of the attribute. */ name: string; /** * The value of the attribute. */ value: string; /** * The namespace of the attribute. */ namespace?: string; /** * The namespace-related prefix of the attribute. */ prefix?: string; } /** * Default tree adapter Node interface. */ export interface DefaultTreeNode { /** * The name of the node. E.g. {@link Document} will have `nodeName` equal to '#document'`. */ nodeName: string; } /** * Default tree adapter ParentNode interface. */ export interface DefaultTreeParentNode extends DefaultTreeNode { /** * Child nodes. */ childNodes: DefaultTreeNode[]; } /** * Default tree adapter ChildNode interface. */ export interface DefaultTreeChildNode extends DefaultTreeNode { /** * Parent node. */ parentNode: DefaultTreeParentNode; } /** * Default tree adapter DocumentType interface. */ export interface DefaultTreeDocumentType extends DefaultTreeNode { /** * The name of the node. */ nodeName: "#documentType"; /** * Document type name. */ name: string; /** * Document type public identifier. */ publicId: string; /** * Document type system identifier. */ systemId: string; } /** * Default tree adapter Document interface. */ export interface DefaultTreeDocument extends DefaultTreeParentNode { /** * The name of the node. */ nodeName: "#document"; /** * [Document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks). */ mode: DocumentMode; } /** * Default tree adapter DocumentFragment interface. */ export interface DefaultTreeDocumentFragment extends DefaultTreeParentNode { /** * The name of the node. */ nodeName: "#document-fragment"; } /** * Default tree adapter Element interface. */ export interface DefaultTreeElement extends DefaultTreeChildNode, DefaultTreeParentNode { /** * The name of the node. Equals to element {@link tagName}. */ nodeName: string; /** * Element tag name. */ tagName: string; /** * Element namespace. */ namespaceURI: string; /** * List of element attributes. */ attrs: Attribute[]; /** * Element source code location info. Available if location info is enabled via {@link ParserOptions}. */ sourceCodeLocation?: ElementLocation; } /** * Default tree adapter CommentNode interface. */ export interface DefaultTreeCommentNode extends DefaultTreeChildNode { /** * The name of the node. */ nodeName: "#comment"; /** * Comment text. */ data: string; /** * Comment source code location info. Available if location info is enabled via {@link ParserOptions}. */ sourceCodeLocation?: Location; } /** * Default tree adapter TextNode interface. */ export interface DefaultTreeTextNode extends DefaultTreeChildNode { /** * The name of the node. */ nodeName: "#text"; /** * Text content. */ value: string; /** * Text node source code location info. Available if location info is enabled via {@link ParserOptions}. */ sourceCodeLocation?: Location; } // Generic node intefaces /** * Generic Node interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeNode}) to get access to the properties. */ export type Node = DefaultTreeNode | object; /** * Generic ChildNode interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeChildNode}) to get access to the properties. */ export type ChildNode = DefaultTreeChildNode | object; /** * Generic ParentNode interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeParentNode}) to get access to the properties. */ export type ParentNode = DefaultTreeParentNode | object; /** * Generic DocumentType interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeDocumentType}) to get access to the properties. */ export type DocumentType = DefaultTreeDocumentType | object; /** * Generic Document interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeDocument}) to get access to the properties. */ export type Document = DefaultTreeDocument | object; /** * Generic DocumentFragment interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeDocumentFragment}) to get access to the properties. */ export type DocumentFragment = DefaultTreeDocumentFragment | object; /** * Generic Element interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeElement}) to get access to the properties. */ export type Element = DefaultTreeElement | object; /** * Generic TextNode interface. * Cast to the actual AST interface (e.g. {@link parse5.DefaultTreeTextNode}) to get access to the properties. */ export type TextNode = DefaultTreeTextNode | object; /** * Generic CommentNode interface. * Cast to the actual AST interface (e.g. {@link parse5.Default.CommentNode}) to get access to the properties. */ export type CommentNode = DefaultTreeCommentNode | object; /** * Tree adapter is a set of utility functions that provides minimal required abstraction layer beetween parser and a specific AST format. * Note that `TreeAdapter` is not designed to be a general purpose AST manipulation library. You can build such library * on top of existing `TreeAdapter` or use one of the existing libraries from npm. * * @see [default implementation](https://github.com/inikulin/parse5/blob/master/lib/tree_adapters/default.js) */ export interface TreeAdapter { /** * Creates a document node. */ createDocument(): Document; /** * Creates a document fragment node. */ createDocumentFragment(): DocumentFragment; /** * Creates an element node. * * @param tagName - Tag name of the element. * @param namespaceURI - Namespace of the element. * @param attrs - Attribute name-value pair array. Foreign attributes may contain `namespace` and `prefix` fields as well. */ createElement( tagName: string, namespaceURI: string, attrs: Attribute[] ): Element; /** * Creates a comment node. * * @param data - Comment text. */ createCommentNode(data: string): CommentNode; /** * Appends a child node to the given parent node. * * @param parentNode - Parent node. * @param newNode - Child node. */ appendChild(parentNode: ParentNode, newNode: Node): void; /** * Inserts a child node to the given parent node before the given reference node. * * @param parentNode - Parent node. * @param newNode - Child node. * @param referenceNode - Reference node. */ insertBefore( parentNode: ParentNode, newNode: Node, referenceNode: Node ): void; /** * Sets the `<template>` element content element. * * @param templateElement - `<template>` element. * @param contentElement - Content element. */ setTemplateContent( templateElement: Element, contentElement: DocumentFragment ): void; /** * Returns the `<template>` element content element. * * @param templateElement - `<template>` element. */ getTemplateContent(templateElement: Element): DocumentFragment; /** * Sets the document type. If the `document` already contains a document type node, the `name`, `publicId` and `systemId` * properties of this node will be updated with the provided values. Otherwise, creates a new document type node * with the given properties and inserts it into the `document`. * * @param document - Document node. * @param name - Document type name. * @param publicId - Document type public identifier. * @param systemId - Document type system identifier. */ setDocumentType( document: Document, name: string, publicId: string, systemId: string ): void; /** * Sets the [document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks). * * @param document - Document node. * @param mode - Document mode. */ setDocumentMode(document: Document, mode: DocumentMode): void; /** * Returns [document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks). * * @param document - Document node. */ getDocumentMode(document: Document): DocumentMode; /** * Removes a node from its parent. * * @param node - Node to remove. */ detachNode(node: Node): void; /** * Inserts text into a node. If the last child of the node is a text node, the provided text will be appended to the * text node content. Otherwise, inserts a new text node with the given text. * * @param parentNode - Node to insert text into. * @param text - Text to insert. */ insertText(parentNode: ParentNode, text: string): void; /** * Inserts text into a sibling node that goes before the reference node. If this sibling node is the text node, * the provided text will be appended to the text node content. Otherwise, inserts a new sibling text node with * the given text before the reference node. * * @param parentNode - Node to insert text into. * @param text - Text to insert. * @param referenceNode - Node to insert text before. */ insertTextBefore( parentNode: ParentNode, text: string, referenceNode: Node ): void; /** * Copies attributes to the given element. Only attributes that are not yet present in the element are copied. * * @param recipient - Element to copy attributes into. * @param attrs - Attributes to copy. */ adoptAttributes(recipient: Element, attrs: Attribute[]): void; /** * Returns the first child of the given node. * * @param node - Node. */ getFirstChild(node: ParentNode): Node; /** * Returns the given node's children in an array. * * @param node - Node. */ getChildNodes(node: ParentNode): Node[]; /** * Returns the given node's parent. * * @param node - Node. */ getParentNode(node: ChildNode): ParentNode; /** * Returns the given element's attributes in an array, in the form of name-value pairs. * Foreign attributes may contain `namespace` and `prefix` fields as well. * * @param element - Element. */ getAttrList(element: Element): Attribute[]; /** * Returns the given element's tag name. * * @param element - Element. */ getTagName(element: Element): string; /** * Returns the given element's namespace. * * @param element - Element. */ getNamespaceURI(element: Element): string; /** * Returns the given text node's content. * * @param textNode - Text node. */ getTextNodeContent(textNode: TextNode): string; /** * Returns the given comment node's content. * * @param commentNode - Comment node. */ getCommentNodeContent(commentNode: CommentNode): string; /** * Returns the given document type node's name. * * @param doctypeNode - Document type node. */ getDocumentTypeNodeName(doctypeNode: DocumentType): string; /** * Returns the given document type node's public identifier. * * @param doctypeNode - Document type node. */ getDocumentTypeNodePublicId(doctypeNode: DocumentType): string; /** * Returns the given document type node's system identifier. * * @param doctypeNode - Document type node. */ getDocumentTypeNodeSystemId(doctypeNode: DocumentType): string; /** * Determines if the given node is a text node. * * @param node - Node. */ isTextNode(node: Node): boolean; /** * Determines if the given node is a comment node. * * @param node - Node. */ isCommentNode(node: Node): boolean; /** * Determines if the given node is a document type node. * * @param node - Node. */ isDocumentTypeNode(node: Node): boolean; /** * Determines if the given node is an element. * * @param node - Node. */ isElementNode(node: Node): boolean; } /** * Parses an HTML string. * * @param html - Input HTML string. * @param options - Parsing options. * * @example * ```js * * const parse5 = require('parse5'); * * const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>'); * * console.log(document.childNodes[1].tagName); //> 'html' * ``` */ export function parse(html: string, options?: ParserOptions): Document; /** * Parses an HTML fragment. * * @param fragmentContext - Parsing context element. If specified, given fragment will be parsed as if it was set to the context element's `innerHTML` property. * @param html - Input HTML fragment string. * @param options - Parsing options. * * @example * ```js * * const parse5 = require('parse5'); * * const documentFragment = parse5.parseFragment('<table></table>'); * * console.log(documentFragment.childNodes[0].tagName); //> 'table' * * // Parses the html fragment in the context of the parsed <table> element. * const trFragment = parser.parseFragment(documentFragment.childNodes[0], '<tr><td>Shake it, baby</td></tr>'); * * console.log(trFragment.childNodes[0].childNodes[0].tagName); //> 'td' * ``` */ export function parseFragment( fragmentContext: Element, html: string, options?: ParserOptions ): DocumentFragment; export function parseFragment( html: string, options?: ParserOptions ): DocumentFragment; /** * Serializes an AST node to an HTML string. * * @param node - Node to serialize. * @param options - Serialization options. * * @example * ```js * * const parse5 = require('parse5'); * * const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>'); * * // Serializes a document. * const html = parse5.serialize(document); * * // Serializes the <html> element content. * const str = parse5.serialize(document.childNodes[1]); * * console.log(str); //> '<head></head><body>Hi there!</body>' * ``` */ export function serialize(node: Node, options?: SerializerOptions): string;
the_stack
interface HTMLAttributes { class?: any style?: string | Partial<CSSStyleDeclaration> accesskey?: string contenteditable?: boolean contextmenu?: string dir?: string disabled?: boolean draggable?: boolean hidden?: boolean id?: string lang?: string spellcheck?: boolean tabindex?: number title?: string role?: string } interface AnchorHTMLAttributes extends HTMLAttributes { download?: any href?: string hreflang?: string media?: string rel?: string target?: string } interface AreaHTMLAttributes extends HTMLAttributes { alt?: string coord?: string download?: any href?: string hreflang?: string media?: string rel?: string shape?: string target?: string } interface AudioHTMLAttributes extends MediaHTMLAttributes {} interface BaseHTMLAttributes extends HTMLAttributes { href?: string target?: string } interface BlockquoteHTMLAttributes extends HTMLAttributes { cite?: string } interface ButtonHTMLAttributes extends HTMLAttributes { autofocus?: boolean disabled?: boolean form?: string formaction?: string formenctype?: string formmethod?: string formnovalidate?: boolean formtarget?: string name?: string type?: string value?: string | string[] | number } interface CanvasHTMLAttributes extends HTMLAttributes { height?: number | string width?: number | string } interface ColHTMLAttributes extends HTMLAttributes { span?: number } interface ColgroupHTMLAttributes extends ColHTMLAttributes {} interface DetailsHTMLAttributes extends HTMLAttributes { open?: boolean } interface DelHTMLAttributes extends HTMLAttributes { cite?: string datetime?: string } interface EmbedHTMLAttributes extends HTMLAttributes { height?: number | string src?: string type?: string width?: number | string } interface FieldsetHTMLAttributes extends HTMLAttributes { disabled?: boolean form?: string name?: string } interface FormHTMLAttributes extends HTMLAttributes { acceptcharset?: string action?: string autocomplete?: string enctype?: string method?: string name?: string novalidate?: boolean target?: string } interface HtmlHTMLAttributes extends HTMLAttributes { manifest?: string } interface IframeHTMLAttributes extends HTMLAttributes { allowfullscreen?: boolean allowtransparency?: boolean frameborder?: number | string height?: number | string marginheight?: number marginwidth?: number name?: string sandbox?: string scrolling?: string seamless?: boolean src?: string srcdoc?: string width?: number | string } interface ImgHTMLAttributes extends HTMLAttributes { alt?: string height?: number | string sizes?: string src?: string srcset?: string usemap?: string width?: number | string } interface InsHTMLAttributes extends HTMLAttributes { cite?: string datetime?: string } interface InputHTMLAttributes extends HTMLAttributes { accept?: string alt?: string autocomplete?: string autofocus?: boolean capture?: boolean // https://www.w3.org/tr/html-media-capture/#the-capture-attribute checked?: boolean crossorigin?: string disabled?: boolean form?: string formaction?: string formenctype?: string formmethod?: string formnovalidate?: boolean formtarget?: string height?: number | string list?: string max?: number | string maxlength?: number min?: number | string minlength?: number multiple?: boolean name?: string pattern?: string placeholder?: string readonly?: boolean required?: boolean size?: number src?: string step?: number | string type?: string value?: string | string[] | number width?: number | string } interface KeygenHTMLAttributes extends HTMLAttributes { autofocus?: boolean challenge?: string disabled?: boolean form?: string keytype?: string keyparams?: string name?: string } interface LabelHTMLAttributes extends HTMLAttributes { form?: string htmlfor?: string } interface LiHTMLAttributes extends HTMLAttributes { value?: string | string[] | number } interface LinkHTMLAttributes extends HTMLAttributes { href?: string hreflang?: string integrity?: string media?: string rel?: string sizes?: string type?: string } interface MapHTMLAttributes extends HTMLAttributes { name?: string } interface MenuHTMLAttributes extends HTMLAttributes { type?: string } interface MediaHTMLAttributes extends HTMLAttributes { autoplay?: boolean controls?: boolean crossorigin?: string loop?: boolean mediagroup?: string muted?: boolean preload?: string src?: string } interface MetaHTMLAttributes extends HTMLAttributes { charset?: string content?: string httpequiv?: string name?: string } interface MeterHTMLAttributes extends HTMLAttributes { form?: string high?: number low?: number max?: number | string min?: number | string optimum?: number value?: string | string[] | number } interface QuoteHTMLAttributes extends HTMLAttributes { cite?: string } interface ObjectHTMLAttributes extends HTMLAttributes { classid?: string data?: string form?: string height?: number | string name?: string type?: string usemap?: string width?: number | string wmode?: string } interface OlHTMLAttributes extends HTMLAttributes { reversed?: boolean start?: number } interface OptgroupHTMLAttributes extends HTMLAttributes { disabled?: boolean label?: string } interface OptionHTMLAttributes extends HTMLAttributes { disabled?: boolean label?: string selected?: boolean value?: string | string[] | number } interface OutputHTMLAttributes extends HTMLAttributes { form?: string htmlfor?: string name?: string } interface ParamHTMLAttributes extends HTMLAttributes { name?: string value?: string | string[] | number } interface ProgressHTMLAttributes extends HTMLAttributes { max?: number | string value?: string | string[] | number } interface ScriptHTMLAttributes extends HTMLAttributes { async?: boolean charset?: string crossorigin?: string defer?: boolean integrity?: string nonce?: string src?: string type?: string } interface SelectHTMLAttributes extends HTMLAttributes { autofocus?: boolean disabled?: boolean form?: string multiple?: boolean name?: string required?: boolean size?: number value?: string | string[] | number } interface SourceHTMLAttributes extends HTMLAttributes { media?: string sizes?: string src?: string srcset?: string type?: string } interface StyleHTMLAttributes extends HTMLAttributes { media?: string nonce?: string scoped?: boolean type?: string } interface TableHTMLAttributes extends HTMLAttributes { cellpadding?: number | string cellspacing?: number | string summary?: string } interface TextareaHTMLAttributes extends HTMLAttributes { autocomplete?: string autofocus?: boolean cols?: number dirname?: string disabled?: boolean form?: string maxlength?: number minlength?: number name?: string placeholder?: string readonly?: boolean required?: boolean rows?: number value?: string | string[] | number wrap?: string } interface TdHTMLAttributes extends HTMLAttributes { colspan?: number headers?: string rowspan?: number } interface ThHTMLAttributes extends HTMLAttributes { colspan?: number headers?: string rowspan?: number scope?: string } interface TimeHTMLAttributes extends HTMLAttributes { datetime?: string } interface TrackHTMLAttributes extends HTMLAttributes { default?: boolean kind?: string label?: string src?: string srclang?: string } interface VideoHTMLAttributes extends MediaHTMLAttributes { height?: number | string playsinline?: boolean poster?: string width?: number | string } interface AllHTMLAttributes extends HTMLAttributes { accept?: string acceptcharset?: string action?: boolean allowfullscreen?: boolean allowtransparency?: boolean alt?: string async?: boolean autocomplete?: string autofocus?: boolean autoplay?: boolean capture?: boolean // https://www.w3.org/tr/html-media-capture/#the-capture-attribute cellpadding?: number | string cellspacing?: number | string challenge?: string charset?: string checked?: boolean cite?: string classid?: string cols?: number colspan?: number content?: string controls?: boolean coord?: string crossorigin?: string data?: string datetime?: string default?: boolean defer?: boolean dirname?: string disabled?: boolean download?: any enctype?: string form?: string formaction?: string formenctype?: string formmethod?: string formnovalidate?: boolean formtarget?: string frameborder?: number | string headers?: string height?: number | string high?: number href?: string hreflang?: string htmlfor?: string httpequiv?: string integrity?: string keyparams?: string keytype?: string kind?: string label?: string list?: string loop?: boolean low?: number manifest?: string marginheight?: number marginwidth?: number max?: number | string maxlength?: number media?: string mediagroup?: string method?: string min?: number | string minlength?: number multiple?: boolean muted?: boolean name?: string nonce?: string novalidate?: boolean open?: boolean optimum?: number pattern?: string placeholder?: string playsinline?: boolean poster?: string preload?: string readonly?: boolean rel?: string required?: boolean reversed?: boolean rows?: number rowspan?: number sandbox?: string scope?: string scoped?: boolean scrolling?: string seamless?: boolean selected?: boolean shape?: string size?: number sizes?: string span?: number src?: string srcdoc?: string srclang?: string srcset?: string start?: number step?: number | string summary?: string target?: string type?: string usemap?: string value?: string | string[] | number width?: number | string wmode?: string wrap?: string } interface IntrinsicElementAttributes { a: AnchorHTMLAttributes abbr: HTMLAttributes address: HTMLAttributes area: AreaHTMLAttributes article: HTMLAttributes aside: HTMLAttributes audio: AudioHTMLAttributes b: HTMLAttributes base: BaseHTMLAttributes bdi: HTMLAttributes bdo: HTMLAttributes big: HTMLAttributes blockquote: BlockquoteHTMLAttributes body: HTMLAttributes br: HTMLAttributes button: ButtonHTMLAttributes canvas: CanvasHTMLAttributes caption: HTMLAttributes cite: HTMLAttributes code: HTMLAttributes col: ColHTMLAttributes colgroup: ColgroupHTMLAttributes data: HTMLAttributes datalist: HTMLAttributes dd: HTMLAttributes del: DelHTMLAttributes details: DetailsHTMLAttributes dfn: HTMLAttributes dialog: HTMLAttributes div: HTMLAttributes dl: HTMLAttributes dt: HTMLAttributes em: HTMLAttributes embed: EmbedHTMLAttributes fieldset: FieldsetHTMLAttributes figcaption: HTMLAttributes figure: HTMLAttributes footer: HTMLAttributes form: FormHTMLAttributes h1: HTMLAttributes h2: HTMLAttributes h3: HTMLAttributes h4: HTMLAttributes h5: HTMLAttributes h6: HTMLAttributes head: HTMLAttributes header: HTMLAttributes hgroup: HTMLAttributes hr: HTMLAttributes html: HtmlHTMLAttributes i: HTMLAttributes iframe: IframeHTMLAttributes img: ImgHTMLAttributes input: InputHTMLAttributes ins: InsHTMLAttributes kbd: HTMLAttributes keygen: KeygenHTMLAttributes label: LabelHTMLAttributes legend: HTMLAttributes li: LiHTMLAttributes link: LinkHTMLAttributes main: HTMLAttributes map: MapHTMLAttributes mark: HTMLAttributes menu: MenuHTMLAttributes menuitem: HTMLAttributes meta: MetaHTMLAttributes meter: MeterHTMLAttributes nav: HTMLAttributes noscript: HTMLAttributes object: ObjectHTMLAttributes ol: OlHTMLAttributes optgroup: OptgroupHTMLAttributes option: OptionHTMLAttributes output: OutputHTMLAttributes p: HTMLAttributes param: ParamHTMLAttributes picture: HTMLAttributes pre: HTMLAttributes progress: ProgressHTMLAttributes q: QuoteHTMLAttributes rp: HTMLAttributes rt: HTMLAttributes ruby: HTMLAttributes s: HTMLAttributes samp: HTMLAttributes script: ScriptHTMLAttributes section: HTMLAttributes select: SelectHTMLAttributes small: HTMLAttributes source: SourceHTMLAttributes span: HTMLAttributes strong: HTMLAttributes style: StyleHTMLAttributes sub: HTMLAttributes summary: HTMLAttributes sup: HTMLAttributes table: TableHTMLAttributes tbody: HTMLAttributes td: TdHTMLAttributes textarea: TextareaHTMLAttributes tfoot: HTMLAttributes th: ThHTMLAttributes thead: HTMLAttributes time: TimeHTMLAttributes title: HTMLAttributes tr: HTMLAttributes track: TrackHTMLAttributes u: HTMLAttributes ul: HTMLAttributes var: HTMLAttributes video: VideoHTMLAttributes wbr: HTMLAttributes } interface Events { // clipboard events onCopy: ClipboardEvent onCut: ClipboardEvent onPaste: ClipboardEvent // composition events onCompositionend: CompositionEvent onCompositionstart: CompositionEvent onCompositionupdate: CompositionEvent // drag drop events onDrag: DragEvent onDragend: DragEvent onDragenter: DragEvent onDragexit: DragEvent onDragleave: DragEvent onDragover: DragEvent onDragstart: DragEvent onDrop: DragEvent // focus events onFocus: FocusEvent onBlur: FocusEvent // form events onChange: Event onInput: Event onReset: Event onSubmit: Event onInvalid: Event // image events onLoad: Event onError: Event // keyboard events onKeydown: KeyboardEvent onKeypress: KeyboardEvent onKeyup: KeyboardEvent // mouse events onClick: MouseEvent onContextmenu: MouseEvent onDblclick: MouseEvent onMousedown: MouseEvent onMouseenter: MouseEvent onMouseleave: MouseEvent onMousemove: MouseEvent onMouseout: MouseEvent onMouseover: MouseEvent onMouseup: MouseEvent // media events onAbort: Event onCanplay: Event onCanplaythrough: Event onDurationchange: Event onEmptied: Event onEncrypted: Event onEnded: Event onLoadeddata: Event onLoadedmetadata: Event onLoadstart: Event onPause: Event onPlay: Event onPlaying: Event onProgress: Event onRatechange: Event onSeeked: Event onSeeking: Event onStalled: Event onSuspend: Event onTimeupdate: Event onVolumechange: Event onWaiting: Event // selection events onSelect: Event // UI events onScroll: UIEvent // touch events onTouchcancel: TouchEvent onTouchend: TouchEvent onTouchmove: TouchEvent onTouchstart: TouchEvent // wheel events onWheel: WheelEvent // animation events onAnimationstart: AnimationEvent onAnimationend: AnimationEvent onAnimationiteration: AnimationEvent // transition events onTransitionend: TransitionEvent onTransitionstart: TransitionEvent } type StringKeyOf<T> = Extract<keyof T, string> type EventHandlers<E> = { [K in StringKeyOf<E>]?: E[K] extends Function ? E[K] : (payload: E[K]) => void } type ElementAttrs<T> = T & EventHandlers<Events> type NativeElements = { [K in StringKeyOf<IntrinsicElementAttributes>]: ElementAttrs< IntrinsicElementAttributes[K] > } declare namespace JSX { interface Element {} interface ElementClass { $props: {} } interface ElementAttributesProperty { $props: {} } interface IntrinsicElements extends NativeElements { // allow arbitrary elements [name: string]: any } }
the_stack
import { configure, IReactionDisposer } from "mobx"; import { types, Instance } from "mobx-state-tree"; import { Field, Form, RepeatingForm, converters } from "../src"; // "always" leads to trouble during initialization. configure({ enforceActions: "observed" }); test("calculated", () => { const M = types .model("M", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { return self.a + self.b; }, })); const form = new Form(M, { calculated: new Field(converters.number, { derived: (node: Instance<typeof M>) => node.sum(), }), a: new Field(converters.number), b: new Field(converters.number), }); const o = M.create({ calculated: 0, a: 1, b: 2 }); const state = form.state(o); const calculated = state.field("calculated"); const a = state.field("a"); const b = state.field("b"); // we show the set value, as no modification was made expect(calculated.raw).toEqual("0"); expect(calculated.value).toEqual(0); // we set it to 4 explicitly calculated.setRaw("4"); expect(calculated.raw).toEqual("4"); // this immediately affects the underlying value expect(calculated.value).toEqual(4); // we now change a, which should modify the derived value a.setRaw("3"); expect(calculated.raw).toEqual("5"); // and also the underlying value, immediately expect(calculated.value).toEqual(5); }); test("calculated repeating", () => { const N = types .model("N", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { return self.a + self.b; }, })); const M = types.model("M", { foo: types.array(N), }); const form = new Form(M, { foo: new RepeatingForm({ calculated: new Field(converters.number, { derived: (node) => node.sum(), }), a: new Field(converters.number), b: new Field(converters.number), }), }); const o = M.create({ foo: [{ calculated: 0, a: 1, b: 2 }] }); const state = form.state(o); const sub = state.repeatingForm("foo").index(0); const calculated = sub.field("calculated"); const a = sub.field("a"); const b = sub.field("b"); // we show the original value as no change was made expect(calculated.raw).toEqual("0"); expect(calculated.value).toEqual(0); // we set it to 4 explicitly calculated.setRaw("4"); expect(calculated.raw).toEqual("4"); // this immediately affects the underlying value expect(calculated.value).toEqual(4); // we now change a, which should modify the derived value a.setRaw("3"); expect(calculated.raw).toEqual("5"); // and also the underlying value, immediately expect(calculated.value).toEqual(5); }); test("calculated repeating push and remove", () => { const N = types .model("N", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { return self.a + self.b; }, })); const M = types.model("M", { foo: types.array(N), }); const form = new Form(M, { foo: new RepeatingForm({ calculated: new Field(converters.number, { derived: (node) => node.sum(), }), a: new Field(converters.number), b: new Field(converters.number), }), }); const o = M.create({ foo: [{ calculated: 0, a: 1, b: 2 }] }); const state = form.state(o); const forms = state.repeatingForm("foo"); forms.push(N.create({ calculated: 0, a: 5, b: 3 })); // we get a form and field here so we can see that its reaction is disposed // later const laterRemoved = forms.index(0); const removedCalculated = laterRemoved.field("calculated"); const sub = forms.index(1); const calculated = sub.field("calculated"); const a = sub.field("a"); const b = sub.field("b"); // we show nothing as we're in add mode expect(calculated.raw).toEqual(""); // we set it to 4 explicitly calculated.setRaw("4"); expect(calculated.raw).toEqual("4"); // this immediately affects the underlying value expect(calculated.value).toEqual(4); // we now change a, which should modify the derived value a.setRaw("3"); expect(calculated.raw).toEqual("6"); // and also the underlying value, immediately expect(calculated.value).toEqual(6); const disposer = removedCalculated._disposer; expect(disposer).not.toBeUndefined(); // to please TS if (disposer == null) { throw new Error("Disposer cannot be undefined"); } let touched = false; const wrappedDisposer = () => { touched = true; disposer(); }; // a bit of a hack to track whether the disposer is called removedCalculated._disposer = wrappedDisposer as IReactionDisposer; forms.remove(o.foo[0]); const sub2 = forms.index(0); const calculated2 = sub2.field("calculated"); expect(calculated2.raw).toEqual("6"); expect(calculated2.value).toEqual(6); calculated2.setRaw("4"); expect(calculated2.value).toEqual(4); const a2 = sub.field("a"); a2.setRaw("7"); expect(calculated2.raw).toBe("10"); expect(touched).toBeTruthy(); }); test("calculated with addModeDefaults", () => { const N = types .model("N", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { return self.a + self.b; }, })); const M = types.model("M", { foo: types.array(N), }); let changeCount = 0; const form = new Form(M, { foo: new RepeatingForm({ calculated: new Field(converters.number, { derived: (node) => { return node.sum(); }, change: () => { changeCount++; }, }), a: new Field(converters.number), b: new Field(converters.number), }), }); const o = M.create({ foo: [{ calculated: 0, a: 1, b: 2 }] }); const state = form.state(o); const forms = state.repeatingForm("foo"); expect(changeCount).toBe(0); forms.push(N.create({ calculated: 0, a: 5, b: 3 }), ["calculated", "a", "b"]); // this shouldn't have issued a change, as the derived value is // calculated during adding expect(changeCount).toBe(0); const sub0 = forms.index(0); const calculated0 = sub0.field("calculated"); // derivation shouldn't have run expect(calculated0.value).toEqual(0); expect(calculated0.raw).toEqual("0"); // we now change a, which should modify the derived value sub0.field("a").setRaw("3"); expect(changeCount).toBe(1); expect(calculated0.value).toEqual(5); expect(calculated0.raw).toEqual("5"); // we expect the same behavior for the new entry const sub1 = forms.index(1); const calculated1 = sub1.field("calculated"); // but derivation should have run expect(calculated1.value).toEqual(8); sub1.field("a").setRaw("6"); expect(changeCount).toBe(2); // we should have calculated the derived expect(calculated1.value).toEqual(9); expect(calculated1.raw).toEqual("9"); // now add a third entry forms.push(N.create({ calculated: 0, a: 5, b: 3 }), ["calculated", "a", "b"]); const sub2 = forms.index(2); const calculated2 = sub2.field("calculated"); expect(calculated2.value).toEqual(8); expect(calculated2.raw).toEqual("8"); expect(changeCount).toBe(2); }); test("calculated with context", () => { const M = types .model("M", { calculated: types.string, a: types.string, b: types.string, }) .views((self) => ({ sum() { return (parseFloat(self.a) + parseFloat(self.b)).toString(); }, })); function getDecimalPlaces(context: any) { expect(context).not.toBeUndefined(); return { decimalPlaces: context.getNumberOfDecimals() }; } const form = new Form(M, { calculated: new Field( converters.dynamic(converters.stringDecimal, getDecimalPlaces), { derived: (node: Instance<typeof M>) => node.sum(), } ), a: new Field( converters.dynamic(converters.stringDecimal, getDecimalPlaces) ), b: new Field( converters.dynamic(converters.stringDecimal, getDecimalPlaces) ), }); const o = M.create({ calculated: "0.0000", a: "1.0000", b: "2.3456" }); const state = form.state(o, { context: { getNumberOfDecimals: () => 4 }, }); const calculated = state.field("calculated"); const a = state.field("a"); const b = state.field("b"); // we show the set value, as no modification was made expect(calculated.raw).toEqual("0.0000"); expect(calculated.value).toEqual("0.0000"); // we now change a, which should modify the derived value a.setRaw("1.2345"); expect(calculated.raw).toEqual("3.5801"); // and also the underlying value, immediately expect(calculated.value).toEqual("3.5801"); }); test("calculated derived update without change", () => { const M = types .model("M", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { return self.a + self.b; }, })); const form = new Form(M, { calculated: new Field(converters.number, { derived: (node: Instance<typeof M>) => node.sum(), }), a: new Field(converters.number), b: new Field(converters.number), }); const o = M.create({ calculated: 0, a: 1, b: 2 }); const state = form.state(o); const calculated = state.field("calculated"); const a = state.field("a"); const b = state.field("b"); // Update our calculated value to match the state of a and b. a.setRaw("3"); // Javascript has no simple variable id comparison, but it does have object property comparison. Therefore, we start with making an object const obj = {}; const descriptor = Object.create(null); // no inherited properties descriptor.calculatedRaw = calculated.raw; descriptor.calculatedValue = calculated.value; Object.defineProperty(obj, "key", descriptor); // not enumerable, not configurable, not writable as defaults // If freeze is available, prevents adding or removing the object prototype properties. (Object.freeze || Object)(descriptor.prototype); // (get, set, calculatedRaw, calculatedValue) // Double check the numbers match common sense expect(descriptor.calculatedRaw).toEqual("5"); expect(descriptor.calculatedValue).toEqual(5); // Check if the calculated value changed after changing one the fields it is derived from. It is not supposed to. b.setRaw("2"); const newObj = {}; const newDescriptor = Object.create(null); newDescriptor.calculatedRaw = calculated.raw; newDescriptor.calculatedValue = calculated.value; Object.defineProperty(newObj, "key", newDescriptor); (Object.freeze || Object)(newDescriptor.prototype); // Check if they're the same or new derived values using the most strict methods possible. expect(Object.is(descriptor.calculatedRaw, newDescriptor.calculatedRaw)).toBe( true ); expect( Object.is(descriptor.calculatedValue, newDescriptor.calculatedValue) ).toBe(true); }); test("dispose", () => { // keep a counter to track how often we call our sum function // it's called more than we would wish, but if we don't properly // dispose of previous state it's called even more often let counter = 0; const M = types .model("M", { calculated: types.number, a: types.number, b: types.number, }) .views((self) => ({ sum() { counter++; return self.a + self.b; }, })); const form = new Form(M, { calculated: new Field(converters.number, { derived: (node: Instance<typeof M>) => node.sum(), }), a: new Field(converters.number), b: new Field(converters.number), }); const o = M.create({ calculated: 0, a: 1, b: 2 }); expect(counter).toBe(0); // previous state is important to do test dispose // happens properly, don't remove! const previousState = form.state(o); expect(counter).toBe(1); const state = form.state(o); expect(counter).toBe(2); const calculated = state.field("calculated"); const a = state.field("a"); const b = state.field("b"); // we show the set value, as no modification was made expect(calculated.raw).toEqual("0"); expect(calculated.value).toEqual(0); // we set it to 4 explicitly calculated.setRaw("4"); expect(calculated.raw).toEqual("4"); // this immediately affects the underlying value expect(calculated.value).toEqual(4); expect(counter).toBe(2); // we now change a, which should modify the derived value a.setRaw("3"); // if we hadn't disposed properly this would have been // called more expect(counter).toBe(3); expect(calculated.raw).toEqual("5"); // and also the underlying value, immediately expect(calculated.value).toEqual(5); });
the_stack